PackageManagerService.java revision 1566233bfdb994cd41d21ffb2615af8d0e29166f
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 2389 // when upgrading from pre-M, promote system app permissions from install to runtime 2390 mPromoteSystemApps = 2391 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2392 2393 // When upgrading from pre-N, we need to handle package extraction like first boot, 2394 // as there is no profiling data available. 2395 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2396 2397 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2398 2399 // save off the names of pre-existing system packages prior to scanning; we don't 2400 // want to automatically grant runtime permissions for new system apps 2401 if (mPromoteSystemApps) { 2402 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2403 while (pkgSettingIter.hasNext()) { 2404 PackageSetting ps = pkgSettingIter.next(); 2405 if (isSystemApp(ps)) { 2406 mExistingSystemPackages.add(ps.name); 2407 } 2408 } 2409 } 2410 2411 mCacheDir = preparePackageParserCache(mIsUpgrade); 2412 2413 // Set flag to monitor and not change apk file paths when 2414 // scanning install directories. 2415 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2416 2417 if (mIsUpgrade || mFirstBoot) { 2418 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2419 } 2420 2421 // Collect vendor overlay packages. (Do this before scanning any apps.) 2422 // For security and version matching reason, only consider 2423 // overlay packages if they reside in the right directory. 2424 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2425 | PackageParser.PARSE_IS_SYSTEM 2426 | PackageParser.PARSE_IS_SYSTEM_DIR 2427 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2428 2429 // Find base frameworks (resource packages without code). 2430 scanDirTracedLI(frameworkDir, mDefParseFlags 2431 | PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR 2433 | PackageParser.PARSE_IS_PRIVILEGED, 2434 scanFlags | SCAN_NO_DEX, 0); 2435 2436 // Collected privileged system packages. 2437 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2438 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2439 | PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR 2441 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2442 2443 // Collect ordinary system packages. 2444 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2445 scanDirTracedLI(systemAppDir, mDefParseFlags 2446 | PackageParser.PARSE_IS_SYSTEM 2447 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2448 2449 // Collect all vendor packages. 2450 File vendorAppDir = new File("/vendor/app"); 2451 try { 2452 vendorAppDir = vendorAppDir.getCanonicalFile(); 2453 } catch (IOException e) { 2454 // failed to look up canonical path, continue with original one 2455 } 2456 scanDirTracedLI(vendorAppDir, mDefParseFlags 2457 | PackageParser.PARSE_IS_SYSTEM 2458 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2459 2460 // Collect all OEM packages. 2461 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2462 scanDirTracedLI(oemAppDir, mDefParseFlags 2463 | PackageParser.PARSE_IS_SYSTEM 2464 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2465 2466 // Prune any system packages that no longer exist. 2467 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2468 if (!mOnlyCore) { 2469 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2470 while (psit.hasNext()) { 2471 PackageSetting ps = psit.next(); 2472 2473 /* 2474 * If this is not a system app, it can't be a 2475 * disable system app. 2476 */ 2477 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2478 continue; 2479 } 2480 2481 /* 2482 * If the package is scanned, it's not erased. 2483 */ 2484 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2485 if (scannedPkg != null) { 2486 /* 2487 * If the system app is both scanned and in the 2488 * disabled packages list, then it must have been 2489 * added via OTA. Remove it from the currently 2490 * scanned package so the previously user-installed 2491 * application can be scanned. 2492 */ 2493 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2494 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2495 + ps.name + "; removing system app. Last known codePath=" 2496 + ps.codePathString + ", installStatus=" + ps.installStatus 2497 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2498 + scannedPkg.mVersionCode); 2499 removePackageLI(scannedPkg, true); 2500 mExpectingBetter.put(ps.name, ps.codePath); 2501 } 2502 2503 continue; 2504 } 2505 2506 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2507 psit.remove(); 2508 logCriticalInfo(Log.WARN, "System package " + ps.name 2509 + " no longer exists; it's data will be wiped"); 2510 // Actual deletion of code and data will be handled by later 2511 // reconciliation step 2512 } else { 2513 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2514 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2515 possiblyDeletedUpdatedSystemApps.add(ps.name); 2516 } 2517 } 2518 } 2519 } 2520 2521 //look for any incomplete package installations 2522 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2523 for (int i = 0; i < deletePkgsList.size(); i++) { 2524 // Actual deletion of code and data will be handled by later 2525 // reconciliation step 2526 final String packageName = deletePkgsList.get(i).name; 2527 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2528 synchronized (mPackages) { 2529 mSettings.removePackageLPw(packageName); 2530 } 2531 } 2532 2533 //delete tmp files 2534 deleteTempPackageFiles(); 2535 2536 // Remove any shared userIDs that have no associated packages 2537 mSettings.pruneSharedUsersLPw(); 2538 2539 if (!mOnlyCore) { 2540 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2541 SystemClock.uptimeMillis()); 2542 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2543 2544 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2545 | PackageParser.PARSE_FORWARD_LOCK, 2546 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 /** 2549 * Remove disable package settings for any updated system 2550 * apps that were removed via an OTA. If they're not a 2551 * previously-updated app, remove them completely. 2552 * Otherwise, just revoke their system-level permissions. 2553 */ 2554 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2555 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2556 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2557 2558 String msg; 2559 if (deletedPkg == null) { 2560 msg = "Updated system package " + deletedAppName 2561 + " no longer exists; it's data will be wiped"; 2562 // Actual deletion of code and data will be handled by later 2563 // reconciliation step 2564 } else { 2565 msg = "Updated system app + " + deletedAppName 2566 + " no longer present; removing system privileges for " 2567 + deletedAppName; 2568 2569 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2570 2571 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2572 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2573 } 2574 logCriticalInfo(Log.WARN, msg); 2575 } 2576 2577 /** 2578 * Make sure all system apps that we expected to appear on 2579 * the userdata partition actually showed up. If they never 2580 * appeared, crawl back and revive the system version. 2581 */ 2582 for (int i = 0; i < mExpectingBetter.size(); i++) { 2583 final String packageName = mExpectingBetter.keyAt(i); 2584 if (!mPackages.containsKey(packageName)) { 2585 final File scanFile = mExpectingBetter.valueAt(i); 2586 2587 logCriticalInfo(Log.WARN, "Expected better " + packageName 2588 + " but never showed up; reverting to system"); 2589 2590 int reparseFlags = mDefParseFlags; 2591 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2592 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2593 | PackageParser.PARSE_IS_SYSTEM_DIR 2594 | PackageParser.PARSE_IS_PRIVILEGED; 2595 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR; 2598 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2599 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2600 | PackageParser.PARSE_IS_SYSTEM_DIR; 2601 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2602 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2603 | PackageParser.PARSE_IS_SYSTEM_DIR; 2604 } else { 2605 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2606 continue; 2607 } 2608 2609 mSettings.enableSystemPackageLPw(packageName); 2610 2611 try { 2612 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2613 } catch (PackageManagerException e) { 2614 Slog.e(TAG, "Failed to parse original system package: " 2615 + e.getMessage()); 2616 } 2617 } 2618 } 2619 } 2620 mExpectingBetter.clear(); 2621 2622 // Resolve the storage manager. 2623 mStorageManagerPackage = getStorageManagerPackageName(); 2624 2625 // Resolve protected action filters. Only the setup wizard is allowed to 2626 // have a high priority filter for these actions. 2627 mSetupWizardPackage = getSetupWizardPackageName(); 2628 if (mProtectedFilters.size() > 0) { 2629 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2630 Slog.i(TAG, "No setup wizard;" 2631 + " All protected intents capped to priority 0"); 2632 } 2633 for (ActivityIntentInfo filter : mProtectedFilters) { 2634 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2635 if (DEBUG_FILTERS) { 2636 Slog.i(TAG, "Found setup wizard;" 2637 + " allow priority " + filter.getPriority() + ";" 2638 + " package: " + filter.activity.info.packageName 2639 + " activity: " + filter.activity.className 2640 + " priority: " + filter.getPriority()); 2641 } 2642 // skip setup wizard; allow it to keep the high priority filter 2643 continue; 2644 } 2645 Slog.w(TAG, "Protected action; cap priority to 0;" 2646 + " package: " + filter.activity.info.packageName 2647 + " activity: " + filter.activity.className 2648 + " origPrio: " + filter.getPriority()); 2649 filter.setPriority(0); 2650 } 2651 } 2652 mDeferProtectedFilters = false; 2653 mProtectedFilters.clear(); 2654 2655 // Now that we know all of the shared libraries, update all clients to have 2656 // the correct library paths. 2657 updateAllSharedLibrariesLPw(null); 2658 2659 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2660 // NOTE: We ignore potential failures here during a system scan (like 2661 // the rest of the commands above) because there's precious little we 2662 // can do about it. A settings error is reported, though. 2663 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2664 } 2665 2666 // Now that we know all the packages we are keeping, 2667 // read and update their last usage times. 2668 mPackageUsage.read(mPackages); 2669 mCompilerStats.read(); 2670 2671 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2672 SystemClock.uptimeMillis()); 2673 Slog.i(TAG, "Time to scan packages: " 2674 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2675 + " seconds"); 2676 2677 // If the platform SDK has changed since the last time we booted, 2678 // we need to re-grant app permission to catch any new ones that 2679 // appear. This is really a hack, and means that apps can in some 2680 // cases get permissions that the user didn't initially explicitly 2681 // allow... it would be nice to have some better way to handle 2682 // this situation. 2683 int updateFlags = UPDATE_PERMISSIONS_ALL; 2684 if (ver.sdkVersion != mSdkVersion) { 2685 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2686 + mSdkVersion + "; regranting permissions for internal storage"); 2687 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2688 } 2689 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2690 ver.sdkVersion = mSdkVersion; 2691 2692 // If this is the first boot or an update from pre-M, and it is a normal 2693 // boot, then we need to initialize the default preferred apps across 2694 // all defined users. 2695 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2696 for (UserInfo user : sUserManager.getUsers(true)) { 2697 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2698 applyFactoryDefaultBrowserLPw(user.id); 2699 primeDomainVerificationsLPw(user.id); 2700 } 2701 } 2702 2703 // Prepare storage for system user really early during boot, 2704 // since core system apps like SettingsProvider and SystemUI 2705 // can't wait for user to start 2706 final int storageFlags; 2707 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2708 storageFlags = StorageManager.FLAG_STORAGE_DE; 2709 } else { 2710 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2711 } 2712 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2713 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2714 true /* onlyCoreApps */); 2715 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "fixup"); 2717 try { 2718 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2719 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2720 } catch (InstallerException e) { 2721 Slog.w(TAG, "Trouble fixing GIDs", e); 2722 } 2723 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2724 2725 if (deferPackages == null || deferPackages.isEmpty()) { 2726 return; 2727 } 2728 int count = 0; 2729 for (String pkgName : deferPackages) { 2730 PackageParser.Package pkg = null; 2731 synchronized (mPackages) { 2732 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2733 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2734 pkg = ps.pkg; 2735 } 2736 } 2737 if (pkg != null) { 2738 synchronized (mInstallLock) { 2739 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2740 true /* maybeMigrateAppData */); 2741 } 2742 count++; 2743 } 2744 } 2745 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2746 }, "prepareAppData"); 2747 2748 // If this is first boot after an OTA, and a normal boot, then 2749 // we need to clear code cache directories. 2750 // Note that we do *not* clear the application profiles. These remain valid 2751 // across OTAs and are used to drive profile verification (post OTA) and 2752 // profile compilation (without waiting to collect a fresh set of profiles). 2753 if (mIsUpgrade && !onlyCore) { 2754 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2755 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2756 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2757 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2758 // No apps are running this early, so no need to freeze 2759 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2760 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2761 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2762 } 2763 } 2764 ver.fingerprint = Build.FINGERPRINT; 2765 } 2766 2767 checkDefaultBrowser(); 2768 2769 // clear only after permissions and other defaults have been updated 2770 mExistingSystemPackages.clear(); 2771 mPromoteSystemApps = false; 2772 2773 // All the changes are done during package scanning. 2774 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2775 2776 // can downgrade to reader 2777 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2778 mSettings.writeLPr(); 2779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2780 2781 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2782 SystemClock.uptimeMillis()); 2783 2784 if (!mOnlyCore) { 2785 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2786 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2787 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2788 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2789 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2790 mIntentFilterVerifierComponent); 2791 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2792 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2793 SharedLibraryInfo.VERSION_UNDEFINED); 2794 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2795 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2796 SharedLibraryInfo.VERSION_UNDEFINED); 2797 } else { 2798 mRequiredVerifierPackage = null; 2799 mRequiredInstallerPackage = null; 2800 mRequiredUninstallerPackage = null; 2801 mIntentFilterVerifierComponent = null; 2802 mIntentFilterVerifier = null; 2803 mServicesSystemSharedLibraryPackageName = null; 2804 mSharedSystemSharedLibraryPackageName = null; 2805 } 2806 2807 mInstallerService = new PackageInstallerService(context, this); 2808 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2809 if (ephemeralResolverComponent != null) { 2810 if (DEBUG_EPHEMERAL) { 2811 Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent); 2812 } 2813 mInstantAppResolverConnection = 2814 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2815 } else { 2816 mInstantAppResolverConnection = null; 2817 } 2818 updateInstantAppInstallerLocked(); 2819 mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr(); 2820 2821 // Read and update the usage of dex files. 2822 // Do this at the end of PM init so that all the packages have their 2823 // data directory reconciled. 2824 // At this point we know the code paths of the packages, so we can validate 2825 // the disk file and build the internal cache. 2826 // The usage file is expected to be small so loading and verifying it 2827 // should take a fairly small time compare to the other activities (e.g. package 2828 // scanning). 2829 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2830 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2831 for (int userId : currentUserIds) { 2832 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2833 } 2834 mDexManager.load(userPackages); 2835 } // synchronized (mPackages) 2836 } // synchronized (mInstallLock) 2837 2838 // Now after opening every single application zip, make sure they 2839 // are all flushed. Not really needed, but keeps things nice and 2840 // tidy. 2841 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2842 Runtime.getRuntime().gc(); 2843 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2844 2845 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2846 FallbackCategoryProvider.loadFallbacks(); 2847 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2848 2849 // The initial scanning above does many calls into installd while 2850 // holding the mPackages lock, but we're mostly interested in yelling 2851 // once we have a booted system. 2852 mInstaller.setWarnIfHeld(mPackages); 2853 2854 // Expose private service for system components to use. 2855 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2857 } 2858 2859 private void updateInstantAppInstallerLocked() { 2860 final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent; 2861 final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr(); 2862 ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null 2863 ? null : newInstantAppInstaller.getComponentName(); 2864 2865 if (newInstantAppInstallerComponent != null 2866 && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) { 2867 if (DEBUG_EPHEMERAL) { 2868 Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent); 2869 } 2870 setUpInstantAppInstallerActivityLP(newInstantAppInstaller); 2871 } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) { 2872 Slog.d(TAG, "Unset ephemeral installer; none available"); 2873 } 2874 mInstantAppInstallerComponent = newInstantAppInstallerComponent; 2875 } 2876 2877 private static File preparePackageParserCache(boolean isUpgrade) { 2878 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2879 return null; 2880 } 2881 2882 // Disable package parsing on eng builds to allow for faster incremental development. 2883 if ("eng".equals(Build.TYPE)) { 2884 return null; 2885 } 2886 2887 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2888 Slog.i(TAG, "Disabling package parser cache due to system property."); 2889 return null; 2890 } 2891 2892 // The base directory for the package parser cache lives under /data/system/. 2893 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2894 "package_cache"); 2895 if (cacheBaseDir == null) { 2896 return null; 2897 } 2898 2899 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2900 // This also serves to "GC" unused entries when the package cache version changes (which 2901 // can only happen during upgrades). 2902 if (isUpgrade) { 2903 FileUtils.deleteContents(cacheBaseDir); 2904 } 2905 2906 2907 // Return the versioned package cache directory. This is something like 2908 // "/data/system/package_cache/1" 2909 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2910 2911 // The following is a workaround to aid development on non-numbered userdebug 2912 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2913 // the system partition is newer. 2914 // 2915 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2916 // that starts with "eng." to signify that this is an engineering build and not 2917 // destined for release. 2918 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2919 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2920 2921 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2922 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2923 // in general and should not be used for production changes. In this specific case, 2924 // we know that they will work. 2925 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2926 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2927 FileUtils.deleteContents(cacheBaseDir); 2928 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2929 } 2930 } 2931 2932 return cacheDir; 2933 } 2934 2935 @Override 2936 public boolean isFirstBoot() { 2937 return mFirstBoot; 2938 } 2939 2940 @Override 2941 public boolean isOnlyCoreApps() { 2942 return mOnlyCore; 2943 } 2944 2945 @Override 2946 public boolean isUpgrade() { 2947 return mIsUpgrade; 2948 } 2949 2950 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2951 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2952 2953 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2954 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2955 UserHandle.USER_SYSTEM); 2956 if (matches.size() == 1) { 2957 return matches.get(0).getComponentInfo().packageName; 2958 } else if (matches.size() == 0) { 2959 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2960 return null; 2961 } 2962 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2963 } 2964 2965 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2966 synchronized (mPackages) { 2967 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2968 if (libraryEntry == null) { 2969 throw new IllegalStateException("Missing required shared library:" + name); 2970 } 2971 return libraryEntry.apk; 2972 } 2973 } 2974 2975 private @NonNull String getRequiredInstallerLPr() { 2976 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2977 intent.addCategory(Intent.CATEGORY_DEFAULT); 2978 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2979 2980 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2981 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2982 UserHandle.USER_SYSTEM); 2983 if (matches.size() == 1) { 2984 ResolveInfo resolveInfo = matches.get(0); 2985 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2986 throw new RuntimeException("The installer must be a privileged app"); 2987 } 2988 return matches.get(0).getComponentInfo().packageName; 2989 } else { 2990 throw new RuntimeException("There must be exactly one installer; found " + matches); 2991 } 2992 } 2993 2994 private @NonNull String getRequiredUninstallerLPr() { 2995 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2996 intent.addCategory(Intent.CATEGORY_DEFAULT); 2997 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2998 2999 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3000 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3001 UserHandle.USER_SYSTEM); 3002 if (resolveInfo == null || 3003 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3004 throw new RuntimeException("There must be exactly one uninstaller; found " 3005 + resolveInfo); 3006 } 3007 return resolveInfo.getComponentInfo().packageName; 3008 } 3009 3010 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3011 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3012 3013 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3014 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3015 UserHandle.USER_SYSTEM); 3016 ResolveInfo best = null; 3017 final int N = matches.size(); 3018 for (int i = 0; i < N; i++) { 3019 final ResolveInfo cur = matches.get(i); 3020 final String packageName = cur.getComponentInfo().packageName; 3021 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3022 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3023 continue; 3024 } 3025 3026 if (best == null || cur.priority > best.priority) { 3027 best = cur; 3028 } 3029 } 3030 3031 if (best != null) { 3032 return best.getComponentInfo().getComponentName(); 3033 } else { 3034 throw new RuntimeException("There must be at least one intent filter verifier"); 3035 } 3036 } 3037 3038 private @Nullable ComponentName getEphemeralResolverLPr() { 3039 final String[] packageArray = 3040 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3041 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3042 if (DEBUG_EPHEMERAL) { 3043 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3044 } 3045 return null; 3046 } 3047 3048 final int callingUid = Binder.getCallingUid(); 3049 final int resolveFlags = 3050 MATCH_DIRECT_BOOT_AWARE 3051 | MATCH_DIRECT_BOOT_UNAWARE 3052 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3053 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3054 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3055 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3056 3057 final int N = resolvers.size(); 3058 if (N == 0) { 3059 if (DEBUG_EPHEMERAL) { 3060 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3061 } 3062 return null; 3063 } 3064 3065 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3066 for (int i = 0; i < N; i++) { 3067 final ResolveInfo info = resolvers.get(i); 3068 3069 if (info.serviceInfo == null) { 3070 continue; 3071 } 3072 3073 final String packageName = info.serviceInfo.packageName; 3074 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3075 if (DEBUG_EPHEMERAL) { 3076 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3077 + " pkg: " + packageName + ", info:" + info); 3078 } 3079 continue; 3080 } 3081 3082 if (DEBUG_EPHEMERAL) { 3083 Slog.v(TAG, "Ephemeral resolver found;" 3084 + " pkg: " + packageName + ", info:" + info); 3085 } 3086 return new ComponentName(packageName, info.serviceInfo.name); 3087 } 3088 if (DEBUG_EPHEMERAL) { 3089 Slog.v(TAG, "Ephemeral resolver NOT found"); 3090 } 3091 return null; 3092 } 3093 3094 private @Nullable ActivityInfo getEphemeralInstallerLPr() { 3095 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3096 intent.addCategory(Intent.CATEGORY_DEFAULT); 3097 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3098 3099 final int resolveFlags = 3100 MATCH_DIRECT_BOOT_AWARE 3101 | MATCH_DIRECT_BOOT_UNAWARE 3102 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3103 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3104 resolveFlags, UserHandle.USER_SYSTEM); 3105 Iterator<ResolveInfo> iter = matches.iterator(); 3106 while (iter.hasNext()) { 3107 final ResolveInfo rInfo = iter.next(); 3108 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3109 if (ps != null) { 3110 final PermissionsState permissionsState = ps.getPermissionsState(); 3111 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3112 continue; 3113 } 3114 } 3115 iter.remove(); 3116 } 3117 if (matches.size() == 0) { 3118 return null; 3119 } else if (matches.size() == 1) { 3120 return (ActivityInfo) matches.get(0).getComponentInfo(); 3121 } else { 3122 throw new RuntimeException( 3123 "There must be at most one ephemeral installer; found " + matches); 3124 } 3125 } 3126 3127 private @Nullable ComponentName getEphemeralResolverSettingsLPr() { 3128 final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3129 intent.addCategory(Intent.CATEGORY_DEFAULT); 3130 final int resolveFlags = 3131 MATCH_DIRECT_BOOT_AWARE 3132 | MATCH_DIRECT_BOOT_UNAWARE 3133 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3134 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 3135 resolveFlags, UserHandle.USER_SYSTEM); 3136 Iterator<ResolveInfo> iter = matches.iterator(); 3137 while (iter.hasNext()) { 3138 final ResolveInfo rInfo = iter.next(); 3139 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3140 if (ps != null) { 3141 final PermissionsState permissionsState = ps.getPermissionsState(); 3142 if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) { 3143 continue; 3144 } 3145 } 3146 iter.remove(); 3147 } 3148 if (matches.size() == 0) { 3149 return null; 3150 } else if (matches.size() == 1) { 3151 return matches.get(0).getComponentInfo().getComponentName(); 3152 } else { 3153 throw new RuntimeException( 3154 "There must be at most one ephemeral resolver settings; found " + matches); 3155 } 3156 } 3157 3158 private void primeDomainVerificationsLPw(int userId) { 3159 if (DEBUG_DOMAIN_VERIFICATION) { 3160 Slog.d(TAG, "Priming domain verifications in user " + userId); 3161 } 3162 3163 SystemConfig systemConfig = SystemConfig.getInstance(); 3164 ArraySet<String> packages = systemConfig.getLinkedApps(); 3165 3166 for (String packageName : packages) { 3167 PackageParser.Package pkg = mPackages.get(packageName); 3168 if (pkg != null) { 3169 if (!pkg.isSystemApp()) { 3170 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3171 continue; 3172 } 3173 3174 ArraySet<String> domains = null; 3175 for (PackageParser.Activity a : pkg.activities) { 3176 for (ActivityIntentInfo filter : a.intents) { 3177 if (hasValidDomains(filter)) { 3178 if (domains == null) { 3179 domains = new ArraySet<String>(); 3180 } 3181 domains.addAll(filter.getHostsList()); 3182 } 3183 } 3184 } 3185 3186 if (domains != null && domains.size() > 0) { 3187 if (DEBUG_DOMAIN_VERIFICATION) { 3188 Slog.v(TAG, " + " + packageName); 3189 } 3190 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3191 // state w.r.t. the formal app-linkage "no verification attempted" state; 3192 // and then 'always' in the per-user state actually used for intent resolution. 3193 final IntentFilterVerificationInfo ivi; 3194 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3195 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3196 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3197 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3198 } else { 3199 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3200 + "' does not handle web links"); 3201 } 3202 } else { 3203 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3204 } 3205 } 3206 3207 scheduleWritePackageRestrictionsLocked(userId); 3208 scheduleWriteSettingsLocked(); 3209 } 3210 3211 private void applyFactoryDefaultBrowserLPw(int userId) { 3212 // The default browser app's package name is stored in a string resource, 3213 // with a product-specific overlay used for vendor customization. 3214 String browserPkg = mContext.getResources().getString( 3215 com.android.internal.R.string.default_browser); 3216 if (!TextUtils.isEmpty(browserPkg)) { 3217 // non-empty string => required to be a known package 3218 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3219 if (ps == null) { 3220 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3221 browserPkg = null; 3222 } else { 3223 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3224 } 3225 } 3226 3227 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3228 // default. If there's more than one, just leave everything alone. 3229 if (browserPkg == null) { 3230 calculateDefaultBrowserLPw(userId); 3231 } 3232 } 3233 3234 private void calculateDefaultBrowserLPw(int userId) { 3235 List<String> allBrowsers = resolveAllBrowserApps(userId); 3236 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3237 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3238 } 3239 3240 private List<String> resolveAllBrowserApps(int userId) { 3241 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3242 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3243 PackageManager.MATCH_ALL, userId); 3244 3245 final int count = list.size(); 3246 List<String> result = new ArrayList<String>(count); 3247 for (int i=0; i<count; i++) { 3248 ResolveInfo info = list.get(i); 3249 if (info.activityInfo == null 3250 || !info.handleAllWebDataURI 3251 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3252 || result.contains(info.activityInfo.packageName)) { 3253 continue; 3254 } 3255 result.add(info.activityInfo.packageName); 3256 } 3257 3258 return result; 3259 } 3260 3261 private boolean packageIsBrowser(String packageName, int userId) { 3262 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3263 PackageManager.MATCH_ALL, userId); 3264 final int N = list.size(); 3265 for (int i = 0; i < N; i++) { 3266 ResolveInfo info = list.get(i); 3267 if (packageName.equals(info.activityInfo.packageName)) { 3268 return true; 3269 } 3270 } 3271 return false; 3272 } 3273 3274 private void checkDefaultBrowser() { 3275 final int myUserId = UserHandle.myUserId(); 3276 final String packageName = getDefaultBrowserPackageName(myUserId); 3277 if (packageName != null) { 3278 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3279 if (info == null) { 3280 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3281 synchronized (mPackages) { 3282 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3283 } 3284 } 3285 } 3286 } 3287 3288 @Override 3289 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3290 throws RemoteException { 3291 try { 3292 return super.onTransact(code, data, reply, flags); 3293 } catch (RuntimeException e) { 3294 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3295 Slog.wtf(TAG, "Package Manager Crash", e); 3296 } 3297 throw e; 3298 } 3299 } 3300 3301 static int[] appendInts(int[] cur, int[] add) { 3302 if (add == null) return cur; 3303 if (cur == null) return add; 3304 final int N = add.length; 3305 for (int i=0; i<N; i++) { 3306 cur = appendInt(cur, add[i]); 3307 } 3308 return cur; 3309 } 3310 3311 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3312 if (!sUserManager.exists(userId)) return null; 3313 if (ps == null) { 3314 return null; 3315 } 3316 final PackageParser.Package p = ps.pkg; 3317 if (p == null) { 3318 return null; 3319 } 3320 // Filter out ephemeral app metadata: 3321 // * The system/shell/root can see metadata for any app 3322 // * An installed app can see metadata for 1) other installed apps 3323 // and 2) ephemeral apps that have explicitly interacted with it 3324 // * Ephemeral apps can only see their own data and exposed installed apps 3325 // * Holding a signature permission allows seeing instant apps 3326 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3327 if (callingAppId != Process.SYSTEM_UID 3328 && callingAppId != Process.SHELL_UID 3329 && callingAppId != Process.ROOT_UID 3330 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3331 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3332 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3333 if (instantAppPackageName != null) { 3334 // ephemeral apps can only get information on themselves or 3335 // installed apps that are exposed. 3336 if (!instantAppPackageName.equals(p.packageName) 3337 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3338 return null; 3339 } 3340 } else { 3341 if (ps.getInstantApp(userId)) { 3342 // only get access to the ephemeral app if we've been granted access 3343 if (!mInstantAppRegistry.isInstantAccessGranted( 3344 userId, callingAppId, ps.appId)) { 3345 return null; 3346 } 3347 } 3348 } 3349 } 3350 3351 final PermissionsState permissionsState = ps.getPermissionsState(); 3352 3353 // Compute GIDs only if requested 3354 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3355 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3356 // Compute granted permissions only if package has requested permissions 3357 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3358 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3359 final PackageUserState state = ps.readUserState(userId); 3360 3361 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3362 && ps.isSystem()) { 3363 flags |= MATCH_ANY_USER; 3364 } 3365 3366 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3367 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3368 3369 if (packageInfo == null) { 3370 return null; 3371 } 3372 3373 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3374 3375 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3376 resolveExternalPackageNameLPr(p); 3377 3378 return packageInfo; 3379 } 3380 3381 @Override 3382 public void checkPackageStartable(String packageName, int userId) { 3383 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3384 3385 synchronized (mPackages) { 3386 final PackageSetting ps = mSettings.mPackages.get(packageName); 3387 if (ps == null) { 3388 throw new SecurityException("Package " + packageName + " was not found!"); 3389 } 3390 3391 if (!ps.getInstalled(userId)) { 3392 throw new SecurityException( 3393 "Package " + packageName + " was not installed for user " + userId + "!"); 3394 } 3395 3396 if (mSafeMode && !ps.isSystem()) { 3397 throw new SecurityException("Package " + packageName + " not a system app!"); 3398 } 3399 3400 if (mFrozenPackages.contains(packageName)) { 3401 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3402 } 3403 3404 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3405 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3406 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3407 } 3408 } 3409 } 3410 3411 @Override 3412 public boolean isPackageAvailable(String packageName, int userId) { 3413 if (!sUserManager.exists(userId)) return false; 3414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3415 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3416 synchronized (mPackages) { 3417 PackageParser.Package p = mPackages.get(packageName); 3418 if (p != null) { 3419 final PackageSetting ps = (PackageSetting) p.mExtras; 3420 if (ps != null) { 3421 final PackageUserState state = ps.readUserState(userId); 3422 if (state != null) { 3423 return PackageParser.isAvailable(state); 3424 } 3425 } 3426 } 3427 } 3428 return false; 3429 } 3430 3431 @Override 3432 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3433 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3434 flags, userId); 3435 } 3436 3437 @Override 3438 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3439 int flags, int userId) { 3440 return getPackageInfoInternal(versionedPackage.getPackageName(), 3441 // TODO: We will change version code to long, so in the new API it is long 3442 (int) versionedPackage.getVersionCode(), flags, userId); 3443 } 3444 3445 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3446 int flags, int userId) { 3447 if (!sUserManager.exists(userId)) return null; 3448 flags = updateFlagsForPackage(flags, userId, packageName); 3449 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3450 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3451 3452 // reader 3453 synchronized (mPackages) { 3454 // Normalize package name to handle renamed packages and static libs 3455 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3456 3457 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3458 if (matchFactoryOnly) { 3459 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3460 if (ps != null) { 3461 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3462 return null; 3463 } 3464 return generatePackageInfo(ps, flags, userId); 3465 } 3466 } 3467 3468 PackageParser.Package p = mPackages.get(packageName); 3469 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3470 return null; 3471 } 3472 if (DEBUG_PACKAGE_INFO) 3473 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3474 if (p != null) { 3475 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3476 Binder.getCallingUid(), userId)) { 3477 return null; 3478 } 3479 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3480 } 3481 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3482 final PackageSetting ps = mSettings.mPackages.get(packageName); 3483 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3484 return null; 3485 } 3486 return generatePackageInfo(ps, flags, userId); 3487 } 3488 } 3489 return null; 3490 } 3491 3492 3493 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3494 // System/shell/root get to see all static libs 3495 final int appId = UserHandle.getAppId(uid); 3496 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3497 || appId == Process.ROOT_UID) { 3498 return false; 3499 } 3500 3501 // No package means no static lib as it is always on internal storage 3502 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3503 return false; 3504 } 3505 3506 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3507 ps.pkg.staticSharedLibVersion); 3508 if (libEntry == null) { 3509 return false; 3510 } 3511 3512 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3513 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3514 if (uidPackageNames == null) { 3515 return true; 3516 } 3517 3518 for (String uidPackageName : uidPackageNames) { 3519 if (ps.name.equals(uidPackageName)) { 3520 return false; 3521 } 3522 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3523 if (uidPs != null) { 3524 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3525 libEntry.info.getName()); 3526 if (index < 0) { 3527 continue; 3528 } 3529 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3530 return false; 3531 } 3532 } 3533 } 3534 return true; 3535 } 3536 3537 @Override 3538 public String[] currentToCanonicalPackageNames(String[] names) { 3539 String[] out = new String[names.length]; 3540 // reader 3541 synchronized (mPackages) { 3542 for (int i=names.length-1; i>=0; i--) { 3543 PackageSetting ps = mSettings.mPackages.get(names[i]); 3544 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3545 } 3546 } 3547 return out; 3548 } 3549 3550 @Override 3551 public String[] canonicalToCurrentPackageNames(String[] names) { 3552 String[] out = new String[names.length]; 3553 // reader 3554 synchronized (mPackages) { 3555 for (int i=names.length-1; i>=0; i--) { 3556 String cur = mSettings.getRenamedPackageLPr(names[i]); 3557 out[i] = cur != null ? cur : names[i]; 3558 } 3559 } 3560 return out; 3561 } 3562 3563 @Override 3564 public int getPackageUid(String packageName, int flags, int userId) { 3565 if (!sUserManager.exists(userId)) return -1; 3566 flags = updateFlagsForPackage(flags, userId, packageName); 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3568 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3569 3570 // reader 3571 synchronized (mPackages) { 3572 final PackageParser.Package p = mPackages.get(packageName); 3573 if (p != null && p.isMatch(flags)) { 3574 return UserHandle.getUid(userId, p.applicationInfo.uid); 3575 } 3576 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3577 final PackageSetting ps = mSettings.mPackages.get(packageName); 3578 if (ps != null && ps.isMatch(flags)) { 3579 return UserHandle.getUid(userId, ps.appId); 3580 } 3581 } 3582 } 3583 3584 return -1; 3585 } 3586 3587 @Override 3588 public int[] getPackageGids(String packageName, int flags, int userId) { 3589 if (!sUserManager.exists(userId)) return null; 3590 flags = updateFlagsForPackage(flags, userId, packageName); 3591 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3592 false /* requireFullPermission */, false /* checkShell */, 3593 "getPackageGids"); 3594 3595 // reader 3596 synchronized (mPackages) { 3597 final PackageParser.Package p = mPackages.get(packageName); 3598 if (p != null && p.isMatch(flags)) { 3599 PackageSetting ps = (PackageSetting) p.mExtras; 3600 // TODO: Shouldn't this be checking for package installed state for userId and 3601 // return null? 3602 return ps.getPermissionsState().computeGids(userId); 3603 } 3604 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3605 final PackageSetting ps = mSettings.mPackages.get(packageName); 3606 if (ps != null && ps.isMatch(flags)) { 3607 return ps.getPermissionsState().computeGids(userId); 3608 } 3609 } 3610 } 3611 3612 return null; 3613 } 3614 3615 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3616 if (bp.perm != null) { 3617 return PackageParser.generatePermissionInfo(bp.perm, flags); 3618 } 3619 PermissionInfo pi = new PermissionInfo(); 3620 pi.name = bp.name; 3621 pi.packageName = bp.sourcePackage; 3622 pi.nonLocalizedLabel = bp.name; 3623 pi.protectionLevel = bp.protectionLevel; 3624 return pi; 3625 } 3626 3627 @Override 3628 public PermissionInfo getPermissionInfo(String name, int flags) { 3629 // reader 3630 synchronized (mPackages) { 3631 final BasePermission p = mSettings.mPermissions.get(name); 3632 if (p != null) { 3633 return generatePermissionInfo(p, flags); 3634 } 3635 return null; 3636 } 3637 } 3638 3639 @Override 3640 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3641 int flags) { 3642 // reader 3643 synchronized (mPackages) { 3644 if (group != null && !mPermissionGroups.containsKey(group)) { 3645 // This is thrown as NameNotFoundException 3646 return null; 3647 } 3648 3649 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3650 for (BasePermission p : mSettings.mPermissions.values()) { 3651 if (group == null) { 3652 if (p.perm == null || p.perm.info.group == null) { 3653 out.add(generatePermissionInfo(p, flags)); 3654 } 3655 } else { 3656 if (p.perm != null && group.equals(p.perm.info.group)) { 3657 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3658 } 3659 } 3660 } 3661 return new ParceledListSlice<>(out); 3662 } 3663 } 3664 3665 @Override 3666 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3667 // reader 3668 synchronized (mPackages) { 3669 return PackageParser.generatePermissionGroupInfo( 3670 mPermissionGroups.get(name), flags); 3671 } 3672 } 3673 3674 @Override 3675 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3676 // reader 3677 synchronized (mPackages) { 3678 final int N = mPermissionGroups.size(); 3679 ArrayList<PermissionGroupInfo> out 3680 = new ArrayList<PermissionGroupInfo>(N); 3681 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3682 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3683 } 3684 return new ParceledListSlice<>(out); 3685 } 3686 } 3687 3688 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3689 int uid, int userId) { 3690 if (!sUserManager.exists(userId)) return null; 3691 PackageSetting ps = mSettings.mPackages.get(packageName); 3692 if (ps != null) { 3693 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3694 return null; 3695 } 3696 if (ps.pkg == null) { 3697 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3698 if (pInfo != null) { 3699 return pInfo.applicationInfo; 3700 } 3701 return null; 3702 } 3703 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3704 ps.readUserState(userId), userId); 3705 if (ai != null) { 3706 rebaseEnabledOverlays(ai, userId); 3707 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3708 } 3709 return ai; 3710 } 3711 return null; 3712 } 3713 3714 @Override 3715 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3716 if (!sUserManager.exists(userId)) return null; 3717 flags = updateFlagsForApplication(flags, userId, packageName); 3718 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3719 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3720 3721 // writer 3722 synchronized (mPackages) { 3723 // Normalize package name to handle renamed packages and static libs 3724 packageName = resolveInternalPackageNameLPr(packageName, 3725 PackageManager.VERSION_CODE_HIGHEST); 3726 3727 PackageParser.Package p = mPackages.get(packageName); 3728 if (DEBUG_PACKAGE_INFO) Log.v( 3729 TAG, "getApplicationInfo " + packageName 3730 + ": " + p); 3731 if (p != null) { 3732 PackageSetting ps = mSettings.mPackages.get(packageName); 3733 if (ps == null) return null; 3734 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3735 return null; 3736 } 3737 // Note: isEnabledLP() does not apply here - always return info 3738 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3739 p, flags, ps.readUserState(userId), userId); 3740 if (ai != null) { 3741 rebaseEnabledOverlays(ai, userId); 3742 ai.packageName = resolveExternalPackageNameLPr(p); 3743 } 3744 return ai; 3745 } 3746 if ("android".equals(packageName)||"system".equals(packageName)) { 3747 return mAndroidApplication; 3748 } 3749 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3750 // Already generates the external package name 3751 return generateApplicationInfoFromSettingsLPw(packageName, 3752 Binder.getCallingUid(), flags, userId); 3753 } 3754 } 3755 return null; 3756 } 3757 3758 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3759 List<String> paths = new ArrayList<>(); 3760 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3761 mEnabledOverlayPaths.get(userId); 3762 if (userSpecificOverlays != null) { 3763 if (!"android".equals(ai.packageName)) { 3764 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3765 if (frameworkOverlays != null) { 3766 paths.addAll(frameworkOverlays); 3767 } 3768 } 3769 3770 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3771 if (appOverlays != null) { 3772 paths.addAll(appOverlays); 3773 } 3774 } 3775 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3776 } 3777 3778 private String normalizePackageNameLPr(String packageName) { 3779 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3780 return normalizedPackageName != null ? normalizedPackageName : packageName; 3781 } 3782 3783 @Override 3784 public void deletePreloadsFileCache() { 3785 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3786 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3787 } 3788 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3789 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3790 FileUtils.deleteContents(dir); 3791 } 3792 3793 @Override 3794 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3795 final IPackageDataObserver observer) { 3796 mContext.enforceCallingOrSelfPermission( 3797 android.Manifest.permission.CLEAR_APP_CACHE, null); 3798 mHandler.post(() -> { 3799 boolean success = false; 3800 try { 3801 freeStorage(volumeUuid, freeStorageSize, 0); 3802 success = true; 3803 } catch (IOException e) { 3804 Slog.w(TAG, e); 3805 } 3806 if (observer != null) { 3807 try { 3808 observer.onRemoveCompleted(null, success); 3809 } catch (RemoteException e) { 3810 Slog.w(TAG, e); 3811 } 3812 } 3813 }); 3814 } 3815 3816 @Override 3817 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3818 final IntentSender pi) { 3819 mContext.enforceCallingOrSelfPermission( 3820 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3821 mHandler.post(() -> { 3822 boolean success = false; 3823 try { 3824 freeStorage(volumeUuid, freeStorageSize, 0); 3825 success = true; 3826 } catch (IOException e) { 3827 Slog.w(TAG, e); 3828 } 3829 if (pi != null) { 3830 try { 3831 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3832 } catch (SendIntentException e) { 3833 Slog.w(TAG, e); 3834 } 3835 } 3836 }); 3837 } 3838 3839 /** 3840 * Blocking call to clear various types of cached data across the system 3841 * until the requested bytes are available. 3842 */ 3843 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3844 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3845 final File file = storage.findPathForUuid(volumeUuid); 3846 if (file.getUsableSpace() >= bytes) return; 3847 3848 if (ENABLE_FREE_CACHE_V2) { 3849 final boolean aggressive = (storageFlags 3850 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3851 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3852 volumeUuid); 3853 3854 // 1. Pre-flight to determine if we have any chance to succeed 3855 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3856 if (internalVolume && (aggressive || SystemProperties 3857 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3858 deletePreloadsFileCache(); 3859 if (file.getUsableSpace() >= bytes) return; 3860 } 3861 3862 // 3. Consider parsed APK data (aggressive only) 3863 if (internalVolume && aggressive) { 3864 FileUtils.deleteContents(mCacheDir); 3865 if (file.getUsableSpace() >= bytes) return; 3866 } 3867 3868 // 4. Consider cached app data (above quotas) 3869 try { 3870 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3871 } catch (InstallerException ignored) { 3872 } 3873 if (file.getUsableSpace() >= bytes) return; 3874 3875 // 5. Consider shared libraries with refcount=0 and age>2h 3876 // 6. Consider dexopt output (aggressive only) 3877 // 7. Consider ephemeral apps not used in last week 3878 3879 // 8. Consider cached app data (below quotas) 3880 try { 3881 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3882 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3883 } catch (InstallerException ignored) { 3884 } 3885 if (file.getUsableSpace() >= bytes) return; 3886 3887 // 9. Consider DropBox entries 3888 // 10. Consider ephemeral cookies 3889 3890 } else { 3891 try { 3892 mInstaller.freeCache(volumeUuid, bytes, 0); 3893 } catch (InstallerException ignored) { 3894 } 3895 if (file.getUsableSpace() >= bytes) return; 3896 } 3897 3898 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3899 } 3900 3901 /** 3902 * Update given flags based on encryption status of current user. 3903 */ 3904 private int updateFlags(int flags, int userId) { 3905 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3906 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3907 // Caller expressed an explicit opinion about what encryption 3908 // aware/unaware components they want to see, so fall through and 3909 // give them what they want 3910 } else { 3911 // Caller expressed no opinion, so match based on user state 3912 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3913 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3914 } else { 3915 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3916 } 3917 } 3918 return flags; 3919 } 3920 3921 private UserManagerInternal getUserManagerInternal() { 3922 if (mUserManagerInternal == null) { 3923 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3924 } 3925 return mUserManagerInternal; 3926 } 3927 3928 private DeviceIdleController.LocalService getDeviceIdleController() { 3929 if (mDeviceIdleController == null) { 3930 mDeviceIdleController = 3931 LocalServices.getService(DeviceIdleController.LocalService.class); 3932 } 3933 return mDeviceIdleController; 3934 } 3935 3936 /** 3937 * Update given flags when being used to request {@link PackageInfo}. 3938 */ 3939 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3940 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3941 boolean triaged = true; 3942 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3943 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3944 // Caller is asking for component details, so they'd better be 3945 // asking for specific encryption matching behavior, or be triaged 3946 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3947 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3948 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3949 triaged = false; 3950 } 3951 } 3952 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3953 | PackageManager.MATCH_SYSTEM_ONLY 3954 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3955 triaged = false; 3956 } 3957 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3958 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3959 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3960 + Debug.getCallers(5)); 3961 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3962 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3963 // If the caller wants all packages and has a restricted profile associated with it, 3964 // then match all users. This is to make sure that launchers that need to access work 3965 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3966 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3967 flags |= PackageManager.MATCH_ANY_USER; 3968 } 3969 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3970 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3971 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3972 } 3973 return updateFlags(flags, userId); 3974 } 3975 3976 /** 3977 * Update given flags when being used to request {@link ApplicationInfo}. 3978 */ 3979 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3980 return updateFlagsForPackage(flags, userId, cookie); 3981 } 3982 3983 /** 3984 * Update given flags when being used to request {@link ComponentInfo}. 3985 */ 3986 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3987 if (cookie instanceof Intent) { 3988 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3989 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3990 } 3991 } 3992 3993 boolean triaged = true; 3994 // Caller is asking for component details, so they'd better be 3995 // asking for specific encryption matching behavior, or be triaged 3996 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3997 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3998 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3999 triaged = false; 4000 } 4001 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4002 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4003 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4004 } 4005 4006 return updateFlags(flags, userId); 4007 } 4008 4009 /** 4010 * Update given intent when being used to request {@link ResolveInfo}. 4011 */ 4012 private Intent updateIntentForResolve(Intent intent) { 4013 if (intent.getSelector() != null) { 4014 intent = intent.getSelector(); 4015 } 4016 if (DEBUG_PREFERRED) { 4017 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4018 } 4019 return intent; 4020 } 4021 4022 /** 4023 * Update given flags when being used to request {@link ResolveInfo}. 4024 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4025 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4026 * flag set. However, this flag is only honoured in three circumstances: 4027 * <ul> 4028 * <li>when called from a system process</li> 4029 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4030 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4031 * action and a {@code android.intent.category.BROWSABLE} category</li> 4032 * </ul> 4033 */ 4034 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4035 boolean includeInstantApps) { 4036 // Safe mode means we shouldn't match any third-party components 4037 if (mSafeMode) { 4038 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4039 } 4040 if (getInstantAppPackageName(callingUid) != null) { 4041 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4042 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4043 flags |= PackageManager.MATCH_INSTANT; 4044 } else { 4045 // Otherwise, prevent leaking ephemeral components 4046 final boolean isSpecialProcess = 4047 callingUid == Process.SYSTEM_UID 4048 || callingUid == Process.SHELL_UID 4049 || callingUid == 0; 4050 final boolean allowMatchInstant = 4051 (includeInstantApps 4052 && Intent.ACTION_VIEW.equals(intent.getAction()) 4053 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4054 && hasWebURI(intent)) 4055 || isSpecialProcess 4056 || mContext.checkCallingOrSelfPermission( 4057 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4058 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4059 if (!allowMatchInstant) { 4060 flags &= ~PackageManager.MATCH_INSTANT; 4061 } 4062 } 4063 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4064 } 4065 4066 @Override 4067 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4068 if (!sUserManager.exists(userId)) return null; 4069 flags = updateFlagsForComponent(flags, userId, component); 4070 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4071 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4072 synchronized (mPackages) { 4073 PackageParser.Activity a = mActivities.mActivities.get(component); 4074 4075 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4076 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4077 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4078 if (ps == null) return null; 4079 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4080 userId); 4081 } 4082 if (mResolveComponentName.equals(component)) { 4083 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4084 new PackageUserState(), userId); 4085 } 4086 } 4087 return null; 4088 } 4089 4090 @Override 4091 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4092 String resolvedType) { 4093 synchronized (mPackages) { 4094 if (component.equals(mResolveComponentName)) { 4095 // The resolver supports EVERYTHING! 4096 return true; 4097 } 4098 PackageParser.Activity a = mActivities.mActivities.get(component); 4099 if (a == null) { 4100 return false; 4101 } 4102 for (int i=0; i<a.intents.size(); i++) { 4103 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4104 intent.getData(), intent.getCategories(), TAG) >= 0) { 4105 return true; 4106 } 4107 } 4108 return false; 4109 } 4110 } 4111 4112 @Override 4113 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4114 if (!sUserManager.exists(userId)) return null; 4115 flags = updateFlagsForComponent(flags, userId, component); 4116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4117 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4118 synchronized (mPackages) { 4119 PackageParser.Activity a = mReceivers.mActivities.get(component); 4120 if (DEBUG_PACKAGE_INFO) Log.v( 4121 TAG, "getReceiverInfo " + component + ": " + a); 4122 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4123 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4124 if (ps == null) return null; 4125 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4126 ps.readUserState(userId), userId); 4127 if (ri != null) { 4128 rebaseEnabledOverlays(ri.applicationInfo, userId); 4129 } 4130 return ri; 4131 } 4132 } 4133 return null; 4134 } 4135 4136 @Override 4137 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4138 if (!sUserManager.exists(userId)) return null; 4139 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4140 4141 flags = updateFlagsForPackage(flags, userId, null); 4142 4143 final boolean canSeeStaticLibraries = 4144 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4145 == PERMISSION_GRANTED 4146 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4147 == PERMISSION_GRANTED 4148 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4149 == PERMISSION_GRANTED 4150 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4151 == PERMISSION_GRANTED; 4152 4153 synchronized (mPackages) { 4154 List<SharedLibraryInfo> result = null; 4155 4156 final int libCount = mSharedLibraries.size(); 4157 for (int i = 0; i < libCount; i++) { 4158 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4159 if (versionedLib == null) { 4160 continue; 4161 } 4162 4163 final int versionCount = versionedLib.size(); 4164 for (int j = 0; j < versionCount; j++) { 4165 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4166 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4167 break; 4168 } 4169 final long identity = Binder.clearCallingIdentity(); 4170 try { 4171 // TODO: We will change version code to long, so in the new API it is long 4172 PackageInfo packageInfo = getPackageInfoVersioned( 4173 libInfo.getDeclaringPackage(), flags, userId); 4174 if (packageInfo == null) { 4175 continue; 4176 } 4177 } finally { 4178 Binder.restoreCallingIdentity(identity); 4179 } 4180 4181 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4182 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4183 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4184 4185 if (result == null) { 4186 result = new ArrayList<>(); 4187 } 4188 result.add(resLibInfo); 4189 } 4190 } 4191 4192 return result != null ? new ParceledListSlice<>(result) : null; 4193 } 4194 } 4195 4196 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4197 SharedLibraryInfo libInfo, int flags, int userId) { 4198 List<VersionedPackage> versionedPackages = null; 4199 final int packageCount = mSettings.mPackages.size(); 4200 for (int i = 0; i < packageCount; i++) { 4201 PackageSetting ps = mSettings.mPackages.valueAt(i); 4202 4203 if (ps == null) { 4204 continue; 4205 } 4206 4207 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4208 continue; 4209 } 4210 4211 final String libName = libInfo.getName(); 4212 if (libInfo.isStatic()) { 4213 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4214 if (libIdx < 0) { 4215 continue; 4216 } 4217 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4218 continue; 4219 } 4220 if (versionedPackages == null) { 4221 versionedPackages = new ArrayList<>(); 4222 } 4223 // If the dependent is a static shared lib, use the public package name 4224 String dependentPackageName = ps.name; 4225 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4226 dependentPackageName = ps.pkg.manifestPackageName; 4227 } 4228 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4229 } else if (ps.pkg != null) { 4230 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4231 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4232 if (versionedPackages == null) { 4233 versionedPackages = new ArrayList<>(); 4234 } 4235 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4236 } 4237 } 4238 } 4239 4240 return versionedPackages; 4241 } 4242 4243 @Override 4244 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4245 if (!sUserManager.exists(userId)) return null; 4246 flags = updateFlagsForComponent(flags, userId, component); 4247 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4248 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4249 synchronized (mPackages) { 4250 PackageParser.Service s = mServices.mServices.get(component); 4251 if (DEBUG_PACKAGE_INFO) Log.v( 4252 TAG, "getServiceInfo " + component + ": " + s); 4253 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4254 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4255 if (ps == null) return null; 4256 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4257 ps.readUserState(userId), userId); 4258 if (si != null) { 4259 rebaseEnabledOverlays(si.applicationInfo, userId); 4260 } 4261 return si; 4262 } 4263 } 4264 return null; 4265 } 4266 4267 @Override 4268 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4269 if (!sUserManager.exists(userId)) return null; 4270 flags = updateFlagsForComponent(flags, userId, component); 4271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4272 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4273 synchronized (mPackages) { 4274 PackageParser.Provider p = mProviders.mProviders.get(component); 4275 if (DEBUG_PACKAGE_INFO) Log.v( 4276 TAG, "getProviderInfo " + component + ": " + p); 4277 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4278 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4279 if (ps == null) return null; 4280 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4281 ps.readUserState(userId), userId); 4282 if (pi != null) { 4283 rebaseEnabledOverlays(pi.applicationInfo, userId); 4284 } 4285 return pi; 4286 } 4287 } 4288 return null; 4289 } 4290 4291 @Override 4292 public String[] getSystemSharedLibraryNames() { 4293 synchronized (mPackages) { 4294 Set<String> libs = null; 4295 final int libCount = mSharedLibraries.size(); 4296 for (int i = 0; i < libCount; i++) { 4297 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4298 if (versionedLib == null) { 4299 continue; 4300 } 4301 final int versionCount = versionedLib.size(); 4302 for (int j = 0; j < versionCount; j++) { 4303 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4304 if (!libEntry.info.isStatic()) { 4305 if (libs == null) { 4306 libs = new ArraySet<>(); 4307 } 4308 libs.add(libEntry.info.getName()); 4309 break; 4310 } 4311 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4312 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4313 UserHandle.getUserId(Binder.getCallingUid()))) { 4314 if (libs == null) { 4315 libs = new ArraySet<>(); 4316 } 4317 libs.add(libEntry.info.getName()); 4318 break; 4319 } 4320 } 4321 } 4322 4323 if (libs != null) { 4324 String[] libsArray = new String[libs.size()]; 4325 libs.toArray(libsArray); 4326 return libsArray; 4327 } 4328 4329 return null; 4330 } 4331 } 4332 4333 @Override 4334 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4335 synchronized (mPackages) { 4336 return mServicesSystemSharedLibraryPackageName; 4337 } 4338 } 4339 4340 @Override 4341 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4342 synchronized (mPackages) { 4343 return mSharedSystemSharedLibraryPackageName; 4344 } 4345 } 4346 4347 private void updateSequenceNumberLP(String packageName, int[] userList) { 4348 for (int i = userList.length - 1; i >= 0; --i) { 4349 final int userId = userList[i]; 4350 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4351 if (changedPackages == null) { 4352 changedPackages = new SparseArray<>(); 4353 mChangedPackages.put(userId, changedPackages); 4354 } 4355 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4356 if (sequenceNumbers == null) { 4357 sequenceNumbers = new HashMap<>(); 4358 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4359 } 4360 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4361 if (sequenceNumber != null) { 4362 changedPackages.remove(sequenceNumber); 4363 } 4364 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4365 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4366 } 4367 mChangedPackagesSequenceNumber++; 4368 } 4369 4370 @Override 4371 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4372 synchronized (mPackages) { 4373 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4374 return null; 4375 } 4376 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4377 if (changedPackages == null) { 4378 return null; 4379 } 4380 final List<String> packageNames = 4381 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4382 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4383 final String packageName = changedPackages.get(i); 4384 if (packageName != null) { 4385 packageNames.add(packageName); 4386 } 4387 } 4388 return packageNames.isEmpty() 4389 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4390 } 4391 } 4392 4393 @Override 4394 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4395 ArrayList<FeatureInfo> res; 4396 synchronized (mAvailableFeatures) { 4397 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4398 res.addAll(mAvailableFeatures.values()); 4399 } 4400 final FeatureInfo fi = new FeatureInfo(); 4401 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4402 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4403 res.add(fi); 4404 4405 return new ParceledListSlice<>(res); 4406 } 4407 4408 @Override 4409 public boolean hasSystemFeature(String name, int version) { 4410 synchronized (mAvailableFeatures) { 4411 final FeatureInfo feat = mAvailableFeatures.get(name); 4412 if (feat == null) { 4413 return false; 4414 } else { 4415 return feat.version >= version; 4416 } 4417 } 4418 } 4419 4420 @Override 4421 public int checkPermission(String permName, String pkgName, int userId) { 4422 if (!sUserManager.exists(userId)) { 4423 return PackageManager.PERMISSION_DENIED; 4424 } 4425 4426 synchronized (mPackages) { 4427 final PackageParser.Package p = mPackages.get(pkgName); 4428 if (p != null && p.mExtras != null) { 4429 final PackageSetting ps = (PackageSetting) p.mExtras; 4430 final PermissionsState permissionsState = ps.getPermissionsState(); 4431 if (permissionsState.hasPermission(permName, userId)) { 4432 return PackageManager.PERMISSION_GRANTED; 4433 } 4434 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4435 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4436 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4437 return PackageManager.PERMISSION_GRANTED; 4438 } 4439 } 4440 } 4441 4442 return PackageManager.PERMISSION_DENIED; 4443 } 4444 4445 @Override 4446 public int checkUidPermission(String permName, int uid) { 4447 final int userId = UserHandle.getUserId(uid); 4448 4449 if (!sUserManager.exists(userId)) { 4450 return PackageManager.PERMISSION_DENIED; 4451 } 4452 4453 synchronized (mPackages) { 4454 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4455 if (obj != null) { 4456 final SettingBase ps = (SettingBase) obj; 4457 final PermissionsState permissionsState = ps.getPermissionsState(); 4458 if (permissionsState.hasPermission(permName, userId)) { 4459 return PackageManager.PERMISSION_GRANTED; 4460 } 4461 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4462 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4463 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4464 return PackageManager.PERMISSION_GRANTED; 4465 } 4466 } else { 4467 ArraySet<String> perms = mSystemPermissions.get(uid); 4468 if (perms != null) { 4469 if (perms.contains(permName)) { 4470 return PackageManager.PERMISSION_GRANTED; 4471 } 4472 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4473 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4474 return PackageManager.PERMISSION_GRANTED; 4475 } 4476 } 4477 } 4478 } 4479 4480 return PackageManager.PERMISSION_DENIED; 4481 } 4482 4483 @Override 4484 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4485 if (UserHandle.getCallingUserId() != userId) { 4486 mContext.enforceCallingPermission( 4487 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4488 "isPermissionRevokedByPolicy for user " + userId); 4489 } 4490 4491 if (checkPermission(permission, packageName, userId) 4492 == PackageManager.PERMISSION_GRANTED) { 4493 return false; 4494 } 4495 4496 final long identity = Binder.clearCallingIdentity(); 4497 try { 4498 final int flags = getPermissionFlags(permission, packageName, userId); 4499 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4500 } finally { 4501 Binder.restoreCallingIdentity(identity); 4502 } 4503 } 4504 4505 @Override 4506 public String getPermissionControllerPackageName() { 4507 synchronized (mPackages) { 4508 return mRequiredInstallerPackage; 4509 } 4510 } 4511 4512 /** 4513 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4514 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4515 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4516 * @param message the message to log on security exception 4517 */ 4518 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4519 boolean checkShell, String message) { 4520 if (userId < 0) { 4521 throw new IllegalArgumentException("Invalid userId " + userId); 4522 } 4523 if (checkShell) { 4524 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4525 } 4526 if (userId == UserHandle.getUserId(callingUid)) return; 4527 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4528 if (requireFullPermission) { 4529 mContext.enforceCallingOrSelfPermission( 4530 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4531 } else { 4532 try { 4533 mContext.enforceCallingOrSelfPermission( 4534 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4535 } catch (SecurityException se) { 4536 mContext.enforceCallingOrSelfPermission( 4537 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4538 } 4539 } 4540 } 4541 } 4542 4543 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4544 if (callingUid == Process.SHELL_UID) { 4545 if (userHandle >= 0 4546 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4547 throw new SecurityException("Shell does not have permission to access user " 4548 + userHandle); 4549 } else if (userHandle < 0) { 4550 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4551 + Debug.getCallers(3)); 4552 } 4553 } 4554 } 4555 4556 private BasePermission findPermissionTreeLP(String permName) { 4557 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4558 if (permName.startsWith(bp.name) && 4559 permName.length() > bp.name.length() && 4560 permName.charAt(bp.name.length()) == '.') { 4561 return bp; 4562 } 4563 } 4564 return null; 4565 } 4566 4567 private BasePermission checkPermissionTreeLP(String permName) { 4568 if (permName != null) { 4569 BasePermission bp = findPermissionTreeLP(permName); 4570 if (bp != null) { 4571 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4572 return bp; 4573 } 4574 throw new SecurityException("Calling uid " 4575 + Binder.getCallingUid() 4576 + " is not allowed to add to permission tree " 4577 + bp.name + " owned by uid " + bp.uid); 4578 } 4579 } 4580 throw new SecurityException("No permission tree found for " + permName); 4581 } 4582 4583 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4584 if (s1 == null) { 4585 return s2 == null; 4586 } 4587 if (s2 == null) { 4588 return false; 4589 } 4590 if (s1.getClass() != s2.getClass()) { 4591 return false; 4592 } 4593 return s1.equals(s2); 4594 } 4595 4596 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4597 if (pi1.icon != pi2.icon) return false; 4598 if (pi1.logo != pi2.logo) return false; 4599 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4600 if (!compareStrings(pi1.name, pi2.name)) return false; 4601 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4602 // We'll take care of setting this one. 4603 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4604 // These are not currently stored in settings. 4605 //if (!compareStrings(pi1.group, pi2.group)) return false; 4606 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4607 //if (pi1.labelRes != pi2.labelRes) return false; 4608 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4609 return true; 4610 } 4611 4612 int permissionInfoFootprint(PermissionInfo info) { 4613 int size = info.name.length(); 4614 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4615 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4616 return size; 4617 } 4618 4619 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4620 int size = 0; 4621 for (BasePermission perm : mSettings.mPermissions.values()) { 4622 if (perm.uid == tree.uid) { 4623 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4624 } 4625 } 4626 return size; 4627 } 4628 4629 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4630 // We calculate the max size of permissions defined by this uid and throw 4631 // if that plus the size of 'info' would exceed our stated maximum. 4632 if (tree.uid != Process.SYSTEM_UID) { 4633 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4634 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4635 throw new SecurityException("Permission tree size cap exceeded"); 4636 } 4637 } 4638 } 4639 4640 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4641 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4642 throw new SecurityException("Label must be specified in permission"); 4643 } 4644 BasePermission tree = checkPermissionTreeLP(info.name); 4645 BasePermission bp = mSettings.mPermissions.get(info.name); 4646 boolean added = bp == null; 4647 boolean changed = true; 4648 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4649 if (added) { 4650 enforcePermissionCapLocked(info, tree); 4651 bp = new BasePermission(info.name, tree.sourcePackage, 4652 BasePermission.TYPE_DYNAMIC); 4653 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4654 throw new SecurityException( 4655 "Not allowed to modify non-dynamic permission " 4656 + info.name); 4657 } else { 4658 if (bp.protectionLevel == fixedLevel 4659 && bp.perm.owner.equals(tree.perm.owner) 4660 && bp.uid == tree.uid 4661 && comparePermissionInfos(bp.perm.info, info)) { 4662 changed = false; 4663 } 4664 } 4665 bp.protectionLevel = fixedLevel; 4666 info = new PermissionInfo(info); 4667 info.protectionLevel = fixedLevel; 4668 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4669 bp.perm.info.packageName = tree.perm.info.packageName; 4670 bp.uid = tree.uid; 4671 if (added) { 4672 mSettings.mPermissions.put(info.name, bp); 4673 } 4674 if (changed) { 4675 if (!async) { 4676 mSettings.writeLPr(); 4677 } else { 4678 scheduleWriteSettingsLocked(); 4679 } 4680 } 4681 return added; 4682 } 4683 4684 @Override 4685 public boolean addPermission(PermissionInfo info) { 4686 synchronized (mPackages) { 4687 return addPermissionLocked(info, false); 4688 } 4689 } 4690 4691 @Override 4692 public boolean addPermissionAsync(PermissionInfo info) { 4693 synchronized (mPackages) { 4694 return addPermissionLocked(info, true); 4695 } 4696 } 4697 4698 @Override 4699 public void removePermission(String name) { 4700 synchronized (mPackages) { 4701 checkPermissionTreeLP(name); 4702 BasePermission bp = mSettings.mPermissions.get(name); 4703 if (bp != null) { 4704 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4705 throw new SecurityException( 4706 "Not allowed to modify non-dynamic permission " 4707 + name); 4708 } 4709 mSettings.mPermissions.remove(name); 4710 mSettings.writeLPr(); 4711 } 4712 } 4713 } 4714 4715 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4716 BasePermission bp) { 4717 int index = pkg.requestedPermissions.indexOf(bp.name); 4718 if (index == -1) { 4719 throw new SecurityException("Package " + pkg.packageName 4720 + " has not requested permission " + bp.name); 4721 } 4722 if (!bp.isRuntime() && !bp.isDevelopment()) { 4723 throw new SecurityException("Permission " + bp.name 4724 + " is not a changeable permission type"); 4725 } 4726 } 4727 4728 @Override 4729 public void grantRuntimePermission(String packageName, String name, final int userId) { 4730 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4731 } 4732 4733 private void grantRuntimePermission(String packageName, String name, final int userId, 4734 boolean overridePolicy) { 4735 if (!sUserManager.exists(userId)) { 4736 Log.e(TAG, "No such user:" + userId); 4737 return; 4738 } 4739 4740 mContext.enforceCallingOrSelfPermission( 4741 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4742 "grantRuntimePermission"); 4743 4744 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4745 true /* requireFullPermission */, true /* checkShell */, 4746 "grantRuntimePermission"); 4747 4748 final int uid; 4749 final SettingBase sb; 4750 4751 synchronized (mPackages) { 4752 final PackageParser.Package pkg = mPackages.get(packageName); 4753 if (pkg == null) { 4754 throw new IllegalArgumentException("Unknown package: " + packageName); 4755 } 4756 4757 final BasePermission bp = mSettings.mPermissions.get(name); 4758 if (bp == null) { 4759 throw new IllegalArgumentException("Unknown permission: " + name); 4760 } 4761 4762 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4763 4764 // If a permission review is required for legacy apps we represent 4765 // their permissions as always granted runtime ones since we need 4766 // to keep the review required permission flag per user while an 4767 // install permission's state is shared across all users. 4768 if (mPermissionReviewRequired 4769 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4770 && bp.isRuntime()) { 4771 return; 4772 } 4773 4774 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4775 sb = (SettingBase) pkg.mExtras; 4776 if (sb == null) { 4777 throw new IllegalArgumentException("Unknown package: " + packageName); 4778 } 4779 4780 final PermissionsState permissionsState = sb.getPermissionsState(); 4781 4782 final int flags = permissionsState.getPermissionFlags(name, userId); 4783 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4784 throw new SecurityException("Cannot grant system fixed permission " 4785 + name + " for package " + packageName); 4786 } 4787 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4788 throw new SecurityException("Cannot grant policy fixed permission " 4789 + name + " for package " + packageName); 4790 } 4791 4792 if (bp.isDevelopment()) { 4793 // Development permissions must be handled specially, since they are not 4794 // normal runtime permissions. For now they apply to all users. 4795 if (permissionsState.grantInstallPermission(bp) != 4796 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4797 scheduleWriteSettingsLocked(); 4798 } 4799 return; 4800 } 4801 4802 final PackageSetting ps = mSettings.mPackages.get(packageName); 4803 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4804 throw new SecurityException("Cannot grant non-ephemeral permission" 4805 + name + " for package " + packageName); 4806 } 4807 4808 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4809 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4810 return; 4811 } 4812 4813 final int result = permissionsState.grantRuntimePermission(bp, userId); 4814 switch (result) { 4815 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4816 return; 4817 } 4818 4819 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4820 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4821 mHandler.post(new Runnable() { 4822 @Override 4823 public void run() { 4824 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4825 } 4826 }); 4827 } 4828 break; 4829 } 4830 4831 if (bp.isRuntime()) { 4832 logPermissionGranted(mContext, name, packageName); 4833 } 4834 4835 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4836 4837 // Not critical if that is lost - app has to request again. 4838 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4839 } 4840 4841 // Only need to do this if user is initialized. Otherwise it's a new user 4842 // and there are no processes running as the user yet and there's no need 4843 // to make an expensive call to remount processes for the changed permissions. 4844 if (READ_EXTERNAL_STORAGE.equals(name) 4845 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4846 final long token = Binder.clearCallingIdentity(); 4847 try { 4848 if (sUserManager.isInitialized(userId)) { 4849 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4850 StorageManagerInternal.class); 4851 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4852 } 4853 } finally { 4854 Binder.restoreCallingIdentity(token); 4855 } 4856 } 4857 } 4858 4859 @Override 4860 public void revokeRuntimePermission(String packageName, String name, int userId) { 4861 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4862 } 4863 4864 private void revokeRuntimePermission(String packageName, String name, int userId, 4865 boolean overridePolicy) { 4866 if (!sUserManager.exists(userId)) { 4867 Log.e(TAG, "No such user:" + userId); 4868 return; 4869 } 4870 4871 mContext.enforceCallingOrSelfPermission( 4872 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4873 "revokeRuntimePermission"); 4874 4875 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4876 true /* requireFullPermission */, true /* checkShell */, 4877 "revokeRuntimePermission"); 4878 4879 final int appId; 4880 4881 synchronized (mPackages) { 4882 final PackageParser.Package pkg = mPackages.get(packageName); 4883 if (pkg == null) { 4884 throw new IllegalArgumentException("Unknown package: " + packageName); 4885 } 4886 4887 final BasePermission bp = mSettings.mPermissions.get(name); 4888 if (bp == null) { 4889 throw new IllegalArgumentException("Unknown permission: " + name); 4890 } 4891 4892 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4893 4894 // If a permission review is required for legacy apps we represent 4895 // their permissions as always granted runtime ones since we need 4896 // to keep the review required permission flag per user while an 4897 // install permission's state is shared across all users. 4898 if (mPermissionReviewRequired 4899 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4900 && bp.isRuntime()) { 4901 return; 4902 } 4903 4904 SettingBase sb = (SettingBase) pkg.mExtras; 4905 if (sb == null) { 4906 throw new IllegalArgumentException("Unknown package: " + packageName); 4907 } 4908 4909 final PermissionsState permissionsState = sb.getPermissionsState(); 4910 4911 final int flags = permissionsState.getPermissionFlags(name, userId); 4912 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4913 throw new SecurityException("Cannot revoke system fixed permission " 4914 + name + " for package " + packageName); 4915 } 4916 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4917 throw new SecurityException("Cannot revoke policy fixed permission " 4918 + name + " for package " + packageName); 4919 } 4920 4921 if (bp.isDevelopment()) { 4922 // Development permissions must be handled specially, since they are not 4923 // normal runtime permissions. For now they apply to all users. 4924 if (permissionsState.revokeInstallPermission(bp) != 4925 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4926 scheduleWriteSettingsLocked(); 4927 } 4928 return; 4929 } 4930 4931 if (permissionsState.revokeRuntimePermission(bp, userId) == 4932 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4933 return; 4934 } 4935 4936 if (bp.isRuntime()) { 4937 logPermissionRevoked(mContext, name, packageName); 4938 } 4939 4940 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4941 4942 // Critical, after this call app should never have the permission. 4943 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4944 4945 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4946 } 4947 4948 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4949 } 4950 4951 /** 4952 * Get the first event id for the permission. 4953 * 4954 * <p>There are four events for each permission: <ul> 4955 * <li>Request permission: first id + 0</li> 4956 * <li>Grant permission: first id + 1</li> 4957 * <li>Request for permission denied: first id + 2</li> 4958 * <li>Revoke permission: first id + 3</li> 4959 * </ul></p> 4960 * 4961 * @param name name of the permission 4962 * 4963 * @return The first event id for the permission 4964 */ 4965 private static int getBaseEventId(@NonNull String name) { 4966 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4967 4968 if (eventIdIndex == -1) { 4969 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4970 || "user".equals(Build.TYPE)) { 4971 Log.i(TAG, "Unknown permission " + name); 4972 4973 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4974 } else { 4975 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4976 // 4977 // Also update 4978 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4979 // - metrics_constants.proto 4980 throw new IllegalStateException("Unknown permission " + name); 4981 } 4982 } 4983 4984 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4985 } 4986 4987 /** 4988 * Log that a permission was revoked. 4989 * 4990 * @param context Context of the caller 4991 * @param name name of the permission 4992 * @param packageName package permission if for 4993 */ 4994 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4995 @NonNull String packageName) { 4996 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4997 } 4998 4999 /** 5000 * Log that a permission request was granted. 5001 * 5002 * @param context Context of the caller 5003 * @param name name of the permission 5004 * @param packageName package permission if for 5005 */ 5006 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5007 @NonNull String packageName) { 5008 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5009 } 5010 5011 @Override 5012 public void resetRuntimePermissions() { 5013 mContext.enforceCallingOrSelfPermission( 5014 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5015 "revokeRuntimePermission"); 5016 5017 int callingUid = Binder.getCallingUid(); 5018 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5019 mContext.enforceCallingOrSelfPermission( 5020 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5021 "resetRuntimePermissions"); 5022 } 5023 5024 synchronized (mPackages) { 5025 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5026 for (int userId : UserManagerService.getInstance().getUserIds()) { 5027 final int packageCount = mPackages.size(); 5028 for (int i = 0; i < packageCount; i++) { 5029 PackageParser.Package pkg = mPackages.valueAt(i); 5030 if (!(pkg.mExtras instanceof PackageSetting)) { 5031 continue; 5032 } 5033 PackageSetting ps = (PackageSetting) pkg.mExtras; 5034 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5035 } 5036 } 5037 } 5038 } 5039 5040 @Override 5041 public int getPermissionFlags(String name, String packageName, int userId) { 5042 if (!sUserManager.exists(userId)) { 5043 return 0; 5044 } 5045 5046 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5047 5048 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5049 true /* requireFullPermission */, false /* checkShell */, 5050 "getPermissionFlags"); 5051 5052 synchronized (mPackages) { 5053 final PackageParser.Package pkg = mPackages.get(packageName); 5054 if (pkg == null) { 5055 return 0; 5056 } 5057 5058 final BasePermission bp = mSettings.mPermissions.get(name); 5059 if (bp == null) { 5060 return 0; 5061 } 5062 5063 SettingBase sb = (SettingBase) pkg.mExtras; 5064 if (sb == null) { 5065 return 0; 5066 } 5067 5068 PermissionsState permissionsState = sb.getPermissionsState(); 5069 return permissionsState.getPermissionFlags(name, userId); 5070 } 5071 } 5072 5073 @Override 5074 public void updatePermissionFlags(String name, String packageName, int flagMask, 5075 int flagValues, int userId) { 5076 if (!sUserManager.exists(userId)) { 5077 return; 5078 } 5079 5080 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5081 5082 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5083 true /* requireFullPermission */, true /* checkShell */, 5084 "updatePermissionFlags"); 5085 5086 // Only the system can change these flags and nothing else. 5087 if (getCallingUid() != Process.SYSTEM_UID) { 5088 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5089 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5090 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5091 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5092 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5093 } 5094 5095 synchronized (mPackages) { 5096 final PackageParser.Package pkg = mPackages.get(packageName); 5097 if (pkg == null) { 5098 throw new IllegalArgumentException("Unknown package: " + packageName); 5099 } 5100 5101 final BasePermission bp = mSettings.mPermissions.get(name); 5102 if (bp == null) { 5103 throw new IllegalArgumentException("Unknown permission: " + name); 5104 } 5105 5106 SettingBase sb = (SettingBase) pkg.mExtras; 5107 if (sb == null) { 5108 throw new IllegalArgumentException("Unknown package: " + packageName); 5109 } 5110 5111 PermissionsState permissionsState = sb.getPermissionsState(); 5112 5113 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5114 5115 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5116 // Install and runtime permissions are stored in different places, 5117 // so figure out what permission changed and persist the change. 5118 if (permissionsState.getInstallPermissionState(name) != null) { 5119 scheduleWriteSettingsLocked(); 5120 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5121 || hadState) { 5122 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5123 } 5124 } 5125 } 5126 } 5127 5128 /** 5129 * Update the permission flags for all packages and runtime permissions of a user in order 5130 * to allow device or profile owner to remove POLICY_FIXED. 5131 */ 5132 @Override 5133 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5134 if (!sUserManager.exists(userId)) { 5135 return; 5136 } 5137 5138 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5139 5140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5141 true /* requireFullPermission */, true /* checkShell */, 5142 "updatePermissionFlagsForAllApps"); 5143 5144 // Only the system can change system fixed flags. 5145 if (getCallingUid() != Process.SYSTEM_UID) { 5146 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5147 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5148 } 5149 5150 synchronized (mPackages) { 5151 boolean changed = false; 5152 final int packageCount = mPackages.size(); 5153 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5154 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5155 SettingBase sb = (SettingBase) pkg.mExtras; 5156 if (sb == null) { 5157 continue; 5158 } 5159 PermissionsState permissionsState = sb.getPermissionsState(); 5160 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5161 userId, flagMask, flagValues); 5162 } 5163 if (changed) { 5164 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5165 } 5166 } 5167 } 5168 5169 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5170 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5171 != PackageManager.PERMISSION_GRANTED 5172 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5173 != PackageManager.PERMISSION_GRANTED) { 5174 throw new SecurityException(message + " requires " 5175 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5176 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5177 } 5178 } 5179 5180 @Override 5181 public boolean shouldShowRequestPermissionRationale(String permissionName, 5182 String packageName, int userId) { 5183 if (UserHandle.getCallingUserId() != userId) { 5184 mContext.enforceCallingPermission( 5185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5186 "canShowRequestPermissionRationale for user " + userId); 5187 } 5188 5189 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5190 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5191 return false; 5192 } 5193 5194 if (checkPermission(permissionName, packageName, userId) 5195 == PackageManager.PERMISSION_GRANTED) { 5196 return false; 5197 } 5198 5199 final int flags; 5200 5201 final long identity = Binder.clearCallingIdentity(); 5202 try { 5203 flags = getPermissionFlags(permissionName, 5204 packageName, userId); 5205 } finally { 5206 Binder.restoreCallingIdentity(identity); 5207 } 5208 5209 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5210 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5211 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5212 5213 if ((flags & fixedFlags) != 0) { 5214 return false; 5215 } 5216 5217 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5218 } 5219 5220 @Override 5221 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5222 mContext.enforceCallingOrSelfPermission( 5223 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5224 "addOnPermissionsChangeListener"); 5225 5226 synchronized (mPackages) { 5227 mOnPermissionChangeListeners.addListenerLocked(listener); 5228 } 5229 } 5230 5231 @Override 5232 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5233 synchronized (mPackages) { 5234 mOnPermissionChangeListeners.removeListenerLocked(listener); 5235 } 5236 } 5237 5238 @Override 5239 public boolean isProtectedBroadcast(String actionName) { 5240 synchronized (mPackages) { 5241 if (mProtectedBroadcasts.contains(actionName)) { 5242 return true; 5243 } else if (actionName != null) { 5244 // TODO: remove these terrible hacks 5245 if (actionName.startsWith("android.net.netmon.lingerExpired") 5246 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5247 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5248 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5249 return true; 5250 } 5251 } 5252 } 5253 return false; 5254 } 5255 5256 @Override 5257 public int checkSignatures(String pkg1, String pkg2) { 5258 synchronized (mPackages) { 5259 final PackageParser.Package p1 = mPackages.get(pkg1); 5260 final PackageParser.Package p2 = mPackages.get(pkg2); 5261 if (p1 == null || p1.mExtras == null 5262 || p2 == null || p2.mExtras == null) { 5263 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5264 } 5265 return compareSignatures(p1.mSignatures, p2.mSignatures); 5266 } 5267 } 5268 5269 @Override 5270 public int checkUidSignatures(int uid1, int uid2) { 5271 // Map to base uids. 5272 uid1 = UserHandle.getAppId(uid1); 5273 uid2 = UserHandle.getAppId(uid2); 5274 // reader 5275 synchronized (mPackages) { 5276 Signature[] s1; 5277 Signature[] s2; 5278 Object obj = mSettings.getUserIdLPr(uid1); 5279 if (obj != null) { 5280 if (obj instanceof SharedUserSetting) { 5281 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5282 } else if (obj instanceof PackageSetting) { 5283 s1 = ((PackageSetting)obj).signatures.mSignatures; 5284 } else { 5285 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5286 } 5287 } else { 5288 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5289 } 5290 obj = mSettings.getUserIdLPr(uid2); 5291 if (obj != null) { 5292 if (obj instanceof SharedUserSetting) { 5293 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5294 } else if (obj instanceof PackageSetting) { 5295 s2 = ((PackageSetting)obj).signatures.mSignatures; 5296 } else { 5297 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5298 } 5299 } else { 5300 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5301 } 5302 return compareSignatures(s1, s2); 5303 } 5304 } 5305 5306 /** 5307 * This method should typically only be used when granting or revoking 5308 * permissions, since the app may immediately restart after this call. 5309 * <p> 5310 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5311 * guard your work against the app being relaunched. 5312 */ 5313 private void killUid(int appId, int userId, String reason) { 5314 final long identity = Binder.clearCallingIdentity(); 5315 try { 5316 IActivityManager am = ActivityManager.getService(); 5317 if (am != null) { 5318 try { 5319 am.killUid(appId, userId, reason); 5320 } catch (RemoteException e) { 5321 /* ignore - same process */ 5322 } 5323 } 5324 } finally { 5325 Binder.restoreCallingIdentity(identity); 5326 } 5327 } 5328 5329 /** 5330 * Compares two sets of signatures. Returns: 5331 * <br /> 5332 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5333 * <br /> 5334 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5335 * <br /> 5336 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5337 * <br /> 5338 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5339 * <br /> 5340 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5341 */ 5342 static int compareSignatures(Signature[] s1, Signature[] s2) { 5343 if (s1 == null) { 5344 return s2 == null 5345 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5346 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5347 } 5348 5349 if (s2 == null) { 5350 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5351 } 5352 5353 if (s1.length != s2.length) { 5354 return PackageManager.SIGNATURE_NO_MATCH; 5355 } 5356 5357 // Since both signature sets are of size 1, we can compare without HashSets. 5358 if (s1.length == 1) { 5359 return s1[0].equals(s2[0]) ? 5360 PackageManager.SIGNATURE_MATCH : 5361 PackageManager.SIGNATURE_NO_MATCH; 5362 } 5363 5364 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5365 for (Signature sig : s1) { 5366 set1.add(sig); 5367 } 5368 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5369 for (Signature sig : s2) { 5370 set2.add(sig); 5371 } 5372 // Make sure s2 contains all signatures in s1. 5373 if (set1.equals(set2)) { 5374 return PackageManager.SIGNATURE_MATCH; 5375 } 5376 return PackageManager.SIGNATURE_NO_MATCH; 5377 } 5378 5379 /** 5380 * If the database version for this type of package (internal storage or 5381 * external storage) is less than the version where package signatures 5382 * were updated, return true. 5383 */ 5384 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5385 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5386 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5387 } 5388 5389 /** 5390 * Used for backward compatibility to make sure any packages with 5391 * certificate chains get upgraded to the new style. {@code existingSigs} 5392 * will be in the old format (since they were stored on disk from before the 5393 * system upgrade) and {@code scannedSigs} will be in the newer format. 5394 */ 5395 private int compareSignaturesCompat(PackageSignatures existingSigs, 5396 PackageParser.Package scannedPkg) { 5397 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5398 return PackageManager.SIGNATURE_NO_MATCH; 5399 } 5400 5401 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5402 for (Signature sig : existingSigs.mSignatures) { 5403 existingSet.add(sig); 5404 } 5405 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5406 for (Signature sig : scannedPkg.mSignatures) { 5407 try { 5408 Signature[] chainSignatures = sig.getChainSignatures(); 5409 for (Signature chainSig : chainSignatures) { 5410 scannedCompatSet.add(chainSig); 5411 } 5412 } catch (CertificateEncodingException e) { 5413 scannedCompatSet.add(sig); 5414 } 5415 } 5416 /* 5417 * Make sure the expanded scanned set contains all signatures in the 5418 * existing one. 5419 */ 5420 if (scannedCompatSet.equals(existingSet)) { 5421 // Migrate the old signatures to the new scheme. 5422 existingSigs.assignSignatures(scannedPkg.mSignatures); 5423 // The new KeySets will be re-added later in the scanning process. 5424 synchronized (mPackages) { 5425 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5426 } 5427 return PackageManager.SIGNATURE_MATCH; 5428 } 5429 return PackageManager.SIGNATURE_NO_MATCH; 5430 } 5431 5432 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5433 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5434 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5435 } 5436 5437 private int compareSignaturesRecover(PackageSignatures existingSigs, 5438 PackageParser.Package scannedPkg) { 5439 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5440 return PackageManager.SIGNATURE_NO_MATCH; 5441 } 5442 5443 String msg = null; 5444 try { 5445 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5446 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5447 + scannedPkg.packageName); 5448 return PackageManager.SIGNATURE_MATCH; 5449 } 5450 } catch (CertificateException e) { 5451 msg = e.getMessage(); 5452 } 5453 5454 logCriticalInfo(Log.INFO, 5455 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5456 return PackageManager.SIGNATURE_NO_MATCH; 5457 } 5458 5459 @Override 5460 public List<String> getAllPackages() { 5461 synchronized (mPackages) { 5462 return new ArrayList<String>(mPackages.keySet()); 5463 } 5464 } 5465 5466 @Override 5467 public String[] getPackagesForUid(int uid) { 5468 final int userId = UserHandle.getUserId(uid); 5469 uid = UserHandle.getAppId(uid); 5470 // reader 5471 synchronized (mPackages) { 5472 Object obj = mSettings.getUserIdLPr(uid); 5473 if (obj instanceof SharedUserSetting) { 5474 final SharedUserSetting sus = (SharedUserSetting) obj; 5475 final int N = sus.packages.size(); 5476 String[] res = new String[N]; 5477 final Iterator<PackageSetting> it = sus.packages.iterator(); 5478 int i = 0; 5479 while (it.hasNext()) { 5480 PackageSetting ps = it.next(); 5481 if (ps.getInstalled(userId)) { 5482 res[i++] = ps.name; 5483 } else { 5484 res = ArrayUtils.removeElement(String.class, res, res[i]); 5485 } 5486 } 5487 return res; 5488 } else if (obj instanceof PackageSetting) { 5489 final PackageSetting ps = (PackageSetting) obj; 5490 if (ps.getInstalled(userId)) { 5491 return new String[]{ps.name}; 5492 } 5493 } 5494 } 5495 return null; 5496 } 5497 5498 @Override 5499 public String getNameForUid(int uid) { 5500 // reader 5501 synchronized (mPackages) { 5502 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5503 if (obj instanceof SharedUserSetting) { 5504 final SharedUserSetting sus = (SharedUserSetting) obj; 5505 return sus.name + ":" + sus.userId; 5506 } else if (obj instanceof PackageSetting) { 5507 final PackageSetting ps = (PackageSetting) obj; 5508 return ps.name; 5509 } 5510 } 5511 return null; 5512 } 5513 5514 @Override 5515 public int getUidForSharedUser(String sharedUserName) { 5516 if(sharedUserName == null) { 5517 return -1; 5518 } 5519 // reader 5520 synchronized (mPackages) { 5521 SharedUserSetting suid; 5522 try { 5523 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5524 if (suid != null) { 5525 return suid.userId; 5526 } 5527 } catch (PackageManagerException ignore) { 5528 // can't happen, but, still need to catch it 5529 } 5530 return -1; 5531 } 5532 } 5533 5534 @Override 5535 public int getFlagsForUid(int uid) { 5536 synchronized (mPackages) { 5537 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5538 if (obj instanceof SharedUserSetting) { 5539 final SharedUserSetting sus = (SharedUserSetting) obj; 5540 return sus.pkgFlags; 5541 } else if (obj instanceof PackageSetting) { 5542 final PackageSetting ps = (PackageSetting) obj; 5543 return ps.pkgFlags; 5544 } 5545 } 5546 return 0; 5547 } 5548 5549 @Override 5550 public int getPrivateFlagsForUid(int uid) { 5551 synchronized (mPackages) { 5552 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5553 if (obj instanceof SharedUserSetting) { 5554 final SharedUserSetting sus = (SharedUserSetting) obj; 5555 return sus.pkgPrivateFlags; 5556 } else if (obj instanceof PackageSetting) { 5557 final PackageSetting ps = (PackageSetting) obj; 5558 return ps.pkgPrivateFlags; 5559 } 5560 } 5561 return 0; 5562 } 5563 5564 @Override 5565 public boolean isUidPrivileged(int uid) { 5566 uid = UserHandle.getAppId(uid); 5567 // reader 5568 synchronized (mPackages) { 5569 Object obj = mSettings.getUserIdLPr(uid); 5570 if (obj instanceof SharedUserSetting) { 5571 final SharedUserSetting sus = (SharedUserSetting) obj; 5572 final Iterator<PackageSetting> it = sus.packages.iterator(); 5573 while (it.hasNext()) { 5574 if (it.next().isPrivileged()) { 5575 return true; 5576 } 5577 } 5578 } else if (obj instanceof PackageSetting) { 5579 final PackageSetting ps = (PackageSetting) obj; 5580 return ps.isPrivileged(); 5581 } 5582 } 5583 return false; 5584 } 5585 5586 @Override 5587 public String[] getAppOpPermissionPackages(String permissionName) { 5588 synchronized (mPackages) { 5589 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5590 if (pkgs == null) { 5591 return null; 5592 } 5593 return pkgs.toArray(new String[pkgs.size()]); 5594 } 5595 } 5596 5597 @Override 5598 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5599 int flags, int userId) { 5600 return resolveIntentInternal( 5601 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5602 } 5603 5604 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5605 int flags, int userId, boolean includeInstantApps) { 5606 try { 5607 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5608 5609 if (!sUserManager.exists(userId)) return null; 5610 final int callingUid = Binder.getCallingUid(); 5611 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5612 enforceCrossUserPermission(callingUid, userId, 5613 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5614 5615 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5616 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5617 flags, userId, includeInstantApps); 5618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5619 5620 final ResolveInfo bestChoice = 5621 chooseBestActivity(intent, resolvedType, flags, query, userId); 5622 return bestChoice; 5623 } finally { 5624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5625 } 5626 } 5627 5628 @Override 5629 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5630 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5631 throw new SecurityException( 5632 "findPersistentPreferredActivity can only be run by the system"); 5633 } 5634 if (!sUserManager.exists(userId)) { 5635 return null; 5636 } 5637 final int callingUid = Binder.getCallingUid(); 5638 intent = updateIntentForResolve(intent); 5639 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5640 final int flags = updateFlagsForResolve( 5641 0, userId, intent, callingUid, false /*includeInstantApps*/); 5642 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5643 userId); 5644 synchronized (mPackages) { 5645 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5646 userId); 5647 } 5648 } 5649 5650 @Override 5651 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5652 IntentFilter filter, int match, ComponentName activity) { 5653 final int userId = UserHandle.getCallingUserId(); 5654 if (DEBUG_PREFERRED) { 5655 Log.v(TAG, "setLastChosenActivity intent=" + intent 5656 + " resolvedType=" + resolvedType 5657 + " flags=" + flags 5658 + " filter=" + filter 5659 + " match=" + match 5660 + " activity=" + activity); 5661 filter.dump(new PrintStreamPrinter(System.out), " "); 5662 } 5663 intent.setComponent(null); 5664 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5665 userId); 5666 // Find any earlier preferred or last chosen entries and nuke them 5667 findPreferredActivity(intent, resolvedType, 5668 flags, query, 0, false, true, false, userId); 5669 // Add the new activity as the last chosen for this filter 5670 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5671 "Setting last chosen"); 5672 } 5673 5674 @Override 5675 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5676 final int userId = UserHandle.getCallingUserId(); 5677 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5678 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5679 userId); 5680 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5681 false, false, false, userId); 5682 } 5683 5684 /** 5685 * Returns whether or not instant apps have been disabled remotely. 5686 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5687 * held. Otherwise we run the risk of deadlock. 5688 */ 5689 private boolean isEphemeralDisabled() { 5690 // ephemeral apps have been disabled across the board 5691 if (DISABLE_EPHEMERAL_APPS) { 5692 return true; 5693 } 5694 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5695 if (!mSystemReady) { 5696 return true; 5697 } 5698 // we can't get a content resolver until the system is ready; these checks must happen last 5699 final ContentResolver resolver = mContext.getContentResolver(); 5700 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5701 return true; 5702 } 5703 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5704 } 5705 5706 private boolean isEphemeralAllowed( 5707 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5708 boolean skipPackageCheck) { 5709 final int callingUser = UserHandle.getCallingUserId(); 5710 if (callingUser != UserHandle.USER_SYSTEM) { 5711 return false; 5712 } 5713 if (mInstantAppResolverConnection == null) { 5714 return false; 5715 } 5716 if (mInstantAppInstallerComponent == null) { 5717 return false; 5718 } 5719 if (intent.getComponent() != null) { 5720 return false; 5721 } 5722 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5723 return false; 5724 } 5725 if (!skipPackageCheck && intent.getPackage() != null) { 5726 return false; 5727 } 5728 final boolean isWebUri = hasWebURI(intent); 5729 if (!isWebUri || intent.getData().getHost() == null) { 5730 return false; 5731 } 5732 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5733 // Or if there's already an ephemeral app installed that handles the action 5734 synchronized (mPackages) { 5735 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5736 for (int n = 0; n < count; n++) { 5737 ResolveInfo info = resolvedActivities.get(n); 5738 String packageName = info.activityInfo.packageName; 5739 PackageSetting ps = mSettings.mPackages.get(packageName); 5740 if (ps != null) { 5741 // Try to get the status from User settings first 5742 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5743 int status = (int) (packedStatus >> 32); 5744 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5745 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5746 if (DEBUG_EPHEMERAL) { 5747 Slog.v(TAG, "DENY ephemeral apps;" 5748 + " pkg: " + packageName + ", status: " + status); 5749 } 5750 return false; 5751 } 5752 if (ps.getInstantApp(userId)) { 5753 if (DEBUG_EPHEMERAL) { 5754 Slog.v(TAG, "DENY instant app installed;" 5755 + " pkg: " + packageName); 5756 } 5757 return false; 5758 } 5759 } 5760 } 5761 } 5762 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5763 return true; 5764 } 5765 5766 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5767 Intent origIntent, String resolvedType, String callingPackage, 5768 int userId) { 5769 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5770 new InstantAppRequest(responseObj, origIntent, resolvedType, 5771 callingPackage, userId)); 5772 mHandler.sendMessage(msg); 5773 } 5774 5775 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5776 int flags, List<ResolveInfo> query, int userId) { 5777 if (query != null) { 5778 final int N = query.size(); 5779 if (N == 1) { 5780 return query.get(0); 5781 } else if (N > 1) { 5782 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5783 // If there is more than one activity with the same priority, 5784 // then let the user decide between them. 5785 ResolveInfo r0 = query.get(0); 5786 ResolveInfo r1 = query.get(1); 5787 if (DEBUG_INTENT_MATCHING || debug) { 5788 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5789 + r1.activityInfo.name + "=" + r1.priority); 5790 } 5791 // If the first activity has a higher priority, or a different 5792 // default, then it is always desirable to pick it. 5793 if (r0.priority != r1.priority 5794 || r0.preferredOrder != r1.preferredOrder 5795 || r0.isDefault != r1.isDefault) { 5796 return query.get(0); 5797 } 5798 // If we have saved a preference for a preferred activity for 5799 // this Intent, use that. 5800 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5801 flags, query, r0.priority, true, false, debug, userId); 5802 if (ri != null) { 5803 return ri; 5804 } 5805 // If we have an ephemeral app, use it 5806 for (int i = 0; i < N; i++) { 5807 ri = query.get(i); 5808 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5809 return ri; 5810 } 5811 } 5812 ri = new ResolveInfo(mResolveInfo); 5813 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5814 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5815 // If all of the options come from the same package, show the application's 5816 // label and icon instead of the generic resolver's. 5817 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5818 // and then throw away the ResolveInfo itself, meaning that the caller loses 5819 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5820 // a fallback for this case; we only set the target package's resources on 5821 // the ResolveInfo, not the ActivityInfo. 5822 final String intentPackage = intent.getPackage(); 5823 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5824 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5825 ri.resolvePackageName = intentPackage; 5826 if (userNeedsBadging(userId)) { 5827 ri.noResourceId = true; 5828 } else { 5829 ri.icon = appi.icon; 5830 } 5831 ri.iconResourceId = appi.icon; 5832 ri.labelRes = appi.labelRes; 5833 } 5834 ri.activityInfo.applicationInfo = new ApplicationInfo( 5835 ri.activityInfo.applicationInfo); 5836 if (userId != 0) { 5837 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5838 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5839 } 5840 // Make sure that the resolver is displayable in car mode 5841 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5842 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5843 return ri; 5844 } 5845 } 5846 return null; 5847 } 5848 5849 /** 5850 * Return true if the given list is not empty and all of its contents have 5851 * an activityInfo with the given package name. 5852 */ 5853 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5854 if (ArrayUtils.isEmpty(list)) { 5855 return false; 5856 } 5857 for (int i = 0, N = list.size(); i < N; i++) { 5858 final ResolveInfo ri = list.get(i); 5859 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5860 if (ai == null || !packageName.equals(ai.packageName)) { 5861 return false; 5862 } 5863 } 5864 return true; 5865 } 5866 5867 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5868 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5869 final int N = query.size(); 5870 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5871 .get(userId); 5872 // Get the list of persistent preferred activities that handle the intent 5873 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5874 List<PersistentPreferredActivity> pprefs = ppir != null 5875 ? ppir.queryIntent(intent, resolvedType, 5876 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5877 userId) 5878 : null; 5879 if (pprefs != null && pprefs.size() > 0) { 5880 final int M = pprefs.size(); 5881 for (int i=0; i<M; i++) { 5882 final PersistentPreferredActivity ppa = pprefs.get(i); 5883 if (DEBUG_PREFERRED || debug) { 5884 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5885 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5886 + "\n component=" + ppa.mComponent); 5887 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5888 } 5889 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5890 flags | MATCH_DISABLED_COMPONENTS, userId); 5891 if (DEBUG_PREFERRED || debug) { 5892 Slog.v(TAG, "Found persistent preferred activity:"); 5893 if (ai != null) { 5894 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5895 } else { 5896 Slog.v(TAG, " null"); 5897 } 5898 } 5899 if (ai == null) { 5900 // This previously registered persistent preferred activity 5901 // component is no longer known. Ignore it and do NOT remove it. 5902 continue; 5903 } 5904 for (int j=0; j<N; j++) { 5905 final ResolveInfo ri = query.get(j); 5906 if (!ri.activityInfo.applicationInfo.packageName 5907 .equals(ai.applicationInfo.packageName)) { 5908 continue; 5909 } 5910 if (!ri.activityInfo.name.equals(ai.name)) { 5911 continue; 5912 } 5913 // Found a persistent preference that can handle the intent. 5914 if (DEBUG_PREFERRED || debug) { 5915 Slog.v(TAG, "Returning persistent preferred activity: " + 5916 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5917 } 5918 return ri; 5919 } 5920 } 5921 } 5922 return null; 5923 } 5924 5925 // TODO: handle preferred activities missing while user has amnesia 5926 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5927 List<ResolveInfo> query, int priority, boolean always, 5928 boolean removeMatches, boolean debug, int userId) { 5929 if (!sUserManager.exists(userId)) return null; 5930 final int callingUid = Binder.getCallingUid(); 5931 flags = updateFlagsForResolve( 5932 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5933 intent = updateIntentForResolve(intent); 5934 // writer 5935 synchronized (mPackages) { 5936 // Try to find a matching persistent preferred activity. 5937 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5938 debug, userId); 5939 5940 // If a persistent preferred activity matched, use it. 5941 if (pri != null) { 5942 return pri; 5943 } 5944 5945 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5946 // Get the list of preferred activities that handle the intent 5947 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5948 List<PreferredActivity> prefs = pir != null 5949 ? pir.queryIntent(intent, resolvedType, 5950 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5951 userId) 5952 : null; 5953 if (prefs != null && prefs.size() > 0) { 5954 boolean changed = false; 5955 try { 5956 // First figure out how good the original match set is. 5957 // We will only allow preferred activities that came 5958 // from the same match quality. 5959 int match = 0; 5960 5961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5962 5963 final int N = query.size(); 5964 for (int j=0; j<N; j++) { 5965 final ResolveInfo ri = query.get(j); 5966 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5967 + ": 0x" + Integer.toHexString(match)); 5968 if (ri.match > match) { 5969 match = ri.match; 5970 } 5971 } 5972 5973 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5974 + Integer.toHexString(match)); 5975 5976 match &= IntentFilter.MATCH_CATEGORY_MASK; 5977 final int M = prefs.size(); 5978 for (int i=0; i<M; i++) { 5979 final PreferredActivity pa = prefs.get(i); 5980 if (DEBUG_PREFERRED || debug) { 5981 Slog.v(TAG, "Checking PreferredActivity ds=" 5982 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5983 + "\n component=" + pa.mPref.mComponent); 5984 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5985 } 5986 if (pa.mPref.mMatch != match) { 5987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5988 + Integer.toHexString(pa.mPref.mMatch)); 5989 continue; 5990 } 5991 // If it's not an "always" type preferred activity and that's what we're 5992 // looking for, skip it. 5993 if (always && !pa.mPref.mAlways) { 5994 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5995 continue; 5996 } 5997 final ActivityInfo ai = getActivityInfo( 5998 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5999 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6000 userId); 6001 if (DEBUG_PREFERRED || debug) { 6002 Slog.v(TAG, "Found preferred activity:"); 6003 if (ai != null) { 6004 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6005 } else { 6006 Slog.v(TAG, " null"); 6007 } 6008 } 6009 if (ai == null) { 6010 // This previously registered preferred activity 6011 // component is no longer known. Most likely an update 6012 // to the app was installed and in the new version this 6013 // component no longer exists. Clean it up by removing 6014 // it from the preferred activities list, and skip it. 6015 Slog.w(TAG, "Removing dangling preferred activity: " 6016 + pa.mPref.mComponent); 6017 pir.removeFilter(pa); 6018 changed = true; 6019 continue; 6020 } 6021 for (int j=0; j<N; j++) { 6022 final ResolveInfo ri = query.get(j); 6023 if (!ri.activityInfo.applicationInfo.packageName 6024 .equals(ai.applicationInfo.packageName)) { 6025 continue; 6026 } 6027 if (!ri.activityInfo.name.equals(ai.name)) { 6028 continue; 6029 } 6030 6031 if (removeMatches) { 6032 pir.removeFilter(pa); 6033 changed = true; 6034 if (DEBUG_PREFERRED) { 6035 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6036 } 6037 break; 6038 } 6039 6040 // Okay we found a previously set preferred or last chosen app. 6041 // If the result set is different from when this 6042 // was created, we need to clear it and re-ask the 6043 // user their preference, if we're looking for an "always" type entry. 6044 if (always && !pa.mPref.sameSet(query)) { 6045 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6046 + intent + " type " + resolvedType); 6047 if (DEBUG_PREFERRED) { 6048 Slog.v(TAG, "Removing preferred activity since set changed " 6049 + pa.mPref.mComponent); 6050 } 6051 pir.removeFilter(pa); 6052 // Re-add the filter as a "last chosen" entry (!always) 6053 PreferredActivity lastChosen = new PreferredActivity( 6054 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6055 pir.addFilter(lastChosen); 6056 changed = true; 6057 return null; 6058 } 6059 6060 // Yay! Either the set matched or we're looking for the last chosen 6061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6062 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6063 return ri; 6064 } 6065 } 6066 } finally { 6067 if (changed) { 6068 if (DEBUG_PREFERRED) { 6069 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6070 } 6071 scheduleWritePackageRestrictionsLocked(userId); 6072 } 6073 } 6074 } 6075 } 6076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6077 return null; 6078 } 6079 6080 /* 6081 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6082 */ 6083 @Override 6084 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6085 int targetUserId) { 6086 mContext.enforceCallingOrSelfPermission( 6087 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6088 List<CrossProfileIntentFilter> matches = 6089 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6090 if (matches != null) { 6091 int size = matches.size(); 6092 for (int i = 0; i < size; i++) { 6093 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6094 } 6095 } 6096 if (hasWebURI(intent)) { 6097 // cross-profile app linking works only towards the parent. 6098 final int callingUid = Binder.getCallingUid(); 6099 final UserInfo parent = getProfileParent(sourceUserId); 6100 synchronized(mPackages) { 6101 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6102 false /*includeInstantApps*/); 6103 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6104 intent, resolvedType, flags, sourceUserId, parent.id); 6105 return xpDomainInfo != null; 6106 } 6107 } 6108 return false; 6109 } 6110 6111 private UserInfo getProfileParent(int userId) { 6112 final long identity = Binder.clearCallingIdentity(); 6113 try { 6114 return sUserManager.getProfileParent(userId); 6115 } finally { 6116 Binder.restoreCallingIdentity(identity); 6117 } 6118 } 6119 6120 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6121 String resolvedType, int userId) { 6122 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6123 if (resolver != null) { 6124 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6125 } 6126 return null; 6127 } 6128 6129 @Override 6130 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6131 String resolvedType, int flags, int userId) { 6132 try { 6133 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6134 6135 return new ParceledListSlice<>( 6136 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6137 } finally { 6138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6139 } 6140 } 6141 6142 /** 6143 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6144 * instant, returns {@code null}. 6145 */ 6146 private String getInstantAppPackageName(int callingUid) { 6147 // If the caller is an isolated app use the owner's uid for the lookup. 6148 if (Process.isIsolated(callingUid)) { 6149 callingUid = mIsolatedOwners.get(callingUid); 6150 } 6151 final int appId = UserHandle.getAppId(callingUid); 6152 synchronized (mPackages) { 6153 final Object obj = mSettings.getUserIdLPr(appId); 6154 if (obj instanceof PackageSetting) { 6155 final PackageSetting ps = (PackageSetting) obj; 6156 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6157 return isInstantApp ? ps.pkg.packageName : null; 6158 } 6159 } 6160 return null; 6161 } 6162 6163 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6164 String resolvedType, int flags, int userId) { 6165 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6166 } 6167 6168 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6169 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6170 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6171 final int callingUid = Binder.getCallingUid(); 6172 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6173 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6174 enforceCrossUserPermission(callingUid, userId, 6175 false /* requireFullPermission */, false /* checkShell */, 6176 "query intent activities"); 6177 ComponentName comp = intent.getComponent(); 6178 if (comp == null) { 6179 if (intent.getSelector() != null) { 6180 intent = intent.getSelector(); 6181 comp = intent.getComponent(); 6182 } 6183 } 6184 6185 if (comp != null) { 6186 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6187 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6188 if (ai != null) { 6189 // When specifying an explicit component, we prevent the activity from being 6190 // used when either 1) the calling package is normal and the activity is within 6191 // an ephemeral application or 2) the calling package is ephemeral and the 6192 // activity is not visible to ephemeral applications. 6193 final boolean matchInstantApp = 6194 (flags & PackageManager.MATCH_INSTANT) != 0; 6195 final boolean matchVisibleToInstantAppOnly = 6196 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6197 final boolean isCallerInstantApp = 6198 instantAppPkgName != null; 6199 final boolean isTargetSameInstantApp = 6200 comp.getPackageName().equals(instantAppPkgName); 6201 final boolean isTargetInstantApp = 6202 (ai.applicationInfo.privateFlags 6203 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6204 final boolean isTargetHiddenFromInstantApp = 6205 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6206 final boolean blockResolution = 6207 !isTargetSameInstantApp 6208 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6209 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6210 && isTargetHiddenFromInstantApp)); 6211 if (!blockResolution) { 6212 final ResolveInfo ri = new ResolveInfo(); 6213 ri.activityInfo = ai; 6214 list.add(ri); 6215 } 6216 } 6217 return applyPostResolutionFilter(list, instantAppPkgName); 6218 } 6219 6220 // reader 6221 boolean sortResult = false; 6222 boolean addEphemeral = false; 6223 List<ResolveInfo> result; 6224 final String pkgName = intent.getPackage(); 6225 final boolean ephemeralDisabled = isEphemeralDisabled(); 6226 synchronized (mPackages) { 6227 if (pkgName == null) { 6228 List<CrossProfileIntentFilter> matchingFilters = 6229 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6230 // Check for results that need to skip the current profile. 6231 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6232 resolvedType, flags, userId); 6233 if (xpResolveInfo != null) { 6234 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6235 xpResult.add(xpResolveInfo); 6236 return applyPostResolutionFilter( 6237 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6238 } 6239 6240 // Check for results in the current profile. 6241 result = filterIfNotSystemUser(mActivities.queryIntent( 6242 intent, resolvedType, flags, userId), userId); 6243 addEphemeral = !ephemeralDisabled 6244 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6245 // Check for cross profile results. 6246 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6247 xpResolveInfo = queryCrossProfileIntents( 6248 matchingFilters, intent, resolvedType, flags, userId, 6249 hasNonNegativePriorityResult); 6250 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6251 boolean isVisibleToUser = filterIfNotSystemUser( 6252 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6253 if (isVisibleToUser) { 6254 result.add(xpResolveInfo); 6255 sortResult = true; 6256 } 6257 } 6258 if (hasWebURI(intent)) { 6259 CrossProfileDomainInfo xpDomainInfo = null; 6260 final UserInfo parent = getProfileParent(userId); 6261 if (parent != null) { 6262 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6263 flags, userId, parent.id); 6264 } 6265 if (xpDomainInfo != null) { 6266 if (xpResolveInfo != null) { 6267 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6268 // in the result. 6269 result.remove(xpResolveInfo); 6270 } 6271 if (result.size() == 0 && !addEphemeral) { 6272 // No result in current profile, but found candidate in parent user. 6273 // And we are not going to add emphemeral app, so we can return the 6274 // result straight away. 6275 result.add(xpDomainInfo.resolveInfo); 6276 return applyPostResolutionFilter(result, instantAppPkgName); 6277 } 6278 } else if (result.size() <= 1 && !addEphemeral) { 6279 // No result in parent user and <= 1 result in current profile, and we 6280 // are not going to add emphemeral app, so we can return the result without 6281 // further processing. 6282 return applyPostResolutionFilter(result, instantAppPkgName); 6283 } 6284 // We have more than one candidate (combining results from current and parent 6285 // profile), so we need filtering and sorting. 6286 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6287 intent, flags, result, xpDomainInfo, userId); 6288 sortResult = true; 6289 } 6290 } else { 6291 final PackageParser.Package pkg = mPackages.get(pkgName); 6292 if (pkg != null) { 6293 return applyPostResolutionFilter(filterIfNotSystemUser( 6294 mActivities.queryIntentForPackage( 6295 intent, resolvedType, flags, pkg.activities, userId), 6296 userId), instantAppPkgName); 6297 } else { 6298 // the caller wants to resolve for a particular package; however, there 6299 // were no installed results, so, try to find an ephemeral result 6300 addEphemeral = !ephemeralDisabled 6301 && isEphemeralAllowed( 6302 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6303 result = new ArrayList<ResolveInfo>(); 6304 } 6305 } 6306 } 6307 if (addEphemeral) { 6308 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6309 final InstantAppRequest requestObject = new InstantAppRequest( 6310 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6311 null /*callingPackage*/, userId); 6312 final AuxiliaryResolveInfo auxiliaryResponse = 6313 InstantAppResolver.doInstantAppResolutionPhaseOne( 6314 mContext, mInstantAppResolverConnection, requestObject); 6315 if (auxiliaryResponse != null) { 6316 if (DEBUG_EPHEMERAL) { 6317 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6318 } 6319 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6320 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6321 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6322 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6323 // make sure this resolver is the default 6324 ephemeralInstaller.isDefault = true; 6325 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6326 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6327 // add a non-generic filter 6328 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6329 ephemeralInstaller.filter.addDataPath( 6330 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6331 ephemeralInstaller.instantAppAvailable = true; 6332 result.add(ephemeralInstaller); 6333 } 6334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6335 } 6336 if (sortResult) { 6337 Collections.sort(result, mResolvePrioritySorter); 6338 } 6339 return applyPostResolutionFilter(result, instantAppPkgName); 6340 } 6341 6342 private static class CrossProfileDomainInfo { 6343 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6344 ResolveInfo resolveInfo; 6345 /* Best domain verification status of the activities found in the other profile */ 6346 int bestDomainVerificationStatus; 6347 } 6348 6349 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6350 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6351 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6352 sourceUserId)) { 6353 return null; 6354 } 6355 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6356 resolvedType, flags, parentUserId); 6357 6358 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6359 return null; 6360 } 6361 CrossProfileDomainInfo result = null; 6362 int size = resultTargetUser.size(); 6363 for (int i = 0; i < size; i++) { 6364 ResolveInfo riTargetUser = resultTargetUser.get(i); 6365 // Intent filter verification is only for filters that specify a host. So don't return 6366 // those that handle all web uris. 6367 if (riTargetUser.handleAllWebDataURI) { 6368 continue; 6369 } 6370 String packageName = riTargetUser.activityInfo.packageName; 6371 PackageSetting ps = mSettings.mPackages.get(packageName); 6372 if (ps == null) { 6373 continue; 6374 } 6375 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6376 int status = (int)(verificationState >> 32); 6377 if (result == null) { 6378 result = new CrossProfileDomainInfo(); 6379 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6380 sourceUserId, parentUserId); 6381 result.bestDomainVerificationStatus = status; 6382 } else { 6383 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6384 result.bestDomainVerificationStatus); 6385 } 6386 } 6387 // Don't consider matches with status NEVER across profiles. 6388 if (result != null && result.bestDomainVerificationStatus 6389 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6390 return null; 6391 } 6392 return result; 6393 } 6394 6395 /** 6396 * Verification statuses are ordered from the worse to the best, except for 6397 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6398 */ 6399 private int bestDomainVerificationStatus(int status1, int status2) { 6400 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6401 return status2; 6402 } 6403 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6404 return status1; 6405 } 6406 return (int) MathUtils.max(status1, status2); 6407 } 6408 6409 private boolean isUserEnabled(int userId) { 6410 long callingId = Binder.clearCallingIdentity(); 6411 try { 6412 UserInfo userInfo = sUserManager.getUserInfo(userId); 6413 return userInfo != null && userInfo.isEnabled(); 6414 } finally { 6415 Binder.restoreCallingIdentity(callingId); 6416 } 6417 } 6418 6419 /** 6420 * Filter out activities with systemUserOnly flag set, when current user is not System. 6421 * 6422 * @return filtered list 6423 */ 6424 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6425 if (userId == UserHandle.USER_SYSTEM) { 6426 return resolveInfos; 6427 } 6428 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6429 ResolveInfo info = resolveInfos.get(i); 6430 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6431 resolveInfos.remove(i); 6432 } 6433 } 6434 return resolveInfos; 6435 } 6436 6437 /** 6438 * Filters out ephemeral activities. 6439 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6440 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6441 * 6442 * @param resolveInfos The pre-filtered list of resolved activities 6443 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6444 * is performed. 6445 * @return A filtered list of resolved activities. 6446 */ 6447 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6448 String ephemeralPkgName) { 6449 // TODO: When adding on-demand split support for non-instant apps, remove this check 6450 // and always apply post filtering 6451 if (ephemeralPkgName == null) { 6452 return resolveInfos; 6453 } 6454 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6455 final ResolveInfo info = resolveInfos.get(i); 6456 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6457 // allow activities that are defined in the provided package 6458 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6459 if (info.activityInfo.splitName != null 6460 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6461 info.activityInfo.splitName)) { 6462 // requested activity is defined in a split that hasn't been installed yet. 6463 // add the installer to the resolve list 6464 if (DEBUG_EPHEMERAL) { 6465 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6466 } 6467 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6468 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6469 info.activityInfo.packageName, info.activityInfo.splitName, 6470 info.activityInfo.applicationInfo.versionCode); 6471 // make sure this resolver is the default 6472 installerInfo.isDefault = true; 6473 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6474 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6475 // add a non-generic filter 6476 installerInfo.filter = new IntentFilter(); 6477 // load resources from the correct package 6478 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6479 resolveInfos.set(i, installerInfo); 6480 } 6481 continue; 6482 } 6483 // allow activities that have been explicitly exposed to ephemeral apps 6484 if (!isEphemeralApp 6485 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6486 continue; 6487 } 6488 resolveInfos.remove(i); 6489 } 6490 return resolveInfos; 6491 } 6492 6493 /** 6494 * @param resolveInfos list of resolve infos in descending priority order 6495 * @return if the list contains a resolve info with non-negative priority 6496 */ 6497 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6498 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6499 } 6500 6501 private static boolean hasWebURI(Intent intent) { 6502 if (intent.getData() == null) { 6503 return false; 6504 } 6505 final String scheme = intent.getScheme(); 6506 if (TextUtils.isEmpty(scheme)) { 6507 return false; 6508 } 6509 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6510 } 6511 6512 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6513 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6514 int userId) { 6515 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6516 6517 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6518 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6519 candidates.size()); 6520 } 6521 6522 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6523 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6524 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6525 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6526 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6527 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6528 6529 synchronized (mPackages) { 6530 final int count = candidates.size(); 6531 // First, try to use linked apps. Partition the candidates into four lists: 6532 // one for the final results, one for the "do not use ever", one for "undefined status" 6533 // and finally one for "browser app type". 6534 for (int n=0; n<count; n++) { 6535 ResolveInfo info = candidates.get(n); 6536 String packageName = info.activityInfo.packageName; 6537 PackageSetting ps = mSettings.mPackages.get(packageName); 6538 if (ps != null) { 6539 // Add to the special match all list (Browser use case) 6540 if (info.handleAllWebDataURI) { 6541 matchAllList.add(info); 6542 continue; 6543 } 6544 // Try to get the status from User settings first 6545 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6546 int status = (int)(packedStatus >> 32); 6547 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6548 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6549 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6550 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6551 + " : linkgen=" + linkGeneration); 6552 } 6553 // Use link-enabled generation as preferredOrder, i.e. 6554 // prefer newly-enabled over earlier-enabled. 6555 info.preferredOrder = linkGeneration; 6556 alwaysList.add(info); 6557 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6558 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6559 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6560 } 6561 neverList.add(info); 6562 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6563 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6564 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6565 } 6566 alwaysAskList.add(info); 6567 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6568 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6569 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6570 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6571 } 6572 undefinedList.add(info); 6573 } 6574 } 6575 } 6576 6577 // We'll want to include browser possibilities in a few cases 6578 boolean includeBrowser = false; 6579 6580 // First try to add the "always" resolution(s) for the current user, if any 6581 if (alwaysList.size() > 0) { 6582 result.addAll(alwaysList); 6583 } else { 6584 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6585 result.addAll(undefinedList); 6586 // Maybe add one for the other profile. 6587 if (xpDomainInfo != null && ( 6588 xpDomainInfo.bestDomainVerificationStatus 6589 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6590 result.add(xpDomainInfo.resolveInfo); 6591 } 6592 includeBrowser = true; 6593 } 6594 6595 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6596 // If there were 'always' entries their preferred order has been set, so we also 6597 // back that off to make the alternatives equivalent 6598 if (alwaysAskList.size() > 0) { 6599 for (ResolveInfo i : result) { 6600 i.preferredOrder = 0; 6601 } 6602 result.addAll(alwaysAskList); 6603 includeBrowser = true; 6604 } 6605 6606 if (includeBrowser) { 6607 // Also add browsers (all of them or only the default one) 6608 if (DEBUG_DOMAIN_VERIFICATION) { 6609 Slog.v(TAG, " ...including browsers in candidate set"); 6610 } 6611 if ((matchFlags & MATCH_ALL) != 0) { 6612 result.addAll(matchAllList); 6613 } else { 6614 // Browser/generic handling case. If there's a default browser, go straight 6615 // to that (but only if there is no other higher-priority match). 6616 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6617 int maxMatchPrio = 0; 6618 ResolveInfo defaultBrowserMatch = null; 6619 final int numCandidates = matchAllList.size(); 6620 for (int n = 0; n < numCandidates; n++) { 6621 ResolveInfo info = matchAllList.get(n); 6622 // track the highest overall match priority... 6623 if (info.priority > maxMatchPrio) { 6624 maxMatchPrio = info.priority; 6625 } 6626 // ...and the highest-priority default browser match 6627 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6628 if (defaultBrowserMatch == null 6629 || (defaultBrowserMatch.priority < info.priority)) { 6630 if (debug) { 6631 Slog.v(TAG, "Considering default browser match " + info); 6632 } 6633 defaultBrowserMatch = info; 6634 } 6635 } 6636 } 6637 if (defaultBrowserMatch != null 6638 && defaultBrowserMatch.priority >= maxMatchPrio 6639 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6640 { 6641 if (debug) { 6642 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6643 } 6644 result.add(defaultBrowserMatch); 6645 } else { 6646 result.addAll(matchAllList); 6647 } 6648 } 6649 6650 // If there is nothing selected, add all candidates and remove the ones that the user 6651 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6652 if (result.size() == 0) { 6653 result.addAll(candidates); 6654 result.removeAll(neverList); 6655 } 6656 } 6657 } 6658 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6659 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6660 result.size()); 6661 for (ResolveInfo info : result) { 6662 Slog.v(TAG, " + " + info.activityInfo); 6663 } 6664 } 6665 return result; 6666 } 6667 6668 // Returns a packed value as a long: 6669 // 6670 // high 'int'-sized word: link status: undefined/ask/never/always. 6671 // low 'int'-sized word: relative priority among 'always' results. 6672 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6673 long result = ps.getDomainVerificationStatusForUser(userId); 6674 // if none available, get the master status 6675 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6676 if (ps.getIntentFilterVerificationInfo() != null) { 6677 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6678 } 6679 } 6680 return result; 6681 } 6682 6683 private ResolveInfo querySkipCurrentProfileIntents( 6684 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6685 int flags, int sourceUserId) { 6686 if (matchingFilters != null) { 6687 int size = matchingFilters.size(); 6688 for (int i = 0; i < size; i ++) { 6689 CrossProfileIntentFilter filter = matchingFilters.get(i); 6690 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6691 // Checking if there are activities in the target user that can handle the 6692 // intent. 6693 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6694 resolvedType, flags, sourceUserId); 6695 if (resolveInfo != null) { 6696 return resolveInfo; 6697 } 6698 } 6699 } 6700 } 6701 return null; 6702 } 6703 6704 // Return matching ResolveInfo in target user if any. 6705 private ResolveInfo queryCrossProfileIntents( 6706 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6707 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6708 if (matchingFilters != null) { 6709 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6710 // match the same intent. For performance reasons, it is better not to 6711 // run queryIntent twice for the same userId 6712 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6713 int size = matchingFilters.size(); 6714 for (int i = 0; i < size; i++) { 6715 CrossProfileIntentFilter filter = matchingFilters.get(i); 6716 int targetUserId = filter.getTargetUserId(); 6717 boolean skipCurrentProfile = 6718 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6719 boolean skipCurrentProfileIfNoMatchFound = 6720 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6721 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6722 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6723 // Checking if there are activities in the target user that can handle the 6724 // intent. 6725 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6726 resolvedType, flags, sourceUserId); 6727 if (resolveInfo != null) return resolveInfo; 6728 alreadyTriedUserIds.put(targetUserId, true); 6729 } 6730 } 6731 } 6732 return null; 6733 } 6734 6735 /** 6736 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6737 * will forward the intent to the filter's target user. 6738 * Otherwise, returns null. 6739 */ 6740 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6741 String resolvedType, int flags, int sourceUserId) { 6742 int targetUserId = filter.getTargetUserId(); 6743 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6744 resolvedType, flags, targetUserId); 6745 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6746 // If all the matches in the target profile are suspended, return null. 6747 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6748 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6749 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6750 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6751 targetUserId); 6752 } 6753 } 6754 } 6755 return null; 6756 } 6757 6758 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6759 int sourceUserId, int targetUserId) { 6760 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6761 long ident = Binder.clearCallingIdentity(); 6762 boolean targetIsProfile; 6763 try { 6764 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6765 } finally { 6766 Binder.restoreCallingIdentity(ident); 6767 } 6768 String className; 6769 if (targetIsProfile) { 6770 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6771 } else { 6772 className = FORWARD_INTENT_TO_PARENT; 6773 } 6774 ComponentName forwardingActivityComponentName = new ComponentName( 6775 mAndroidApplication.packageName, className); 6776 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6777 sourceUserId); 6778 if (!targetIsProfile) { 6779 forwardingActivityInfo.showUserIcon = targetUserId; 6780 forwardingResolveInfo.noResourceId = true; 6781 } 6782 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6783 forwardingResolveInfo.priority = 0; 6784 forwardingResolveInfo.preferredOrder = 0; 6785 forwardingResolveInfo.match = 0; 6786 forwardingResolveInfo.isDefault = true; 6787 forwardingResolveInfo.filter = filter; 6788 forwardingResolveInfo.targetUserId = targetUserId; 6789 return forwardingResolveInfo; 6790 } 6791 6792 @Override 6793 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6794 Intent[] specifics, String[] specificTypes, Intent intent, 6795 String resolvedType, int flags, int userId) { 6796 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6797 specificTypes, intent, resolvedType, flags, userId)); 6798 } 6799 6800 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6801 Intent[] specifics, String[] specificTypes, Intent intent, 6802 String resolvedType, int flags, int userId) { 6803 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6804 final int callingUid = Binder.getCallingUid(); 6805 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6806 false /*includeInstantApps*/); 6807 enforceCrossUserPermission(callingUid, userId, 6808 false /*requireFullPermission*/, false /*checkShell*/, 6809 "query intent activity options"); 6810 final String resultsAction = intent.getAction(); 6811 6812 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6813 | PackageManager.GET_RESOLVED_FILTER, userId); 6814 6815 if (DEBUG_INTENT_MATCHING) { 6816 Log.v(TAG, "Query " + intent + ": " + results); 6817 } 6818 6819 int specificsPos = 0; 6820 int N; 6821 6822 // todo: note that the algorithm used here is O(N^2). This 6823 // isn't a problem in our current environment, but if we start running 6824 // into situations where we have more than 5 or 10 matches then this 6825 // should probably be changed to something smarter... 6826 6827 // First we go through and resolve each of the specific items 6828 // that were supplied, taking care of removing any corresponding 6829 // duplicate items in the generic resolve list. 6830 if (specifics != null) { 6831 for (int i=0; i<specifics.length; i++) { 6832 final Intent sintent = specifics[i]; 6833 if (sintent == null) { 6834 continue; 6835 } 6836 6837 if (DEBUG_INTENT_MATCHING) { 6838 Log.v(TAG, "Specific #" + i + ": " + sintent); 6839 } 6840 6841 String action = sintent.getAction(); 6842 if (resultsAction != null && resultsAction.equals(action)) { 6843 // If this action was explicitly requested, then don't 6844 // remove things that have it. 6845 action = null; 6846 } 6847 6848 ResolveInfo ri = null; 6849 ActivityInfo ai = null; 6850 6851 ComponentName comp = sintent.getComponent(); 6852 if (comp == null) { 6853 ri = resolveIntent( 6854 sintent, 6855 specificTypes != null ? specificTypes[i] : null, 6856 flags, userId); 6857 if (ri == null) { 6858 continue; 6859 } 6860 if (ri == mResolveInfo) { 6861 // ACK! Must do something better with this. 6862 } 6863 ai = ri.activityInfo; 6864 comp = new ComponentName(ai.applicationInfo.packageName, 6865 ai.name); 6866 } else { 6867 ai = getActivityInfo(comp, flags, userId); 6868 if (ai == null) { 6869 continue; 6870 } 6871 } 6872 6873 // Look for any generic query activities that are duplicates 6874 // of this specific one, and remove them from the results. 6875 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6876 N = results.size(); 6877 int j; 6878 for (j=specificsPos; j<N; j++) { 6879 ResolveInfo sri = results.get(j); 6880 if ((sri.activityInfo.name.equals(comp.getClassName()) 6881 && sri.activityInfo.applicationInfo.packageName.equals( 6882 comp.getPackageName())) 6883 || (action != null && sri.filter.matchAction(action))) { 6884 results.remove(j); 6885 if (DEBUG_INTENT_MATCHING) Log.v( 6886 TAG, "Removing duplicate item from " + j 6887 + " due to specific " + specificsPos); 6888 if (ri == null) { 6889 ri = sri; 6890 } 6891 j--; 6892 N--; 6893 } 6894 } 6895 6896 // Add this specific item to its proper place. 6897 if (ri == null) { 6898 ri = new ResolveInfo(); 6899 ri.activityInfo = ai; 6900 } 6901 results.add(specificsPos, ri); 6902 ri.specificIndex = i; 6903 specificsPos++; 6904 } 6905 } 6906 6907 // Now we go through the remaining generic results and remove any 6908 // duplicate actions that are found here. 6909 N = results.size(); 6910 for (int i=specificsPos; i<N-1; i++) { 6911 final ResolveInfo rii = results.get(i); 6912 if (rii.filter == null) { 6913 continue; 6914 } 6915 6916 // Iterate over all of the actions of this result's intent 6917 // filter... typically this should be just one. 6918 final Iterator<String> it = rii.filter.actionsIterator(); 6919 if (it == null) { 6920 continue; 6921 } 6922 while (it.hasNext()) { 6923 final String action = it.next(); 6924 if (resultsAction != null && resultsAction.equals(action)) { 6925 // If this action was explicitly requested, then don't 6926 // remove things that have it. 6927 continue; 6928 } 6929 for (int j=i+1; j<N; j++) { 6930 final ResolveInfo rij = results.get(j); 6931 if (rij.filter != null && rij.filter.hasAction(action)) { 6932 results.remove(j); 6933 if (DEBUG_INTENT_MATCHING) Log.v( 6934 TAG, "Removing duplicate item from " + j 6935 + " due to action " + action + " at " + i); 6936 j--; 6937 N--; 6938 } 6939 } 6940 } 6941 6942 // If the caller didn't request filter information, drop it now 6943 // so we don't have to marshall/unmarshall it. 6944 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6945 rii.filter = null; 6946 } 6947 } 6948 6949 // Filter out the caller activity if so requested. 6950 if (caller != null) { 6951 N = results.size(); 6952 for (int i=0; i<N; i++) { 6953 ActivityInfo ainfo = results.get(i).activityInfo; 6954 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6955 && caller.getClassName().equals(ainfo.name)) { 6956 results.remove(i); 6957 break; 6958 } 6959 } 6960 } 6961 6962 // If the caller didn't request filter information, 6963 // drop them now so we don't have to 6964 // marshall/unmarshall it. 6965 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6966 N = results.size(); 6967 for (int i=0; i<N; i++) { 6968 results.get(i).filter = null; 6969 } 6970 } 6971 6972 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6973 return results; 6974 } 6975 6976 @Override 6977 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6978 String resolvedType, int flags, int userId) { 6979 return new ParceledListSlice<>( 6980 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6981 } 6982 6983 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6984 String resolvedType, int flags, int userId) { 6985 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6986 final int callingUid = Binder.getCallingUid(); 6987 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6988 false /*includeInstantApps*/); 6989 ComponentName comp = intent.getComponent(); 6990 if (comp == null) { 6991 if (intent.getSelector() != null) { 6992 intent = intent.getSelector(); 6993 comp = intent.getComponent(); 6994 } 6995 } 6996 if (comp != null) { 6997 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6998 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6999 if (ai != null) { 7000 ResolveInfo ri = new ResolveInfo(); 7001 ri.activityInfo = ai; 7002 list.add(ri); 7003 } 7004 return list; 7005 } 7006 7007 // reader 7008 synchronized (mPackages) { 7009 String pkgName = intent.getPackage(); 7010 if (pkgName == null) { 7011 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7012 } 7013 final PackageParser.Package pkg = mPackages.get(pkgName); 7014 if (pkg != null) { 7015 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7016 userId); 7017 } 7018 return Collections.emptyList(); 7019 } 7020 } 7021 7022 @Override 7023 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7024 final int callingUid = Binder.getCallingUid(); 7025 return resolveServiceInternal( 7026 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7027 } 7028 7029 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7030 int userId, int callingUid, boolean includeInstantApps) { 7031 if (!sUserManager.exists(userId)) return null; 7032 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7033 List<ResolveInfo> query = queryIntentServicesInternal( 7034 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7035 if (query != null) { 7036 if (query.size() >= 1) { 7037 // If there is more than one service with the same priority, 7038 // just arbitrarily pick the first one. 7039 return query.get(0); 7040 } 7041 } 7042 return null; 7043 } 7044 7045 @Override 7046 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7047 String resolvedType, int flags, int userId) { 7048 final int callingUid = Binder.getCallingUid(); 7049 return new ParceledListSlice<>(queryIntentServicesInternal( 7050 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7051 } 7052 7053 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7054 String resolvedType, int flags, int userId, int callingUid, 7055 boolean includeInstantApps) { 7056 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7057 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7058 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7059 ComponentName comp = intent.getComponent(); 7060 if (comp == null) { 7061 if (intent.getSelector() != null) { 7062 intent = intent.getSelector(); 7063 comp = intent.getComponent(); 7064 } 7065 } 7066 if (comp != null) { 7067 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7068 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7069 if (si != null) { 7070 // When specifying an explicit component, we prevent the service from being 7071 // used when either 1) the service is in an instant application and the 7072 // caller is not the same instant application or 2) the calling package is 7073 // ephemeral and the activity is not visible to ephemeral applications. 7074 final boolean matchVisibleToInstantAppOnly = 7075 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7076 final boolean isCallerInstantApp = 7077 instantAppPkgName != null; 7078 final boolean isTargetSameInstantApp = 7079 comp.getPackageName().equals(instantAppPkgName); 7080 final boolean isTargetHiddenFromInstantApp = 7081 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7082 final boolean blockResolution = 7083 !isTargetSameInstantApp 7084 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7085 && isTargetHiddenFromInstantApp)); 7086 if (!blockResolution) { 7087 final ResolveInfo ri = new ResolveInfo(); 7088 ri.serviceInfo = si; 7089 list.add(ri); 7090 } 7091 } 7092 return list; 7093 } 7094 7095 // reader 7096 synchronized (mPackages) { 7097 String pkgName = intent.getPackage(); 7098 if (pkgName == null) { 7099 return applyPostServiceResolutionFilter( 7100 mServices.queryIntent(intent, resolvedType, flags, userId), 7101 instantAppPkgName); 7102 } 7103 final PackageParser.Package pkg = mPackages.get(pkgName); 7104 if (pkg != null) { 7105 return applyPostServiceResolutionFilter( 7106 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7107 userId), 7108 instantAppPkgName); 7109 } 7110 return Collections.emptyList(); 7111 } 7112 } 7113 7114 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7115 String instantAppPkgName) { 7116 // TODO: When adding on-demand split support for non-instant apps, remove this check 7117 // and always apply post filtering 7118 if (instantAppPkgName == null) { 7119 return resolveInfos; 7120 } 7121 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7122 final ResolveInfo info = resolveInfos.get(i); 7123 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7124 // allow services that are defined in the provided package 7125 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7126 if (info.serviceInfo.splitName != null 7127 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7128 info.serviceInfo.splitName)) { 7129 // requested service is defined in a split that hasn't been installed yet. 7130 // add the installer to the resolve list 7131 if (DEBUG_EPHEMERAL) { 7132 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7133 } 7134 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7135 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7136 info.serviceInfo.packageName, info.serviceInfo.splitName, 7137 info.serviceInfo.applicationInfo.versionCode); 7138 // make sure this resolver is the default 7139 installerInfo.isDefault = true; 7140 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7141 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7142 // add a non-generic filter 7143 installerInfo.filter = new IntentFilter(); 7144 // load resources from the correct package 7145 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7146 resolveInfos.set(i, installerInfo); 7147 } 7148 continue; 7149 } 7150 // allow services that have been explicitly exposed to ephemeral apps 7151 if (!isEphemeralApp 7152 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7153 continue; 7154 } 7155 resolveInfos.remove(i); 7156 } 7157 return resolveInfos; 7158 } 7159 7160 @Override 7161 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7162 String resolvedType, int flags, int userId) { 7163 return new ParceledListSlice<>( 7164 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7165 } 7166 7167 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7168 Intent intent, String resolvedType, int flags, int userId) { 7169 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7170 final int callingUid = Binder.getCallingUid(); 7171 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7172 false /*includeInstantApps*/); 7173 ComponentName comp = intent.getComponent(); 7174 if (comp == null) { 7175 if (intent.getSelector() != null) { 7176 intent = intent.getSelector(); 7177 comp = intent.getComponent(); 7178 } 7179 } 7180 if (comp != null) { 7181 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7182 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7183 if (pi != null) { 7184 final ResolveInfo ri = new ResolveInfo(); 7185 ri.providerInfo = pi; 7186 list.add(ri); 7187 } 7188 return list; 7189 } 7190 7191 // reader 7192 synchronized (mPackages) { 7193 String pkgName = intent.getPackage(); 7194 if (pkgName == null) { 7195 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7196 } 7197 final PackageParser.Package pkg = mPackages.get(pkgName); 7198 if (pkg != null) { 7199 return mProviders.queryIntentForPackage( 7200 intent, resolvedType, flags, pkg.providers, userId); 7201 } 7202 return Collections.emptyList(); 7203 } 7204 } 7205 7206 @Override 7207 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7208 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7209 flags = updateFlagsForPackage(flags, userId, null); 7210 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7211 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7212 true /* requireFullPermission */, false /* checkShell */, 7213 "get installed packages"); 7214 7215 // writer 7216 synchronized (mPackages) { 7217 ArrayList<PackageInfo> list; 7218 if (listUninstalled) { 7219 list = new ArrayList<>(mSettings.mPackages.size()); 7220 for (PackageSetting ps : mSettings.mPackages.values()) { 7221 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7222 continue; 7223 } 7224 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7225 if (pi != null) { 7226 list.add(pi); 7227 } 7228 } 7229 } else { 7230 list = new ArrayList<>(mPackages.size()); 7231 for (PackageParser.Package p : mPackages.values()) { 7232 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7233 Binder.getCallingUid(), userId)) { 7234 continue; 7235 } 7236 final PackageInfo pi = generatePackageInfo((PackageSetting) 7237 p.mExtras, flags, userId); 7238 if (pi != null) { 7239 list.add(pi); 7240 } 7241 } 7242 } 7243 7244 return new ParceledListSlice<>(list); 7245 } 7246 } 7247 7248 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7249 String[] permissions, boolean[] tmp, int flags, int userId) { 7250 int numMatch = 0; 7251 final PermissionsState permissionsState = ps.getPermissionsState(); 7252 for (int i=0; i<permissions.length; i++) { 7253 final String permission = permissions[i]; 7254 if (permissionsState.hasPermission(permission, userId)) { 7255 tmp[i] = true; 7256 numMatch++; 7257 } else { 7258 tmp[i] = false; 7259 } 7260 } 7261 if (numMatch == 0) { 7262 return; 7263 } 7264 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7265 7266 // The above might return null in cases of uninstalled apps or install-state 7267 // skew across users/profiles. 7268 if (pi != null) { 7269 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7270 if (numMatch == permissions.length) { 7271 pi.requestedPermissions = permissions; 7272 } else { 7273 pi.requestedPermissions = new String[numMatch]; 7274 numMatch = 0; 7275 for (int i=0; i<permissions.length; i++) { 7276 if (tmp[i]) { 7277 pi.requestedPermissions[numMatch] = permissions[i]; 7278 numMatch++; 7279 } 7280 } 7281 } 7282 } 7283 list.add(pi); 7284 } 7285 } 7286 7287 @Override 7288 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7289 String[] permissions, int flags, int userId) { 7290 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7291 flags = updateFlagsForPackage(flags, userId, permissions); 7292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7293 true /* requireFullPermission */, false /* checkShell */, 7294 "get packages holding permissions"); 7295 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7296 7297 // writer 7298 synchronized (mPackages) { 7299 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7300 boolean[] tmpBools = new boolean[permissions.length]; 7301 if (listUninstalled) { 7302 for (PackageSetting ps : mSettings.mPackages.values()) { 7303 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7304 userId); 7305 } 7306 } else { 7307 for (PackageParser.Package pkg : mPackages.values()) { 7308 PackageSetting ps = (PackageSetting)pkg.mExtras; 7309 if (ps != null) { 7310 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7311 userId); 7312 } 7313 } 7314 } 7315 7316 return new ParceledListSlice<PackageInfo>(list); 7317 } 7318 } 7319 7320 @Override 7321 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7322 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7323 flags = updateFlagsForApplication(flags, userId, null); 7324 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7325 7326 // writer 7327 synchronized (mPackages) { 7328 ArrayList<ApplicationInfo> list; 7329 if (listUninstalled) { 7330 list = new ArrayList<>(mSettings.mPackages.size()); 7331 for (PackageSetting ps : mSettings.mPackages.values()) { 7332 ApplicationInfo ai; 7333 int effectiveFlags = flags; 7334 if (ps.isSystem()) { 7335 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7336 } 7337 if (ps.pkg != null) { 7338 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7339 continue; 7340 } 7341 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7342 ps.readUserState(userId), userId); 7343 if (ai != null) { 7344 rebaseEnabledOverlays(ai, userId); 7345 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7346 } 7347 } else { 7348 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7349 // and already converts to externally visible package name 7350 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7351 Binder.getCallingUid(), effectiveFlags, userId); 7352 } 7353 if (ai != null) { 7354 list.add(ai); 7355 } 7356 } 7357 } else { 7358 list = new ArrayList<>(mPackages.size()); 7359 for (PackageParser.Package p : mPackages.values()) { 7360 if (p.mExtras != null) { 7361 PackageSetting ps = (PackageSetting) p.mExtras; 7362 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7363 continue; 7364 } 7365 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7366 ps.readUserState(userId), userId); 7367 if (ai != null) { 7368 rebaseEnabledOverlays(ai, userId); 7369 ai.packageName = resolveExternalPackageNameLPr(p); 7370 list.add(ai); 7371 } 7372 } 7373 } 7374 } 7375 7376 return new ParceledListSlice<>(list); 7377 } 7378 } 7379 7380 @Override 7381 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7382 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7383 return null; 7384 } 7385 7386 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7387 "getEphemeralApplications"); 7388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7389 true /* requireFullPermission */, false /* checkShell */, 7390 "getEphemeralApplications"); 7391 synchronized (mPackages) { 7392 List<InstantAppInfo> instantApps = mInstantAppRegistry 7393 .getInstantAppsLPr(userId); 7394 if (instantApps != null) { 7395 return new ParceledListSlice<>(instantApps); 7396 } 7397 } 7398 return null; 7399 } 7400 7401 @Override 7402 public boolean isInstantApp(String packageName, int userId) { 7403 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7404 true /* requireFullPermission */, false /* checkShell */, 7405 "isInstantApp"); 7406 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7407 return false; 7408 } 7409 int uid = Binder.getCallingUid(); 7410 if (Process.isIsolated(uid)) { 7411 uid = mIsolatedOwners.get(uid); 7412 } 7413 7414 synchronized (mPackages) { 7415 final PackageSetting ps = mSettings.mPackages.get(packageName); 7416 PackageParser.Package pkg = mPackages.get(packageName); 7417 final boolean returnAllowed = 7418 ps != null 7419 && (isCallerSameApp(packageName, uid) 7420 || mContext.checkCallingOrSelfPermission( 7421 android.Manifest.permission.ACCESS_INSTANT_APPS) 7422 == PERMISSION_GRANTED 7423 || mInstantAppRegistry.isInstantAccessGranted( 7424 userId, UserHandle.getAppId(uid), ps.appId)); 7425 if (returnAllowed) { 7426 return ps.getInstantApp(userId); 7427 } 7428 } 7429 return false; 7430 } 7431 7432 @Override 7433 public byte[] getInstantAppCookie(String packageName, int userId) { 7434 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7435 return null; 7436 } 7437 7438 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7439 true /* requireFullPermission */, false /* checkShell */, 7440 "getInstantAppCookie"); 7441 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7442 return null; 7443 } 7444 synchronized (mPackages) { 7445 return mInstantAppRegistry.getInstantAppCookieLPw( 7446 packageName, userId); 7447 } 7448 } 7449 7450 @Override 7451 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7452 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7453 return true; 7454 } 7455 7456 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7457 true /* requireFullPermission */, true /* checkShell */, 7458 "setInstantAppCookie"); 7459 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7460 return false; 7461 } 7462 synchronized (mPackages) { 7463 return mInstantAppRegistry.setInstantAppCookieLPw( 7464 packageName, cookie, userId); 7465 } 7466 } 7467 7468 @Override 7469 public Bitmap getInstantAppIcon(String packageName, int userId) { 7470 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7471 return null; 7472 } 7473 7474 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7475 "getInstantAppIcon"); 7476 7477 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7478 true /* requireFullPermission */, false /* checkShell */, 7479 "getInstantAppIcon"); 7480 7481 synchronized (mPackages) { 7482 return mInstantAppRegistry.getInstantAppIconLPw( 7483 packageName, userId); 7484 } 7485 } 7486 7487 private boolean isCallerSameApp(String packageName, int uid) { 7488 PackageParser.Package pkg = mPackages.get(packageName); 7489 return pkg != null 7490 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7491 } 7492 7493 @Override 7494 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7495 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7496 } 7497 7498 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7499 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7500 7501 // reader 7502 synchronized (mPackages) { 7503 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7504 final int userId = UserHandle.getCallingUserId(); 7505 while (i.hasNext()) { 7506 final PackageParser.Package p = i.next(); 7507 if (p.applicationInfo == null) continue; 7508 7509 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7510 && !p.applicationInfo.isDirectBootAware(); 7511 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7512 && p.applicationInfo.isDirectBootAware(); 7513 7514 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7515 && (!mSafeMode || isSystemApp(p)) 7516 && (matchesUnaware || matchesAware)) { 7517 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7518 if (ps != null) { 7519 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7520 ps.readUserState(userId), userId); 7521 if (ai != null) { 7522 rebaseEnabledOverlays(ai, userId); 7523 finalList.add(ai); 7524 } 7525 } 7526 } 7527 } 7528 } 7529 7530 return finalList; 7531 } 7532 7533 @Override 7534 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7535 if (!sUserManager.exists(userId)) return null; 7536 flags = updateFlagsForComponent(flags, userId, name); 7537 // reader 7538 synchronized (mPackages) { 7539 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7540 PackageSetting ps = provider != null 7541 ? mSettings.mPackages.get(provider.owner.packageName) 7542 : null; 7543 return ps != null 7544 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7545 ? PackageParser.generateProviderInfo(provider, flags, 7546 ps.readUserState(userId), userId) 7547 : null; 7548 } 7549 } 7550 7551 /** 7552 * @deprecated 7553 */ 7554 @Deprecated 7555 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7556 // reader 7557 synchronized (mPackages) { 7558 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7559 .entrySet().iterator(); 7560 final int userId = UserHandle.getCallingUserId(); 7561 while (i.hasNext()) { 7562 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7563 PackageParser.Provider p = entry.getValue(); 7564 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7565 7566 if (ps != null && p.syncable 7567 && (!mSafeMode || (p.info.applicationInfo.flags 7568 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7569 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7570 ps.readUserState(userId), userId); 7571 if (info != null) { 7572 outNames.add(entry.getKey()); 7573 outInfo.add(info); 7574 } 7575 } 7576 } 7577 } 7578 } 7579 7580 @Override 7581 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7582 int uid, int flags, String metaDataKey) { 7583 final int userId = processName != null ? UserHandle.getUserId(uid) 7584 : UserHandle.getCallingUserId(); 7585 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7586 flags = updateFlagsForComponent(flags, userId, processName); 7587 7588 ArrayList<ProviderInfo> finalList = null; 7589 // reader 7590 synchronized (mPackages) { 7591 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7592 while (i.hasNext()) { 7593 final PackageParser.Provider p = i.next(); 7594 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7595 if (ps != null && p.info.authority != null 7596 && (processName == null 7597 || (p.info.processName.equals(processName) 7598 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7599 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7600 7601 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7602 // parameter. 7603 if (metaDataKey != null 7604 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7605 continue; 7606 } 7607 7608 if (finalList == null) { 7609 finalList = new ArrayList<ProviderInfo>(3); 7610 } 7611 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7612 ps.readUserState(userId), userId); 7613 if (info != null) { 7614 finalList.add(info); 7615 } 7616 } 7617 } 7618 } 7619 7620 if (finalList != null) { 7621 Collections.sort(finalList, mProviderInitOrderSorter); 7622 return new ParceledListSlice<ProviderInfo>(finalList); 7623 } 7624 7625 return ParceledListSlice.emptyList(); 7626 } 7627 7628 @Override 7629 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7630 // reader 7631 synchronized (mPackages) { 7632 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7633 return PackageParser.generateInstrumentationInfo(i, flags); 7634 } 7635 } 7636 7637 @Override 7638 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7639 String targetPackage, int flags) { 7640 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7641 } 7642 7643 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7644 int flags) { 7645 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7646 7647 // reader 7648 synchronized (mPackages) { 7649 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7650 while (i.hasNext()) { 7651 final PackageParser.Instrumentation p = i.next(); 7652 if (targetPackage == null 7653 || targetPackage.equals(p.info.targetPackage)) { 7654 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7655 flags); 7656 if (ii != null) { 7657 finalList.add(ii); 7658 } 7659 } 7660 } 7661 } 7662 7663 return finalList; 7664 } 7665 7666 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7667 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7668 try { 7669 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7670 } finally { 7671 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7672 } 7673 } 7674 7675 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7676 final File[] files = dir.listFiles(); 7677 if (ArrayUtils.isEmpty(files)) { 7678 Log.d(TAG, "No files in app dir " + dir); 7679 return; 7680 } 7681 7682 if (DEBUG_PACKAGE_SCANNING) { 7683 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7684 + " flags=0x" + Integer.toHexString(parseFlags)); 7685 } 7686 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7687 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7688 7689 // Submit files for parsing in parallel 7690 int fileCount = 0; 7691 for (File file : files) { 7692 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7693 && !PackageInstallerService.isStageName(file.getName()); 7694 if (!isPackage) { 7695 // Ignore entries which are not packages 7696 continue; 7697 } 7698 parallelPackageParser.submit(file, parseFlags); 7699 fileCount++; 7700 } 7701 7702 // Process results one by one 7703 for (; fileCount > 0; fileCount--) { 7704 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7705 Throwable throwable = parseResult.throwable; 7706 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7707 7708 if (throwable == null) { 7709 // Static shared libraries have synthetic package names 7710 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7711 renameStaticSharedLibraryPackage(parseResult.pkg); 7712 } 7713 try { 7714 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7715 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7716 currentTime, null); 7717 } 7718 } catch (PackageManagerException e) { 7719 errorCode = e.error; 7720 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7721 } 7722 } else if (throwable instanceof PackageParser.PackageParserException) { 7723 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7724 throwable; 7725 errorCode = e.error; 7726 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7727 } else { 7728 throw new IllegalStateException("Unexpected exception occurred while parsing " 7729 + parseResult.scanFile, throwable); 7730 } 7731 7732 // Delete invalid userdata apps 7733 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7734 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7735 logCriticalInfo(Log.WARN, 7736 "Deleting invalid package at " + parseResult.scanFile); 7737 removeCodePathLI(parseResult.scanFile); 7738 } 7739 } 7740 parallelPackageParser.close(); 7741 } 7742 7743 private static File getSettingsProblemFile() { 7744 File dataDir = Environment.getDataDirectory(); 7745 File systemDir = new File(dataDir, "system"); 7746 File fname = new File(systemDir, "uiderrors.txt"); 7747 return fname; 7748 } 7749 7750 static void reportSettingsProblem(int priority, String msg) { 7751 logCriticalInfo(priority, msg); 7752 } 7753 7754 public static void logCriticalInfo(int priority, String msg) { 7755 Slog.println(priority, TAG, msg); 7756 EventLogTags.writePmCriticalInfo(msg); 7757 try { 7758 File fname = getSettingsProblemFile(); 7759 FileOutputStream out = new FileOutputStream(fname, true); 7760 PrintWriter pw = new FastPrintWriter(out); 7761 SimpleDateFormat formatter = new SimpleDateFormat(); 7762 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7763 pw.println(dateString + ": " + msg); 7764 pw.close(); 7765 FileUtils.setPermissions( 7766 fname.toString(), 7767 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7768 -1, -1); 7769 } catch (java.io.IOException e) { 7770 } 7771 } 7772 7773 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7774 if (srcFile.isDirectory()) { 7775 final File baseFile = new File(pkg.baseCodePath); 7776 long maxModifiedTime = baseFile.lastModified(); 7777 if (pkg.splitCodePaths != null) { 7778 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7779 final File splitFile = new File(pkg.splitCodePaths[i]); 7780 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7781 } 7782 } 7783 return maxModifiedTime; 7784 } 7785 return srcFile.lastModified(); 7786 } 7787 7788 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7789 final int policyFlags) throws PackageManagerException { 7790 // When upgrading from pre-N MR1, verify the package time stamp using the package 7791 // directory and not the APK file. 7792 final long lastModifiedTime = mIsPreNMR1Upgrade 7793 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7794 if (ps != null 7795 && ps.codePath.equals(srcFile) 7796 && ps.timeStamp == lastModifiedTime 7797 && !isCompatSignatureUpdateNeeded(pkg) 7798 && !isRecoverSignatureUpdateNeeded(pkg)) { 7799 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7800 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7801 ArraySet<PublicKey> signingKs; 7802 synchronized (mPackages) { 7803 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7804 } 7805 if (ps.signatures.mSignatures != null 7806 && ps.signatures.mSignatures.length != 0 7807 && signingKs != null) { 7808 // Optimization: reuse the existing cached certificates 7809 // if the package appears to be unchanged. 7810 pkg.mSignatures = ps.signatures.mSignatures; 7811 pkg.mSigningKeys = signingKs; 7812 return; 7813 } 7814 7815 Slog.w(TAG, "PackageSetting for " + ps.name 7816 + " is missing signatures. Collecting certs again to recover them."); 7817 } else { 7818 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7819 } 7820 7821 try { 7822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7823 PackageParser.collectCertificates(pkg, policyFlags); 7824 } catch (PackageParserException e) { 7825 throw PackageManagerException.from(e); 7826 } finally { 7827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7828 } 7829 } 7830 7831 /** 7832 * Traces a package scan. 7833 * @see #scanPackageLI(File, int, int, long, UserHandle) 7834 */ 7835 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7836 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7838 try { 7839 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7840 } finally { 7841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7842 } 7843 } 7844 7845 /** 7846 * Scans a package and returns the newly parsed package. 7847 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7848 */ 7849 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7850 long currentTime, UserHandle user) throws PackageManagerException { 7851 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7852 PackageParser pp = new PackageParser(); 7853 pp.setSeparateProcesses(mSeparateProcesses); 7854 pp.setOnlyCoreApps(mOnlyCore); 7855 pp.setDisplayMetrics(mMetrics); 7856 pp.setCallback(mPackageParserCallback); 7857 7858 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7859 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7860 } 7861 7862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7863 final PackageParser.Package pkg; 7864 try { 7865 pkg = pp.parsePackage(scanFile, parseFlags); 7866 } catch (PackageParserException e) { 7867 throw PackageManagerException.from(e); 7868 } finally { 7869 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7870 } 7871 7872 // Static shared libraries have synthetic package names 7873 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7874 renameStaticSharedLibraryPackage(pkg); 7875 } 7876 7877 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7878 } 7879 7880 /** 7881 * Scans a package and returns the newly parsed package. 7882 * @throws PackageManagerException on a parse error. 7883 */ 7884 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7885 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7886 throws PackageManagerException { 7887 // If the package has children and this is the first dive in the function 7888 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7889 // packages (parent and children) would be successfully scanned before the 7890 // actual scan since scanning mutates internal state and we want to atomically 7891 // install the package and its children. 7892 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7893 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7894 scanFlags |= SCAN_CHECK_ONLY; 7895 } 7896 } else { 7897 scanFlags &= ~SCAN_CHECK_ONLY; 7898 } 7899 7900 // Scan the parent 7901 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7902 scanFlags, currentTime, user); 7903 7904 // Scan the children 7905 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7906 for (int i = 0; i < childCount; i++) { 7907 PackageParser.Package childPackage = pkg.childPackages.get(i); 7908 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7909 currentTime, user); 7910 } 7911 7912 7913 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7914 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7915 } 7916 7917 return scannedPkg; 7918 } 7919 7920 /** 7921 * Scans a package and returns the newly parsed package. 7922 * @throws PackageManagerException on a parse error. 7923 */ 7924 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7925 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7926 throws PackageManagerException { 7927 PackageSetting ps = null; 7928 PackageSetting updatedPkg; 7929 // reader 7930 synchronized (mPackages) { 7931 // Look to see if we already know about this package. 7932 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7933 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7934 // This package has been renamed to its original name. Let's 7935 // use that. 7936 ps = mSettings.getPackageLPr(oldName); 7937 } 7938 // If there was no original package, see one for the real package name. 7939 if (ps == null) { 7940 ps = mSettings.getPackageLPr(pkg.packageName); 7941 } 7942 // Check to see if this package could be hiding/updating a system 7943 // package. Must look for it either under the original or real 7944 // package name depending on our state. 7945 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7946 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7947 7948 // If this is a package we don't know about on the system partition, we 7949 // may need to remove disabled child packages on the system partition 7950 // or may need to not add child packages if the parent apk is updated 7951 // on the data partition and no longer defines this child package. 7952 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7953 // If this is a parent package for an updated system app and this system 7954 // app got an OTA update which no longer defines some of the child packages 7955 // we have to prune them from the disabled system packages. 7956 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7957 if (disabledPs != null) { 7958 final int scannedChildCount = (pkg.childPackages != null) 7959 ? pkg.childPackages.size() : 0; 7960 final int disabledChildCount = disabledPs.childPackageNames != null 7961 ? disabledPs.childPackageNames.size() : 0; 7962 for (int i = 0; i < disabledChildCount; i++) { 7963 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7964 boolean disabledPackageAvailable = false; 7965 for (int j = 0; j < scannedChildCount; j++) { 7966 PackageParser.Package childPkg = pkg.childPackages.get(j); 7967 if (childPkg.packageName.equals(disabledChildPackageName)) { 7968 disabledPackageAvailable = true; 7969 break; 7970 } 7971 } 7972 if (!disabledPackageAvailable) { 7973 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7974 } 7975 } 7976 } 7977 } 7978 } 7979 7980 boolean updatedPkgBetter = false; 7981 // First check if this is a system package that may involve an update 7982 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7983 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7984 // it needs to drop FLAG_PRIVILEGED. 7985 if (locationIsPrivileged(scanFile)) { 7986 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7987 } else { 7988 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7989 } 7990 7991 if (ps != null && !ps.codePath.equals(scanFile)) { 7992 // The path has changed from what was last scanned... check the 7993 // version of the new path against what we have stored to determine 7994 // what to do. 7995 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7996 if (pkg.mVersionCode <= ps.versionCode) { 7997 // The system package has been updated and the code path does not match 7998 // Ignore entry. Skip it. 7999 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8000 + " ignored: updated version " + ps.versionCode 8001 + " better than this " + pkg.mVersionCode); 8002 if (!updatedPkg.codePath.equals(scanFile)) { 8003 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8004 + ps.name + " changing from " + updatedPkg.codePathString 8005 + " to " + scanFile); 8006 updatedPkg.codePath = scanFile; 8007 updatedPkg.codePathString = scanFile.toString(); 8008 updatedPkg.resourcePath = scanFile; 8009 updatedPkg.resourcePathString = scanFile.toString(); 8010 } 8011 updatedPkg.pkg = pkg; 8012 updatedPkg.versionCode = pkg.mVersionCode; 8013 8014 // Update the disabled system child packages to point to the package too. 8015 final int childCount = updatedPkg.childPackageNames != null 8016 ? updatedPkg.childPackageNames.size() : 0; 8017 for (int i = 0; i < childCount; i++) { 8018 String childPackageName = updatedPkg.childPackageNames.get(i); 8019 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8020 childPackageName); 8021 if (updatedChildPkg != null) { 8022 updatedChildPkg.pkg = pkg; 8023 updatedChildPkg.versionCode = pkg.mVersionCode; 8024 } 8025 } 8026 8027 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8028 + scanFile + " ignored: updated version " + ps.versionCode 8029 + " better than this " + pkg.mVersionCode); 8030 } else { 8031 // The current app on the system partition is better than 8032 // what we have updated to on the data partition; switch 8033 // back to the system partition version. 8034 // At this point, its safely assumed that package installation for 8035 // apps in system partition will go through. If not there won't be a working 8036 // version of the app 8037 // writer 8038 synchronized (mPackages) { 8039 // Just remove the loaded entries from package lists. 8040 mPackages.remove(ps.name); 8041 } 8042 8043 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8044 + " reverting from " + ps.codePathString 8045 + ": new version " + pkg.mVersionCode 8046 + " better than installed " + ps.versionCode); 8047 8048 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8049 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8050 synchronized (mInstallLock) { 8051 args.cleanUpResourcesLI(); 8052 } 8053 synchronized (mPackages) { 8054 mSettings.enableSystemPackageLPw(ps.name); 8055 } 8056 updatedPkgBetter = true; 8057 } 8058 } 8059 } 8060 8061 if (updatedPkg != null) { 8062 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8063 // initially 8064 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8065 8066 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8067 // flag set initially 8068 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8069 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8070 } 8071 } 8072 8073 // Verify certificates against what was last scanned 8074 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8075 8076 /* 8077 * A new system app appeared, but we already had a non-system one of the 8078 * same name installed earlier. 8079 */ 8080 boolean shouldHideSystemApp = false; 8081 if (updatedPkg == null && ps != null 8082 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8083 /* 8084 * Check to make sure the signatures match first. If they don't, 8085 * wipe the installed application and its data. 8086 */ 8087 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8088 != PackageManager.SIGNATURE_MATCH) { 8089 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8090 + " signatures don't match existing userdata copy; removing"); 8091 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8092 "scanPackageInternalLI")) { 8093 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8094 } 8095 ps = null; 8096 } else { 8097 /* 8098 * If the newly-added system app is an older version than the 8099 * already installed version, hide it. It will be scanned later 8100 * and re-added like an update. 8101 */ 8102 if (pkg.mVersionCode <= ps.versionCode) { 8103 shouldHideSystemApp = true; 8104 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8105 + " but new version " + pkg.mVersionCode + " better than installed " 8106 + ps.versionCode + "; hiding system"); 8107 } else { 8108 /* 8109 * The newly found system app is a newer version that the 8110 * one previously installed. Simply remove the 8111 * already-installed application and replace it with our own 8112 * while keeping the application data. 8113 */ 8114 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8115 + " reverting from " + ps.codePathString + ": new version " 8116 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8117 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8118 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8119 synchronized (mInstallLock) { 8120 args.cleanUpResourcesLI(); 8121 } 8122 } 8123 } 8124 } 8125 8126 // The apk is forward locked (not public) if its code and resources 8127 // are kept in different files. (except for app in either system or 8128 // vendor path). 8129 // TODO grab this value from PackageSettings 8130 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8131 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8132 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8133 } 8134 } 8135 8136 // TODO: extend to support forward-locked splits 8137 String resourcePath = null; 8138 String baseResourcePath = null; 8139 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8140 if (ps != null && ps.resourcePathString != null) { 8141 resourcePath = ps.resourcePathString; 8142 baseResourcePath = ps.resourcePathString; 8143 } else { 8144 // Should not happen at all. Just log an error. 8145 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8146 } 8147 } else { 8148 resourcePath = pkg.codePath; 8149 baseResourcePath = pkg.baseCodePath; 8150 } 8151 8152 // Set application objects path explicitly. 8153 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8154 pkg.setApplicationInfoCodePath(pkg.codePath); 8155 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8156 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8157 pkg.setApplicationInfoResourcePath(resourcePath); 8158 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8159 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8160 8161 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8162 if (ps != null && ps.getInstantApp(userId)) { 8163 scanFlags |= SCAN_AS_INSTANT_APP; 8164 } 8165 8166 // Note that we invoke the following method only if we are about to unpack an application 8167 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8168 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8169 8170 /* 8171 * If the system app should be overridden by a previously installed 8172 * data, hide the system app now and let the /data/app scan pick it up 8173 * again. 8174 */ 8175 if (shouldHideSystemApp) { 8176 synchronized (mPackages) { 8177 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8178 } 8179 } 8180 8181 return scannedPkg; 8182 } 8183 8184 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8185 // Derive the new package synthetic package name 8186 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8187 + pkg.staticSharedLibVersion); 8188 } 8189 8190 private static String fixProcessName(String defProcessName, 8191 String processName) { 8192 if (processName == null) { 8193 return defProcessName; 8194 } 8195 return processName; 8196 } 8197 8198 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8199 throws PackageManagerException { 8200 if (pkgSetting.signatures.mSignatures != null) { 8201 // Already existing package. Make sure signatures match 8202 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8203 == PackageManager.SIGNATURE_MATCH; 8204 if (!match) { 8205 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8206 == PackageManager.SIGNATURE_MATCH; 8207 } 8208 if (!match) { 8209 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8210 == PackageManager.SIGNATURE_MATCH; 8211 } 8212 if (!match) { 8213 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8214 + pkg.packageName + " signatures do not match the " 8215 + "previously installed version; ignoring!"); 8216 } 8217 } 8218 8219 // Check for shared user signatures 8220 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8221 // Already existing package. Make sure signatures match 8222 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8223 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8224 if (!match) { 8225 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8226 == PackageManager.SIGNATURE_MATCH; 8227 } 8228 if (!match) { 8229 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8230 == PackageManager.SIGNATURE_MATCH; 8231 } 8232 if (!match) { 8233 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8234 "Package " + pkg.packageName 8235 + " has no signatures that match those in shared user " 8236 + pkgSetting.sharedUser.name + "; ignoring!"); 8237 } 8238 } 8239 } 8240 8241 /** 8242 * Enforces that only the system UID or root's UID can call a method exposed 8243 * via Binder. 8244 * 8245 * @param message used as message if SecurityException is thrown 8246 * @throws SecurityException if the caller is not system or root 8247 */ 8248 private static final void enforceSystemOrRoot(String message) { 8249 final int uid = Binder.getCallingUid(); 8250 if (uid != Process.SYSTEM_UID && uid != 0) { 8251 throw new SecurityException(message); 8252 } 8253 } 8254 8255 @Override 8256 public void performFstrimIfNeeded() { 8257 enforceSystemOrRoot("Only the system can request fstrim"); 8258 8259 // Before everything else, see whether we need to fstrim. 8260 try { 8261 IStorageManager sm = PackageHelper.getStorageManager(); 8262 if (sm != null) { 8263 boolean doTrim = false; 8264 final long interval = android.provider.Settings.Global.getLong( 8265 mContext.getContentResolver(), 8266 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8267 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8268 if (interval > 0) { 8269 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8270 if (timeSinceLast > interval) { 8271 doTrim = true; 8272 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8273 + "; running immediately"); 8274 } 8275 } 8276 if (doTrim) { 8277 final boolean dexOptDialogShown; 8278 synchronized (mPackages) { 8279 dexOptDialogShown = mDexOptDialogShown; 8280 } 8281 if (!isFirstBoot() && dexOptDialogShown) { 8282 try { 8283 ActivityManager.getService().showBootMessage( 8284 mContext.getResources().getString( 8285 R.string.android_upgrading_fstrim), true); 8286 } catch (RemoteException e) { 8287 } 8288 } 8289 sm.runMaintenance(); 8290 } 8291 } else { 8292 Slog.e(TAG, "storageManager service unavailable!"); 8293 } 8294 } catch (RemoteException e) { 8295 // Can't happen; StorageManagerService is local 8296 } 8297 } 8298 8299 @Override 8300 public void updatePackagesIfNeeded() { 8301 enforceSystemOrRoot("Only the system can request package update"); 8302 8303 // We need to re-extract after an OTA. 8304 boolean causeUpgrade = isUpgrade(); 8305 8306 // First boot or factory reset. 8307 // Note: we also handle devices that are upgrading to N right now as if it is their 8308 // first boot, as they do not have profile data. 8309 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8310 8311 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8312 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8313 8314 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8315 return; 8316 } 8317 8318 List<PackageParser.Package> pkgs; 8319 synchronized (mPackages) { 8320 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8321 } 8322 8323 final long startTime = System.nanoTime(); 8324 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8325 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8326 8327 final int elapsedTimeSeconds = 8328 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8329 8330 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8331 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8332 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8333 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8334 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8335 } 8336 8337 /** 8338 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8339 * containing statistics about the invocation. The array consists of three elements, 8340 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8341 * and {@code numberOfPackagesFailed}. 8342 */ 8343 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8344 String compilerFilter) { 8345 8346 int numberOfPackagesVisited = 0; 8347 int numberOfPackagesOptimized = 0; 8348 int numberOfPackagesSkipped = 0; 8349 int numberOfPackagesFailed = 0; 8350 final int numberOfPackagesToDexopt = pkgs.size(); 8351 8352 for (PackageParser.Package pkg : pkgs) { 8353 numberOfPackagesVisited++; 8354 8355 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8356 if (DEBUG_DEXOPT) { 8357 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8358 } 8359 numberOfPackagesSkipped++; 8360 continue; 8361 } 8362 8363 if (DEBUG_DEXOPT) { 8364 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8365 numberOfPackagesToDexopt + ": " + pkg.packageName); 8366 } 8367 8368 if (showDialog) { 8369 try { 8370 ActivityManager.getService().showBootMessage( 8371 mContext.getResources().getString(R.string.android_upgrading_apk, 8372 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8373 } catch (RemoteException e) { 8374 } 8375 synchronized (mPackages) { 8376 mDexOptDialogShown = true; 8377 } 8378 } 8379 8380 // If the OTA updates a system app which was previously preopted to a non-preopted state 8381 // the app might end up being verified at runtime. That's because by default the apps 8382 // are verify-profile but for preopted apps there's no profile. 8383 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8384 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8385 // filter (by default interpret-only). 8386 // Note that at this stage unused apps are already filtered. 8387 if (isSystemApp(pkg) && 8388 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8389 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8390 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8391 } 8392 8393 // checkProfiles is false to avoid merging profiles during boot which 8394 // might interfere with background compilation (b/28612421). 8395 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8396 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8397 // trade-off worth doing to save boot time work. 8398 int dexOptStatus = performDexOptTraced(pkg.packageName, 8399 false /* checkProfiles */, 8400 compilerFilter, 8401 false /* force */); 8402 switch (dexOptStatus) { 8403 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8404 numberOfPackagesOptimized++; 8405 break; 8406 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8407 numberOfPackagesSkipped++; 8408 break; 8409 case PackageDexOptimizer.DEX_OPT_FAILED: 8410 numberOfPackagesFailed++; 8411 break; 8412 default: 8413 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8414 break; 8415 } 8416 } 8417 8418 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8419 numberOfPackagesFailed }; 8420 } 8421 8422 @Override 8423 public void notifyPackageUse(String packageName, int reason) { 8424 synchronized (mPackages) { 8425 PackageParser.Package p = mPackages.get(packageName); 8426 if (p == null) { 8427 return; 8428 } 8429 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8430 } 8431 } 8432 8433 @Override 8434 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8435 int userId = UserHandle.getCallingUserId(); 8436 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8437 if (ai == null) { 8438 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8439 + loadingPackageName + ", user=" + userId); 8440 return; 8441 } 8442 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8443 } 8444 8445 // TODO: this is not used nor needed. Delete it. 8446 @Override 8447 public boolean performDexOptIfNeeded(String packageName) { 8448 int dexOptStatus = performDexOptTraced(packageName, 8449 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8450 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8451 } 8452 8453 @Override 8454 public boolean performDexOpt(String packageName, 8455 boolean checkProfiles, int compileReason, boolean force) { 8456 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8457 getCompilerFilterForReason(compileReason), force); 8458 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8459 } 8460 8461 @Override 8462 public boolean performDexOptMode(String packageName, 8463 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8464 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8465 targetCompilerFilter, force); 8466 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8467 } 8468 8469 private int performDexOptTraced(String packageName, 8470 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8472 try { 8473 return performDexOptInternal(packageName, checkProfiles, 8474 targetCompilerFilter, force); 8475 } finally { 8476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8477 } 8478 } 8479 8480 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8481 // if the package can now be considered up to date for the given filter. 8482 private int performDexOptInternal(String packageName, 8483 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8484 PackageParser.Package p; 8485 synchronized (mPackages) { 8486 p = mPackages.get(packageName); 8487 if (p == null) { 8488 // Package could not be found. Report failure. 8489 return PackageDexOptimizer.DEX_OPT_FAILED; 8490 } 8491 mPackageUsage.maybeWriteAsync(mPackages); 8492 mCompilerStats.maybeWriteAsync(); 8493 } 8494 long callingId = Binder.clearCallingIdentity(); 8495 try { 8496 synchronized (mInstallLock) { 8497 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8498 targetCompilerFilter, force); 8499 } 8500 } finally { 8501 Binder.restoreCallingIdentity(callingId); 8502 } 8503 } 8504 8505 public ArraySet<String> getOptimizablePackages() { 8506 ArraySet<String> pkgs = new ArraySet<String>(); 8507 synchronized (mPackages) { 8508 for (PackageParser.Package p : mPackages.values()) { 8509 if (PackageDexOptimizer.canOptimizePackage(p)) { 8510 pkgs.add(p.packageName); 8511 } 8512 } 8513 } 8514 return pkgs; 8515 } 8516 8517 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8518 boolean checkProfiles, String targetCompilerFilter, 8519 boolean force) { 8520 // Select the dex optimizer based on the force parameter. 8521 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8522 // allocate an object here. 8523 PackageDexOptimizer pdo = force 8524 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8525 : mPackageDexOptimizer; 8526 8527 // Dexopt all dependencies first. Note: we ignore the return value and march on 8528 // on errors. 8529 // Note that we are going to call performDexOpt on those libraries as many times as 8530 // they are referenced in packages. When we do a batch of performDexOpt (for example 8531 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8532 // and the first package that uses the library will dexopt it. The 8533 // others will see that the compiled code for the library is up to date. 8534 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8535 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8536 if (!deps.isEmpty()) { 8537 for (PackageParser.Package depPackage : deps) { 8538 // TODO: Analyze and investigate if we (should) profile libraries. 8539 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8540 false /* checkProfiles */, 8541 targetCompilerFilter, 8542 getOrCreateCompilerPackageStats(depPackage), 8543 true /* isUsedByOtherApps */); 8544 } 8545 } 8546 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8547 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8548 mDexManager.isUsedByOtherApps(p.packageName)); 8549 } 8550 8551 // Performs dexopt on the used secondary dex files belonging to the given package. 8552 // Returns true if all dex files were process successfully (which could mean either dexopt or 8553 // skip). Returns false if any of the files caused errors. 8554 @Override 8555 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8556 boolean force) { 8557 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8558 } 8559 8560 public boolean performDexOptSecondary(String packageName, int compileReason, 8561 boolean force) { 8562 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8563 } 8564 8565 /** 8566 * Reconcile the information we have about the secondary dex files belonging to 8567 * {@code packagName} and the actual dex files. For all dex files that were 8568 * deleted, update the internal records and delete the generated oat files. 8569 */ 8570 @Override 8571 public void reconcileSecondaryDexFiles(String packageName) { 8572 mDexManager.reconcileSecondaryDexFiles(packageName); 8573 } 8574 8575 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8576 // a reference there. 8577 /*package*/ DexManager getDexManager() { 8578 return mDexManager; 8579 } 8580 8581 /** 8582 * Execute the background dexopt job immediately. 8583 */ 8584 @Override 8585 public boolean runBackgroundDexoptJob() { 8586 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8587 } 8588 8589 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8590 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8591 || p.usesStaticLibraries != null) { 8592 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8593 Set<String> collectedNames = new HashSet<>(); 8594 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8595 8596 retValue.remove(p); 8597 8598 return retValue; 8599 } else { 8600 return Collections.emptyList(); 8601 } 8602 } 8603 8604 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8605 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8606 if (!collectedNames.contains(p.packageName)) { 8607 collectedNames.add(p.packageName); 8608 collected.add(p); 8609 8610 if (p.usesLibraries != null) { 8611 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8612 null, collected, collectedNames); 8613 } 8614 if (p.usesOptionalLibraries != null) { 8615 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8616 null, collected, collectedNames); 8617 } 8618 if (p.usesStaticLibraries != null) { 8619 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8620 p.usesStaticLibrariesVersions, collected, collectedNames); 8621 } 8622 } 8623 } 8624 8625 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8626 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8627 final int libNameCount = libs.size(); 8628 for (int i = 0; i < libNameCount; i++) { 8629 String libName = libs.get(i); 8630 int version = (versions != null && versions.length == libNameCount) 8631 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8632 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8633 if (libPkg != null) { 8634 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8635 } 8636 } 8637 } 8638 8639 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8640 synchronized (mPackages) { 8641 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8642 if (libEntry != null) { 8643 return mPackages.get(libEntry.apk); 8644 } 8645 return null; 8646 } 8647 } 8648 8649 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8650 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8651 if (versionedLib == null) { 8652 return null; 8653 } 8654 return versionedLib.get(version); 8655 } 8656 8657 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8658 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8659 pkg.staticSharedLibName); 8660 if (versionedLib == null) { 8661 return null; 8662 } 8663 int previousLibVersion = -1; 8664 final int versionCount = versionedLib.size(); 8665 for (int i = 0; i < versionCount; i++) { 8666 final int libVersion = versionedLib.keyAt(i); 8667 if (libVersion < pkg.staticSharedLibVersion) { 8668 previousLibVersion = Math.max(previousLibVersion, libVersion); 8669 } 8670 } 8671 if (previousLibVersion >= 0) { 8672 return versionedLib.get(previousLibVersion); 8673 } 8674 return null; 8675 } 8676 8677 public void shutdown() { 8678 mPackageUsage.writeNow(mPackages); 8679 mCompilerStats.writeNow(); 8680 } 8681 8682 @Override 8683 public void dumpProfiles(String packageName) { 8684 PackageParser.Package pkg; 8685 synchronized (mPackages) { 8686 pkg = mPackages.get(packageName); 8687 if (pkg == null) { 8688 throw new IllegalArgumentException("Unknown package: " + packageName); 8689 } 8690 } 8691 /* Only the shell, root, or the app user should be able to dump profiles. */ 8692 int callingUid = Binder.getCallingUid(); 8693 if (callingUid != Process.SHELL_UID && 8694 callingUid != Process.ROOT_UID && 8695 callingUid != pkg.applicationInfo.uid) { 8696 throw new SecurityException("dumpProfiles"); 8697 } 8698 8699 synchronized (mInstallLock) { 8700 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8701 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8702 try { 8703 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8704 String codePaths = TextUtils.join(";", allCodePaths); 8705 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8706 } catch (InstallerException e) { 8707 Slog.w(TAG, "Failed to dump profiles", e); 8708 } 8709 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8710 } 8711 } 8712 8713 @Override 8714 public void forceDexOpt(String packageName) { 8715 enforceSystemOrRoot("forceDexOpt"); 8716 8717 PackageParser.Package pkg; 8718 synchronized (mPackages) { 8719 pkg = mPackages.get(packageName); 8720 if (pkg == null) { 8721 throw new IllegalArgumentException("Unknown package: " + packageName); 8722 } 8723 } 8724 8725 synchronized (mInstallLock) { 8726 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8727 8728 // Whoever is calling forceDexOpt wants a fully compiled package. 8729 // Don't use profiles since that may cause compilation to be skipped. 8730 final int res = performDexOptInternalWithDependenciesLI(pkg, 8731 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8732 true /* force */); 8733 8734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8735 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8736 throw new IllegalStateException("Failed to dexopt: " + res); 8737 } 8738 } 8739 } 8740 8741 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8742 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8743 Slog.w(TAG, "Unable to update from " + oldPkg.name 8744 + " to " + newPkg.packageName 8745 + ": old package not in system partition"); 8746 return false; 8747 } else if (mPackages.get(oldPkg.name) != null) { 8748 Slog.w(TAG, "Unable to update from " + oldPkg.name 8749 + " to " + newPkg.packageName 8750 + ": old package still exists"); 8751 return false; 8752 } 8753 return true; 8754 } 8755 8756 void removeCodePathLI(File codePath) { 8757 if (codePath.isDirectory()) { 8758 try { 8759 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8760 } catch (InstallerException e) { 8761 Slog.w(TAG, "Failed to remove code path", e); 8762 } 8763 } else { 8764 codePath.delete(); 8765 } 8766 } 8767 8768 private int[] resolveUserIds(int userId) { 8769 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8770 } 8771 8772 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8773 if (pkg == null) { 8774 Slog.wtf(TAG, "Package was null!", new Throwable()); 8775 return; 8776 } 8777 clearAppDataLeafLIF(pkg, userId, flags); 8778 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8779 for (int i = 0; i < childCount; i++) { 8780 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8781 } 8782 } 8783 8784 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8785 final PackageSetting ps; 8786 synchronized (mPackages) { 8787 ps = mSettings.mPackages.get(pkg.packageName); 8788 } 8789 for (int realUserId : resolveUserIds(userId)) { 8790 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8791 try { 8792 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8793 ceDataInode); 8794 } catch (InstallerException e) { 8795 Slog.w(TAG, String.valueOf(e)); 8796 } 8797 } 8798 } 8799 8800 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8801 if (pkg == null) { 8802 Slog.wtf(TAG, "Package was null!", new Throwable()); 8803 return; 8804 } 8805 destroyAppDataLeafLIF(pkg, userId, flags); 8806 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8807 for (int i = 0; i < childCount; i++) { 8808 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8809 } 8810 } 8811 8812 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8813 final PackageSetting ps; 8814 synchronized (mPackages) { 8815 ps = mSettings.mPackages.get(pkg.packageName); 8816 } 8817 for (int realUserId : resolveUserIds(userId)) { 8818 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8819 try { 8820 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8821 ceDataInode); 8822 } catch (InstallerException e) { 8823 Slog.w(TAG, String.valueOf(e)); 8824 } 8825 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8826 } 8827 } 8828 8829 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8830 if (pkg == null) { 8831 Slog.wtf(TAG, "Package was null!", new Throwable()); 8832 return; 8833 } 8834 destroyAppProfilesLeafLIF(pkg); 8835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8836 for (int i = 0; i < childCount; i++) { 8837 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8838 } 8839 } 8840 8841 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8842 try { 8843 mInstaller.destroyAppProfiles(pkg.packageName); 8844 } catch (InstallerException e) { 8845 Slog.w(TAG, String.valueOf(e)); 8846 } 8847 } 8848 8849 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8850 if (pkg == null) { 8851 Slog.wtf(TAG, "Package was null!", new Throwable()); 8852 return; 8853 } 8854 clearAppProfilesLeafLIF(pkg); 8855 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8856 for (int i = 0; i < childCount; i++) { 8857 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8858 } 8859 } 8860 8861 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8862 try { 8863 mInstaller.clearAppProfiles(pkg.packageName); 8864 } catch (InstallerException e) { 8865 Slog.w(TAG, String.valueOf(e)); 8866 } 8867 } 8868 8869 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8870 long lastUpdateTime) { 8871 // Set parent install/update time 8872 PackageSetting ps = (PackageSetting) pkg.mExtras; 8873 if (ps != null) { 8874 ps.firstInstallTime = firstInstallTime; 8875 ps.lastUpdateTime = lastUpdateTime; 8876 } 8877 // Set children install/update time 8878 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8879 for (int i = 0; i < childCount; i++) { 8880 PackageParser.Package childPkg = pkg.childPackages.get(i); 8881 ps = (PackageSetting) childPkg.mExtras; 8882 if (ps != null) { 8883 ps.firstInstallTime = firstInstallTime; 8884 ps.lastUpdateTime = lastUpdateTime; 8885 } 8886 } 8887 } 8888 8889 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8890 PackageParser.Package changingLib) { 8891 if (file.path != null) { 8892 usesLibraryFiles.add(file.path); 8893 return; 8894 } 8895 PackageParser.Package p = mPackages.get(file.apk); 8896 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8897 // If we are doing this while in the middle of updating a library apk, 8898 // then we need to make sure to use that new apk for determining the 8899 // dependencies here. (We haven't yet finished committing the new apk 8900 // to the package manager state.) 8901 if (p == null || p.packageName.equals(changingLib.packageName)) { 8902 p = changingLib; 8903 } 8904 } 8905 if (p != null) { 8906 usesLibraryFiles.addAll(p.getAllCodePaths()); 8907 } 8908 } 8909 8910 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8911 PackageParser.Package changingLib) throws PackageManagerException { 8912 if (pkg == null) { 8913 return; 8914 } 8915 ArraySet<String> usesLibraryFiles = null; 8916 if (pkg.usesLibraries != null) { 8917 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8918 null, null, pkg.packageName, changingLib, true, null); 8919 } 8920 if (pkg.usesStaticLibraries != null) { 8921 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8922 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8923 pkg.packageName, changingLib, true, usesLibraryFiles); 8924 } 8925 if (pkg.usesOptionalLibraries != null) { 8926 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8927 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8928 } 8929 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8930 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8931 } else { 8932 pkg.usesLibraryFiles = null; 8933 } 8934 } 8935 8936 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8937 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8938 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8939 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8940 throws PackageManagerException { 8941 final int libCount = requestedLibraries.size(); 8942 for (int i = 0; i < libCount; i++) { 8943 final String libName = requestedLibraries.get(i); 8944 final int libVersion = requiredVersions != null ? requiredVersions[i] 8945 : SharedLibraryInfo.VERSION_UNDEFINED; 8946 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8947 if (libEntry == null) { 8948 if (required) { 8949 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8950 "Package " + packageName + " requires unavailable shared library " 8951 + libName + "; failing!"); 8952 } else { 8953 Slog.w(TAG, "Package " + packageName 8954 + " desires unavailable shared library " 8955 + libName + "; ignoring!"); 8956 } 8957 } else { 8958 if (requiredVersions != null && requiredCertDigests != null) { 8959 if (libEntry.info.getVersion() != requiredVersions[i]) { 8960 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8961 "Package " + packageName + " requires unavailable static shared" 8962 + " library " + libName + " version " 8963 + libEntry.info.getVersion() + "; failing!"); 8964 } 8965 8966 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8967 if (libPkg == null) { 8968 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8969 "Package " + packageName + " requires unavailable static shared" 8970 + " library; failing!"); 8971 } 8972 8973 String expectedCertDigest = requiredCertDigests[i]; 8974 String libCertDigest = PackageUtils.computeCertSha256Digest( 8975 libPkg.mSignatures[0]); 8976 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8977 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8978 "Package " + packageName + " requires differently signed" + 8979 " static shared library; failing!"); 8980 } 8981 } 8982 8983 if (outUsedLibraries == null) { 8984 outUsedLibraries = new ArraySet<>(); 8985 } 8986 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8987 } 8988 } 8989 return outUsedLibraries; 8990 } 8991 8992 private static boolean hasString(List<String> list, List<String> which) { 8993 if (list == null) { 8994 return false; 8995 } 8996 for (int i=list.size()-1; i>=0; i--) { 8997 for (int j=which.size()-1; j>=0; j--) { 8998 if (which.get(j).equals(list.get(i))) { 8999 return true; 9000 } 9001 } 9002 } 9003 return false; 9004 } 9005 9006 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9007 PackageParser.Package changingPkg) { 9008 ArrayList<PackageParser.Package> res = null; 9009 for (PackageParser.Package pkg : mPackages.values()) { 9010 if (changingPkg != null 9011 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9012 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9013 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9014 changingPkg.staticSharedLibName)) { 9015 return null; 9016 } 9017 if (res == null) { 9018 res = new ArrayList<>(); 9019 } 9020 res.add(pkg); 9021 try { 9022 updateSharedLibrariesLPr(pkg, changingPkg); 9023 } catch (PackageManagerException e) { 9024 // If a system app update or an app and a required lib missing we 9025 // delete the package and for updated system apps keep the data as 9026 // it is better for the user to reinstall than to be in an limbo 9027 // state. Also libs disappearing under an app should never happen 9028 // - just in case. 9029 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9030 final int flags = pkg.isUpdatedSystemApp() 9031 ? PackageManager.DELETE_KEEP_DATA : 0; 9032 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9033 flags , null, true, null); 9034 } 9035 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9036 } 9037 } 9038 return res; 9039 } 9040 9041 /** 9042 * Derive the value of the {@code cpuAbiOverride} based on the provided 9043 * value and an optional stored value from the package settings. 9044 */ 9045 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9046 String cpuAbiOverride = null; 9047 9048 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9049 cpuAbiOverride = null; 9050 } else if (abiOverride != null) { 9051 cpuAbiOverride = abiOverride; 9052 } else if (settings != null) { 9053 cpuAbiOverride = settings.cpuAbiOverrideString; 9054 } 9055 9056 return cpuAbiOverride; 9057 } 9058 9059 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9060 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9061 throws PackageManagerException { 9062 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9063 // If the package has children and this is the first dive in the function 9064 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9065 // whether all packages (parent and children) would be successfully scanned 9066 // before the actual scan since scanning mutates internal state and we want 9067 // to atomically install the package and its children. 9068 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9069 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9070 scanFlags |= SCAN_CHECK_ONLY; 9071 } 9072 } else { 9073 scanFlags &= ~SCAN_CHECK_ONLY; 9074 } 9075 9076 final PackageParser.Package scannedPkg; 9077 try { 9078 // Scan the parent 9079 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9080 // Scan the children 9081 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9082 for (int i = 0; i < childCount; i++) { 9083 PackageParser.Package childPkg = pkg.childPackages.get(i); 9084 scanPackageLI(childPkg, policyFlags, 9085 scanFlags, currentTime, user); 9086 } 9087 } finally { 9088 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9089 } 9090 9091 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9092 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9093 } 9094 9095 return scannedPkg; 9096 } 9097 9098 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9099 int scanFlags, long currentTime, @Nullable UserHandle user) 9100 throws PackageManagerException { 9101 boolean success = false; 9102 try { 9103 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9104 currentTime, user); 9105 success = true; 9106 return res; 9107 } finally { 9108 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9109 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9110 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9111 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9112 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9113 } 9114 } 9115 } 9116 9117 /** 9118 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9119 */ 9120 private static boolean apkHasCode(String fileName) { 9121 StrictJarFile jarFile = null; 9122 try { 9123 jarFile = new StrictJarFile(fileName, 9124 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9125 return jarFile.findEntry("classes.dex") != null; 9126 } catch (IOException ignore) { 9127 } finally { 9128 try { 9129 if (jarFile != null) { 9130 jarFile.close(); 9131 } 9132 } catch (IOException ignore) {} 9133 } 9134 return false; 9135 } 9136 9137 /** 9138 * Enforces code policy for the package. This ensures that if an APK has 9139 * declared hasCode="true" in its manifest that the APK actually contains 9140 * code. 9141 * 9142 * @throws PackageManagerException If bytecode could not be found when it should exist 9143 */ 9144 private static void assertCodePolicy(PackageParser.Package pkg) 9145 throws PackageManagerException { 9146 final boolean shouldHaveCode = 9147 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9148 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9149 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9150 "Package " + pkg.baseCodePath + " code is missing"); 9151 } 9152 9153 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9154 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9155 final boolean splitShouldHaveCode = 9156 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9157 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9158 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9159 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9160 } 9161 } 9162 } 9163 } 9164 9165 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9166 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9167 throws PackageManagerException { 9168 if (DEBUG_PACKAGE_SCANNING) { 9169 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9170 Log.d(TAG, "Scanning package " + pkg.packageName); 9171 } 9172 9173 applyPolicy(pkg, policyFlags); 9174 9175 assertPackageIsValid(pkg, policyFlags, scanFlags); 9176 9177 // Initialize package source and resource directories 9178 final File scanFile = new File(pkg.codePath); 9179 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9180 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9181 9182 SharedUserSetting suid = null; 9183 PackageSetting pkgSetting = null; 9184 9185 // Getting the package setting may have a side-effect, so if we 9186 // are only checking if scan would succeed, stash a copy of the 9187 // old setting to restore at the end. 9188 PackageSetting nonMutatedPs = null; 9189 9190 // We keep references to the derived CPU Abis from settings in oder to reuse 9191 // them in the case where we're not upgrading or booting for the first time. 9192 String primaryCpuAbiFromSettings = null; 9193 String secondaryCpuAbiFromSettings = null; 9194 9195 // writer 9196 synchronized (mPackages) { 9197 if (pkg.mSharedUserId != null) { 9198 // SIDE EFFECTS; may potentially allocate a new shared user 9199 suid = mSettings.getSharedUserLPw( 9200 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9201 if (DEBUG_PACKAGE_SCANNING) { 9202 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9203 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9204 + "): packages=" + suid.packages); 9205 } 9206 } 9207 9208 // Check if we are renaming from an original package name. 9209 PackageSetting origPackage = null; 9210 String realName = null; 9211 if (pkg.mOriginalPackages != null) { 9212 // This package may need to be renamed to a previously 9213 // installed name. Let's check on that... 9214 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9215 if (pkg.mOriginalPackages.contains(renamed)) { 9216 // This package had originally been installed as the 9217 // original name, and we have already taken care of 9218 // transitioning to the new one. Just update the new 9219 // one to continue using the old name. 9220 realName = pkg.mRealPackage; 9221 if (!pkg.packageName.equals(renamed)) { 9222 // Callers into this function may have already taken 9223 // care of renaming the package; only do it here if 9224 // it is not already done. 9225 pkg.setPackageName(renamed); 9226 } 9227 } else { 9228 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9229 if ((origPackage = mSettings.getPackageLPr( 9230 pkg.mOriginalPackages.get(i))) != null) { 9231 // We do have the package already installed under its 9232 // original name... should we use it? 9233 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9234 // New package is not compatible with original. 9235 origPackage = null; 9236 continue; 9237 } else if (origPackage.sharedUser != null) { 9238 // Make sure uid is compatible between packages. 9239 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9240 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9241 + " to " + pkg.packageName + ": old uid " 9242 + origPackage.sharedUser.name 9243 + " differs from " + pkg.mSharedUserId); 9244 origPackage = null; 9245 continue; 9246 } 9247 // TODO: Add case when shared user id is added [b/28144775] 9248 } else { 9249 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9250 + pkg.packageName + " to old name " + origPackage.name); 9251 } 9252 break; 9253 } 9254 } 9255 } 9256 } 9257 9258 if (mTransferedPackages.contains(pkg.packageName)) { 9259 Slog.w(TAG, "Package " + pkg.packageName 9260 + " was transferred to another, but its .apk remains"); 9261 } 9262 9263 // See comments in nonMutatedPs declaration 9264 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9265 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9266 if (foundPs != null) { 9267 nonMutatedPs = new PackageSetting(foundPs); 9268 } 9269 } 9270 9271 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9272 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9273 if (foundPs != null) { 9274 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9275 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9276 } 9277 } 9278 9279 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9280 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9281 PackageManagerService.reportSettingsProblem(Log.WARN, 9282 "Package " + pkg.packageName + " shared user changed from " 9283 + (pkgSetting.sharedUser != null 9284 ? pkgSetting.sharedUser.name : "<nothing>") 9285 + " to " 9286 + (suid != null ? suid.name : "<nothing>") 9287 + "; replacing with new"); 9288 pkgSetting = null; 9289 } 9290 final PackageSetting oldPkgSetting = 9291 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9292 final PackageSetting disabledPkgSetting = 9293 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9294 9295 String[] usesStaticLibraries = null; 9296 if (pkg.usesStaticLibraries != null) { 9297 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9298 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9299 } 9300 9301 if (pkgSetting == null) { 9302 final String parentPackageName = (pkg.parentPackage != null) 9303 ? pkg.parentPackage.packageName : null; 9304 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9305 // REMOVE SharedUserSetting from method; update in a separate call 9306 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9307 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9308 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9309 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9310 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9311 true /*allowInstall*/, instantApp, parentPackageName, 9312 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9313 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9314 // SIDE EFFECTS; updates system state; move elsewhere 9315 if (origPackage != null) { 9316 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9317 } 9318 mSettings.addUserToSettingLPw(pkgSetting); 9319 } else { 9320 // REMOVE SharedUserSetting from method; update in a separate call. 9321 // 9322 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9323 // secondaryCpuAbi are not known at this point so we always update them 9324 // to null here, only to reset them at a later point. 9325 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9326 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9327 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9328 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9329 UserManagerService.getInstance(), usesStaticLibraries, 9330 pkg.usesStaticLibrariesVersions); 9331 } 9332 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9333 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9334 9335 // SIDE EFFECTS; modifies system state; move elsewhere 9336 if (pkgSetting.origPackage != null) { 9337 // If we are first transitioning from an original package, 9338 // fix up the new package's name now. We need to do this after 9339 // looking up the package under its new name, so getPackageLP 9340 // can take care of fiddling things correctly. 9341 pkg.setPackageName(origPackage.name); 9342 9343 // File a report about this. 9344 String msg = "New package " + pkgSetting.realName 9345 + " renamed to replace old package " + pkgSetting.name; 9346 reportSettingsProblem(Log.WARN, msg); 9347 9348 // Make a note of it. 9349 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9350 mTransferedPackages.add(origPackage.name); 9351 } 9352 9353 // No longer need to retain this. 9354 pkgSetting.origPackage = null; 9355 } 9356 9357 // SIDE EFFECTS; modifies system state; move elsewhere 9358 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9359 // Make a note of it. 9360 mTransferedPackages.add(pkg.packageName); 9361 } 9362 9363 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9364 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9365 } 9366 9367 if ((scanFlags & SCAN_BOOTING) == 0 9368 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9369 // Check all shared libraries and map to their actual file path. 9370 // We only do this here for apps not on a system dir, because those 9371 // are the only ones that can fail an install due to this. We 9372 // will take care of the system apps by updating all of their 9373 // library paths after the scan is done. Also during the initial 9374 // scan don't update any libs as we do this wholesale after all 9375 // apps are scanned to avoid dependency based scanning. 9376 updateSharedLibrariesLPr(pkg, null); 9377 } 9378 9379 if (mFoundPolicyFile) { 9380 SELinuxMMAC.assignSeInfoValue(pkg); 9381 } 9382 pkg.applicationInfo.uid = pkgSetting.appId; 9383 pkg.mExtras = pkgSetting; 9384 9385 9386 // Static shared libs have same package with different versions where 9387 // we internally use a synthetic package name to allow multiple versions 9388 // of the same package, therefore we need to compare signatures against 9389 // the package setting for the latest library version. 9390 PackageSetting signatureCheckPs = pkgSetting; 9391 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9392 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9393 if (libraryEntry != null) { 9394 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9395 } 9396 } 9397 9398 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9399 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9400 // We just determined the app is signed correctly, so bring 9401 // over the latest parsed certs. 9402 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9403 } else { 9404 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9405 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9406 "Package " + pkg.packageName + " upgrade keys do not match the " 9407 + "previously installed version"); 9408 } else { 9409 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9410 String msg = "System package " + pkg.packageName 9411 + " signature changed; retaining data."; 9412 reportSettingsProblem(Log.WARN, msg); 9413 } 9414 } 9415 } else { 9416 try { 9417 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9418 verifySignaturesLP(signatureCheckPs, pkg); 9419 // We just determined the app is signed correctly, so bring 9420 // over the latest parsed certs. 9421 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9422 } catch (PackageManagerException e) { 9423 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9424 throw e; 9425 } 9426 // The signature has changed, but this package is in the system 9427 // image... let's recover! 9428 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9429 // However... if this package is part of a shared user, but it 9430 // doesn't match the signature of the shared user, let's fail. 9431 // What this means is that you can't change the signatures 9432 // associated with an overall shared user, which doesn't seem all 9433 // that unreasonable. 9434 if (signatureCheckPs.sharedUser != null) { 9435 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9436 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9437 throw new PackageManagerException( 9438 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9439 "Signature mismatch for shared user: " 9440 + pkgSetting.sharedUser); 9441 } 9442 } 9443 // File a report about this. 9444 String msg = "System package " + pkg.packageName 9445 + " signature changed; retaining data."; 9446 reportSettingsProblem(Log.WARN, msg); 9447 } 9448 } 9449 9450 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9451 // This package wants to adopt ownership of permissions from 9452 // another package. 9453 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9454 final String origName = pkg.mAdoptPermissions.get(i); 9455 final PackageSetting orig = mSettings.getPackageLPr(origName); 9456 if (orig != null) { 9457 if (verifyPackageUpdateLPr(orig, pkg)) { 9458 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9459 + pkg.packageName); 9460 // SIDE EFFECTS; updates permissions system state; move elsewhere 9461 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9462 } 9463 } 9464 } 9465 } 9466 } 9467 9468 pkg.applicationInfo.processName = fixProcessName( 9469 pkg.applicationInfo.packageName, 9470 pkg.applicationInfo.processName); 9471 9472 if (pkg != mPlatformPackage) { 9473 // Get all of our default paths setup 9474 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9475 } 9476 9477 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9478 9479 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9480 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9481 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9482 derivePackageAbi( 9483 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9485 9486 // Some system apps still use directory structure for native libraries 9487 // in which case we might end up not detecting abi solely based on apk 9488 // structure. Try to detect abi based on directory structure. 9489 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9490 pkg.applicationInfo.primaryCpuAbi == null) { 9491 setBundledAppAbisAndRoots(pkg, pkgSetting); 9492 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9493 } 9494 } else { 9495 // This is not a first boot or an upgrade, don't bother deriving the 9496 // ABI during the scan. Instead, trust the value that was stored in the 9497 // package setting. 9498 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9499 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9500 9501 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9502 9503 if (DEBUG_ABI_SELECTION) { 9504 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9505 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9506 pkg.applicationInfo.secondaryCpuAbi); 9507 } 9508 } 9509 } else { 9510 if ((scanFlags & SCAN_MOVE) != 0) { 9511 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9512 // but we already have this packages package info in the PackageSetting. We just 9513 // use that and derive the native library path based on the new codepath. 9514 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9515 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9516 } 9517 9518 // Set native library paths again. For moves, the path will be updated based on the 9519 // ABIs we've determined above. For non-moves, the path will be updated based on the 9520 // ABIs we determined during compilation, but the path will depend on the final 9521 // package path (after the rename away from the stage path). 9522 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9523 } 9524 9525 // This is a special case for the "system" package, where the ABI is 9526 // dictated by the zygote configuration (and init.rc). We should keep track 9527 // of this ABI so that we can deal with "normal" applications that run under 9528 // the same UID correctly. 9529 if (mPlatformPackage == pkg) { 9530 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9531 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9532 } 9533 9534 // If there's a mismatch between the abi-override in the package setting 9535 // and the abiOverride specified for the install. Warn about this because we 9536 // would've already compiled the app without taking the package setting into 9537 // account. 9538 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9539 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9540 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9541 " for package " + pkg.packageName); 9542 } 9543 } 9544 9545 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9546 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9547 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9548 9549 // Copy the derived override back to the parsed package, so that we can 9550 // update the package settings accordingly. 9551 pkg.cpuAbiOverride = cpuAbiOverride; 9552 9553 if (DEBUG_ABI_SELECTION) { 9554 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9555 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9556 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9557 } 9558 9559 // Push the derived path down into PackageSettings so we know what to 9560 // clean up at uninstall time. 9561 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9562 9563 if (DEBUG_ABI_SELECTION) { 9564 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9565 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9566 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9567 } 9568 9569 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9570 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9571 // We don't do this here during boot because we can do it all 9572 // at once after scanning all existing packages. 9573 // 9574 // We also do this *before* we perform dexopt on this package, so that 9575 // we can avoid redundant dexopts, and also to make sure we've got the 9576 // code and package path correct. 9577 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9578 } 9579 9580 if (mFactoryTest && pkg.requestedPermissions.contains( 9581 android.Manifest.permission.FACTORY_TEST)) { 9582 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9583 } 9584 9585 if (isSystemApp(pkg)) { 9586 pkgSetting.isOrphaned = true; 9587 } 9588 9589 // Take care of first install / last update times. 9590 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9591 if (currentTime != 0) { 9592 if (pkgSetting.firstInstallTime == 0) { 9593 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9594 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9595 pkgSetting.lastUpdateTime = currentTime; 9596 } 9597 } else if (pkgSetting.firstInstallTime == 0) { 9598 // We need *something*. Take time time stamp of the file. 9599 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9600 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9601 if (scanFileTime != pkgSetting.timeStamp) { 9602 // A package on the system image has changed; consider this 9603 // to be an update. 9604 pkgSetting.lastUpdateTime = scanFileTime; 9605 } 9606 } 9607 pkgSetting.setTimeStamp(scanFileTime); 9608 9609 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9610 if (nonMutatedPs != null) { 9611 synchronized (mPackages) { 9612 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9613 } 9614 } 9615 } else { 9616 final int userId = user == null ? 0 : user.getIdentifier(); 9617 // Modify state for the given package setting 9618 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9619 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9620 if (pkgSetting.getInstantApp(userId)) { 9621 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9622 } 9623 } 9624 return pkg; 9625 } 9626 9627 /** 9628 * Applies policy to the parsed package based upon the given policy flags. 9629 * Ensures the package is in a good state. 9630 * <p> 9631 * Implementation detail: This method must NOT have any side effect. It would 9632 * ideally be static, but, it requires locks to read system state. 9633 */ 9634 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9635 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9636 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9637 if (pkg.applicationInfo.isDirectBootAware()) { 9638 // we're direct boot aware; set for all components 9639 for (PackageParser.Service s : pkg.services) { 9640 s.info.encryptionAware = s.info.directBootAware = true; 9641 } 9642 for (PackageParser.Provider p : pkg.providers) { 9643 p.info.encryptionAware = p.info.directBootAware = true; 9644 } 9645 for (PackageParser.Activity a : pkg.activities) { 9646 a.info.encryptionAware = a.info.directBootAware = true; 9647 } 9648 for (PackageParser.Activity r : pkg.receivers) { 9649 r.info.encryptionAware = r.info.directBootAware = true; 9650 } 9651 } 9652 } else { 9653 // Only allow system apps to be flagged as core apps. 9654 pkg.coreApp = false; 9655 // clear flags not applicable to regular apps 9656 pkg.applicationInfo.privateFlags &= 9657 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9658 pkg.applicationInfo.privateFlags &= 9659 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9660 } 9661 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9662 9663 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9664 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9665 } 9666 9667 if (!isSystemApp(pkg)) { 9668 // Only system apps can use these features. 9669 pkg.mOriginalPackages = null; 9670 pkg.mRealPackage = null; 9671 pkg.mAdoptPermissions = null; 9672 } 9673 } 9674 9675 /** 9676 * Asserts the parsed package is valid according to the given policy. If the 9677 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9678 * <p> 9679 * Implementation detail: This method must NOT have any side effects. It would 9680 * ideally be static, but, it requires locks to read system state. 9681 * 9682 * @throws PackageManagerException If the package fails any of the validation checks 9683 */ 9684 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9685 throws PackageManagerException { 9686 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9687 assertCodePolicy(pkg); 9688 } 9689 9690 if (pkg.applicationInfo.getCodePath() == null || 9691 pkg.applicationInfo.getResourcePath() == null) { 9692 // Bail out. The resource and code paths haven't been set. 9693 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9694 "Code and resource paths haven't been set correctly"); 9695 } 9696 9697 // Make sure we're not adding any bogus keyset info 9698 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9699 ksms.assertScannedPackageValid(pkg); 9700 9701 synchronized (mPackages) { 9702 // The special "android" package can only be defined once 9703 if (pkg.packageName.equals("android")) { 9704 if (mAndroidApplication != null) { 9705 Slog.w(TAG, "*************************************************"); 9706 Slog.w(TAG, "Core android package being redefined. Skipping."); 9707 Slog.w(TAG, " codePath=" + pkg.codePath); 9708 Slog.w(TAG, "*************************************************"); 9709 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9710 "Core android package being redefined. Skipping."); 9711 } 9712 } 9713 9714 // A package name must be unique; don't allow duplicates 9715 if (mPackages.containsKey(pkg.packageName)) { 9716 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9717 "Application package " + pkg.packageName 9718 + " already installed. Skipping duplicate."); 9719 } 9720 9721 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9722 // Static libs have a synthetic package name containing the version 9723 // but we still want the base name to be unique. 9724 if (mPackages.containsKey(pkg.manifestPackageName)) { 9725 throw new PackageManagerException( 9726 "Duplicate static shared lib provider package"); 9727 } 9728 9729 // Static shared libraries should have at least O target SDK 9730 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9731 throw new PackageManagerException( 9732 "Packages declaring static-shared libs must target O SDK or higher"); 9733 } 9734 9735 // Package declaring static a shared lib cannot be instant apps 9736 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9737 throw new PackageManagerException( 9738 "Packages declaring static-shared libs cannot be instant apps"); 9739 } 9740 9741 // Package declaring static a shared lib cannot be renamed since the package 9742 // name is synthetic and apps can't code around package manager internals. 9743 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9744 throw new PackageManagerException( 9745 "Packages declaring static-shared libs cannot be renamed"); 9746 } 9747 9748 // Package declaring static a shared lib cannot declare child packages 9749 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9750 throw new PackageManagerException( 9751 "Packages declaring static-shared libs cannot have child packages"); 9752 } 9753 9754 // Package declaring static a shared lib cannot declare dynamic libs 9755 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9756 throw new PackageManagerException( 9757 "Packages declaring static-shared libs cannot declare dynamic libs"); 9758 } 9759 9760 // Package declaring static a shared lib cannot declare shared users 9761 if (pkg.mSharedUserId != null) { 9762 throw new PackageManagerException( 9763 "Packages declaring static-shared libs cannot declare shared users"); 9764 } 9765 9766 // Static shared libs cannot declare activities 9767 if (!pkg.activities.isEmpty()) { 9768 throw new PackageManagerException( 9769 "Static shared libs cannot declare activities"); 9770 } 9771 9772 // Static shared libs cannot declare services 9773 if (!pkg.services.isEmpty()) { 9774 throw new PackageManagerException( 9775 "Static shared libs cannot declare services"); 9776 } 9777 9778 // Static shared libs cannot declare providers 9779 if (!pkg.providers.isEmpty()) { 9780 throw new PackageManagerException( 9781 "Static shared libs cannot declare content providers"); 9782 } 9783 9784 // Static shared libs cannot declare receivers 9785 if (!pkg.receivers.isEmpty()) { 9786 throw new PackageManagerException( 9787 "Static shared libs cannot declare broadcast receivers"); 9788 } 9789 9790 // Static shared libs cannot declare permission groups 9791 if (!pkg.permissionGroups.isEmpty()) { 9792 throw new PackageManagerException( 9793 "Static shared libs cannot declare permission groups"); 9794 } 9795 9796 // Static shared libs cannot declare permissions 9797 if (!pkg.permissions.isEmpty()) { 9798 throw new PackageManagerException( 9799 "Static shared libs cannot declare permissions"); 9800 } 9801 9802 // Static shared libs cannot declare protected broadcasts 9803 if (pkg.protectedBroadcasts != null) { 9804 throw new PackageManagerException( 9805 "Static shared libs cannot declare protected broadcasts"); 9806 } 9807 9808 // Static shared libs cannot be overlay targets 9809 if (pkg.mOverlayTarget != null) { 9810 throw new PackageManagerException( 9811 "Static shared libs cannot be overlay targets"); 9812 } 9813 9814 // The version codes must be ordered as lib versions 9815 int minVersionCode = Integer.MIN_VALUE; 9816 int maxVersionCode = Integer.MAX_VALUE; 9817 9818 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9819 pkg.staticSharedLibName); 9820 if (versionedLib != null) { 9821 final int versionCount = versionedLib.size(); 9822 for (int i = 0; i < versionCount; i++) { 9823 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9824 // TODO: We will change version code to long, so in the new API it is long 9825 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9826 .getVersionCode(); 9827 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9828 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9829 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9830 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9831 } else { 9832 minVersionCode = maxVersionCode = libVersionCode; 9833 break; 9834 } 9835 } 9836 } 9837 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9838 throw new PackageManagerException("Static shared" 9839 + " lib version codes must be ordered as lib versions"); 9840 } 9841 } 9842 9843 // Only privileged apps and updated privileged apps can add child packages. 9844 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9845 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9846 throw new PackageManagerException("Only privileged apps can add child " 9847 + "packages. Ignoring package " + pkg.packageName); 9848 } 9849 final int childCount = pkg.childPackages.size(); 9850 for (int i = 0; i < childCount; i++) { 9851 PackageParser.Package childPkg = pkg.childPackages.get(i); 9852 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9853 childPkg.packageName)) { 9854 throw new PackageManagerException("Can't override child of " 9855 + "another disabled app. Ignoring package " + pkg.packageName); 9856 } 9857 } 9858 } 9859 9860 // If we're only installing presumed-existing packages, require that the 9861 // scanned APK is both already known and at the path previously established 9862 // for it. Previously unknown packages we pick up normally, but if we have an 9863 // a priori expectation about this package's install presence, enforce it. 9864 // With a singular exception for new system packages. When an OTA contains 9865 // a new system package, we allow the codepath to change from a system location 9866 // to the user-installed location. If we don't allow this change, any newer, 9867 // user-installed version of the application will be ignored. 9868 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9869 if (mExpectingBetter.containsKey(pkg.packageName)) { 9870 logCriticalInfo(Log.WARN, 9871 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9872 } else { 9873 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9874 if (known != null) { 9875 if (DEBUG_PACKAGE_SCANNING) { 9876 Log.d(TAG, "Examining " + pkg.codePath 9877 + " and requiring known paths " + known.codePathString 9878 + " & " + known.resourcePathString); 9879 } 9880 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9881 || !pkg.applicationInfo.getResourcePath().equals( 9882 known.resourcePathString)) { 9883 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9884 "Application package " + pkg.packageName 9885 + " found at " + pkg.applicationInfo.getCodePath() 9886 + " but expected at " + known.codePathString 9887 + "; ignoring."); 9888 } 9889 } 9890 } 9891 } 9892 9893 // Verify that this new package doesn't have any content providers 9894 // that conflict with existing packages. Only do this if the 9895 // package isn't already installed, since we don't want to break 9896 // things that are installed. 9897 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9898 final int N = pkg.providers.size(); 9899 int i; 9900 for (i=0; i<N; i++) { 9901 PackageParser.Provider p = pkg.providers.get(i); 9902 if (p.info.authority != null) { 9903 String names[] = p.info.authority.split(";"); 9904 for (int j = 0; j < names.length; j++) { 9905 if (mProvidersByAuthority.containsKey(names[j])) { 9906 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9907 final String otherPackageName = 9908 ((other != null && other.getComponentName() != null) ? 9909 other.getComponentName().getPackageName() : "?"); 9910 throw new PackageManagerException( 9911 INSTALL_FAILED_CONFLICTING_PROVIDER, 9912 "Can't install because provider name " + names[j] 9913 + " (in package " + pkg.applicationInfo.packageName 9914 + ") is already used by " + otherPackageName); 9915 } 9916 } 9917 } 9918 } 9919 } 9920 } 9921 } 9922 9923 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9924 int type, String declaringPackageName, int declaringVersionCode) { 9925 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9926 if (versionedLib == null) { 9927 versionedLib = new SparseArray<>(); 9928 mSharedLibraries.put(name, versionedLib); 9929 if (type == SharedLibraryInfo.TYPE_STATIC) { 9930 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9931 } 9932 } else if (versionedLib.indexOfKey(version) >= 0) { 9933 return false; 9934 } 9935 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9936 version, type, declaringPackageName, declaringVersionCode); 9937 versionedLib.put(version, libEntry); 9938 return true; 9939 } 9940 9941 private boolean removeSharedLibraryLPw(String name, int version) { 9942 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9943 if (versionedLib == null) { 9944 return false; 9945 } 9946 final int libIdx = versionedLib.indexOfKey(version); 9947 if (libIdx < 0) { 9948 return false; 9949 } 9950 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9951 versionedLib.remove(version); 9952 if (versionedLib.size() <= 0) { 9953 mSharedLibraries.remove(name); 9954 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9955 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9956 .getPackageName()); 9957 } 9958 } 9959 return true; 9960 } 9961 9962 /** 9963 * Adds a scanned package to the system. When this method is finished, the package will 9964 * be available for query, resolution, etc... 9965 */ 9966 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9967 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9968 final String pkgName = pkg.packageName; 9969 if (mCustomResolverComponentName != null && 9970 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9971 setUpCustomResolverActivity(pkg); 9972 } 9973 9974 if (pkg.packageName.equals("android")) { 9975 synchronized (mPackages) { 9976 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9977 // Set up information for our fall-back user intent resolution activity. 9978 mPlatformPackage = pkg; 9979 pkg.mVersionCode = mSdkVersion; 9980 mAndroidApplication = pkg.applicationInfo; 9981 if (!mResolverReplaced) { 9982 mResolveActivity.applicationInfo = mAndroidApplication; 9983 mResolveActivity.name = ResolverActivity.class.getName(); 9984 mResolveActivity.packageName = mAndroidApplication.packageName; 9985 mResolveActivity.processName = "system:ui"; 9986 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9987 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9988 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9989 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9990 mResolveActivity.exported = true; 9991 mResolveActivity.enabled = true; 9992 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9993 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9994 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9995 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9996 | ActivityInfo.CONFIG_ORIENTATION 9997 | ActivityInfo.CONFIG_KEYBOARD 9998 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9999 mResolveInfo.activityInfo = mResolveActivity; 10000 mResolveInfo.priority = 0; 10001 mResolveInfo.preferredOrder = 0; 10002 mResolveInfo.match = 0; 10003 mResolveComponentName = new ComponentName( 10004 mAndroidApplication.packageName, mResolveActivity.name); 10005 } 10006 } 10007 } 10008 } 10009 10010 ArrayList<PackageParser.Package> clientLibPkgs = null; 10011 // writer 10012 synchronized (mPackages) { 10013 boolean hasStaticSharedLibs = false; 10014 10015 // Any app can add new static shared libraries 10016 if (pkg.staticSharedLibName != null) { 10017 // Static shared libs don't allow renaming as they have synthetic package 10018 // names to allow install of multiple versions, so use name from manifest. 10019 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10020 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10021 pkg.manifestPackageName, pkg.mVersionCode)) { 10022 hasStaticSharedLibs = true; 10023 } else { 10024 Slog.w(TAG, "Package " + pkg.packageName + " library " 10025 + pkg.staticSharedLibName + " already exists; skipping"); 10026 } 10027 // Static shared libs cannot be updated once installed since they 10028 // use synthetic package name which includes the version code, so 10029 // not need to update other packages's shared lib dependencies. 10030 } 10031 10032 if (!hasStaticSharedLibs 10033 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10034 // Only system apps can add new dynamic shared libraries. 10035 if (pkg.libraryNames != null) { 10036 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10037 String name = pkg.libraryNames.get(i); 10038 boolean allowed = false; 10039 if (pkg.isUpdatedSystemApp()) { 10040 // New library entries can only be added through the 10041 // system image. This is important to get rid of a lot 10042 // of nasty edge cases: for example if we allowed a non- 10043 // system update of the app to add a library, then uninstalling 10044 // the update would make the library go away, and assumptions 10045 // we made such as through app install filtering would now 10046 // have allowed apps on the device which aren't compatible 10047 // with it. Better to just have the restriction here, be 10048 // conservative, and create many fewer cases that can negatively 10049 // impact the user experience. 10050 final PackageSetting sysPs = mSettings 10051 .getDisabledSystemPkgLPr(pkg.packageName); 10052 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10053 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10054 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10055 allowed = true; 10056 break; 10057 } 10058 } 10059 } 10060 } else { 10061 allowed = true; 10062 } 10063 if (allowed) { 10064 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10065 SharedLibraryInfo.VERSION_UNDEFINED, 10066 SharedLibraryInfo.TYPE_DYNAMIC, 10067 pkg.packageName, pkg.mVersionCode)) { 10068 Slog.w(TAG, "Package " + pkg.packageName + " library " 10069 + name + " already exists; skipping"); 10070 } 10071 } else { 10072 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10073 + name + " that is not declared on system image; skipping"); 10074 } 10075 } 10076 10077 if ((scanFlags & SCAN_BOOTING) == 0) { 10078 // If we are not booting, we need to update any applications 10079 // that are clients of our shared library. If we are booting, 10080 // this will all be done once the scan is complete. 10081 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10082 } 10083 } 10084 } 10085 } 10086 10087 if ((scanFlags & SCAN_BOOTING) != 0) { 10088 // No apps can run during boot scan, so they don't need to be frozen 10089 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10090 // Caller asked to not kill app, so it's probably not frozen 10091 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10092 // Caller asked us to ignore frozen check for some reason; they 10093 // probably didn't know the package name 10094 } else { 10095 // We're doing major surgery on this package, so it better be frozen 10096 // right now to keep it from launching 10097 checkPackageFrozen(pkgName); 10098 } 10099 10100 // Also need to kill any apps that are dependent on the library. 10101 if (clientLibPkgs != null) { 10102 for (int i=0; i<clientLibPkgs.size(); i++) { 10103 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10104 killApplication(clientPkg.applicationInfo.packageName, 10105 clientPkg.applicationInfo.uid, "update lib"); 10106 } 10107 } 10108 10109 // writer 10110 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10111 10112 synchronized (mPackages) { 10113 // We don't expect installation to fail beyond this point 10114 10115 // Add the new setting to mSettings 10116 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10117 // Add the new setting to mPackages 10118 mPackages.put(pkg.applicationInfo.packageName, pkg); 10119 // Make sure we don't accidentally delete its data. 10120 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10121 while (iter.hasNext()) { 10122 PackageCleanItem item = iter.next(); 10123 if (pkgName.equals(item.packageName)) { 10124 iter.remove(); 10125 } 10126 } 10127 10128 // Add the package's KeySets to the global KeySetManagerService 10129 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10130 ksms.addScannedPackageLPw(pkg); 10131 10132 int N = pkg.providers.size(); 10133 StringBuilder r = null; 10134 int i; 10135 for (i=0; i<N; i++) { 10136 PackageParser.Provider p = pkg.providers.get(i); 10137 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10138 p.info.processName); 10139 mProviders.addProvider(p); 10140 p.syncable = p.info.isSyncable; 10141 if (p.info.authority != null) { 10142 String names[] = p.info.authority.split(";"); 10143 p.info.authority = null; 10144 for (int j = 0; j < names.length; j++) { 10145 if (j == 1 && p.syncable) { 10146 // We only want the first authority for a provider to possibly be 10147 // syncable, so if we already added this provider using a different 10148 // authority clear the syncable flag. We copy the provider before 10149 // changing it because the mProviders object contains a reference 10150 // to a provider that we don't want to change. 10151 // Only do this for the second authority since the resulting provider 10152 // object can be the same for all future authorities for this provider. 10153 p = new PackageParser.Provider(p); 10154 p.syncable = false; 10155 } 10156 if (!mProvidersByAuthority.containsKey(names[j])) { 10157 mProvidersByAuthority.put(names[j], p); 10158 if (p.info.authority == null) { 10159 p.info.authority = names[j]; 10160 } else { 10161 p.info.authority = p.info.authority + ";" + names[j]; 10162 } 10163 if (DEBUG_PACKAGE_SCANNING) { 10164 if (chatty) 10165 Log.d(TAG, "Registered content provider: " + names[j] 10166 + ", className = " + p.info.name + ", isSyncable = " 10167 + p.info.isSyncable); 10168 } 10169 } else { 10170 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10171 Slog.w(TAG, "Skipping provider name " + names[j] + 10172 " (in package " + pkg.applicationInfo.packageName + 10173 "): name already used by " 10174 + ((other != null && other.getComponentName() != null) 10175 ? other.getComponentName().getPackageName() : "?")); 10176 } 10177 } 10178 } 10179 if (chatty) { 10180 if (r == null) { 10181 r = new StringBuilder(256); 10182 } else { 10183 r.append(' '); 10184 } 10185 r.append(p.info.name); 10186 } 10187 } 10188 if (r != null) { 10189 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10190 } 10191 10192 N = pkg.services.size(); 10193 r = null; 10194 for (i=0; i<N; i++) { 10195 PackageParser.Service s = pkg.services.get(i); 10196 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10197 s.info.processName); 10198 mServices.addService(s); 10199 if (chatty) { 10200 if (r == null) { 10201 r = new StringBuilder(256); 10202 } else { 10203 r.append(' '); 10204 } 10205 r.append(s.info.name); 10206 } 10207 } 10208 if (r != null) { 10209 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10210 } 10211 10212 N = pkg.receivers.size(); 10213 r = null; 10214 for (i=0; i<N; i++) { 10215 PackageParser.Activity a = pkg.receivers.get(i); 10216 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10217 a.info.processName); 10218 mReceivers.addActivity(a, "receiver"); 10219 if (chatty) { 10220 if (r == null) { 10221 r = new StringBuilder(256); 10222 } else { 10223 r.append(' '); 10224 } 10225 r.append(a.info.name); 10226 } 10227 } 10228 if (r != null) { 10229 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10230 } 10231 10232 N = pkg.activities.size(); 10233 r = null; 10234 for (i=0; i<N; i++) { 10235 PackageParser.Activity a = pkg.activities.get(i); 10236 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10237 a.info.processName); 10238 mActivities.addActivity(a, "activity"); 10239 if (chatty) { 10240 if (r == null) { 10241 r = new StringBuilder(256); 10242 } else { 10243 r.append(' '); 10244 } 10245 r.append(a.info.name); 10246 } 10247 } 10248 if (r != null) { 10249 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10250 } 10251 10252 N = pkg.permissionGroups.size(); 10253 r = null; 10254 for (i=0; i<N; i++) { 10255 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10256 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10257 final String curPackageName = cur == null ? null : cur.info.packageName; 10258 // Dont allow ephemeral apps to define new permission groups. 10259 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10260 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10261 + pg.info.packageName 10262 + " ignored: instant apps cannot define new permission groups."); 10263 continue; 10264 } 10265 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10266 if (cur == null || isPackageUpdate) { 10267 mPermissionGroups.put(pg.info.name, pg); 10268 if (chatty) { 10269 if (r == null) { 10270 r = new StringBuilder(256); 10271 } else { 10272 r.append(' '); 10273 } 10274 if (isPackageUpdate) { 10275 r.append("UPD:"); 10276 } 10277 r.append(pg.info.name); 10278 } 10279 } else { 10280 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10281 + pg.info.packageName + " ignored: original from " 10282 + cur.info.packageName); 10283 if (chatty) { 10284 if (r == null) { 10285 r = new StringBuilder(256); 10286 } else { 10287 r.append(' '); 10288 } 10289 r.append("DUP:"); 10290 r.append(pg.info.name); 10291 } 10292 } 10293 } 10294 if (r != null) { 10295 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10296 } 10297 10298 N = pkg.permissions.size(); 10299 r = null; 10300 for (i=0; i<N; i++) { 10301 PackageParser.Permission p = pkg.permissions.get(i); 10302 10303 // Dont allow ephemeral apps to define new permissions. 10304 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10305 Slog.w(TAG, "Permission " + p.info.name + " from package " 10306 + p.info.packageName 10307 + " ignored: instant apps cannot define new permissions."); 10308 continue; 10309 } 10310 10311 // Assume by default that we did not install this permission into the system. 10312 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10313 10314 // Now that permission groups have a special meaning, we ignore permission 10315 // groups for legacy apps to prevent unexpected behavior. In particular, 10316 // permissions for one app being granted to someone just becase they happen 10317 // to be in a group defined by another app (before this had no implications). 10318 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10319 p.group = mPermissionGroups.get(p.info.group); 10320 // Warn for a permission in an unknown group. 10321 if (p.info.group != null && p.group == null) { 10322 Slog.w(TAG, "Permission " + p.info.name + " from package " 10323 + p.info.packageName + " in an unknown group " + p.info.group); 10324 } 10325 } 10326 10327 ArrayMap<String, BasePermission> permissionMap = 10328 p.tree ? mSettings.mPermissionTrees 10329 : mSettings.mPermissions; 10330 BasePermission bp = permissionMap.get(p.info.name); 10331 10332 // Allow system apps to redefine non-system permissions 10333 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10334 final boolean currentOwnerIsSystem = (bp.perm != null 10335 && isSystemApp(bp.perm.owner)); 10336 if (isSystemApp(p.owner)) { 10337 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10338 // It's a built-in permission and no owner, take ownership now 10339 bp.packageSetting = pkgSetting; 10340 bp.perm = p; 10341 bp.uid = pkg.applicationInfo.uid; 10342 bp.sourcePackage = p.info.packageName; 10343 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10344 } else if (!currentOwnerIsSystem) { 10345 String msg = "New decl " + p.owner + " of permission " 10346 + p.info.name + " is system; overriding " + bp.sourcePackage; 10347 reportSettingsProblem(Log.WARN, msg); 10348 bp = null; 10349 } 10350 } 10351 } 10352 10353 if (bp == null) { 10354 bp = new BasePermission(p.info.name, p.info.packageName, 10355 BasePermission.TYPE_NORMAL); 10356 permissionMap.put(p.info.name, bp); 10357 } 10358 10359 if (bp.perm == null) { 10360 if (bp.sourcePackage == null 10361 || bp.sourcePackage.equals(p.info.packageName)) { 10362 BasePermission tree = findPermissionTreeLP(p.info.name); 10363 if (tree == null 10364 || tree.sourcePackage.equals(p.info.packageName)) { 10365 bp.packageSetting = pkgSetting; 10366 bp.perm = p; 10367 bp.uid = pkg.applicationInfo.uid; 10368 bp.sourcePackage = p.info.packageName; 10369 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10370 if (chatty) { 10371 if (r == null) { 10372 r = new StringBuilder(256); 10373 } else { 10374 r.append(' '); 10375 } 10376 r.append(p.info.name); 10377 } 10378 } else { 10379 Slog.w(TAG, "Permission " + p.info.name + " from package " 10380 + p.info.packageName + " ignored: base tree " 10381 + tree.name + " is from package " 10382 + tree.sourcePackage); 10383 } 10384 } else { 10385 Slog.w(TAG, "Permission " + p.info.name + " from package " 10386 + p.info.packageName + " ignored: original from " 10387 + bp.sourcePackage); 10388 } 10389 } else if (chatty) { 10390 if (r == null) { 10391 r = new StringBuilder(256); 10392 } else { 10393 r.append(' '); 10394 } 10395 r.append("DUP:"); 10396 r.append(p.info.name); 10397 } 10398 if (bp.perm == p) { 10399 bp.protectionLevel = p.info.protectionLevel; 10400 } 10401 } 10402 10403 if (r != null) { 10404 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10405 } 10406 10407 N = pkg.instrumentation.size(); 10408 r = null; 10409 for (i=0; i<N; i++) { 10410 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10411 a.info.packageName = pkg.applicationInfo.packageName; 10412 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10413 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10414 a.info.splitNames = pkg.splitNames; 10415 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10416 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10417 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10418 a.info.dataDir = pkg.applicationInfo.dataDir; 10419 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10420 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10421 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10422 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10423 mInstrumentation.put(a.getComponentName(), a); 10424 if (chatty) { 10425 if (r == null) { 10426 r = new StringBuilder(256); 10427 } else { 10428 r.append(' '); 10429 } 10430 r.append(a.info.name); 10431 } 10432 } 10433 if (r != null) { 10434 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10435 } 10436 10437 if (pkg.protectedBroadcasts != null) { 10438 N = pkg.protectedBroadcasts.size(); 10439 for (i=0; i<N; i++) { 10440 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10441 } 10442 } 10443 } 10444 10445 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10446 } 10447 10448 /** 10449 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10450 * is derived purely on the basis of the contents of {@code scanFile} and 10451 * {@code cpuAbiOverride}. 10452 * 10453 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10454 */ 10455 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10456 String cpuAbiOverride, boolean extractLibs, 10457 File appLib32InstallDir) 10458 throws PackageManagerException { 10459 // Give ourselves some initial paths; we'll come back for another 10460 // pass once we've determined ABI below. 10461 setNativeLibraryPaths(pkg, appLib32InstallDir); 10462 10463 // We would never need to extract libs for forward-locked and external packages, 10464 // since the container service will do it for us. We shouldn't attempt to 10465 // extract libs from system app when it was not updated. 10466 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10467 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10468 extractLibs = false; 10469 } 10470 10471 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10472 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10473 10474 NativeLibraryHelper.Handle handle = null; 10475 try { 10476 handle = NativeLibraryHelper.Handle.create(pkg); 10477 // TODO(multiArch): This can be null for apps that didn't go through the 10478 // usual installation process. We can calculate it again, like we 10479 // do during install time. 10480 // 10481 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10482 // unnecessary. 10483 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10484 10485 // Null out the abis so that they can be recalculated. 10486 pkg.applicationInfo.primaryCpuAbi = null; 10487 pkg.applicationInfo.secondaryCpuAbi = null; 10488 if (isMultiArch(pkg.applicationInfo)) { 10489 // Warn if we've set an abiOverride for multi-lib packages.. 10490 // By definition, we need to copy both 32 and 64 bit libraries for 10491 // such packages. 10492 if (pkg.cpuAbiOverride != null 10493 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10494 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10495 } 10496 10497 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10498 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10499 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10500 if (extractLibs) { 10501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10502 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10503 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10504 useIsaSpecificSubdirs); 10505 } else { 10506 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10507 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10508 } 10509 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10510 } 10511 10512 maybeThrowExceptionForMultiArchCopy( 10513 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10514 10515 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10516 if (extractLibs) { 10517 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10518 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10519 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10520 useIsaSpecificSubdirs); 10521 } else { 10522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10523 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10524 } 10525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10526 } 10527 10528 maybeThrowExceptionForMultiArchCopy( 10529 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10530 10531 if (abi64 >= 0) { 10532 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10533 } 10534 10535 if (abi32 >= 0) { 10536 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10537 if (abi64 >= 0) { 10538 if (pkg.use32bitAbi) { 10539 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10540 pkg.applicationInfo.primaryCpuAbi = abi; 10541 } else { 10542 pkg.applicationInfo.secondaryCpuAbi = abi; 10543 } 10544 } else { 10545 pkg.applicationInfo.primaryCpuAbi = abi; 10546 } 10547 } 10548 10549 } else { 10550 String[] abiList = (cpuAbiOverride != null) ? 10551 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10552 10553 // Enable gross and lame hacks for apps that are built with old 10554 // SDK tools. We must scan their APKs for renderscript bitcode and 10555 // not launch them if it's present. Don't bother checking on devices 10556 // that don't have 64 bit support. 10557 boolean needsRenderScriptOverride = false; 10558 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10559 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10560 abiList = Build.SUPPORTED_32_BIT_ABIS; 10561 needsRenderScriptOverride = true; 10562 } 10563 10564 final int copyRet; 10565 if (extractLibs) { 10566 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10567 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10568 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10569 } else { 10570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10571 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10572 } 10573 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10574 10575 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10576 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10577 "Error unpackaging native libs for app, errorCode=" + copyRet); 10578 } 10579 10580 if (copyRet >= 0) { 10581 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10582 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10583 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10584 } else if (needsRenderScriptOverride) { 10585 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10586 } 10587 } 10588 } catch (IOException ioe) { 10589 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10590 } finally { 10591 IoUtils.closeQuietly(handle); 10592 } 10593 10594 // Now that we've calculated the ABIs and determined if it's an internal app, 10595 // we will go ahead and populate the nativeLibraryPath. 10596 setNativeLibraryPaths(pkg, appLib32InstallDir); 10597 } 10598 10599 /** 10600 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10601 * i.e, so that all packages can be run inside a single process if required. 10602 * 10603 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10604 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10605 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10606 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10607 * updating a package that belongs to a shared user. 10608 * 10609 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10610 * adds unnecessary complexity. 10611 */ 10612 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10613 PackageParser.Package scannedPackage) { 10614 String requiredInstructionSet = null; 10615 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10616 requiredInstructionSet = VMRuntime.getInstructionSet( 10617 scannedPackage.applicationInfo.primaryCpuAbi); 10618 } 10619 10620 PackageSetting requirer = null; 10621 for (PackageSetting ps : packagesForUser) { 10622 // If packagesForUser contains scannedPackage, we skip it. This will happen 10623 // when scannedPackage is an update of an existing package. Without this check, 10624 // we will never be able to change the ABI of any package belonging to a shared 10625 // user, even if it's compatible with other packages. 10626 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10627 if (ps.primaryCpuAbiString == null) { 10628 continue; 10629 } 10630 10631 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10632 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10633 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10634 // this but there's not much we can do. 10635 String errorMessage = "Instruction set mismatch, " 10636 + ((requirer == null) ? "[caller]" : requirer) 10637 + " requires " + requiredInstructionSet + " whereas " + ps 10638 + " requires " + instructionSet; 10639 Slog.w(TAG, errorMessage); 10640 } 10641 10642 if (requiredInstructionSet == null) { 10643 requiredInstructionSet = instructionSet; 10644 requirer = ps; 10645 } 10646 } 10647 } 10648 10649 if (requiredInstructionSet != null) { 10650 String adjustedAbi; 10651 if (requirer != null) { 10652 // requirer != null implies that either scannedPackage was null or that scannedPackage 10653 // did not require an ABI, in which case we have to adjust scannedPackage to match 10654 // the ABI of the set (which is the same as requirer's ABI) 10655 adjustedAbi = requirer.primaryCpuAbiString; 10656 if (scannedPackage != null) { 10657 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10658 } 10659 } else { 10660 // requirer == null implies that we're updating all ABIs in the set to 10661 // match scannedPackage. 10662 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10663 } 10664 10665 for (PackageSetting ps : packagesForUser) { 10666 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10667 if (ps.primaryCpuAbiString != null) { 10668 continue; 10669 } 10670 10671 ps.primaryCpuAbiString = adjustedAbi; 10672 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10673 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10674 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10675 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10676 + " (requirer=" 10677 + (requirer != null ? requirer.pkg : "null") 10678 + ", scannedPackage=" 10679 + (scannedPackage != null ? scannedPackage : "null") 10680 + ")"); 10681 try { 10682 mInstaller.rmdex(ps.codePathString, 10683 getDexCodeInstructionSet(getPreferredInstructionSet())); 10684 } catch (InstallerException ignored) { 10685 } 10686 } 10687 } 10688 } 10689 } 10690 } 10691 10692 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10693 synchronized (mPackages) { 10694 mResolverReplaced = true; 10695 // Set up information for custom user intent resolution activity. 10696 mResolveActivity.applicationInfo = pkg.applicationInfo; 10697 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10698 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10699 mResolveActivity.processName = pkg.applicationInfo.packageName; 10700 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10701 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10702 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10703 mResolveActivity.theme = 0; 10704 mResolveActivity.exported = true; 10705 mResolveActivity.enabled = true; 10706 mResolveInfo.activityInfo = mResolveActivity; 10707 mResolveInfo.priority = 0; 10708 mResolveInfo.preferredOrder = 0; 10709 mResolveInfo.match = 0; 10710 mResolveComponentName = mCustomResolverComponentName; 10711 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10712 mResolveComponentName); 10713 } 10714 } 10715 10716 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10717 if (installerActivity == null) { 10718 if (DEBUG_EPHEMERAL) { 10719 Slog.d(TAG, "Clear ephemeral installer activity"); 10720 } 10721 mInstantAppInstallerActivity = null; 10722 return; 10723 } 10724 10725 if (DEBUG_EPHEMERAL) { 10726 Slog.d(TAG, "Set ephemeral installer activity: " 10727 + installerActivity.getComponentName()); 10728 } 10729 // Set up information for ephemeral installer activity 10730 mInstantAppInstallerActivity = installerActivity; 10731 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10732 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10733 mInstantAppInstallerActivity.exported = true; 10734 mInstantAppInstallerActivity.enabled = true; 10735 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10736 mInstantAppInstallerInfo.priority = 0; 10737 mInstantAppInstallerInfo.preferredOrder = 1; 10738 mInstantAppInstallerInfo.isDefault = true; 10739 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10740 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10741 } 10742 10743 private static String calculateBundledApkRoot(final String codePathString) { 10744 final File codePath = new File(codePathString); 10745 final File codeRoot; 10746 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10747 codeRoot = Environment.getRootDirectory(); 10748 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10749 codeRoot = Environment.getOemDirectory(); 10750 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10751 codeRoot = Environment.getVendorDirectory(); 10752 } else { 10753 // Unrecognized code path; take its top real segment as the apk root: 10754 // e.g. /something/app/blah.apk => /something 10755 try { 10756 File f = codePath.getCanonicalFile(); 10757 File parent = f.getParentFile(); // non-null because codePath is a file 10758 File tmp; 10759 while ((tmp = parent.getParentFile()) != null) { 10760 f = parent; 10761 parent = tmp; 10762 } 10763 codeRoot = f; 10764 Slog.w(TAG, "Unrecognized code path " 10765 + codePath + " - using " + codeRoot); 10766 } catch (IOException e) { 10767 // Can't canonicalize the code path -- shenanigans? 10768 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10769 return Environment.getRootDirectory().getPath(); 10770 } 10771 } 10772 return codeRoot.getPath(); 10773 } 10774 10775 /** 10776 * Derive and set the location of native libraries for the given package, 10777 * which varies depending on where and how the package was installed. 10778 */ 10779 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10780 final ApplicationInfo info = pkg.applicationInfo; 10781 final String codePath = pkg.codePath; 10782 final File codeFile = new File(codePath); 10783 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10784 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10785 10786 info.nativeLibraryRootDir = null; 10787 info.nativeLibraryRootRequiresIsa = false; 10788 info.nativeLibraryDir = null; 10789 info.secondaryNativeLibraryDir = null; 10790 10791 if (isApkFile(codeFile)) { 10792 // Monolithic install 10793 if (bundledApp) { 10794 // If "/system/lib64/apkname" exists, assume that is the per-package 10795 // native library directory to use; otherwise use "/system/lib/apkname". 10796 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10797 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10798 getPrimaryInstructionSet(info)); 10799 10800 // This is a bundled system app so choose the path based on the ABI. 10801 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10802 // is just the default path. 10803 final String apkName = deriveCodePathName(codePath); 10804 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10805 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10806 apkName).getAbsolutePath(); 10807 10808 if (info.secondaryCpuAbi != null) { 10809 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10810 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10811 secondaryLibDir, apkName).getAbsolutePath(); 10812 } 10813 } else if (asecApp) { 10814 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10815 .getAbsolutePath(); 10816 } else { 10817 final String apkName = deriveCodePathName(codePath); 10818 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10819 .getAbsolutePath(); 10820 } 10821 10822 info.nativeLibraryRootRequiresIsa = false; 10823 info.nativeLibraryDir = info.nativeLibraryRootDir; 10824 } else { 10825 // Cluster install 10826 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10827 info.nativeLibraryRootRequiresIsa = true; 10828 10829 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10830 getPrimaryInstructionSet(info)).getAbsolutePath(); 10831 10832 if (info.secondaryCpuAbi != null) { 10833 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10834 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10835 } 10836 } 10837 } 10838 10839 /** 10840 * Calculate the abis and roots for a bundled app. These can uniquely 10841 * be determined from the contents of the system partition, i.e whether 10842 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10843 * of this information, and instead assume that the system was built 10844 * sensibly. 10845 */ 10846 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10847 PackageSetting pkgSetting) { 10848 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10849 10850 // If "/system/lib64/apkname" exists, assume that is the per-package 10851 // native library directory to use; otherwise use "/system/lib/apkname". 10852 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10853 setBundledAppAbi(pkg, apkRoot, apkName); 10854 // pkgSetting might be null during rescan following uninstall of updates 10855 // to a bundled app, so accommodate that possibility. The settings in 10856 // that case will be established later from the parsed package. 10857 // 10858 // If the settings aren't null, sync them up with what we've just derived. 10859 // note that apkRoot isn't stored in the package settings. 10860 if (pkgSetting != null) { 10861 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10862 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10863 } 10864 } 10865 10866 /** 10867 * Deduces the ABI of a bundled app and sets the relevant fields on the 10868 * parsed pkg object. 10869 * 10870 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10871 * under which system libraries are installed. 10872 * @param apkName the name of the installed package. 10873 */ 10874 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10875 final File codeFile = new File(pkg.codePath); 10876 10877 final boolean has64BitLibs; 10878 final boolean has32BitLibs; 10879 if (isApkFile(codeFile)) { 10880 // Monolithic install 10881 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10882 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10883 } else { 10884 // Cluster install 10885 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10886 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10887 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10888 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10889 has64BitLibs = (new File(rootDir, isa)).exists(); 10890 } else { 10891 has64BitLibs = false; 10892 } 10893 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10894 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10895 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10896 has32BitLibs = (new File(rootDir, isa)).exists(); 10897 } else { 10898 has32BitLibs = false; 10899 } 10900 } 10901 10902 if (has64BitLibs && !has32BitLibs) { 10903 // The package has 64 bit libs, but not 32 bit libs. Its primary 10904 // ABI should be 64 bit. We can safely assume here that the bundled 10905 // native libraries correspond to the most preferred ABI in the list. 10906 10907 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10908 pkg.applicationInfo.secondaryCpuAbi = null; 10909 } else if (has32BitLibs && !has64BitLibs) { 10910 // The package has 32 bit libs but not 64 bit libs. Its primary 10911 // ABI should be 32 bit. 10912 10913 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10914 pkg.applicationInfo.secondaryCpuAbi = null; 10915 } else if (has32BitLibs && has64BitLibs) { 10916 // The application has both 64 and 32 bit bundled libraries. We check 10917 // here that the app declares multiArch support, and warn if it doesn't. 10918 // 10919 // We will be lenient here and record both ABIs. The primary will be the 10920 // ABI that's higher on the list, i.e, a device that's configured to prefer 10921 // 64 bit apps will see a 64 bit primary ABI, 10922 10923 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10924 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10925 } 10926 10927 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10928 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10929 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10930 } else { 10931 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10932 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10933 } 10934 } else { 10935 pkg.applicationInfo.primaryCpuAbi = null; 10936 pkg.applicationInfo.secondaryCpuAbi = null; 10937 } 10938 } 10939 10940 private void killApplication(String pkgName, int appId, String reason) { 10941 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10942 } 10943 10944 private void killApplication(String pkgName, int appId, int userId, String reason) { 10945 // Request the ActivityManager to kill the process(only for existing packages) 10946 // so that we do not end up in a confused state while the user is still using the older 10947 // version of the application while the new one gets installed. 10948 final long token = Binder.clearCallingIdentity(); 10949 try { 10950 IActivityManager am = ActivityManager.getService(); 10951 if (am != null) { 10952 try { 10953 am.killApplication(pkgName, appId, userId, reason); 10954 } catch (RemoteException e) { 10955 } 10956 } 10957 } finally { 10958 Binder.restoreCallingIdentity(token); 10959 } 10960 } 10961 10962 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10963 // Remove the parent package setting 10964 PackageSetting ps = (PackageSetting) pkg.mExtras; 10965 if (ps != null) { 10966 removePackageLI(ps, chatty); 10967 } 10968 // Remove the child package setting 10969 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10970 for (int i = 0; i < childCount; i++) { 10971 PackageParser.Package childPkg = pkg.childPackages.get(i); 10972 ps = (PackageSetting) childPkg.mExtras; 10973 if (ps != null) { 10974 removePackageLI(ps, chatty); 10975 } 10976 } 10977 } 10978 10979 void removePackageLI(PackageSetting ps, boolean chatty) { 10980 if (DEBUG_INSTALL) { 10981 if (chatty) 10982 Log.d(TAG, "Removing package " + ps.name); 10983 } 10984 10985 // writer 10986 synchronized (mPackages) { 10987 mPackages.remove(ps.name); 10988 final PackageParser.Package pkg = ps.pkg; 10989 if (pkg != null) { 10990 cleanPackageDataStructuresLILPw(pkg, chatty); 10991 } 10992 } 10993 } 10994 10995 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10996 if (DEBUG_INSTALL) { 10997 if (chatty) 10998 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10999 } 11000 11001 // writer 11002 synchronized (mPackages) { 11003 // Remove the parent package 11004 mPackages.remove(pkg.applicationInfo.packageName); 11005 cleanPackageDataStructuresLILPw(pkg, chatty); 11006 11007 // Remove the child packages 11008 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11009 for (int i = 0; i < childCount; i++) { 11010 PackageParser.Package childPkg = pkg.childPackages.get(i); 11011 mPackages.remove(childPkg.applicationInfo.packageName); 11012 cleanPackageDataStructuresLILPw(childPkg, chatty); 11013 } 11014 } 11015 } 11016 11017 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11018 int N = pkg.providers.size(); 11019 StringBuilder r = null; 11020 int i; 11021 for (i=0; i<N; i++) { 11022 PackageParser.Provider p = pkg.providers.get(i); 11023 mProviders.removeProvider(p); 11024 if (p.info.authority == null) { 11025 11026 /* There was another ContentProvider with this authority when 11027 * this app was installed so this authority is null, 11028 * Ignore it as we don't have to unregister the provider. 11029 */ 11030 continue; 11031 } 11032 String names[] = p.info.authority.split(";"); 11033 for (int j = 0; j < names.length; j++) { 11034 if (mProvidersByAuthority.get(names[j]) == p) { 11035 mProvidersByAuthority.remove(names[j]); 11036 if (DEBUG_REMOVE) { 11037 if (chatty) 11038 Log.d(TAG, "Unregistered content provider: " + names[j] 11039 + ", className = " + p.info.name + ", isSyncable = " 11040 + p.info.isSyncable); 11041 } 11042 } 11043 } 11044 if (DEBUG_REMOVE && chatty) { 11045 if (r == null) { 11046 r = new StringBuilder(256); 11047 } else { 11048 r.append(' '); 11049 } 11050 r.append(p.info.name); 11051 } 11052 } 11053 if (r != null) { 11054 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11055 } 11056 11057 N = pkg.services.size(); 11058 r = null; 11059 for (i=0; i<N; i++) { 11060 PackageParser.Service s = pkg.services.get(i); 11061 mServices.removeService(s); 11062 if (chatty) { 11063 if (r == null) { 11064 r = new StringBuilder(256); 11065 } else { 11066 r.append(' '); 11067 } 11068 r.append(s.info.name); 11069 } 11070 } 11071 if (r != null) { 11072 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11073 } 11074 11075 N = pkg.receivers.size(); 11076 r = null; 11077 for (i=0; i<N; i++) { 11078 PackageParser.Activity a = pkg.receivers.get(i); 11079 mReceivers.removeActivity(a, "receiver"); 11080 if (DEBUG_REMOVE && chatty) { 11081 if (r == null) { 11082 r = new StringBuilder(256); 11083 } else { 11084 r.append(' '); 11085 } 11086 r.append(a.info.name); 11087 } 11088 } 11089 if (r != null) { 11090 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11091 } 11092 11093 N = pkg.activities.size(); 11094 r = null; 11095 for (i=0; i<N; i++) { 11096 PackageParser.Activity a = pkg.activities.get(i); 11097 mActivities.removeActivity(a, "activity"); 11098 if (DEBUG_REMOVE && chatty) { 11099 if (r == null) { 11100 r = new StringBuilder(256); 11101 } else { 11102 r.append(' '); 11103 } 11104 r.append(a.info.name); 11105 } 11106 } 11107 if (r != null) { 11108 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11109 } 11110 11111 N = pkg.permissions.size(); 11112 r = null; 11113 for (i=0; i<N; i++) { 11114 PackageParser.Permission p = pkg.permissions.get(i); 11115 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11116 if (bp == null) { 11117 bp = mSettings.mPermissionTrees.get(p.info.name); 11118 } 11119 if (bp != null && bp.perm == p) { 11120 bp.perm = null; 11121 if (DEBUG_REMOVE && chatty) { 11122 if (r == null) { 11123 r = new StringBuilder(256); 11124 } else { 11125 r.append(' '); 11126 } 11127 r.append(p.info.name); 11128 } 11129 } 11130 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11131 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11132 if (appOpPkgs != null) { 11133 appOpPkgs.remove(pkg.packageName); 11134 } 11135 } 11136 } 11137 if (r != null) { 11138 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11139 } 11140 11141 N = pkg.requestedPermissions.size(); 11142 r = null; 11143 for (i=0; i<N; i++) { 11144 String perm = pkg.requestedPermissions.get(i); 11145 BasePermission bp = mSettings.mPermissions.get(perm); 11146 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11147 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11148 if (appOpPkgs != null) { 11149 appOpPkgs.remove(pkg.packageName); 11150 if (appOpPkgs.isEmpty()) { 11151 mAppOpPermissionPackages.remove(perm); 11152 } 11153 } 11154 } 11155 } 11156 if (r != null) { 11157 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11158 } 11159 11160 N = pkg.instrumentation.size(); 11161 r = null; 11162 for (i=0; i<N; i++) { 11163 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11164 mInstrumentation.remove(a.getComponentName()); 11165 if (DEBUG_REMOVE && chatty) { 11166 if (r == null) { 11167 r = new StringBuilder(256); 11168 } else { 11169 r.append(' '); 11170 } 11171 r.append(a.info.name); 11172 } 11173 } 11174 if (r != null) { 11175 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11176 } 11177 11178 r = null; 11179 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11180 // Only system apps can hold shared libraries. 11181 if (pkg.libraryNames != null) { 11182 for (i = 0; i < pkg.libraryNames.size(); i++) { 11183 String name = pkg.libraryNames.get(i); 11184 if (removeSharedLibraryLPw(name, 0)) { 11185 if (DEBUG_REMOVE && chatty) { 11186 if (r == null) { 11187 r = new StringBuilder(256); 11188 } else { 11189 r.append(' '); 11190 } 11191 r.append(name); 11192 } 11193 } 11194 } 11195 } 11196 } 11197 11198 r = null; 11199 11200 // Any package can hold static shared libraries. 11201 if (pkg.staticSharedLibName != null) { 11202 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11203 if (DEBUG_REMOVE && chatty) { 11204 if (r == null) { 11205 r = new StringBuilder(256); 11206 } else { 11207 r.append(' '); 11208 } 11209 r.append(pkg.staticSharedLibName); 11210 } 11211 } 11212 } 11213 11214 if (r != null) { 11215 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11216 } 11217 } 11218 11219 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11220 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11221 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11222 return true; 11223 } 11224 } 11225 return false; 11226 } 11227 11228 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11229 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11230 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11231 11232 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11233 // Update the parent permissions 11234 updatePermissionsLPw(pkg.packageName, pkg, flags); 11235 // Update the child permissions 11236 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11237 for (int i = 0; i < childCount; i++) { 11238 PackageParser.Package childPkg = pkg.childPackages.get(i); 11239 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11240 } 11241 } 11242 11243 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11244 int flags) { 11245 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11246 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11247 } 11248 11249 private void updatePermissionsLPw(String changingPkg, 11250 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11251 // Make sure there are no dangling permission trees. 11252 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11253 while (it.hasNext()) { 11254 final BasePermission bp = it.next(); 11255 if (bp.packageSetting == null) { 11256 // We may not yet have parsed the package, so just see if 11257 // we still know about its settings. 11258 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11259 } 11260 if (bp.packageSetting == null) { 11261 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11262 + " from package " + bp.sourcePackage); 11263 it.remove(); 11264 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11265 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11266 Slog.i(TAG, "Removing old permission tree: " + bp.name 11267 + " from package " + bp.sourcePackage); 11268 flags |= UPDATE_PERMISSIONS_ALL; 11269 it.remove(); 11270 } 11271 } 11272 } 11273 11274 // Make sure all dynamic permissions have been assigned to a package, 11275 // and make sure there are no dangling permissions. 11276 it = mSettings.mPermissions.values().iterator(); 11277 while (it.hasNext()) { 11278 final BasePermission bp = it.next(); 11279 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11280 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11281 + bp.name + " pkg=" + bp.sourcePackage 11282 + " info=" + bp.pendingInfo); 11283 if (bp.packageSetting == null && bp.pendingInfo != null) { 11284 final BasePermission tree = findPermissionTreeLP(bp.name); 11285 if (tree != null && tree.perm != null) { 11286 bp.packageSetting = tree.packageSetting; 11287 bp.perm = new PackageParser.Permission(tree.perm.owner, 11288 new PermissionInfo(bp.pendingInfo)); 11289 bp.perm.info.packageName = tree.perm.info.packageName; 11290 bp.perm.info.name = bp.name; 11291 bp.uid = tree.uid; 11292 } 11293 } 11294 } 11295 if (bp.packageSetting == null) { 11296 // We may not yet have parsed the package, so just see if 11297 // we still know about its settings. 11298 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11299 } 11300 if (bp.packageSetting == null) { 11301 Slog.w(TAG, "Removing dangling permission: " + bp.name 11302 + " from package " + bp.sourcePackage); 11303 it.remove(); 11304 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11305 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11306 Slog.i(TAG, "Removing old permission: " + bp.name 11307 + " from package " + bp.sourcePackage); 11308 flags |= UPDATE_PERMISSIONS_ALL; 11309 it.remove(); 11310 } 11311 } 11312 } 11313 11314 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11315 // Now update the permissions for all packages, in particular 11316 // replace the granted permissions of the system packages. 11317 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11318 for (PackageParser.Package pkg : mPackages.values()) { 11319 if (pkg != pkgInfo) { 11320 // Only replace for packages on requested volume 11321 final String volumeUuid = getVolumeUuidForPackage(pkg); 11322 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11323 && Objects.equals(replaceVolumeUuid, volumeUuid); 11324 grantPermissionsLPw(pkg, replace, changingPkg); 11325 } 11326 } 11327 } 11328 11329 if (pkgInfo != null) { 11330 // Only replace for packages on requested volume 11331 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11332 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11333 && Objects.equals(replaceVolumeUuid, volumeUuid); 11334 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11335 } 11336 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11337 } 11338 11339 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11340 String packageOfInterest) { 11341 // IMPORTANT: There are two types of permissions: install and runtime. 11342 // Install time permissions are granted when the app is installed to 11343 // all device users and users added in the future. Runtime permissions 11344 // are granted at runtime explicitly to specific users. Normal and signature 11345 // protected permissions are install time permissions. Dangerous permissions 11346 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11347 // otherwise they are runtime permissions. This function does not manage 11348 // runtime permissions except for the case an app targeting Lollipop MR1 11349 // being upgraded to target a newer SDK, in which case dangerous permissions 11350 // are transformed from install time to runtime ones. 11351 11352 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11353 if (ps == null) { 11354 return; 11355 } 11356 11357 PermissionsState permissionsState = ps.getPermissionsState(); 11358 PermissionsState origPermissions = permissionsState; 11359 11360 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11361 11362 boolean runtimePermissionsRevoked = false; 11363 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11364 11365 boolean changedInstallPermission = false; 11366 11367 if (replace) { 11368 ps.installPermissionsFixed = false; 11369 if (!ps.isSharedUser()) { 11370 origPermissions = new PermissionsState(permissionsState); 11371 permissionsState.reset(); 11372 } else { 11373 // We need to know only about runtime permission changes since the 11374 // calling code always writes the install permissions state but 11375 // the runtime ones are written only if changed. The only cases of 11376 // changed runtime permissions here are promotion of an install to 11377 // runtime and revocation of a runtime from a shared user. 11378 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11379 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11380 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11381 runtimePermissionsRevoked = true; 11382 } 11383 } 11384 } 11385 11386 permissionsState.setGlobalGids(mGlobalGids); 11387 11388 final int N = pkg.requestedPermissions.size(); 11389 for (int i=0; i<N; i++) { 11390 final String name = pkg.requestedPermissions.get(i); 11391 final BasePermission bp = mSettings.mPermissions.get(name); 11392 11393 if (DEBUG_INSTALL) { 11394 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11395 } 11396 11397 if (bp == null || bp.packageSetting == null) { 11398 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11399 Slog.w(TAG, "Unknown permission " + name 11400 + " in package " + pkg.packageName); 11401 } 11402 continue; 11403 } 11404 11405 11406 // Limit ephemeral apps to ephemeral allowed permissions. 11407 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11408 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11409 + pkg.packageName); 11410 continue; 11411 } 11412 11413 final String perm = bp.name; 11414 boolean allowedSig = false; 11415 int grant = GRANT_DENIED; 11416 11417 // Keep track of app op permissions. 11418 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11419 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11420 if (pkgs == null) { 11421 pkgs = new ArraySet<>(); 11422 mAppOpPermissionPackages.put(bp.name, pkgs); 11423 } 11424 pkgs.add(pkg.packageName); 11425 } 11426 11427 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11428 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11429 >= Build.VERSION_CODES.M; 11430 switch (level) { 11431 case PermissionInfo.PROTECTION_NORMAL: { 11432 // For all apps normal permissions are install time ones. 11433 grant = GRANT_INSTALL; 11434 } break; 11435 11436 case PermissionInfo.PROTECTION_DANGEROUS: { 11437 // If a permission review is required for legacy apps we represent 11438 // their permissions as always granted runtime ones since we need 11439 // to keep the review required permission flag per user while an 11440 // install permission's state is shared across all users. 11441 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11442 // For legacy apps dangerous permissions are install time ones. 11443 grant = GRANT_INSTALL; 11444 } else if (origPermissions.hasInstallPermission(bp.name)) { 11445 // For legacy apps that became modern, install becomes runtime. 11446 grant = GRANT_UPGRADE; 11447 } else if (mPromoteSystemApps 11448 && isSystemApp(ps) 11449 && mExistingSystemPackages.contains(ps.name)) { 11450 // For legacy system apps, install becomes runtime. 11451 // We cannot check hasInstallPermission() for system apps since those 11452 // permissions were granted implicitly and not persisted pre-M. 11453 grant = GRANT_UPGRADE; 11454 } else { 11455 // For modern apps keep runtime permissions unchanged. 11456 grant = GRANT_RUNTIME; 11457 } 11458 } break; 11459 11460 case PermissionInfo.PROTECTION_SIGNATURE: { 11461 // For all apps signature permissions are install time ones. 11462 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11463 if (allowedSig) { 11464 grant = GRANT_INSTALL; 11465 } 11466 } break; 11467 } 11468 11469 if (DEBUG_INSTALL) { 11470 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11471 } 11472 11473 if (grant != GRANT_DENIED) { 11474 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11475 // If this is an existing, non-system package, then 11476 // we can't add any new permissions to it. 11477 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11478 // Except... if this is a permission that was added 11479 // to the platform (note: need to only do this when 11480 // updating the platform). 11481 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11482 grant = GRANT_DENIED; 11483 } 11484 } 11485 } 11486 11487 switch (grant) { 11488 case GRANT_INSTALL: { 11489 // Revoke this as runtime permission to handle the case of 11490 // a runtime permission being downgraded to an install one. 11491 // Also in permission review mode we keep dangerous permissions 11492 // for legacy apps 11493 for (int userId : UserManagerService.getInstance().getUserIds()) { 11494 if (origPermissions.getRuntimePermissionState( 11495 bp.name, userId) != null) { 11496 // Revoke the runtime permission and clear the flags. 11497 origPermissions.revokeRuntimePermission(bp, userId); 11498 origPermissions.updatePermissionFlags(bp, userId, 11499 PackageManager.MASK_PERMISSION_FLAGS, 0); 11500 // If we revoked a permission permission, we have to write. 11501 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11502 changedRuntimePermissionUserIds, userId); 11503 } 11504 } 11505 // Grant an install permission. 11506 if (permissionsState.grantInstallPermission(bp) != 11507 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11508 changedInstallPermission = true; 11509 } 11510 } break; 11511 11512 case GRANT_RUNTIME: { 11513 // Grant previously granted runtime permissions. 11514 for (int userId : UserManagerService.getInstance().getUserIds()) { 11515 PermissionState permissionState = origPermissions 11516 .getRuntimePermissionState(bp.name, userId); 11517 int flags = permissionState != null 11518 ? permissionState.getFlags() : 0; 11519 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11520 // Don't propagate the permission in a permission review mode if 11521 // the former was revoked, i.e. marked to not propagate on upgrade. 11522 // Note that in a permission review mode install permissions are 11523 // represented as constantly granted runtime ones since we need to 11524 // keep a per user state associated with the permission. Also the 11525 // revoke on upgrade flag is no longer applicable and is reset. 11526 final boolean revokeOnUpgrade = (flags & PackageManager 11527 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11528 if (revokeOnUpgrade) { 11529 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11530 // Since we changed the flags, we have to write. 11531 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11532 changedRuntimePermissionUserIds, userId); 11533 } 11534 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11535 if (permissionsState.grantRuntimePermission(bp, userId) == 11536 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11537 // If we cannot put the permission as it was, 11538 // we have to write. 11539 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11540 changedRuntimePermissionUserIds, userId); 11541 } 11542 } 11543 11544 // If the app supports runtime permissions no need for a review. 11545 if (mPermissionReviewRequired 11546 && appSupportsRuntimePermissions 11547 && (flags & PackageManager 11548 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11549 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11550 // Since we changed the flags, we have to write. 11551 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11552 changedRuntimePermissionUserIds, userId); 11553 } 11554 } else if (mPermissionReviewRequired 11555 && !appSupportsRuntimePermissions) { 11556 // For legacy apps that need a permission review, every new 11557 // runtime permission is granted but it is pending a review. 11558 // We also need to review only platform defined runtime 11559 // permissions as these are the only ones the platform knows 11560 // how to disable the API to simulate revocation as legacy 11561 // apps don't expect to run with revoked permissions. 11562 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11563 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11564 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11565 // We changed the flags, hence have to write. 11566 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11567 changedRuntimePermissionUserIds, userId); 11568 } 11569 } 11570 if (permissionsState.grantRuntimePermission(bp, userId) 11571 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11572 // We changed the permission, hence have to write. 11573 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11574 changedRuntimePermissionUserIds, userId); 11575 } 11576 } 11577 // Propagate the permission flags. 11578 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11579 } 11580 } break; 11581 11582 case GRANT_UPGRADE: { 11583 // Grant runtime permissions for a previously held install permission. 11584 PermissionState permissionState = origPermissions 11585 .getInstallPermissionState(bp.name); 11586 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11587 11588 if (origPermissions.revokeInstallPermission(bp) 11589 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11590 // We will be transferring the permission flags, so clear them. 11591 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11592 PackageManager.MASK_PERMISSION_FLAGS, 0); 11593 changedInstallPermission = true; 11594 } 11595 11596 // If the permission is not to be promoted to runtime we ignore it and 11597 // also its other flags as they are not applicable to install permissions. 11598 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11599 for (int userId : currentUserIds) { 11600 if (permissionsState.grantRuntimePermission(bp, userId) != 11601 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11602 // Transfer the permission flags. 11603 permissionsState.updatePermissionFlags(bp, userId, 11604 flags, flags); 11605 // If we granted the permission, we have to write. 11606 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11607 changedRuntimePermissionUserIds, userId); 11608 } 11609 } 11610 } 11611 } break; 11612 11613 default: { 11614 if (packageOfInterest == null 11615 || packageOfInterest.equals(pkg.packageName)) { 11616 Slog.w(TAG, "Not granting permission " + perm 11617 + " to package " + pkg.packageName 11618 + " because it was previously installed without"); 11619 } 11620 } break; 11621 } 11622 } else { 11623 if (permissionsState.revokeInstallPermission(bp) != 11624 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11625 // Also drop the permission flags. 11626 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11627 PackageManager.MASK_PERMISSION_FLAGS, 0); 11628 changedInstallPermission = true; 11629 Slog.i(TAG, "Un-granting permission " + perm 11630 + " from package " + pkg.packageName 11631 + " (protectionLevel=" + bp.protectionLevel 11632 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11633 + ")"); 11634 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11635 // Don't print warning for app op permissions, since it is fine for them 11636 // not to be granted, there is a UI for the user to decide. 11637 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11638 Slog.w(TAG, "Not granting permission " + perm 11639 + " to package " + pkg.packageName 11640 + " (protectionLevel=" + bp.protectionLevel 11641 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11642 + ")"); 11643 } 11644 } 11645 } 11646 } 11647 11648 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11649 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11650 // This is the first that we have heard about this package, so the 11651 // permissions we have now selected are fixed until explicitly 11652 // changed. 11653 ps.installPermissionsFixed = true; 11654 } 11655 11656 // Persist the runtime permissions state for users with changes. If permissions 11657 // were revoked because no app in the shared user declares them we have to 11658 // write synchronously to avoid losing runtime permissions state. 11659 for (int userId : changedRuntimePermissionUserIds) { 11660 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11661 } 11662 } 11663 11664 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11665 boolean allowed = false; 11666 final int NP = PackageParser.NEW_PERMISSIONS.length; 11667 for (int ip=0; ip<NP; ip++) { 11668 final PackageParser.NewPermissionInfo npi 11669 = PackageParser.NEW_PERMISSIONS[ip]; 11670 if (npi.name.equals(perm) 11671 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11672 allowed = true; 11673 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11674 + pkg.packageName); 11675 break; 11676 } 11677 } 11678 return allowed; 11679 } 11680 11681 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11682 BasePermission bp, PermissionsState origPermissions) { 11683 boolean privilegedPermission = (bp.protectionLevel 11684 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11685 boolean privappPermissionsDisable = 11686 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11687 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11688 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11689 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11690 && !platformPackage && platformPermission) { 11691 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11692 .getPrivAppPermissions(pkg.packageName); 11693 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11694 if (!whitelisted) { 11695 Slog.w(TAG, "Privileged permission " + perm + " for package " 11696 + pkg.packageName + " - not in privapp-permissions whitelist"); 11697 // Only report violations for apps on system image 11698 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11699 if (mPrivappPermissionsViolations == null) { 11700 mPrivappPermissionsViolations = new ArraySet<>(); 11701 } 11702 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11703 } 11704 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11705 return false; 11706 } 11707 } 11708 } 11709 boolean allowed = (compareSignatures( 11710 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11711 == PackageManager.SIGNATURE_MATCH) 11712 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11713 == PackageManager.SIGNATURE_MATCH); 11714 if (!allowed && privilegedPermission) { 11715 if (isSystemApp(pkg)) { 11716 // For updated system applications, a system permission 11717 // is granted only if it had been defined by the original application. 11718 if (pkg.isUpdatedSystemApp()) { 11719 final PackageSetting sysPs = mSettings 11720 .getDisabledSystemPkgLPr(pkg.packageName); 11721 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11722 // If the original was granted this permission, we take 11723 // that grant decision as read and propagate it to the 11724 // update. 11725 if (sysPs.isPrivileged()) { 11726 allowed = true; 11727 } 11728 } else { 11729 // The system apk may have been updated with an older 11730 // version of the one on the data partition, but which 11731 // granted a new system permission that it didn't have 11732 // before. In this case we do want to allow the app to 11733 // now get the new permission if the ancestral apk is 11734 // privileged to get it. 11735 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11736 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11737 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11738 allowed = true; 11739 break; 11740 } 11741 } 11742 } 11743 // Also if a privileged parent package on the system image or any of 11744 // its children requested a privileged permission, the updated child 11745 // packages can also get the permission. 11746 if (pkg.parentPackage != null) { 11747 final PackageSetting disabledSysParentPs = mSettings 11748 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11749 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11750 && disabledSysParentPs.isPrivileged()) { 11751 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11752 allowed = true; 11753 } else if (disabledSysParentPs.pkg.childPackages != null) { 11754 final int count = disabledSysParentPs.pkg.childPackages.size(); 11755 for (int i = 0; i < count; i++) { 11756 PackageParser.Package disabledSysChildPkg = 11757 disabledSysParentPs.pkg.childPackages.get(i); 11758 if (isPackageRequestingPermission(disabledSysChildPkg, 11759 perm)) { 11760 allowed = true; 11761 break; 11762 } 11763 } 11764 } 11765 } 11766 } 11767 } 11768 } else { 11769 allowed = isPrivilegedApp(pkg); 11770 } 11771 } 11772 } 11773 if (!allowed) { 11774 if (!allowed && (bp.protectionLevel 11775 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11776 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11777 // If this was a previously normal/dangerous permission that got moved 11778 // to a system permission as part of the runtime permission redesign, then 11779 // we still want to blindly grant it to old apps. 11780 allowed = true; 11781 } 11782 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11783 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11784 // If this permission is to be granted to the system installer and 11785 // this app is an installer, then it gets the permission. 11786 allowed = true; 11787 } 11788 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11789 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11790 // If this permission is to be granted to the system verifier and 11791 // this app is a verifier, then it gets the permission. 11792 allowed = true; 11793 } 11794 if (!allowed && (bp.protectionLevel 11795 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11796 && isSystemApp(pkg)) { 11797 // Any pre-installed system app is allowed to get this permission. 11798 allowed = true; 11799 } 11800 if (!allowed && (bp.protectionLevel 11801 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11802 // For development permissions, a development permission 11803 // is granted only if it was already granted. 11804 allowed = origPermissions.hasInstallPermission(perm); 11805 } 11806 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11807 && pkg.packageName.equals(mSetupWizardPackage)) { 11808 // If this permission is to be granted to the system setup wizard and 11809 // this app is a setup wizard, then it gets the permission. 11810 allowed = true; 11811 } 11812 } 11813 return allowed; 11814 } 11815 11816 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11817 final int permCount = pkg.requestedPermissions.size(); 11818 for (int j = 0; j < permCount; j++) { 11819 String requestedPermission = pkg.requestedPermissions.get(j); 11820 if (permission.equals(requestedPermission)) { 11821 return true; 11822 } 11823 } 11824 return false; 11825 } 11826 11827 final class ActivityIntentResolver 11828 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11829 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11830 boolean defaultOnly, int userId) { 11831 if (!sUserManager.exists(userId)) return null; 11832 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11833 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11834 } 11835 11836 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11837 int userId) { 11838 if (!sUserManager.exists(userId)) return null; 11839 mFlags = flags; 11840 return super.queryIntent(intent, resolvedType, 11841 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11842 userId); 11843 } 11844 11845 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11846 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11847 if (!sUserManager.exists(userId)) return null; 11848 if (packageActivities == null) { 11849 return null; 11850 } 11851 mFlags = flags; 11852 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11853 final int N = packageActivities.size(); 11854 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11855 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11856 11857 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11858 for (int i = 0; i < N; ++i) { 11859 intentFilters = packageActivities.get(i).intents; 11860 if (intentFilters != null && intentFilters.size() > 0) { 11861 PackageParser.ActivityIntentInfo[] array = 11862 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11863 intentFilters.toArray(array); 11864 listCut.add(array); 11865 } 11866 } 11867 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11868 } 11869 11870 /** 11871 * Finds a privileged activity that matches the specified activity names. 11872 */ 11873 private PackageParser.Activity findMatchingActivity( 11874 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11875 for (PackageParser.Activity sysActivity : activityList) { 11876 if (sysActivity.info.name.equals(activityInfo.name)) { 11877 return sysActivity; 11878 } 11879 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11880 return sysActivity; 11881 } 11882 if (sysActivity.info.targetActivity != null) { 11883 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11884 return sysActivity; 11885 } 11886 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11887 return sysActivity; 11888 } 11889 } 11890 } 11891 return null; 11892 } 11893 11894 public class IterGenerator<E> { 11895 public Iterator<E> generate(ActivityIntentInfo info) { 11896 return null; 11897 } 11898 } 11899 11900 public class ActionIterGenerator extends IterGenerator<String> { 11901 @Override 11902 public Iterator<String> generate(ActivityIntentInfo info) { 11903 return info.actionsIterator(); 11904 } 11905 } 11906 11907 public class CategoriesIterGenerator extends IterGenerator<String> { 11908 @Override 11909 public Iterator<String> generate(ActivityIntentInfo info) { 11910 return info.categoriesIterator(); 11911 } 11912 } 11913 11914 public class SchemesIterGenerator extends IterGenerator<String> { 11915 @Override 11916 public Iterator<String> generate(ActivityIntentInfo info) { 11917 return info.schemesIterator(); 11918 } 11919 } 11920 11921 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11922 @Override 11923 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11924 return info.authoritiesIterator(); 11925 } 11926 } 11927 11928 /** 11929 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11930 * MODIFIED. Do not pass in a list that should not be changed. 11931 */ 11932 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11933 IterGenerator<T> generator, Iterator<T> searchIterator) { 11934 // loop through the set of actions; every one must be found in the intent filter 11935 while (searchIterator.hasNext()) { 11936 // we must have at least one filter in the list to consider a match 11937 if (intentList.size() == 0) { 11938 break; 11939 } 11940 11941 final T searchAction = searchIterator.next(); 11942 11943 // loop through the set of intent filters 11944 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11945 while (intentIter.hasNext()) { 11946 final ActivityIntentInfo intentInfo = intentIter.next(); 11947 boolean selectionFound = false; 11948 11949 // loop through the intent filter's selection criteria; at least one 11950 // of them must match the searched criteria 11951 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11952 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11953 final T intentSelection = intentSelectionIter.next(); 11954 if (intentSelection != null && intentSelection.equals(searchAction)) { 11955 selectionFound = true; 11956 break; 11957 } 11958 } 11959 11960 // the selection criteria wasn't found in this filter's set; this filter 11961 // is not a potential match 11962 if (!selectionFound) { 11963 intentIter.remove(); 11964 } 11965 } 11966 } 11967 } 11968 11969 private boolean isProtectedAction(ActivityIntentInfo filter) { 11970 final Iterator<String> actionsIter = filter.actionsIterator(); 11971 while (actionsIter != null && actionsIter.hasNext()) { 11972 final String filterAction = actionsIter.next(); 11973 if (PROTECTED_ACTIONS.contains(filterAction)) { 11974 return true; 11975 } 11976 } 11977 return false; 11978 } 11979 11980 /** 11981 * Adjusts the priority of the given intent filter according to policy. 11982 * <p> 11983 * <ul> 11984 * <li>The priority for non privileged applications is capped to '0'</li> 11985 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11986 * <li>The priority for unbundled updates to privileged applications is capped to the 11987 * priority defined on the system partition</li> 11988 * </ul> 11989 * <p> 11990 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11991 * allowed to obtain any priority on any action. 11992 */ 11993 private void adjustPriority( 11994 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11995 // nothing to do; priority is fine as-is 11996 if (intent.getPriority() <= 0) { 11997 return; 11998 } 11999 12000 final ActivityInfo activityInfo = intent.activity.info; 12001 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12002 12003 final boolean privilegedApp = 12004 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12005 if (!privilegedApp) { 12006 // non-privileged applications can never define a priority >0 12007 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12008 + " package: " + applicationInfo.packageName 12009 + " activity: " + intent.activity.className 12010 + " origPrio: " + intent.getPriority()); 12011 intent.setPriority(0); 12012 return; 12013 } 12014 12015 if (systemActivities == null) { 12016 // the system package is not disabled; we're parsing the system partition 12017 if (isProtectedAction(intent)) { 12018 if (mDeferProtectedFilters) { 12019 // We can't deal with these just yet. No component should ever obtain a 12020 // >0 priority for a protected actions, with ONE exception -- the setup 12021 // wizard. The setup wizard, however, cannot be known until we're able to 12022 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12023 // until all intent filters have been processed. Chicken, meet egg. 12024 // Let the filter temporarily have a high priority and rectify the 12025 // priorities after all system packages have been scanned. 12026 mProtectedFilters.add(intent); 12027 if (DEBUG_FILTERS) { 12028 Slog.i(TAG, "Protected action; save for later;" 12029 + " package: " + applicationInfo.packageName 12030 + " activity: " + intent.activity.className 12031 + " origPrio: " + intent.getPriority()); 12032 } 12033 return; 12034 } else { 12035 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12036 Slog.i(TAG, "No setup wizard;" 12037 + " All protected intents capped to priority 0"); 12038 } 12039 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12040 if (DEBUG_FILTERS) { 12041 Slog.i(TAG, "Found setup wizard;" 12042 + " allow priority " + intent.getPriority() + ";" 12043 + " package: " + intent.activity.info.packageName 12044 + " activity: " + intent.activity.className 12045 + " priority: " + intent.getPriority()); 12046 } 12047 // setup wizard gets whatever it wants 12048 return; 12049 } 12050 Slog.w(TAG, "Protected action; cap priority to 0;" 12051 + " package: " + intent.activity.info.packageName 12052 + " activity: " + intent.activity.className 12053 + " origPrio: " + intent.getPriority()); 12054 intent.setPriority(0); 12055 return; 12056 } 12057 } 12058 // privileged apps on the system image get whatever priority they request 12059 return; 12060 } 12061 12062 // privileged app unbundled update ... try to find the same activity 12063 final PackageParser.Activity foundActivity = 12064 findMatchingActivity(systemActivities, activityInfo); 12065 if (foundActivity == null) { 12066 // this is a new activity; it cannot obtain >0 priority 12067 if (DEBUG_FILTERS) { 12068 Slog.i(TAG, "New activity; cap priority to 0;" 12069 + " package: " + applicationInfo.packageName 12070 + " activity: " + intent.activity.className 12071 + " origPrio: " + intent.getPriority()); 12072 } 12073 intent.setPriority(0); 12074 return; 12075 } 12076 12077 // found activity, now check for filter equivalence 12078 12079 // a shallow copy is enough; we modify the list, not its contents 12080 final List<ActivityIntentInfo> intentListCopy = 12081 new ArrayList<>(foundActivity.intents); 12082 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12083 12084 // find matching action subsets 12085 final Iterator<String> actionsIterator = intent.actionsIterator(); 12086 if (actionsIterator != null) { 12087 getIntentListSubset( 12088 intentListCopy, new ActionIterGenerator(), actionsIterator); 12089 if (intentListCopy.size() == 0) { 12090 // no more intents to match; we're not equivalent 12091 if (DEBUG_FILTERS) { 12092 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12093 + " package: " + applicationInfo.packageName 12094 + " activity: " + intent.activity.className 12095 + " origPrio: " + intent.getPriority()); 12096 } 12097 intent.setPriority(0); 12098 return; 12099 } 12100 } 12101 12102 // find matching category subsets 12103 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12104 if (categoriesIterator != null) { 12105 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12106 categoriesIterator); 12107 if (intentListCopy.size() == 0) { 12108 // no more intents to match; we're not equivalent 12109 if (DEBUG_FILTERS) { 12110 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12111 + " package: " + applicationInfo.packageName 12112 + " activity: " + intent.activity.className 12113 + " origPrio: " + intent.getPriority()); 12114 } 12115 intent.setPriority(0); 12116 return; 12117 } 12118 } 12119 12120 // find matching schemes subsets 12121 final Iterator<String> schemesIterator = intent.schemesIterator(); 12122 if (schemesIterator != null) { 12123 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12124 schemesIterator); 12125 if (intentListCopy.size() == 0) { 12126 // no more intents to match; we're not equivalent 12127 if (DEBUG_FILTERS) { 12128 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12129 + " package: " + applicationInfo.packageName 12130 + " activity: " + intent.activity.className 12131 + " origPrio: " + intent.getPriority()); 12132 } 12133 intent.setPriority(0); 12134 return; 12135 } 12136 } 12137 12138 // find matching authorities subsets 12139 final Iterator<IntentFilter.AuthorityEntry> 12140 authoritiesIterator = intent.authoritiesIterator(); 12141 if (authoritiesIterator != null) { 12142 getIntentListSubset(intentListCopy, 12143 new AuthoritiesIterGenerator(), 12144 authoritiesIterator); 12145 if (intentListCopy.size() == 0) { 12146 // no more intents to match; we're not equivalent 12147 if (DEBUG_FILTERS) { 12148 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12149 + " package: " + applicationInfo.packageName 12150 + " activity: " + intent.activity.className 12151 + " origPrio: " + intent.getPriority()); 12152 } 12153 intent.setPriority(0); 12154 return; 12155 } 12156 } 12157 12158 // we found matching filter(s); app gets the max priority of all intents 12159 int cappedPriority = 0; 12160 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12161 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12162 } 12163 if (intent.getPriority() > cappedPriority) { 12164 if (DEBUG_FILTERS) { 12165 Slog.i(TAG, "Found matching filter(s);" 12166 + " cap priority to " + cappedPriority + ";" 12167 + " package: " + applicationInfo.packageName 12168 + " activity: " + intent.activity.className 12169 + " origPrio: " + intent.getPriority()); 12170 } 12171 intent.setPriority(cappedPriority); 12172 return; 12173 } 12174 // all this for nothing; the requested priority was <= what was on the system 12175 } 12176 12177 public final void addActivity(PackageParser.Activity a, String type) { 12178 mActivities.put(a.getComponentName(), a); 12179 if (DEBUG_SHOW_INFO) 12180 Log.v( 12181 TAG, " " + type + " " + 12182 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12183 if (DEBUG_SHOW_INFO) 12184 Log.v(TAG, " Class=" + a.info.name); 12185 final int NI = a.intents.size(); 12186 for (int j=0; j<NI; j++) { 12187 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12188 if ("activity".equals(type)) { 12189 final PackageSetting ps = 12190 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12191 final List<PackageParser.Activity> systemActivities = 12192 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12193 adjustPriority(systemActivities, intent); 12194 } 12195 if (DEBUG_SHOW_INFO) { 12196 Log.v(TAG, " IntentFilter:"); 12197 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12198 } 12199 if (!intent.debugCheck()) { 12200 Log.w(TAG, "==> For Activity " + a.info.name); 12201 } 12202 addFilter(intent); 12203 } 12204 } 12205 12206 public final void removeActivity(PackageParser.Activity a, String type) { 12207 mActivities.remove(a.getComponentName()); 12208 if (DEBUG_SHOW_INFO) { 12209 Log.v(TAG, " " + type + " " 12210 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12211 : a.info.name) + ":"); 12212 Log.v(TAG, " Class=" + a.info.name); 12213 } 12214 final int NI = a.intents.size(); 12215 for (int j=0; j<NI; j++) { 12216 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12217 if (DEBUG_SHOW_INFO) { 12218 Log.v(TAG, " IntentFilter:"); 12219 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12220 } 12221 removeFilter(intent); 12222 } 12223 } 12224 12225 @Override 12226 protected boolean allowFilterResult( 12227 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12228 ActivityInfo filterAi = filter.activity.info; 12229 for (int i=dest.size()-1; i>=0; i--) { 12230 ActivityInfo destAi = dest.get(i).activityInfo; 12231 if (destAi.name == filterAi.name 12232 && destAi.packageName == filterAi.packageName) { 12233 return false; 12234 } 12235 } 12236 return true; 12237 } 12238 12239 @Override 12240 protected ActivityIntentInfo[] newArray(int size) { 12241 return new ActivityIntentInfo[size]; 12242 } 12243 12244 @Override 12245 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12246 if (!sUserManager.exists(userId)) return true; 12247 PackageParser.Package p = filter.activity.owner; 12248 if (p != null) { 12249 PackageSetting ps = (PackageSetting)p.mExtras; 12250 if (ps != null) { 12251 // System apps are never considered stopped for purposes of 12252 // filtering, because there may be no way for the user to 12253 // actually re-launch them. 12254 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12255 && ps.getStopped(userId); 12256 } 12257 } 12258 return false; 12259 } 12260 12261 @Override 12262 protected boolean isPackageForFilter(String packageName, 12263 PackageParser.ActivityIntentInfo info) { 12264 return packageName.equals(info.activity.owner.packageName); 12265 } 12266 12267 @Override 12268 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12269 int match, int userId) { 12270 if (!sUserManager.exists(userId)) return null; 12271 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12272 return null; 12273 } 12274 final PackageParser.Activity activity = info.activity; 12275 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12276 if (ps == null) { 12277 return null; 12278 } 12279 final PackageUserState userState = ps.readUserState(userId); 12280 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12281 userState, userId); 12282 if (ai == null) { 12283 return null; 12284 } 12285 final boolean matchVisibleToInstantApp = 12286 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12287 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12288 // throw out filters that aren't visible to ephemeral apps 12289 if (matchVisibleToInstantApp 12290 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12291 return null; 12292 } 12293 // throw out ephemeral filters if we're not explicitly requesting them 12294 if (!isInstantApp && userState.instantApp) { 12295 return null; 12296 } 12297 // throw out instant app filters if updates are available; will trigger 12298 // instant app resolution 12299 if (userState.instantApp && ps.isUpdateAvailable()) { 12300 return null; 12301 } 12302 final ResolveInfo res = new ResolveInfo(); 12303 res.activityInfo = ai; 12304 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12305 res.filter = info; 12306 } 12307 if (info != null) { 12308 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12309 } 12310 res.priority = info.getPriority(); 12311 res.preferredOrder = activity.owner.mPreferredOrder; 12312 //System.out.println("Result: " + res.activityInfo.className + 12313 // " = " + res.priority); 12314 res.match = match; 12315 res.isDefault = info.hasDefault; 12316 res.labelRes = info.labelRes; 12317 res.nonLocalizedLabel = info.nonLocalizedLabel; 12318 if (userNeedsBadging(userId)) { 12319 res.noResourceId = true; 12320 } else { 12321 res.icon = info.icon; 12322 } 12323 res.iconResourceId = info.icon; 12324 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12325 res.instantAppAvailable = userState.instantApp; 12326 return res; 12327 } 12328 12329 @Override 12330 protected void sortResults(List<ResolveInfo> results) { 12331 Collections.sort(results, mResolvePrioritySorter); 12332 } 12333 12334 @Override 12335 protected void dumpFilter(PrintWriter out, String prefix, 12336 PackageParser.ActivityIntentInfo filter) { 12337 out.print(prefix); out.print( 12338 Integer.toHexString(System.identityHashCode(filter.activity))); 12339 out.print(' '); 12340 filter.activity.printComponentShortName(out); 12341 out.print(" filter "); 12342 out.println(Integer.toHexString(System.identityHashCode(filter))); 12343 } 12344 12345 @Override 12346 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12347 return filter.activity; 12348 } 12349 12350 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12351 PackageParser.Activity activity = (PackageParser.Activity)label; 12352 out.print(prefix); out.print( 12353 Integer.toHexString(System.identityHashCode(activity))); 12354 out.print(' '); 12355 activity.printComponentShortName(out); 12356 if (count > 1) { 12357 out.print(" ("); out.print(count); out.print(" filters)"); 12358 } 12359 out.println(); 12360 } 12361 12362 // Keys are String (activity class name), values are Activity. 12363 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12364 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12365 private int mFlags; 12366 } 12367 12368 private final class ServiceIntentResolver 12369 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12370 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12371 boolean defaultOnly, int userId) { 12372 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12373 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12374 } 12375 12376 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12377 int userId) { 12378 if (!sUserManager.exists(userId)) return null; 12379 mFlags = flags; 12380 return super.queryIntent(intent, resolvedType, 12381 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12382 userId); 12383 } 12384 12385 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12386 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12387 if (!sUserManager.exists(userId)) return null; 12388 if (packageServices == null) { 12389 return null; 12390 } 12391 mFlags = flags; 12392 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12393 final int N = packageServices.size(); 12394 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12395 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12396 12397 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12398 for (int i = 0; i < N; ++i) { 12399 intentFilters = packageServices.get(i).intents; 12400 if (intentFilters != null && intentFilters.size() > 0) { 12401 PackageParser.ServiceIntentInfo[] array = 12402 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12403 intentFilters.toArray(array); 12404 listCut.add(array); 12405 } 12406 } 12407 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12408 } 12409 12410 public final void addService(PackageParser.Service s) { 12411 mServices.put(s.getComponentName(), s); 12412 if (DEBUG_SHOW_INFO) { 12413 Log.v(TAG, " " 12414 + (s.info.nonLocalizedLabel != null 12415 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12416 Log.v(TAG, " Class=" + s.info.name); 12417 } 12418 final int NI = s.intents.size(); 12419 int j; 12420 for (j=0; j<NI; j++) { 12421 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12422 if (DEBUG_SHOW_INFO) { 12423 Log.v(TAG, " IntentFilter:"); 12424 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12425 } 12426 if (!intent.debugCheck()) { 12427 Log.w(TAG, "==> For Service " + s.info.name); 12428 } 12429 addFilter(intent); 12430 } 12431 } 12432 12433 public final void removeService(PackageParser.Service s) { 12434 mServices.remove(s.getComponentName()); 12435 if (DEBUG_SHOW_INFO) { 12436 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12437 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12438 Log.v(TAG, " Class=" + s.info.name); 12439 } 12440 final int NI = s.intents.size(); 12441 int j; 12442 for (j=0; j<NI; j++) { 12443 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12444 if (DEBUG_SHOW_INFO) { 12445 Log.v(TAG, " IntentFilter:"); 12446 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12447 } 12448 removeFilter(intent); 12449 } 12450 } 12451 12452 @Override 12453 protected boolean allowFilterResult( 12454 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12455 ServiceInfo filterSi = filter.service.info; 12456 for (int i=dest.size()-1; i>=0; i--) { 12457 ServiceInfo destAi = dest.get(i).serviceInfo; 12458 if (destAi.name == filterSi.name 12459 && destAi.packageName == filterSi.packageName) { 12460 return false; 12461 } 12462 } 12463 return true; 12464 } 12465 12466 @Override 12467 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12468 return new PackageParser.ServiceIntentInfo[size]; 12469 } 12470 12471 @Override 12472 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12473 if (!sUserManager.exists(userId)) return true; 12474 PackageParser.Package p = filter.service.owner; 12475 if (p != null) { 12476 PackageSetting ps = (PackageSetting)p.mExtras; 12477 if (ps != null) { 12478 // System apps are never considered stopped for purposes of 12479 // filtering, because there may be no way for the user to 12480 // actually re-launch them. 12481 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12482 && ps.getStopped(userId); 12483 } 12484 } 12485 return false; 12486 } 12487 12488 @Override 12489 protected boolean isPackageForFilter(String packageName, 12490 PackageParser.ServiceIntentInfo info) { 12491 return packageName.equals(info.service.owner.packageName); 12492 } 12493 12494 @Override 12495 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12496 int match, int userId) { 12497 if (!sUserManager.exists(userId)) return null; 12498 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12499 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12500 return null; 12501 } 12502 final PackageParser.Service service = info.service; 12503 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12504 if (ps == null) { 12505 return null; 12506 } 12507 final PackageUserState userState = ps.readUserState(userId); 12508 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12509 userState, userId); 12510 if (si == null) { 12511 return null; 12512 } 12513 final boolean matchVisibleToInstantApp = 12514 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12515 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12516 // throw out filters that aren't visible to ephemeral apps 12517 if (matchVisibleToInstantApp 12518 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12519 return null; 12520 } 12521 // throw out ephemeral filters if we're not explicitly requesting them 12522 if (!isInstantApp && userState.instantApp) { 12523 return null; 12524 } 12525 // throw out instant app filters if updates are available; will trigger 12526 // instant app resolution 12527 if (userState.instantApp && ps.isUpdateAvailable()) { 12528 return null; 12529 } 12530 final ResolveInfo res = new ResolveInfo(); 12531 res.serviceInfo = si; 12532 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12533 res.filter = filter; 12534 } 12535 res.priority = info.getPriority(); 12536 res.preferredOrder = service.owner.mPreferredOrder; 12537 res.match = match; 12538 res.isDefault = info.hasDefault; 12539 res.labelRes = info.labelRes; 12540 res.nonLocalizedLabel = info.nonLocalizedLabel; 12541 res.icon = info.icon; 12542 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12543 return res; 12544 } 12545 12546 @Override 12547 protected void sortResults(List<ResolveInfo> results) { 12548 Collections.sort(results, mResolvePrioritySorter); 12549 } 12550 12551 @Override 12552 protected void dumpFilter(PrintWriter out, String prefix, 12553 PackageParser.ServiceIntentInfo filter) { 12554 out.print(prefix); out.print( 12555 Integer.toHexString(System.identityHashCode(filter.service))); 12556 out.print(' '); 12557 filter.service.printComponentShortName(out); 12558 out.print(" filter "); 12559 out.println(Integer.toHexString(System.identityHashCode(filter))); 12560 } 12561 12562 @Override 12563 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12564 return filter.service; 12565 } 12566 12567 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12568 PackageParser.Service service = (PackageParser.Service)label; 12569 out.print(prefix); out.print( 12570 Integer.toHexString(System.identityHashCode(service))); 12571 out.print(' '); 12572 service.printComponentShortName(out); 12573 if (count > 1) { 12574 out.print(" ("); out.print(count); out.print(" filters)"); 12575 } 12576 out.println(); 12577 } 12578 12579// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12580// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12581// final List<ResolveInfo> retList = Lists.newArrayList(); 12582// while (i.hasNext()) { 12583// final ResolveInfo resolveInfo = (ResolveInfo) i; 12584// if (isEnabledLP(resolveInfo.serviceInfo)) { 12585// retList.add(resolveInfo); 12586// } 12587// } 12588// return retList; 12589// } 12590 12591 // Keys are String (activity class name), values are Activity. 12592 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12593 = new ArrayMap<ComponentName, PackageParser.Service>(); 12594 private int mFlags; 12595 } 12596 12597 private final class ProviderIntentResolver 12598 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12599 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12600 boolean defaultOnly, int userId) { 12601 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12602 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12603 } 12604 12605 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12606 int userId) { 12607 if (!sUserManager.exists(userId)) 12608 return null; 12609 mFlags = flags; 12610 return super.queryIntent(intent, resolvedType, 12611 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12612 userId); 12613 } 12614 12615 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12616 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12617 if (!sUserManager.exists(userId)) 12618 return null; 12619 if (packageProviders == null) { 12620 return null; 12621 } 12622 mFlags = flags; 12623 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12624 final int N = packageProviders.size(); 12625 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12626 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12627 12628 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12629 for (int i = 0; i < N; ++i) { 12630 intentFilters = packageProviders.get(i).intents; 12631 if (intentFilters != null && intentFilters.size() > 0) { 12632 PackageParser.ProviderIntentInfo[] array = 12633 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12634 intentFilters.toArray(array); 12635 listCut.add(array); 12636 } 12637 } 12638 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12639 } 12640 12641 public final void addProvider(PackageParser.Provider p) { 12642 if (mProviders.containsKey(p.getComponentName())) { 12643 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12644 return; 12645 } 12646 12647 mProviders.put(p.getComponentName(), p); 12648 if (DEBUG_SHOW_INFO) { 12649 Log.v(TAG, " " 12650 + (p.info.nonLocalizedLabel != null 12651 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12652 Log.v(TAG, " Class=" + p.info.name); 12653 } 12654 final int NI = p.intents.size(); 12655 int j; 12656 for (j = 0; j < NI; j++) { 12657 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12658 if (DEBUG_SHOW_INFO) { 12659 Log.v(TAG, " IntentFilter:"); 12660 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12661 } 12662 if (!intent.debugCheck()) { 12663 Log.w(TAG, "==> For Provider " + p.info.name); 12664 } 12665 addFilter(intent); 12666 } 12667 } 12668 12669 public final void removeProvider(PackageParser.Provider p) { 12670 mProviders.remove(p.getComponentName()); 12671 if (DEBUG_SHOW_INFO) { 12672 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12673 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12674 Log.v(TAG, " Class=" + p.info.name); 12675 } 12676 final int NI = p.intents.size(); 12677 int j; 12678 for (j = 0; j < NI; j++) { 12679 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12680 if (DEBUG_SHOW_INFO) { 12681 Log.v(TAG, " IntentFilter:"); 12682 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12683 } 12684 removeFilter(intent); 12685 } 12686 } 12687 12688 @Override 12689 protected boolean allowFilterResult( 12690 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12691 ProviderInfo filterPi = filter.provider.info; 12692 for (int i = dest.size() - 1; i >= 0; i--) { 12693 ProviderInfo destPi = dest.get(i).providerInfo; 12694 if (destPi.name == filterPi.name 12695 && destPi.packageName == filterPi.packageName) { 12696 return false; 12697 } 12698 } 12699 return true; 12700 } 12701 12702 @Override 12703 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12704 return new PackageParser.ProviderIntentInfo[size]; 12705 } 12706 12707 @Override 12708 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12709 if (!sUserManager.exists(userId)) 12710 return true; 12711 PackageParser.Package p = filter.provider.owner; 12712 if (p != null) { 12713 PackageSetting ps = (PackageSetting) p.mExtras; 12714 if (ps != null) { 12715 // System apps are never considered stopped for purposes of 12716 // filtering, because there may be no way for the user to 12717 // actually re-launch them. 12718 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12719 && ps.getStopped(userId); 12720 } 12721 } 12722 return false; 12723 } 12724 12725 @Override 12726 protected boolean isPackageForFilter(String packageName, 12727 PackageParser.ProviderIntentInfo info) { 12728 return packageName.equals(info.provider.owner.packageName); 12729 } 12730 12731 @Override 12732 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12733 int match, int userId) { 12734 if (!sUserManager.exists(userId)) 12735 return null; 12736 final PackageParser.ProviderIntentInfo info = filter; 12737 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12738 return null; 12739 } 12740 final PackageParser.Provider provider = info.provider; 12741 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12742 if (ps == null) { 12743 return null; 12744 } 12745 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12746 ps.readUserState(userId), userId); 12747 if (pi == null) { 12748 return null; 12749 } 12750 final ResolveInfo res = new ResolveInfo(); 12751 res.providerInfo = pi; 12752 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12753 res.filter = filter; 12754 } 12755 res.priority = info.getPriority(); 12756 res.preferredOrder = provider.owner.mPreferredOrder; 12757 res.match = match; 12758 res.isDefault = info.hasDefault; 12759 res.labelRes = info.labelRes; 12760 res.nonLocalizedLabel = info.nonLocalizedLabel; 12761 res.icon = info.icon; 12762 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12763 return res; 12764 } 12765 12766 @Override 12767 protected void sortResults(List<ResolveInfo> results) { 12768 Collections.sort(results, mResolvePrioritySorter); 12769 } 12770 12771 @Override 12772 protected void dumpFilter(PrintWriter out, String prefix, 12773 PackageParser.ProviderIntentInfo filter) { 12774 out.print(prefix); 12775 out.print( 12776 Integer.toHexString(System.identityHashCode(filter.provider))); 12777 out.print(' '); 12778 filter.provider.printComponentShortName(out); 12779 out.print(" filter "); 12780 out.println(Integer.toHexString(System.identityHashCode(filter))); 12781 } 12782 12783 @Override 12784 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12785 return filter.provider; 12786 } 12787 12788 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12789 PackageParser.Provider provider = (PackageParser.Provider)label; 12790 out.print(prefix); out.print( 12791 Integer.toHexString(System.identityHashCode(provider))); 12792 out.print(' '); 12793 provider.printComponentShortName(out); 12794 if (count > 1) { 12795 out.print(" ("); out.print(count); out.print(" filters)"); 12796 } 12797 out.println(); 12798 } 12799 12800 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12801 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12802 private int mFlags; 12803 } 12804 12805 static final class EphemeralIntentResolver 12806 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12807 /** 12808 * The result that has the highest defined order. Ordering applies on a 12809 * per-package basis. Mapping is from package name to Pair of order and 12810 * EphemeralResolveInfo. 12811 * <p> 12812 * NOTE: This is implemented as a field variable for convenience and efficiency. 12813 * By having a field variable, we're able to track filter ordering as soon as 12814 * a non-zero order is defined. Otherwise, multiple loops across the result set 12815 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12816 * this needs to be contained entirely within {@link #filterResults}. 12817 */ 12818 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12819 12820 @Override 12821 protected AuxiliaryResolveInfo[] newArray(int size) { 12822 return new AuxiliaryResolveInfo[size]; 12823 } 12824 12825 @Override 12826 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12827 return true; 12828 } 12829 12830 @Override 12831 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12832 int userId) { 12833 if (!sUserManager.exists(userId)) { 12834 return null; 12835 } 12836 final String packageName = responseObj.resolveInfo.getPackageName(); 12837 final Integer order = responseObj.getOrder(); 12838 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12839 mOrderResult.get(packageName); 12840 // ordering is enabled and this item's order isn't high enough 12841 if (lastOrderResult != null && lastOrderResult.first >= order) { 12842 return null; 12843 } 12844 final InstantAppResolveInfo res = responseObj.resolveInfo; 12845 if (order > 0) { 12846 // non-zero order, enable ordering 12847 mOrderResult.put(packageName, new Pair<>(order, res)); 12848 } 12849 return responseObj; 12850 } 12851 12852 @Override 12853 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12854 // only do work if ordering is enabled [most of the time it won't be] 12855 if (mOrderResult.size() == 0) { 12856 return; 12857 } 12858 int resultSize = results.size(); 12859 for (int i = 0; i < resultSize; i++) { 12860 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12861 final String packageName = info.getPackageName(); 12862 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12863 if (savedInfo == null) { 12864 // package doesn't having ordering 12865 continue; 12866 } 12867 if (savedInfo.second == info) { 12868 // circled back to the highest ordered item; remove from order list 12869 mOrderResult.remove(savedInfo); 12870 if (mOrderResult.size() == 0) { 12871 // no more ordered items 12872 break; 12873 } 12874 continue; 12875 } 12876 // item has a worse order, remove it from the result list 12877 results.remove(i); 12878 resultSize--; 12879 i--; 12880 } 12881 } 12882 } 12883 12884 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12885 new Comparator<ResolveInfo>() { 12886 public int compare(ResolveInfo r1, ResolveInfo r2) { 12887 int v1 = r1.priority; 12888 int v2 = r2.priority; 12889 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12890 if (v1 != v2) { 12891 return (v1 > v2) ? -1 : 1; 12892 } 12893 v1 = r1.preferredOrder; 12894 v2 = r2.preferredOrder; 12895 if (v1 != v2) { 12896 return (v1 > v2) ? -1 : 1; 12897 } 12898 if (r1.isDefault != r2.isDefault) { 12899 return r1.isDefault ? -1 : 1; 12900 } 12901 v1 = r1.match; 12902 v2 = r2.match; 12903 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12904 if (v1 != v2) { 12905 return (v1 > v2) ? -1 : 1; 12906 } 12907 if (r1.system != r2.system) { 12908 return r1.system ? -1 : 1; 12909 } 12910 if (r1.activityInfo != null) { 12911 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12912 } 12913 if (r1.serviceInfo != null) { 12914 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12915 } 12916 if (r1.providerInfo != null) { 12917 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12918 } 12919 return 0; 12920 } 12921 }; 12922 12923 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12924 new Comparator<ProviderInfo>() { 12925 public int compare(ProviderInfo p1, ProviderInfo p2) { 12926 final int v1 = p1.initOrder; 12927 final int v2 = p2.initOrder; 12928 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12929 } 12930 }; 12931 12932 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12933 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12934 final int[] userIds) { 12935 mHandler.post(new Runnable() { 12936 @Override 12937 public void run() { 12938 try { 12939 final IActivityManager am = ActivityManager.getService(); 12940 if (am == null) return; 12941 final int[] resolvedUserIds; 12942 if (userIds == null) { 12943 resolvedUserIds = am.getRunningUserIds(); 12944 } else { 12945 resolvedUserIds = userIds; 12946 } 12947 for (int id : resolvedUserIds) { 12948 final Intent intent = new Intent(action, 12949 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12950 if (extras != null) { 12951 intent.putExtras(extras); 12952 } 12953 if (targetPkg != null) { 12954 intent.setPackage(targetPkg); 12955 } 12956 // Modify the UID when posting to other users 12957 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12958 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12959 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12960 intent.putExtra(Intent.EXTRA_UID, uid); 12961 } 12962 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12963 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12964 if (DEBUG_BROADCASTS) { 12965 RuntimeException here = new RuntimeException("here"); 12966 here.fillInStackTrace(); 12967 Slog.d(TAG, "Sending to user " + id + ": " 12968 + intent.toShortString(false, true, false, false) 12969 + " " + intent.getExtras(), here); 12970 } 12971 am.broadcastIntent(null, intent, null, finishedReceiver, 12972 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12973 null, finishedReceiver != null, false, id); 12974 } 12975 } catch (RemoteException ex) { 12976 } 12977 } 12978 }); 12979 } 12980 12981 /** 12982 * Check if the external storage media is available. This is true if there 12983 * is a mounted external storage medium or if the external storage is 12984 * emulated. 12985 */ 12986 private boolean isExternalMediaAvailable() { 12987 return mMediaMounted || Environment.isExternalStorageEmulated(); 12988 } 12989 12990 @Override 12991 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12992 // writer 12993 synchronized (mPackages) { 12994 if (!isExternalMediaAvailable()) { 12995 // If the external storage is no longer mounted at this point, 12996 // the caller may not have been able to delete all of this 12997 // packages files and can not delete any more. Bail. 12998 return null; 12999 } 13000 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13001 if (lastPackage != null) { 13002 pkgs.remove(lastPackage); 13003 } 13004 if (pkgs.size() > 0) { 13005 return pkgs.get(0); 13006 } 13007 } 13008 return null; 13009 } 13010 13011 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13012 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13013 userId, andCode ? 1 : 0, packageName); 13014 if (mSystemReady) { 13015 msg.sendToTarget(); 13016 } else { 13017 if (mPostSystemReadyMessages == null) { 13018 mPostSystemReadyMessages = new ArrayList<>(); 13019 } 13020 mPostSystemReadyMessages.add(msg); 13021 } 13022 } 13023 13024 void startCleaningPackages() { 13025 // reader 13026 if (!isExternalMediaAvailable()) { 13027 return; 13028 } 13029 synchronized (mPackages) { 13030 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13031 return; 13032 } 13033 } 13034 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13035 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13036 IActivityManager am = ActivityManager.getService(); 13037 if (am != null) { 13038 try { 13039 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13040 UserHandle.USER_SYSTEM); 13041 } catch (RemoteException e) { 13042 } 13043 } 13044 } 13045 13046 @Override 13047 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13048 int installFlags, String installerPackageName, int userId) { 13049 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13050 13051 final int callingUid = Binder.getCallingUid(); 13052 enforceCrossUserPermission(callingUid, userId, 13053 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13054 13055 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13056 try { 13057 if (observer != null) { 13058 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13059 } 13060 } catch (RemoteException re) { 13061 } 13062 return; 13063 } 13064 13065 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13066 installFlags |= PackageManager.INSTALL_FROM_ADB; 13067 13068 } else { 13069 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13070 // about installerPackageName. 13071 13072 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13073 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13074 } 13075 13076 UserHandle user; 13077 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13078 user = UserHandle.ALL; 13079 } else { 13080 user = new UserHandle(userId); 13081 } 13082 13083 // Only system components can circumvent runtime permissions when installing. 13084 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13085 && mContext.checkCallingOrSelfPermission(Manifest.permission 13086 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13087 throw new SecurityException("You need the " 13088 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13089 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13090 } 13091 13092 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13093 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13094 throw new IllegalArgumentException( 13095 "New installs into ASEC containers no longer supported"); 13096 } 13097 13098 final File originFile = new File(originPath); 13099 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13100 13101 final Message msg = mHandler.obtainMessage(INIT_COPY); 13102 final VerificationInfo verificationInfo = new VerificationInfo( 13103 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13104 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13105 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13106 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13107 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13108 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13109 msg.obj = params; 13110 13111 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13112 System.identityHashCode(msg.obj)); 13113 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13114 System.identityHashCode(msg.obj)); 13115 13116 mHandler.sendMessage(msg); 13117 } 13118 13119 13120 /** 13121 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13122 * it is acting on behalf on an enterprise or the user). 13123 * 13124 * Note that the ordering of the conditionals in this method is important. The checks we perform 13125 * are as follows, in this order: 13126 * 13127 * 1) If the install is being performed by a system app, we can trust the app to have set the 13128 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13129 * what it is. 13130 * 2) If the install is being performed by a device or profile owner app, the install reason 13131 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13132 * set the install reason correctly. If the app targets an older SDK version where install 13133 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13134 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13135 * 3) In all other cases, the install is being performed by a regular app that is neither part 13136 * of the system nor a device or profile owner. We have no reason to believe that this app is 13137 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13138 * set to enterprise policy and if so, change it to unknown instead. 13139 */ 13140 private int fixUpInstallReason(String installerPackageName, int installerUid, 13141 int installReason) { 13142 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13143 == PERMISSION_GRANTED) { 13144 // If the install is being performed by a system app, we trust that app to have set the 13145 // install reason correctly. 13146 return installReason; 13147 } 13148 13149 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13150 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13151 if (dpm != null) { 13152 ComponentName owner = null; 13153 try { 13154 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13155 if (owner == null) { 13156 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13157 } 13158 } catch (RemoteException e) { 13159 } 13160 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13161 // If the install is being performed by a device or profile owner, the install 13162 // reason should be enterprise policy. 13163 return PackageManager.INSTALL_REASON_POLICY; 13164 } 13165 } 13166 13167 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13168 // If the install is being performed by a regular app (i.e. neither system app nor 13169 // device or profile owner), we have no reason to believe that the app is acting on 13170 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13171 // change it to unknown instead. 13172 return PackageManager.INSTALL_REASON_UNKNOWN; 13173 } 13174 13175 // If the install is being performed by a regular app and the install reason was set to any 13176 // value but enterprise policy, leave the install reason unchanged. 13177 return installReason; 13178 } 13179 13180 void installStage(String packageName, File stagedDir, String stagedCid, 13181 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13182 String installerPackageName, int installerUid, UserHandle user, 13183 Certificate[][] certificates) { 13184 if (DEBUG_EPHEMERAL) { 13185 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13186 Slog.d(TAG, "Ephemeral install of " + packageName); 13187 } 13188 } 13189 final VerificationInfo verificationInfo = new VerificationInfo( 13190 sessionParams.originatingUri, sessionParams.referrerUri, 13191 sessionParams.originatingUid, installerUid); 13192 13193 final OriginInfo origin; 13194 if (stagedDir != null) { 13195 origin = OriginInfo.fromStagedFile(stagedDir); 13196 } else { 13197 origin = OriginInfo.fromStagedContainer(stagedCid); 13198 } 13199 13200 final Message msg = mHandler.obtainMessage(INIT_COPY); 13201 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13202 sessionParams.installReason); 13203 final InstallParams params = new InstallParams(origin, null, observer, 13204 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13205 verificationInfo, user, sessionParams.abiOverride, 13206 sessionParams.grantedRuntimePermissions, certificates, installReason); 13207 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13208 msg.obj = params; 13209 13210 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13211 System.identityHashCode(msg.obj)); 13212 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13213 System.identityHashCode(msg.obj)); 13214 13215 mHandler.sendMessage(msg); 13216 } 13217 13218 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13219 int userId) { 13220 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13221 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13222 } 13223 13224 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13225 int appId, int... userIds) { 13226 if (ArrayUtils.isEmpty(userIds)) { 13227 return; 13228 } 13229 Bundle extras = new Bundle(1); 13230 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13231 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13232 13233 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13234 packageName, extras, 0, null, null, userIds); 13235 if (isSystem) { 13236 mHandler.post(() -> { 13237 for (int userId : userIds) { 13238 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13239 } 13240 } 13241 ); 13242 } 13243 } 13244 13245 /** 13246 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13247 * automatically without needing an explicit launch. 13248 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13249 */ 13250 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13251 // If user is not running, the app didn't miss any broadcast 13252 if (!mUserManagerInternal.isUserRunning(userId)) { 13253 return; 13254 } 13255 final IActivityManager am = ActivityManager.getService(); 13256 try { 13257 // Deliver LOCKED_BOOT_COMPLETED first 13258 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13259 .setPackage(packageName); 13260 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13261 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13262 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13263 13264 // Deliver BOOT_COMPLETED only if user is unlocked 13265 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13266 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13267 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13268 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13269 } 13270 } catch (RemoteException e) { 13271 throw e.rethrowFromSystemServer(); 13272 } 13273 } 13274 13275 @Override 13276 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13277 int userId) { 13278 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13279 PackageSetting pkgSetting; 13280 final int uid = Binder.getCallingUid(); 13281 enforceCrossUserPermission(uid, userId, 13282 true /* requireFullPermission */, true /* checkShell */, 13283 "setApplicationHiddenSetting for user " + userId); 13284 13285 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13286 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13287 return false; 13288 } 13289 13290 long callingId = Binder.clearCallingIdentity(); 13291 try { 13292 boolean sendAdded = false; 13293 boolean sendRemoved = false; 13294 // writer 13295 synchronized (mPackages) { 13296 pkgSetting = mSettings.mPackages.get(packageName); 13297 if (pkgSetting == null) { 13298 return false; 13299 } 13300 // Do not allow "android" is being disabled 13301 if ("android".equals(packageName)) { 13302 Slog.w(TAG, "Cannot hide package: android"); 13303 return false; 13304 } 13305 // Cannot hide static shared libs as they are considered 13306 // a part of the using app (emulating static linking). Also 13307 // static libs are installed always on internal storage. 13308 PackageParser.Package pkg = mPackages.get(packageName); 13309 if (pkg != null && pkg.staticSharedLibName != null) { 13310 Slog.w(TAG, "Cannot hide package: " + packageName 13311 + " providing static shared library: " 13312 + pkg.staticSharedLibName); 13313 return false; 13314 } 13315 // Only allow protected packages to hide themselves. 13316 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13317 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13318 Slog.w(TAG, "Not hiding protected package: " + packageName); 13319 return false; 13320 } 13321 13322 if (pkgSetting.getHidden(userId) != hidden) { 13323 pkgSetting.setHidden(hidden, userId); 13324 mSettings.writePackageRestrictionsLPr(userId); 13325 if (hidden) { 13326 sendRemoved = true; 13327 } else { 13328 sendAdded = true; 13329 } 13330 } 13331 } 13332 if (sendAdded) { 13333 sendPackageAddedForUser(packageName, pkgSetting, userId); 13334 return true; 13335 } 13336 if (sendRemoved) { 13337 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13338 "hiding pkg"); 13339 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13340 return true; 13341 } 13342 } finally { 13343 Binder.restoreCallingIdentity(callingId); 13344 } 13345 return false; 13346 } 13347 13348 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13349 int userId) { 13350 final PackageRemovedInfo info = new PackageRemovedInfo(); 13351 info.removedPackage = packageName; 13352 info.removedUsers = new int[] {userId}; 13353 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13354 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13355 } 13356 13357 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13358 if (pkgList.length > 0) { 13359 Bundle extras = new Bundle(1); 13360 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13361 13362 sendPackageBroadcast( 13363 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13364 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13365 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13366 new int[] {userId}); 13367 } 13368 } 13369 13370 /** 13371 * Returns true if application is not found or there was an error. Otherwise it returns 13372 * the hidden state of the package for the given user. 13373 */ 13374 @Override 13375 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13376 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13378 true /* requireFullPermission */, false /* checkShell */, 13379 "getApplicationHidden for user " + userId); 13380 PackageSetting pkgSetting; 13381 long callingId = Binder.clearCallingIdentity(); 13382 try { 13383 // writer 13384 synchronized (mPackages) { 13385 pkgSetting = mSettings.mPackages.get(packageName); 13386 if (pkgSetting == null) { 13387 return true; 13388 } 13389 return pkgSetting.getHidden(userId); 13390 } 13391 } finally { 13392 Binder.restoreCallingIdentity(callingId); 13393 } 13394 } 13395 13396 /** 13397 * @hide 13398 */ 13399 @Override 13400 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13401 int installReason) { 13402 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13403 null); 13404 PackageSetting pkgSetting; 13405 final int uid = Binder.getCallingUid(); 13406 enforceCrossUserPermission(uid, userId, 13407 true /* requireFullPermission */, true /* checkShell */, 13408 "installExistingPackage for user " + userId); 13409 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13410 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13411 } 13412 13413 long callingId = Binder.clearCallingIdentity(); 13414 try { 13415 boolean installed = false; 13416 final boolean instantApp = 13417 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13418 final boolean fullApp = 13419 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13420 13421 // writer 13422 synchronized (mPackages) { 13423 pkgSetting = mSettings.mPackages.get(packageName); 13424 if (pkgSetting == null) { 13425 return PackageManager.INSTALL_FAILED_INVALID_URI; 13426 } 13427 if (!pkgSetting.getInstalled(userId)) { 13428 pkgSetting.setInstalled(true, userId); 13429 pkgSetting.setHidden(false, userId); 13430 pkgSetting.setInstallReason(installReason, userId); 13431 mSettings.writePackageRestrictionsLPr(userId); 13432 mSettings.writeKernelMappingLPr(pkgSetting); 13433 installed = true; 13434 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13435 // upgrade app from instant to full; we don't allow app downgrade 13436 installed = true; 13437 } 13438 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13439 } 13440 13441 if (installed) { 13442 if (pkgSetting.pkg != null) { 13443 synchronized (mInstallLock) { 13444 // We don't need to freeze for a brand new install 13445 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13446 } 13447 } 13448 sendPackageAddedForUser(packageName, pkgSetting, userId); 13449 synchronized (mPackages) { 13450 updateSequenceNumberLP(packageName, new int[]{ userId }); 13451 } 13452 } 13453 } finally { 13454 Binder.restoreCallingIdentity(callingId); 13455 } 13456 13457 return PackageManager.INSTALL_SUCCEEDED; 13458 } 13459 13460 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13461 boolean instantApp, boolean fullApp) { 13462 // no state specified; do nothing 13463 if (!instantApp && !fullApp) { 13464 return; 13465 } 13466 if (userId != UserHandle.USER_ALL) { 13467 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13468 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13469 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13470 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13471 } 13472 } else { 13473 for (int currentUserId : sUserManager.getUserIds()) { 13474 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13475 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13476 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13477 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13478 } 13479 } 13480 } 13481 } 13482 13483 boolean isUserRestricted(int userId, String restrictionKey) { 13484 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13485 if (restrictions.getBoolean(restrictionKey, false)) { 13486 Log.w(TAG, "User is restricted: " + restrictionKey); 13487 return true; 13488 } 13489 return false; 13490 } 13491 13492 @Override 13493 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13494 int userId) { 13495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13496 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13497 true /* requireFullPermission */, true /* checkShell */, 13498 "setPackagesSuspended for user " + userId); 13499 13500 if (ArrayUtils.isEmpty(packageNames)) { 13501 return packageNames; 13502 } 13503 13504 // List of package names for whom the suspended state has changed. 13505 List<String> changedPackages = new ArrayList<>(packageNames.length); 13506 // List of package names for whom the suspended state is not set as requested in this 13507 // method. 13508 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13509 long callingId = Binder.clearCallingIdentity(); 13510 try { 13511 for (int i = 0; i < packageNames.length; i++) { 13512 String packageName = packageNames[i]; 13513 boolean changed = false; 13514 final int appId; 13515 synchronized (mPackages) { 13516 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13517 if (pkgSetting == null) { 13518 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13519 + "\". Skipping suspending/un-suspending."); 13520 unactionedPackages.add(packageName); 13521 continue; 13522 } 13523 appId = pkgSetting.appId; 13524 if (pkgSetting.getSuspended(userId) != suspended) { 13525 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13526 unactionedPackages.add(packageName); 13527 continue; 13528 } 13529 pkgSetting.setSuspended(suspended, userId); 13530 mSettings.writePackageRestrictionsLPr(userId); 13531 changed = true; 13532 changedPackages.add(packageName); 13533 } 13534 } 13535 13536 if (changed && suspended) { 13537 killApplication(packageName, UserHandle.getUid(userId, appId), 13538 "suspending package"); 13539 } 13540 } 13541 } finally { 13542 Binder.restoreCallingIdentity(callingId); 13543 } 13544 13545 if (!changedPackages.isEmpty()) { 13546 sendPackagesSuspendedForUser(changedPackages.toArray( 13547 new String[changedPackages.size()]), userId, suspended); 13548 } 13549 13550 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13551 } 13552 13553 @Override 13554 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13555 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13556 true /* requireFullPermission */, false /* checkShell */, 13557 "isPackageSuspendedForUser for user " + userId); 13558 synchronized (mPackages) { 13559 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13560 if (pkgSetting == null) { 13561 throw new IllegalArgumentException("Unknown target package: " + packageName); 13562 } 13563 return pkgSetting.getSuspended(userId); 13564 } 13565 } 13566 13567 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13568 if (isPackageDeviceAdmin(packageName, userId)) { 13569 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13570 + "\": has an active device admin"); 13571 return false; 13572 } 13573 13574 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13575 if (packageName.equals(activeLauncherPackageName)) { 13576 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13577 + "\": contains the active launcher"); 13578 return false; 13579 } 13580 13581 if (packageName.equals(mRequiredInstallerPackage)) { 13582 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13583 + "\": required for package installation"); 13584 return false; 13585 } 13586 13587 if (packageName.equals(mRequiredUninstallerPackage)) { 13588 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13589 + "\": required for package uninstallation"); 13590 return false; 13591 } 13592 13593 if (packageName.equals(mRequiredVerifierPackage)) { 13594 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13595 + "\": required for package verification"); 13596 return false; 13597 } 13598 13599 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13600 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13601 + "\": is the default dialer"); 13602 return false; 13603 } 13604 13605 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13606 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13607 + "\": protected package"); 13608 return false; 13609 } 13610 13611 // Cannot suspend static shared libs as they are considered 13612 // a part of the using app (emulating static linking). Also 13613 // static libs are installed always on internal storage. 13614 PackageParser.Package pkg = mPackages.get(packageName); 13615 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13616 Slog.w(TAG, "Cannot suspend package: " + packageName 13617 + " providing static shared library: " 13618 + pkg.staticSharedLibName); 13619 return false; 13620 } 13621 13622 return true; 13623 } 13624 13625 private String getActiveLauncherPackageName(int userId) { 13626 Intent intent = new Intent(Intent.ACTION_MAIN); 13627 intent.addCategory(Intent.CATEGORY_HOME); 13628 ResolveInfo resolveInfo = resolveIntent( 13629 intent, 13630 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13631 PackageManager.MATCH_DEFAULT_ONLY, 13632 userId); 13633 13634 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13635 } 13636 13637 private String getDefaultDialerPackageName(int userId) { 13638 synchronized (mPackages) { 13639 return mSettings.getDefaultDialerPackageNameLPw(userId); 13640 } 13641 } 13642 13643 @Override 13644 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13645 mContext.enforceCallingOrSelfPermission( 13646 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13647 "Only package verification agents can verify applications"); 13648 13649 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13650 final PackageVerificationResponse response = new PackageVerificationResponse( 13651 verificationCode, Binder.getCallingUid()); 13652 msg.arg1 = id; 13653 msg.obj = response; 13654 mHandler.sendMessage(msg); 13655 } 13656 13657 @Override 13658 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13659 long millisecondsToDelay) { 13660 mContext.enforceCallingOrSelfPermission( 13661 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13662 "Only package verification agents can extend verification timeouts"); 13663 13664 final PackageVerificationState state = mPendingVerification.get(id); 13665 final PackageVerificationResponse response = new PackageVerificationResponse( 13666 verificationCodeAtTimeout, Binder.getCallingUid()); 13667 13668 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13669 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13670 } 13671 if (millisecondsToDelay < 0) { 13672 millisecondsToDelay = 0; 13673 } 13674 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13675 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13676 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13677 } 13678 13679 if ((state != null) && !state.timeoutExtended()) { 13680 state.extendTimeout(); 13681 13682 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13683 msg.arg1 = id; 13684 msg.obj = response; 13685 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13686 } 13687 } 13688 13689 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13690 int verificationCode, UserHandle user) { 13691 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13692 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13693 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13694 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13695 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13696 13697 mContext.sendBroadcastAsUser(intent, user, 13698 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13699 } 13700 13701 private ComponentName matchComponentForVerifier(String packageName, 13702 List<ResolveInfo> receivers) { 13703 ActivityInfo targetReceiver = null; 13704 13705 final int NR = receivers.size(); 13706 for (int i = 0; i < NR; i++) { 13707 final ResolveInfo info = receivers.get(i); 13708 if (info.activityInfo == null) { 13709 continue; 13710 } 13711 13712 if (packageName.equals(info.activityInfo.packageName)) { 13713 targetReceiver = info.activityInfo; 13714 break; 13715 } 13716 } 13717 13718 if (targetReceiver == null) { 13719 return null; 13720 } 13721 13722 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13723 } 13724 13725 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13726 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13727 if (pkgInfo.verifiers.length == 0) { 13728 return null; 13729 } 13730 13731 final int N = pkgInfo.verifiers.length; 13732 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13733 for (int i = 0; i < N; i++) { 13734 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13735 13736 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13737 receivers); 13738 if (comp == null) { 13739 continue; 13740 } 13741 13742 final int verifierUid = getUidForVerifier(verifierInfo); 13743 if (verifierUid == -1) { 13744 continue; 13745 } 13746 13747 if (DEBUG_VERIFY) { 13748 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13749 + " with the correct signature"); 13750 } 13751 sufficientVerifiers.add(comp); 13752 verificationState.addSufficientVerifier(verifierUid); 13753 } 13754 13755 return sufficientVerifiers; 13756 } 13757 13758 private int getUidForVerifier(VerifierInfo verifierInfo) { 13759 synchronized (mPackages) { 13760 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13761 if (pkg == null) { 13762 return -1; 13763 } else if (pkg.mSignatures.length != 1) { 13764 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13765 + " has more than one signature; ignoring"); 13766 return -1; 13767 } 13768 13769 /* 13770 * If the public key of the package's signature does not match 13771 * our expected public key, then this is a different package and 13772 * we should skip. 13773 */ 13774 13775 final byte[] expectedPublicKey; 13776 try { 13777 final Signature verifierSig = pkg.mSignatures[0]; 13778 final PublicKey publicKey = verifierSig.getPublicKey(); 13779 expectedPublicKey = publicKey.getEncoded(); 13780 } catch (CertificateException e) { 13781 return -1; 13782 } 13783 13784 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13785 13786 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13787 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13788 + " does not have the expected public key; ignoring"); 13789 return -1; 13790 } 13791 13792 return pkg.applicationInfo.uid; 13793 } 13794 } 13795 13796 @Override 13797 public void finishPackageInstall(int token, boolean didLaunch) { 13798 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13799 13800 if (DEBUG_INSTALL) { 13801 Slog.v(TAG, "BM finishing package install for " + token); 13802 } 13803 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13804 13805 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13806 mHandler.sendMessage(msg); 13807 } 13808 13809 /** 13810 * Get the verification agent timeout. 13811 * 13812 * @return verification timeout in milliseconds 13813 */ 13814 private long getVerificationTimeout() { 13815 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13816 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13817 DEFAULT_VERIFICATION_TIMEOUT); 13818 } 13819 13820 /** 13821 * Get the default verification agent response code. 13822 * 13823 * @return default verification response code 13824 */ 13825 private int getDefaultVerificationResponse() { 13826 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13827 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13828 DEFAULT_VERIFICATION_RESPONSE); 13829 } 13830 13831 /** 13832 * Check whether or not package verification has been enabled. 13833 * 13834 * @return true if verification should be performed 13835 */ 13836 private boolean isVerificationEnabled(int userId, int installFlags) { 13837 if (!DEFAULT_VERIFY_ENABLE) { 13838 return false; 13839 } 13840 13841 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13842 13843 // Check if installing from ADB 13844 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13845 // Do not run verification in a test harness environment 13846 if (ActivityManager.isRunningInTestHarness()) { 13847 return false; 13848 } 13849 if (ensureVerifyAppsEnabled) { 13850 return true; 13851 } 13852 // Check if the developer does not want package verification for ADB installs 13853 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13854 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13855 return false; 13856 } 13857 } 13858 13859 if (ensureVerifyAppsEnabled) { 13860 return true; 13861 } 13862 13863 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13864 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13865 } 13866 13867 @Override 13868 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13869 throws RemoteException { 13870 mContext.enforceCallingOrSelfPermission( 13871 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13872 "Only intentfilter verification agents can verify applications"); 13873 13874 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13875 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13876 Binder.getCallingUid(), verificationCode, failedDomains); 13877 msg.arg1 = id; 13878 msg.obj = response; 13879 mHandler.sendMessage(msg); 13880 } 13881 13882 @Override 13883 public int getIntentVerificationStatus(String packageName, int userId) { 13884 synchronized (mPackages) { 13885 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13886 } 13887 } 13888 13889 @Override 13890 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13891 mContext.enforceCallingOrSelfPermission( 13892 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13893 13894 boolean result = false; 13895 synchronized (mPackages) { 13896 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13897 } 13898 if (result) { 13899 scheduleWritePackageRestrictionsLocked(userId); 13900 } 13901 return result; 13902 } 13903 13904 @Override 13905 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13906 String packageName) { 13907 synchronized (mPackages) { 13908 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13909 } 13910 } 13911 13912 @Override 13913 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13914 if (TextUtils.isEmpty(packageName)) { 13915 return ParceledListSlice.emptyList(); 13916 } 13917 synchronized (mPackages) { 13918 PackageParser.Package pkg = mPackages.get(packageName); 13919 if (pkg == null || pkg.activities == null) { 13920 return ParceledListSlice.emptyList(); 13921 } 13922 final int count = pkg.activities.size(); 13923 ArrayList<IntentFilter> result = new ArrayList<>(); 13924 for (int n=0; n<count; n++) { 13925 PackageParser.Activity activity = pkg.activities.get(n); 13926 if (activity.intents != null && activity.intents.size() > 0) { 13927 result.addAll(activity.intents); 13928 } 13929 } 13930 return new ParceledListSlice<>(result); 13931 } 13932 } 13933 13934 @Override 13935 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13936 mContext.enforceCallingOrSelfPermission( 13937 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13938 13939 synchronized (mPackages) { 13940 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13941 if (packageName != null) { 13942 result |= updateIntentVerificationStatus(packageName, 13943 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13944 userId); 13945 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13946 packageName, userId); 13947 } 13948 return result; 13949 } 13950 } 13951 13952 @Override 13953 public String getDefaultBrowserPackageName(int userId) { 13954 synchronized (mPackages) { 13955 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13956 } 13957 } 13958 13959 /** 13960 * Get the "allow unknown sources" setting. 13961 * 13962 * @return the current "allow unknown sources" setting 13963 */ 13964 private int getUnknownSourcesSettings() { 13965 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13966 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13967 -1); 13968 } 13969 13970 @Override 13971 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13972 final int uid = Binder.getCallingUid(); 13973 // writer 13974 synchronized (mPackages) { 13975 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13976 if (targetPackageSetting == null) { 13977 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13978 } 13979 13980 PackageSetting installerPackageSetting; 13981 if (installerPackageName != null) { 13982 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13983 if (installerPackageSetting == null) { 13984 throw new IllegalArgumentException("Unknown installer package: " 13985 + installerPackageName); 13986 } 13987 } else { 13988 installerPackageSetting = null; 13989 } 13990 13991 Signature[] callerSignature; 13992 Object obj = mSettings.getUserIdLPr(uid); 13993 if (obj != null) { 13994 if (obj instanceof SharedUserSetting) { 13995 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13996 } else if (obj instanceof PackageSetting) { 13997 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13998 } else { 13999 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14000 } 14001 } else { 14002 throw new SecurityException("Unknown calling UID: " + uid); 14003 } 14004 14005 // Verify: can't set installerPackageName to a package that is 14006 // not signed with the same cert as the caller. 14007 if (installerPackageSetting != null) { 14008 if (compareSignatures(callerSignature, 14009 installerPackageSetting.signatures.mSignatures) 14010 != PackageManager.SIGNATURE_MATCH) { 14011 throw new SecurityException( 14012 "Caller does not have same cert as new installer package " 14013 + installerPackageName); 14014 } 14015 } 14016 14017 // Verify: if target already has an installer package, it must 14018 // be signed with the same cert as the caller. 14019 if (targetPackageSetting.installerPackageName != null) { 14020 PackageSetting setting = mSettings.mPackages.get( 14021 targetPackageSetting.installerPackageName); 14022 // If the currently set package isn't valid, then it's always 14023 // okay to change it. 14024 if (setting != null) { 14025 if (compareSignatures(callerSignature, 14026 setting.signatures.mSignatures) 14027 != PackageManager.SIGNATURE_MATCH) { 14028 throw new SecurityException( 14029 "Caller does not have same cert as old installer package " 14030 + targetPackageSetting.installerPackageName); 14031 } 14032 } 14033 } 14034 14035 // Okay! 14036 targetPackageSetting.installerPackageName = installerPackageName; 14037 if (installerPackageName != null) { 14038 mSettings.mInstallerPackages.add(installerPackageName); 14039 } 14040 scheduleWriteSettingsLocked(); 14041 } 14042 } 14043 14044 @Override 14045 public void setApplicationCategoryHint(String packageName, int categoryHint, 14046 String callerPackageName) { 14047 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14048 callerPackageName); 14049 synchronized (mPackages) { 14050 PackageSetting ps = mSettings.mPackages.get(packageName); 14051 if (ps == null) { 14052 throw new IllegalArgumentException("Unknown target package " + packageName); 14053 } 14054 14055 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14056 throw new IllegalArgumentException("Calling package " + callerPackageName 14057 + " is not installer for " + packageName); 14058 } 14059 14060 if (ps.categoryHint != categoryHint) { 14061 ps.categoryHint = categoryHint; 14062 scheduleWriteSettingsLocked(); 14063 } 14064 } 14065 } 14066 14067 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14068 // Queue up an async operation since the package installation may take a little while. 14069 mHandler.post(new Runnable() { 14070 public void run() { 14071 mHandler.removeCallbacks(this); 14072 // Result object to be returned 14073 PackageInstalledInfo res = new PackageInstalledInfo(); 14074 res.setReturnCode(currentStatus); 14075 res.uid = -1; 14076 res.pkg = null; 14077 res.removedInfo = null; 14078 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14079 args.doPreInstall(res.returnCode); 14080 synchronized (mInstallLock) { 14081 installPackageTracedLI(args, res); 14082 } 14083 args.doPostInstall(res.returnCode, res.uid); 14084 } 14085 14086 // A restore should be performed at this point if (a) the install 14087 // succeeded, (b) the operation is not an update, and (c) the new 14088 // package has not opted out of backup participation. 14089 final boolean update = res.removedInfo != null 14090 && res.removedInfo.removedPackage != null; 14091 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14092 boolean doRestore = !update 14093 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14094 14095 // Set up the post-install work request bookkeeping. This will be used 14096 // and cleaned up by the post-install event handling regardless of whether 14097 // there's a restore pass performed. Token values are >= 1. 14098 int token; 14099 if (mNextInstallToken < 0) mNextInstallToken = 1; 14100 token = mNextInstallToken++; 14101 14102 PostInstallData data = new PostInstallData(args, res); 14103 mRunningInstalls.put(token, data); 14104 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14105 14106 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14107 // Pass responsibility to the Backup Manager. It will perform a 14108 // restore if appropriate, then pass responsibility back to the 14109 // Package Manager to run the post-install observer callbacks 14110 // and broadcasts. 14111 IBackupManager bm = IBackupManager.Stub.asInterface( 14112 ServiceManager.getService(Context.BACKUP_SERVICE)); 14113 if (bm != null) { 14114 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14115 + " to BM for possible restore"); 14116 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14117 try { 14118 // TODO: http://b/22388012 14119 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14120 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14121 } else { 14122 doRestore = false; 14123 } 14124 } catch (RemoteException e) { 14125 // can't happen; the backup manager is local 14126 } catch (Exception e) { 14127 Slog.e(TAG, "Exception trying to enqueue restore", e); 14128 doRestore = false; 14129 } 14130 } else { 14131 Slog.e(TAG, "Backup Manager not found!"); 14132 doRestore = false; 14133 } 14134 } 14135 14136 if (!doRestore) { 14137 // No restore possible, or the Backup Manager was mysteriously not 14138 // available -- just fire the post-install work request directly. 14139 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14140 14141 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14142 14143 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14144 mHandler.sendMessage(msg); 14145 } 14146 } 14147 }); 14148 } 14149 14150 /** 14151 * Callback from PackageSettings whenever an app is first transitioned out of the 14152 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14153 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14154 * here whether the app is the target of an ongoing install, and only send the 14155 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14156 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14157 * handling. 14158 */ 14159 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14160 // Serialize this with the rest of the install-process message chain. In the 14161 // restore-at-install case, this Runnable will necessarily run before the 14162 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14163 // are coherent. In the non-restore case, the app has already completed install 14164 // and been launched through some other means, so it is not in a problematic 14165 // state for observers to see the FIRST_LAUNCH signal. 14166 mHandler.post(new Runnable() { 14167 @Override 14168 public void run() { 14169 for (int i = 0; i < mRunningInstalls.size(); i++) { 14170 final PostInstallData data = mRunningInstalls.valueAt(i); 14171 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14172 continue; 14173 } 14174 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14175 // right package; but is it for the right user? 14176 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14177 if (userId == data.res.newUsers[uIndex]) { 14178 if (DEBUG_BACKUP) { 14179 Slog.i(TAG, "Package " + pkgName 14180 + " being restored so deferring FIRST_LAUNCH"); 14181 } 14182 return; 14183 } 14184 } 14185 } 14186 } 14187 // didn't find it, so not being restored 14188 if (DEBUG_BACKUP) { 14189 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14190 } 14191 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14192 } 14193 }); 14194 } 14195 14196 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14197 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14198 installerPkg, null, userIds); 14199 } 14200 14201 private abstract class HandlerParams { 14202 private static final int MAX_RETRIES = 4; 14203 14204 /** 14205 * Number of times startCopy() has been attempted and had a non-fatal 14206 * error. 14207 */ 14208 private int mRetries = 0; 14209 14210 /** User handle for the user requesting the information or installation. */ 14211 private final UserHandle mUser; 14212 String traceMethod; 14213 int traceCookie; 14214 14215 HandlerParams(UserHandle user) { 14216 mUser = user; 14217 } 14218 14219 UserHandle getUser() { 14220 return mUser; 14221 } 14222 14223 HandlerParams setTraceMethod(String traceMethod) { 14224 this.traceMethod = traceMethod; 14225 return this; 14226 } 14227 14228 HandlerParams setTraceCookie(int traceCookie) { 14229 this.traceCookie = traceCookie; 14230 return this; 14231 } 14232 14233 final boolean startCopy() { 14234 boolean res; 14235 try { 14236 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14237 14238 if (++mRetries > MAX_RETRIES) { 14239 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14240 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14241 handleServiceError(); 14242 return false; 14243 } else { 14244 handleStartCopy(); 14245 res = true; 14246 } 14247 } catch (RemoteException e) { 14248 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14249 mHandler.sendEmptyMessage(MCS_RECONNECT); 14250 res = false; 14251 } 14252 handleReturnCode(); 14253 return res; 14254 } 14255 14256 final void serviceError() { 14257 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14258 handleServiceError(); 14259 handleReturnCode(); 14260 } 14261 14262 abstract void handleStartCopy() throws RemoteException; 14263 abstract void handleServiceError(); 14264 abstract void handleReturnCode(); 14265 } 14266 14267 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14268 for (File path : paths) { 14269 try { 14270 mcs.clearDirectory(path.getAbsolutePath()); 14271 } catch (RemoteException e) { 14272 } 14273 } 14274 } 14275 14276 static class OriginInfo { 14277 /** 14278 * Location where install is coming from, before it has been 14279 * copied/renamed into place. This could be a single monolithic APK 14280 * file, or a cluster directory. This location may be untrusted. 14281 */ 14282 final File file; 14283 final String cid; 14284 14285 /** 14286 * Flag indicating that {@link #file} or {@link #cid} has already been 14287 * staged, meaning downstream users don't need to defensively copy the 14288 * contents. 14289 */ 14290 final boolean staged; 14291 14292 /** 14293 * Flag indicating that {@link #file} or {@link #cid} is an already 14294 * installed app that is being moved. 14295 */ 14296 final boolean existing; 14297 14298 final String resolvedPath; 14299 final File resolvedFile; 14300 14301 static OriginInfo fromNothing() { 14302 return new OriginInfo(null, null, false, false); 14303 } 14304 14305 static OriginInfo fromUntrustedFile(File file) { 14306 return new OriginInfo(file, null, false, false); 14307 } 14308 14309 static OriginInfo fromExistingFile(File file) { 14310 return new OriginInfo(file, null, false, true); 14311 } 14312 14313 static OriginInfo fromStagedFile(File file) { 14314 return new OriginInfo(file, null, true, false); 14315 } 14316 14317 static OriginInfo fromStagedContainer(String cid) { 14318 return new OriginInfo(null, cid, true, false); 14319 } 14320 14321 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14322 this.file = file; 14323 this.cid = cid; 14324 this.staged = staged; 14325 this.existing = existing; 14326 14327 if (cid != null) { 14328 resolvedPath = PackageHelper.getSdDir(cid); 14329 resolvedFile = new File(resolvedPath); 14330 } else if (file != null) { 14331 resolvedPath = file.getAbsolutePath(); 14332 resolvedFile = file; 14333 } else { 14334 resolvedPath = null; 14335 resolvedFile = null; 14336 } 14337 } 14338 } 14339 14340 static class MoveInfo { 14341 final int moveId; 14342 final String fromUuid; 14343 final String toUuid; 14344 final String packageName; 14345 final String dataAppName; 14346 final int appId; 14347 final String seinfo; 14348 final int targetSdkVersion; 14349 14350 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14351 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14352 this.moveId = moveId; 14353 this.fromUuid = fromUuid; 14354 this.toUuid = toUuid; 14355 this.packageName = packageName; 14356 this.dataAppName = dataAppName; 14357 this.appId = appId; 14358 this.seinfo = seinfo; 14359 this.targetSdkVersion = targetSdkVersion; 14360 } 14361 } 14362 14363 static class VerificationInfo { 14364 /** A constant used to indicate that a uid value is not present. */ 14365 public static final int NO_UID = -1; 14366 14367 /** URI referencing where the package was downloaded from. */ 14368 final Uri originatingUri; 14369 14370 /** HTTP referrer URI associated with the originatingURI. */ 14371 final Uri referrer; 14372 14373 /** UID of the application that the install request originated from. */ 14374 final int originatingUid; 14375 14376 /** UID of application requesting the install */ 14377 final int installerUid; 14378 14379 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14380 this.originatingUri = originatingUri; 14381 this.referrer = referrer; 14382 this.originatingUid = originatingUid; 14383 this.installerUid = installerUid; 14384 } 14385 } 14386 14387 class InstallParams extends HandlerParams { 14388 final OriginInfo origin; 14389 final MoveInfo move; 14390 final IPackageInstallObserver2 observer; 14391 int installFlags; 14392 final String installerPackageName; 14393 final String volumeUuid; 14394 private InstallArgs mArgs; 14395 private int mRet; 14396 final String packageAbiOverride; 14397 final String[] grantedRuntimePermissions; 14398 final VerificationInfo verificationInfo; 14399 final Certificate[][] certificates; 14400 final int installReason; 14401 14402 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14403 int installFlags, String installerPackageName, String volumeUuid, 14404 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14405 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14406 super(user); 14407 this.origin = origin; 14408 this.move = move; 14409 this.observer = observer; 14410 this.installFlags = installFlags; 14411 this.installerPackageName = installerPackageName; 14412 this.volumeUuid = volumeUuid; 14413 this.verificationInfo = verificationInfo; 14414 this.packageAbiOverride = packageAbiOverride; 14415 this.grantedRuntimePermissions = grantedPermissions; 14416 this.certificates = certificates; 14417 this.installReason = installReason; 14418 } 14419 14420 @Override 14421 public String toString() { 14422 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14423 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14424 } 14425 14426 private int installLocationPolicy(PackageInfoLite pkgLite) { 14427 String packageName = pkgLite.packageName; 14428 int installLocation = pkgLite.installLocation; 14429 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14430 // reader 14431 synchronized (mPackages) { 14432 // Currently installed package which the new package is attempting to replace or 14433 // null if no such package is installed. 14434 PackageParser.Package installedPkg = mPackages.get(packageName); 14435 // Package which currently owns the data which the new package will own if installed. 14436 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14437 // will be null whereas dataOwnerPkg will contain information about the package 14438 // which was uninstalled while keeping its data. 14439 PackageParser.Package dataOwnerPkg = installedPkg; 14440 if (dataOwnerPkg == null) { 14441 PackageSetting ps = mSettings.mPackages.get(packageName); 14442 if (ps != null) { 14443 dataOwnerPkg = ps.pkg; 14444 } 14445 } 14446 14447 if (dataOwnerPkg != null) { 14448 // If installed, the package will get access to data left on the device by its 14449 // predecessor. As a security measure, this is permited only if this is not a 14450 // version downgrade or if the predecessor package is marked as debuggable and 14451 // a downgrade is explicitly requested. 14452 // 14453 // On debuggable platform builds, downgrades are permitted even for 14454 // non-debuggable packages to make testing easier. Debuggable platform builds do 14455 // not offer security guarantees and thus it's OK to disable some security 14456 // mechanisms to make debugging/testing easier on those builds. However, even on 14457 // debuggable builds downgrades of packages are permitted only if requested via 14458 // installFlags. This is because we aim to keep the behavior of debuggable 14459 // platform builds as close as possible to the behavior of non-debuggable 14460 // platform builds. 14461 final boolean downgradeRequested = 14462 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14463 final boolean packageDebuggable = 14464 (dataOwnerPkg.applicationInfo.flags 14465 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14466 final boolean downgradePermitted = 14467 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14468 if (!downgradePermitted) { 14469 try { 14470 checkDowngrade(dataOwnerPkg, pkgLite); 14471 } catch (PackageManagerException e) { 14472 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14473 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14474 } 14475 } 14476 } 14477 14478 if (installedPkg != null) { 14479 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14480 // Check for updated system application. 14481 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14482 if (onSd) { 14483 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14484 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14485 } 14486 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14487 } else { 14488 if (onSd) { 14489 // Install flag overrides everything. 14490 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14491 } 14492 // If current upgrade specifies particular preference 14493 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14494 // Application explicitly specified internal. 14495 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14496 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14497 // App explictly prefers external. Let policy decide 14498 } else { 14499 // Prefer previous location 14500 if (isExternal(installedPkg)) { 14501 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14502 } 14503 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14504 } 14505 } 14506 } else { 14507 // Invalid install. Return error code 14508 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14509 } 14510 } 14511 } 14512 // All the special cases have been taken care of. 14513 // Return result based on recommended install location. 14514 if (onSd) { 14515 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14516 } 14517 return pkgLite.recommendedInstallLocation; 14518 } 14519 14520 /* 14521 * Invoke remote method to get package information and install 14522 * location values. Override install location based on default 14523 * policy if needed and then create install arguments based 14524 * on the install location. 14525 */ 14526 public void handleStartCopy() throws RemoteException { 14527 int ret = PackageManager.INSTALL_SUCCEEDED; 14528 14529 // If we're already staged, we've firmly committed to an install location 14530 if (origin.staged) { 14531 if (origin.file != null) { 14532 installFlags |= PackageManager.INSTALL_INTERNAL; 14533 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14534 } else if (origin.cid != null) { 14535 installFlags |= PackageManager.INSTALL_EXTERNAL; 14536 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14537 } else { 14538 throw new IllegalStateException("Invalid stage location"); 14539 } 14540 } 14541 14542 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14543 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14544 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14545 PackageInfoLite pkgLite = null; 14546 14547 if (onInt && onSd) { 14548 // Check if both bits are set. 14549 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14550 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14551 } else if (onSd && ephemeral) { 14552 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14553 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14554 } else { 14555 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14556 packageAbiOverride); 14557 14558 if (DEBUG_EPHEMERAL && ephemeral) { 14559 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14560 } 14561 14562 /* 14563 * If we have too little free space, try to free cache 14564 * before giving up. 14565 */ 14566 if (!origin.staged && pkgLite.recommendedInstallLocation 14567 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14568 // TODO: focus freeing disk space on the target device 14569 final StorageManager storage = StorageManager.from(mContext); 14570 final long lowThreshold = storage.getStorageLowBytes( 14571 Environment.getDataDirectory()); 14572 14573 final long sizeBytes = mContainerService.calculateInstalledSize( 14574 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14575 14576 try { 14577 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14578 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14579 installFlags, packageAbiOverride); 14580 } catch (InstallerException e) { 14581 Slog.w(TAG, "Failed to free cache", e); 14582 } 14583 14584 /* 14585 * The cache free must have deleted the file we 14586 * downloaded to install. 14587 * 14588 * TODO: fix the "freeCache" call to not delete 14589 * the file we care about. 14590 */ 14591 if (pkgLite.recommendedInstallLocation 14592 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14593 pkgLite.recommendedInstallLocation 14594 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14595 } 14596 } 14597 } 14598 14599 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14600 int loc = pkgLite.recommendedInstallLocation; 14601 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14602 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14603 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14604 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14605 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14606 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14607 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14608 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14609 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14610 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14611 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14612 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14613 } else { 14614 // Override with defaults if needed. 14615 loc = installLocationPolicy(pkgLite); 14616 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14617 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14618 } else if (!onSd && !onInt) { 14619 // Override install location with flags 14620 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14621 // Set the flag to install on external media. 14622 installFlags |= PackageManager.INSTALL_EXTERNAL; 14623 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14624 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14625 if (DEBUG_EPHEMERAL) { 14626 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14627 } 14628 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14629 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14630 |PackageManager.INSTALL_INTERNAL); 14631 } else { 14632 // Make sure the flag for installing on external 14633 // media is unset 14634 installFlags |= PackageManager.INSTALL_INTERNAL; 14635 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14636 } 14637 } 14638 } 14639 } 14640 14641 final InstallArgs args = createInstallArgs(this); 14642 mArgs = args; 14643 14644 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14645 // TODO: http://b/22976637 14646 // Apps installed for "all" users use the device owner to verify the app 14647 UserHandle verifierUser = getUser(); 14648 if (verifierUser == UserHandle.ALL) { 14649 verifierUser = UserHandle.SYSTEM; 14650 } 14651 14652 /* 14653 * Determine if we have any installed package verifiers. If we 14654 * do, then we'll defer to them to verify the packages. 14655 */ 14656 final int requiredUid = mRequiredVerifierPackage == null ? -1 14657 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14658 verifierUser.getIdentifier()); 14659 if (!origin.existing && requiredUid != -1 14660 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14661 final Intent verification = new Intent( 14662 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14663 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14664 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14665 PACKAGE_MIME_TYPE); 14666 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14667 14668 // Query all live verifiers based on current user state 14669 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14670 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14671 14672 if (DEBUG_VERIFY) { 14673 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14674 + verification.toString() + " with " + pkgLite.verifiers.length 14675 + " optional verifiers"); 14676 } 14677 14678 final int verificationId = mPendingVerificationToken++; 14679 14680 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14681 14682 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14683 installerPackageName); 14684 14685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14686 installFlags); 14687 14688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14689 pkgLite.packageName); 14690 14691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14692 pkgLite.versionCode); 14693 14694 if (verificationInfo != null) { 14695 if (verificationInfo.originatingUri != null) { 14696 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14697 verificationInfo.originatingUri); 14698 } 14699 if (verificationInfo.referrer != null) { 14700 verification.putExtra(Intent.EXTRA_REFERRER, 14701 verificationInfo.referrer); 14702 } 14703 if (verificationInfo.originatingUid >= 0) { 14704 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14705 verificationInfo.originatingUid); 14706 } 14707 if (verificationInfo.installerUid >= 0) { 14708 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14709 verificationInfo.installerUid); 14710 } 14711 } 14712 14713 final PackageVerificationState verificationState = new PackageVerificationState( 14714 requiredUid, args); 14715 14716 mPendingVerification.append(verificationId, verificationState); 14717 14718 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14719 receivers, verificationState); 14720 14721 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14722 final long idleDuration = getVerificationTimeout(); 14723 14724 /* 14725 * If any sufficient verifiers were listed in the package 14726 * manifest, attempt to ask them. 14727 */ 14728 if (sufficientVerifiers != null) { 14729 final int N = sufficientVerifiers.size(); 14730 if (N == 0) { 14731 Slog.i(TAG, "Additional verifiers required, but none installed."); 14732 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14733 } else { 14734 for (int i = 0; i < N; i++) { 14735 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14736 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14737 verifierComponent.getPackageName(), idleDuration, 14738 verifierUser.getIdentifier(), false, "package verifier"); 14739 14740 final Intent sufficientIntent = new Intent(verification); 14741 sufficientIntent.setComponent(verifierComponent); 14742 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14743 } 14744 } 14745 } 14746 14747 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14748 mRequiredVerifierPackage, receivers); 14749 if (ret == PackageManager.INSTALL_SUCCEEDED 14750 && mRequiredVerifierPackage != null) { 14751 Trace.asyncTraceBegin( 14752 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14753 /* 14754 * Send the intent to the required verification agent, 14755 * but only start the verification timeout after the 14756 * target BroadcastReceivers have run. 14757 */ 14758 verification.setComponent(requiredVerifierComponent); 14759 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14760 mRequiredVerifierPackage, idleDuration, 14761 verifierUser.getIdentifier(), false, "package verifier"); 14762 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14763 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14764 new BroadcastReceiver() { 14765 @Override 14766 public void onReceive(Context context, Intent intent) { 14767 final Message msg = mHandler 14768 .obtainMessage(CHECK_PENDING_VERIFICATION); 14769 msg.arg1 = verificationId; 14770 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14771 } 14772 }, null, 0, null, null); 14773 14774 /* 14775 * We don't want the copy to proceed until verification 14776 * succeeds, so null out this field. 14777 */ 14778 mArgs = null; 14779 } 14780 } else { 14781 /* 14782 * No package verification is enabled, so immediately start 14783 * the remote call to initiate copy using temporary file. 14784 */ 14785 ret = args.copyApk(mContainerService, true); 14786 } 14787 } 14788 14789 mRet = ret; 14790 } 14791 14792 @Override 14793 void handleReturnCode() { 14794 // If mArgs is null, then MCS couldn't be reached. When it 14795 // reconnects, it will try again to install. At that point, this 14796 // will succeed. 14797 if (mArgs != null) { 14798 processPendingInstall(mArgs, mRet); 14799 } 14800 } 14801 14802 @Override 14803 void handleServiceError() { 14804 mArgs = createInstallArgs(this); 14805 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14806 } 14807 14808 public boolean isForwardLocked() { 14809 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14810 } 14811 } 14812 14813 /** 14814 * Used during creation of InstallArgs 14815 * 14816 * @param installFlags package installation flags 14817 * @return true if should be installed on external storage 14818 */ 14819 private static boolean installOnExternalAsec(int installFlags) { 14820 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14821 return false; 14822 } 14823 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14824 return true; 14825 } 14826 return false; 14827 } 14828 14829 /** 14830 * Used during creation of InstallArgs 14831 * 14832 * @param installFlags package installation flags 14833 * @return true if should be installed as forward locked 14834 */ 14835 private static boolean installForwardLocked(int installFlags) { 14836 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14837 } 14838 14839 private InstallArgs createInstallArgs(InstallParams params) { 14840 if (params.move != null) { 14841 return new MoveInstallArgs(params); 14842 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14843 return new AsecInstallArgs(params); 14844 } else { 14845 return new FileInstallArgs(params); 14846 } 14847 } 14848 14849 /** 14850 * Create args that describe an existing installed package. Typically used 14851 * when cleaning up old installs, or used as a move source. 14852 */ 14853 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14854 String resourcePath, String[] instructionSets) { 14855 final boolean isInAsec; 14856 if (installOnExternalAsec(installFlags)) { 14857 /* Apps on SD card are always in ASEC containers. */ 14858 isInAsec = true; 14859 } else if (installForwardLocked(installFlags) 14860 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14861 /* 14862 * Forward-locked apps are only in ASEC containers if they're the 14863 * new style 14864 */ 14865 isInAsec = true; 14866 } else { 14867 isInAsec = false; 14868 } 14869 14870 if (isInAsec) { 14871 return new AsecInstallArgs(codePath, instructionSets, 14872 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14873 } else { 14874 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14875 } 14876 } 14877 14878 static abstract class InstallArgs { 14879 /** @see InstallParams#origin */ 14880 final OriginInfo origin; 14881 /** @see InstallParams#move */ 14882 final MoveInfo move; 14883 14884 final IPackageInstallObserver2 observer; 14885 // Always refers to PackageManager flags only 14886 final int installFlags; 14887 final String installerPackageName; 14888 final String volumeUuid; 14889 final UserHandle user; 14890 final String abiOverride; 14891 final String[] installGrantPermissions; 14892 /** If non-null, drop an async trace when the install completes */ 14893 final String traceMethod; 14894 final int traceCookie; 14895 final Certificate[][] certificates; 14896 final int installReason; 14897 14898 // The list of instruction sets supported by this app. This is currently 14899 // only used during the rmdex() phase to clean up resources. We can get rid of this 14900 // if we move dex files under the common app path. 14901 /* nullable */ String[] instructionSets; 14902 14903 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14904 int installFlags, String installerPackageName, String volumeUuid, 14905 UserHandle user, String[] instructionSets, 14906 String abiOverride, String[] installGrantPermissions, 14907 String traceMethod, int traceCookie, Certificate[][] certificates, 14908 int installReason) { 14909 this.origin = origin; 14910 this.move = move; 14911 this.installFlags = installFlags; 14912 this.observer = observer; 14913 this.installerPackageName = installerPackageName; 14914 this.volumeUuid = volumeUuid; 14915 this.user = user; 14916 this.instructionSets = instructionSets; 14917 this.abiOverride = abiOverride; 14918 this.installGrantPermissions = installGrantPermissions; 14919 this.traceMethod = traceMethod; 14920 this.traceCookie = traceCookie; 14921 this.certificates = certificates; 14922 this.installReason = installReason; 14923 } 14924 14925 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14926 abstract int doPreInstall(int status); 14927 14928 /** 14929 * Rename package into final resting place. All paths on the given 14930 * scanned package should be updated to reflect the rename. 14931 */ 14932 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14933 abstract int doPostInstall(int status, int uid); 14934 14935 /** @see PackageSettingBase#codePathString */ 14936 abstract String getCodePath(); 14937 /** @see PackageSettingBase#resourcePathString */ 14938 abstract String getResourcePath(); 14939 14940 // Need installer lock especially for dex file removal. 14941 abstract void cleanUpResourcesLI(); 14942 abstract boolean doPostDeleteLI(boolean delete); 14943 14944 /** 14945 * Called before the source arguments are copied. This is used mostly 14946 * for MoveParams when it needs to read the source file to put it in the 14947 * destination. 14948 */ 14949 int doPreCopy() { 14950 return PackageManager.INSTALL_SUCCEEDED; 14951 } 14952 14953 /** 14954 * Called after the source arguments are copied. This is used mostly for 14955 * MoveParams when it needs to read the source file to put it in the 14956 * destination. 14957 */ 14958 int doPostCopy(int uid) { 14959 return PackageManager.INSTALL_SUCCEEDED; 14960 } 14961 14962 protected boolean isFwdLocked() { 14963 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14964 } 14965 14966 protected boolean isExternalAsec() { 14967 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14968 } 14969 14970 protected boolean isEphemeral() { 14971 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14972 } 14973 14974 UserHandle getUser() { 14975 return user; 14976 } 14977 } 14978 14979 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14980 if (!allCodePaths.isEmpty()) { 14981 if (instructionSets == null) { 14982 throw new IllegalStateException("instructionSet == null"); 14983 } 14984 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14985 for (String codePath : allCodePaths) { 14986 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14987 try { 14988 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14989 } catch (InstallerException ignored) { 14990 } 14991 } 14992 } 14993 } 14994 } 14995 14996 /** 14997 * Logic to handle installation of non-ASEC applications, including copying 14998 * and renaming logic. 14999 */ 15000 class FileInstallArgs extends InstallArgs { 15001 private File codeFile; 15002 private File resourceFile; 15003 15004 // Example topology: 15005 // /data/app/com.example/base.apk 15006 // /data/app/com.example/split_foo.apk 15007 // /data/app/com.example/lib/arm/libfoo.so 15008 // /data/app/com.example/lib/arm64/libfoo.so 15009 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15010 15011 /** New install */ 15012 FileInstallArgs(InstallParams params) { 15013 super(params.origin, params.move, params.observer, params.installFlags, 15014 params.installerPackageName, params.volumeUuid, 15015 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15016 params.grantedRuntimePermissions, 15017 params.traceMethod, params.traceCookie, params.certificates, 15018 params.installReason); 15019 if (isFwdLocked()) { 15020 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15021 } 15022 } 15023 15024 /** Existing install */ 15025 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15026 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15027 null, null, null, 0, null /*certificates*/, 15028 PackageManager.INSTALL_REASON_UNKNOWN); 15029 this.codeFile = (codePath != null) ? new File(codePath) : null; 15030 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15031 } 15032 15033 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15034 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15035 try { 15036 return doCopyApk(imcs, temp); 15037 } finally { 15038 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15039 } 15040 } 15041 15042 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15043 if (origin.staged) { 15044 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15045 codeFile = origin.file; 15046 resourceFile = origin.file; 15047 return PackageManager.INSTALL_SUCCEEDED; 15048 } 15049 15050 try { 15051 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15052 final File tempDir = 15053 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15054 codeFile = tempDir; 15055 resourceFile = tempDir; 15056 } catch (IOException e) { 15057 Slog.w(TAG, "Failed to create copy file: " + e); 15058 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15059 } 15060 15061 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15062 @Override 15063 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15064 if (!FileUtils.isValidExtFilename(name)) { 15065 throw new IllegalArgumentException("Invalid filename: " + name); 15066 } 15067 try { 15068 final File file = new File(codeFile, name); 15069 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15070 O_RDWR | O_CREAT, 0644); 15071 Os.chmod(file.getAbsolutePath(), 0644); 15072 return new ParcelFileDescriptor(fd); 15073 } catch (ErrnoException e) { 15074 throw new RemoteException("Failed to open: " + e.getMessage()); 15075 } 15076 } 15077 }; 15078 15079 int ret = PackageManager.INSTALL_SUCCEEDED; 15080 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15081 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15082 Slog.e(TAG, "Failed to copy package"); 15083 return ret; 15084 } 15085 15086 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15087 NativeLibraryHelper.Handle handle = null; 15088 try { 15089 handle = NativeLibraryHelper.Handle.create(codeFile); 15090 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15091 abiOverride); 15092 } catch (IOException e) { 15093 Slog.e(TAG, "Copying native libraries failed", e); 15094 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15095 } finally { 15096 IoUtils.closeQuietly(handle); 15097 } 15098 15099 return ret; 15100 } 15101 15102 int doPreInstall(int status) { 15103 if (status != PackageManager.INSTALL_SUCCEEDED) { 15104 cleanUp(); 15105 } 15106 return status; 15107 } 15108 15109 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15110 if (status != PackageManager.INSTALL_SUCCEEDED) { 15111 cleanUp(); 15112 return false; 15113 } 15114 15115 final File targetDir = codeFile.getParentFile(); 15116 final File beforeCodeFile = codeFile; 15117 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15118 15119 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15120 try { 15121 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15122 } catch (ErrnoException e) { 15123 Slog.w(TAG, "Failed to rename", e); 15124 return false; 15125 } 15126 15127 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15128 Slog.w(TAG, "Failed to restorecon"); 15129 return false; 15130 } 15131 15132 // Reflect the rename internally 15133 codeFile = afterCodeFile; 15134 resourceFile = afterCodeFile; 15135 15136 // Reflect the rename in scanned details 15137 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15138 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15139 afterCodeFile, pkg.baseCodePath)); 15140 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15141 afterCodeFile, pkg.splitCodePaths)); 15142 15143 // Reflect the rename in app info 15144 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15145 pkg.setApplicationInfoCodePath(pkg.codePath); 15146 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15147 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15148 pkg.setApplicationInfoResourcePath(pkg.codePath); 15149 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15150 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15151 15152 return true; 15153 } 15154 15155 int doPostInstall(int status, int uid) { 15156 if (status != PackageManager.INSTALL_SUCCEEDED) { 15157 cleanUp(); 15158 } 15159 return status; 15160 } 15161 15162 @Override 15163 String getCodePath() { 15164 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15165 } 15166 15167 @Override 15168 String getResourcePath() { 15169 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15170 } 15171 15172 private boolean cleanUp() { 15173 if (codeFile == null || !codeFile.exists()) { 15174 return false; 15175 } 15176 15177 removeCodePathLI(codeFile); 15178 15179 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15180 resourceFile.delete(); 15181 } 15182 15183 return true; 15184 } 15185 15186 void cleanUpResourcesLI() { 15187 // Try enumerating all code paths before deleting 15188 List<String> allCodePaths = Collections.EMPTY_LIST; 15189 if (codeFile != null && codeFile.exists()) { 15190 try { 15191 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15192 allCodePaths = pkg.getAllCodePaths(); 15193 } catch (PackageParserException e) { 15194 // Ignored; we tried our best 15195 } 15196 } 15197 15198 cleanUp(); 15199 removeDexFiles(allCodePaths, instructionSets); 15200 } 15201 15202 boolean doPostDeleteLI(boolean delete) { 15203 // XXX err, shouldn't we respect the delete flag? 15204 cleanUpResourcesLI(); 15205 return true; 15206 } 15207 } 15208 15209 private boolean isAsecExternal(String cid) { 15210 final String asecPath = PackageHelper.getSdFilesystem(cid); 15211 return !asecPath.startsWith(mAsecInternalPath); 15212 } 15213 15214 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15215 PackageManagerException { 15216 if (copyRet < 0) { 15217 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15218 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15219 throw new PackageManagerException(copyRet, message); 15220 } 15221 } 15222 } 15223 15224 /** 15225 * Extract the StorageManagerService "container ID" from the full code path of an 15226 * .apk. 15227 */ 15228 static String cidFromCodePath(String fullCodePath) { 15229 int eidx = fullCodePath.lastIndexOf("/"); 15230 String subStr1 = fullCodePath.substring(0, eidx); 15231 int sidx = subStr1.lastIndexOf("/"); 15232 return subStr1.substring(sidx+1, eidx); 15233 } 15234 15235 /** 15236 * Logic to handle installation of ASEC applications, including copying and 15237 * renaming logic. 15238 */ 15239 class AsecInstallArgs extends InstallArgs { 15240 static final String RES_FILE_NAME = "pkg.apk"; 15241 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15242 15243 String cid; 15244 String packagePath; 15245 String resourcePath; 15246 15247 /** New install */ 15248 AsecInstallArgs(InstallParams params) { 15249 super(params.origin, params.move, params.observer, params.installFlags, 15250 params.installerPackageName, params.volumeUuid, 15251 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15252 params.grantedRuntimePermissions, 15253 params.traceMethod, params.traceCookie, params.certificates, 15254 params.installReason); 15255 } 15256 15257 /** Existing install */ 15258 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15259 boolean isExternal, boolean isForwardLocked) { 15260 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15261 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15262 instructionSets, null, null, null, 0, null /*certificates*/, 15263 PackageManager.INSTALL_REASON_UNKNOWN); 15264 // Hackily pretend we're still looking at a full code path 15265 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15266 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15267 } 15268 15269 // Extract cid from fullCodePath 15270 int eidx = fullCodePath.lastIndexOf("/"); 15271 String subStr1 = fullCodePath.substring(0, eidx); 15272 int sidx = subStr1.lastIndexOf("/"); 15273 cid = subStr1.substring(sidx+1, eidx); 15274 setMountPath(subStr1); 15275 } 15276 15277 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15278 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15279 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15280 instructionSets, null, null, null, 0, null /*certificates*/, 15281 PackageManager.INSTALL_REASON_UNKNOWN); 15282 this.cid = cid; 15283 setMountPath(PackageHelper.getSdDir(cid)); 15284 } 15285 15286 void createCopyFile() { 15287 cid = mInstallerService.allocateExternalStageCidLegacy(); 15288 } 15289 15290 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15291 if (origin.staged && origin.cid != null) { 15292 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15293 cid = origin.cid; 15294 setMountPath(PackageHelper.getSdDir(cid)); 15295 return PackageManager.INSTALL_SUCCEEDED; 15296 } 15297 15298 if (temp) { 15299 createCopyFile(); 15300 } else { 15301 /* 15302 * Pre-emptively destroy the container since it's destroyed if 15303 * copying fails due to it existing anyway. 15304 */ 15305 PackageHelper.destroySdDir(cid); 15306 } 15307 15308 final String newMountPath = imcs.copyPackageToContainer( 15309 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15310 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15311 15312 if (newMountPath != null) { 15313 setMountPath(newMountPath); 15314 return PackageManager.INSTALL_SUCCEEDED; 15315 } else { 15316 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15317 } 15318 } 15319 15320 @Override 15321 String getCodePath() { 15322 return packagePath; 15323 } 15324 15325 @Override 15326 String getResourcePath() { 15327 return resourcePath; 15328 } 15329 15330 int doPreInstall(int status) { 15331 if (status != PackageManager.INSTALL_SUCCEEDED) { 15332 // Destroy container 15333 PackageHelper.destroySdDir(cid); 15334 } else { 15335 boolean mounted = PackageHelper.isContainerMounted(cid); 15336 if (!mounted) { 15337 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15338 Process.SYSTEM_UID); 15339 if (newMountPath != null) { 15340 setMountPath(newMountPath); 15341 } else { 15342 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15343 } 15344 } 15345 } 15346 return status; 15347 } 15348 15349 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15350 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15351 String newMountPath = null; 15352 if (PackageHelper.isContainerMounted(cid)) { 15353 // Unmount the container 15354 if (!PackageHelper.unMountSdDir(cid)) { 15355 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15356 return false; 15357 } 15358 } 15359 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15360 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15361 " which might be stale. Will try to clean up."); 15362 // Clean up the stale container and proceed to recreate. 15363 if (!PackageHelper.destroySdDir(newCacheId)) { 15364 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15365 return false; 15366 } 15367 // Successfully cleaned up stale container. Try to rename again. 15368 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15369 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15370 + " inspite of cleaning it up."); 15371 return false; 15372 } 15373 } 15374 if (!PackageHelper.isContainerMounted(newCacheId)) { 15375 Slog.w(TAG, "Mounting container " + newCacheId); 15376 newMountPath = PackageHelper.mountSdDir(newCacheId, 15377 getEncryptKey(), Process.SYSTEM_UID); 15378 } else { 15379 newMountPath = PackageHelper.getSdDir(newCacheId); 15380 } 15381 if (newMountPath == null) { 15382 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15383 return false; 15384 } 15385 Log.i(TAG, "Succesfully renamed " + cid + 15386 " to " + newCacheId + 15387 " at new path: " + newMountPath); 15388 cid = newCacheId; 15389 15390 final File beforeCodeFile = new File(packagePath); 15391 setMountPath(newMountPath); 15392 final File afterCodeFile = new File(packagePath); 15393 15394 // Reflect the rename in scanned details 15395 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15396 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15397 afterCodeFile, pkg.baseCodePath)); 15398 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15399 afterCodeFile, pkg.splitCodePaths)); 15400 15401 // Reflect the rename in app info 15402 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15403 pkg.setApplicationInfoCodePath(pkg.codePath); 15404 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15405 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15406 pkg.setApplicationInfoResourcePath(pkg.codePath); 15407 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15408 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15409 15410 return true; 15411 } 15412 15413 private void setMountPath(String mountPath) { 15414 final File mountFile = new File(mountPath); 15415 15416 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15417 if (monolithicFile.exists()) { 15418 packagePath = monolithicFile.getAbsolutePath(); 15419 if (isFwdLocked()) { 15420 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15421 } else { 15422 resourcePath = packagePath; 15423 } 15424 } else { 15425 packagePath = mountFile.getAbsolutePath(); 15426 resourcePath = packagePath; 15427 } 15428 } 15429 15430 int doPostInstall(int status, int uid) { 15431 if (status != PackageManager.INSTALL_SUCCEEDED) { 15432 cleanUp(); 15433 } else { 15434 final int groupOwner; 15435 final String protectedFile; 15436 if (isFwdLocked()) { 15437 groupOwner = UserHandle.getSharedAppGid(uid); 15438 protectedFile = RES_FILE_NAME; 15439 } else { 15440 groupOwner = -1; 15441 protectedFile = null; 15442 } 15443 15444 if (uid < Process.FIRST_APPLICATION_UID 15445 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15446 Slog.e(TAG, "Failed to finalize " + cid); 15447 PackageHelper.destroySdDir(cid); 15448 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15449 } 15450 15451 boolean mounted = PackageHelper.isContainerMounted(cid); 15452 if (!mounted) { 15453 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15454 } 15455 } 15456 return status; 15457 } 15458 15459 private void cleanUp() { 15460 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15461 15462 // Destroy secure container 15463 PackageHelper.destroySdDir(cid); 15464 } 15465 15466 private List<String> getAllCodePaths() { 15467 final File codeFile = new File(getCodePath()); 15468 if (codeFile != null && codeFile.exists()) { 15469 try { 15470 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15471 return pkg.getAllCodePaths(); 15472 } catch (PackageParserException e) { 15473 // Ignored; we tried our best 15474 } 15475 } 15476 return Collections.EMPTY_LIST; 15477 } 15478 15479 void cleanUpResourcesLI() { 15480 // Enumerate all code paths before deleting 15481 cleanUpResourcesLI(getAllCodePaths()); 15482 } 15483 15484 private void cleanUpResourcesLI(List<String> allCodePaths) { 15485 cleanUp(); 15486 removeDexFiles(allCodePaths, instructionSets); 15487 } 15488 15489 String getPackageName() { 15490 return getAsecPackageName(cid); 15491 } 15492 15493 boolean doPostDeleteLI(boolean delete) { 15494 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15495 final List<String> allCodePaths = getAllCodePaths(); 15496 boolean mounted = PackageHelper.isContainerMounted(cid); 15497 if (mounted) { 15498 // Unmount first 15499 if (PackageHelper.unMountSdDir(cid)) { 15500 mounted = false; 15501 } 15502 } 15503 if (!mounted && delete) { 15504 cleanUpResourcesLI(allCodePaths); 15505 } 15506 return !mounted; 15507 } 15508 15509 @Override 15510 int doPreCopy() { 15511 if (isFwdLocked()) { 15512 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15513 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15514 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15515 } 15516 } 15517 15518 return PackageManager.INSTALL_SUCCEEDED; 15519 } 15520 15521 @Override 15522 int doPostCopy(int uid) { 15523 if (isFwdLocked()) { 15524 if (uid < Process.FIRST_APPLICATION_UID 15525 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15526 RES_FILE_NAME)) { 15527 Slog.e(TAG, "Failed to finalize " + cid); 15528 PackageHelper.destroySdDir(cid); 15529 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15530 } 15531 } 15532 15533 return PackageManager.INSTALL_SUCCEEDED; 15534 } 15535 } 15536 15537 /** 15538 * Logic to handle movement of existing installed applications. 15539 */ 15540 class MoveInstallArgs extends InstallArgs { 15541 private File codeFile; 15542 private File resourceFile; 15543 15544 /** New install */ 15545 MoveInstallArgs(InstallParams params) { 15546 super(params.origin, params.move, params.observer, params.installFlags, 15547 params.installerPackageName, params.volumeUuid, 15548 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15549 params.grantedRuntimePermissions, 15550 params.traceMethod, params.traceCookie, params.certificates, 15551 params.installReason); 15552 } 15553 15554 int copyApk(IMediaContainerService imcs, boolean temp) { 15555 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15556 + move.fromUuid + " to " + move.toUuid); 15557 synchronized (mInstaller) { 15558 try { 15559 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15560 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15561 } catch (InstallerException e) { 15562 Slog.w(TAG, "Failed to move app", e); 15563 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15564 } 15565 } 15566 15567 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15568 resourceFile = codeFile; 15569 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15570 15571 return PackageManager.INSTALL_SUCCEEDED; 15572 } 15573 15574 int doPreInstall(int status) { 15575 if (status != PackageManager.INSTALL_SUCCEEDED) { 15576 cleanUp(move.toUuid); 15577 } 15578 return status; 15579 } 15580 15581 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15582 if (status != PackageManager.INSTALL_SUCCEEDED) { 15583 cleanUp(move.toUuid); 15584 return false; 15585 } 15586 15587 // Reflect the move in app info 15588 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15589 pkg.setApplicationInfoCodePath(pkg.codePath); 15590 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15591 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15592 pkg.setApplicationInfoResourcePath(pkg.codePath); 15593 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15594 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15595 15596 return true; 15597 } 15598 15599 int doPostInstall(int status, int uid) { 15600 if (status == PackageManager.INSTALL_SUCCEEDED) { 15601 cleanUp(move.fromUuid); 15602 } else { 15603 cleanUp(move.toUuid); 15604 } 15605 return status; 15606 } 15607 15608 @Override 15609 String getCodePath() { 15610 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15611 } 15612 15613 @Override 15614 String getResourcePath() { 15615 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15616 } 15617 15618 private boolean cleanUp(String volumeUuid) { 15619 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15620 move.dataAppName); 15621 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15622 final int[] userIds = sUserManager.getUserIds(); 15623 synchronized (mInstallLock) { 15624 // Clean up both app data and code 15625 // All package moves are frozen until finished 15626 for (int userId : userIds) { 15627 try { 15628 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15629 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15630 } catch (InstallerException e) { 15631 Slog.w(TAG, String.valueOf(e)); 15632 } 15633 } 15634 removeCodePathLI(codeFile); 15635 } 15636 return true; 15637 } 15638 15639 void cleanUpResourcesLI() { 15640 throw new UnsupportedOperationException(); 15641 } 15642 15643 boolean doPostDeleteLI(boolean delete) { 15644 throw new UnsupportedOperationException(); 15645 } 15646 } 15647 15648 static String getAsecPackageName(String packageCid) { 15649 int idx = packageCid.lastIndexOf("-"); 15650 if (idx == -1) { 15651 return packageCid; 15652 } 15653 return packageCid.substring(0, idx); 15654 } 15655 15656 // Utility method used to create code paths based on package name and available index. 15657 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15658 String idxStr = ""; 15659 int idx = 1; 15660 // Fall back to default value of idx=1 if prefix is not 15661 // part of oldCodePath 15662 if (oldCodePath != null) { 15663 String subStr = oldCodePath; 15664 // Drop the suffix right away 15665 if (suffix != null && subStr.endsWith(suffix)) { 15666 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15667 } 15668 // If oldCodePath already contains prefix find out the 15669 // ending index to either increment or decrement. 15670 int sidx = subStr.lastIndexOf(prefix); 15671 if (sidx != -1) { 15672 subStr = subStr.substring(sidx + prefix.length()); 15673 if (subStr != null) { 15674 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15675 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15676 } 15677 try { 15678 idx = Integer.parseInt(subStr); 15679 if (idx <= 1) { 15680 idx++; 15681 } else { 15682 idx--; 15683 } 15684 } catch(NumberFormatException e) { 15685 } 15686 } 15687 } 15688 } 15689 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15690 return prefix + idxStr; 15691 } 15692 15693 private File getNextCodePath(File targetDir, String packageName) { 15694 File result; 15695 SecureRandom random = new SecureRandom(); 15696 byte[] bytes = new byte[16]; 15697 do { 15698 random.nextBytes(bytes); 15699 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15700 result = new File(targetDir, packageName + "-" + suffix); 15701 } while (result.exists()); 15702 return result; 15703 } 15704 15705 // Utility method that returns the relative package path with respect 15706 // to the installation directory. Like say for /data/data/com.test-1.apk 15707 // string com.test-1 is returned. 15708 static String deriveCodePathName(String codePath) { 15709 if (codePath == null) { 15710 return null; 15711 } 15712 final File codeFile = new File(codePath); 15713 final String name = codeFile.getName(); 15714 if (codeFile.isDirectory()) { 15715 return name; 15716 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15717 final int lastDot = name.lastIndexOf('.'); 15718 return name.substring(0, lastDot); 15719 } else { 15720 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15721 return null; 15722 } 15723 } 15724 15725 static class PackageInstalledInfo { 15726 String name; 15727 int uid; 15728 // The set of users that originally had this package installed. 15729 int[] origUsers; 15730 // The set of users that now have this package installed. 15731 int[] newUsers; 15732 PackageParser.Package pkg; 15733 int returnCode; 15734 String returnMsg; 15735 PackageRemovedInfo removedInfo; 15736 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15737 15738 public void setError(int code, String msg) { 15739 setReturnCode(code); 15740 setReturnMessage(msg); 15741 Slog.w(TAG, msg); 15742 } 15743 15744 public void setError(String msg, PackageParserException e) { 15745 setReturnCode(e.error); 15746 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15747 Slog.w(TAG, msg, e); 15748 } 15749 15750 public void setError(String msg, PackageManagerException e) { 15751 returnCode = e.error; 15752 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15753 Slog.w(TAG, msg, e); 15754 } 15755 15756 public void setReturnCode(int returnCode) { 15757 this.returnCode = returnCode; 15758 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15759 for (int i = 0; i < childCount; i++) { 15760 addedChildPackages.valueAt(i).returnCode = returnCode; 15761 } 15762 } 15763 15764 private void setReturnMessage(String returnMsg) { 15765 this.returnMsg = returnMsg; 15766 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15767 for (int i = 0; i < childCount; i++) { 15768 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15769 } 15770 } 15771 15772 // In some error cases we want to convey more info back to the observer 15773 String origPackage; 15774 String origPermission; 15775 } 15776 15777 /* 15778 * Install a non-existing package. 15779 */ 15780 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15781 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15782 PackageInstalledInfo res, int installReason) { 15783 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15784 15785 // Remember this for later, in case we need to rollback this install 15786 String pkgName = pkg.packageName; 15787 15788 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15789 15790 synchronized(mPackages) { 15791 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15792 if (renamedPackage != null) { 15793 // A package with the same name is already installed, though 15794 // it has been renamed to an older name. The package we 15795 // are trying to install should be installed as an update to 15796 // the existing one, but that has not been requested, so bail. 15797 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15798 + " without first uninstalling package running as " 15799 + renamedPackage); 15800 return; 15801 } 15802 if (mPackages.containsKey(pkgName)) { 15803 // Don't allow installation over an existing package with the same name. 15804 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15805 + " without first uninstalling."); 15806 return; 15807 } 15808 } 15809 15810 try { 15811 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15812 System.currentTimeMillis(), user); 15813 15814 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15815 15816 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15817 prepareAppDataAfterInstallLIF(newPackage); 15818 15819 } else { 15820 // Remove package from internal structures, but keep around any 15821 // data that might have already existed 15822 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15823 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15824 } 15825 } catch (PackageManagerException e) { 15826 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15827 } 15828 15829 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15830 } 15831 15832 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15833 // Can't rotate keys during boot or if sharedUser. 15834 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15835 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15836 return false; 15837 } 15838 // app is using upgradeKeySets; make sure all are valid 15839 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15840 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15841 for (int i = 0; i < upgradeKeySets.length; i++) { 15842 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15843 Slog.wtf(TAG, "Package " 15844 + (oldPs.name != null ? oldPs.name : "<null>") 15845 + " contains upgrade-key-set reference to unknown key-set: " 15846 + upgradeKeySets[i] 15847 + " reverting to signatures check."); 15848 return false; 15849 } 15850 } 15851 return true; 15852 } 15853 15854 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15855 // Upgrade keysets are being used. Determine if new package has a superset of the 15856 // required keys. 15857 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15858 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15859 for (int i = 0; i < upgradeKeySets.length; i++) { 15860 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15861 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15862 return true; 15863 } 15864 } 15865 return false; 15866 } 15867 15868 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15869 try (DigestInputStream digestStream = 15870 new DigestInputStream(new FileInputStream(file), digest)) { 15871 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15872 } 15873 } 15874 15875 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15876 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15877 int installReason) { 15878 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15879 15880 final PackageParser.Package oldPackage; 15881 final String pkgName = pkg.packageName; 15882 final int[] allUsers; 15883 final int[] installedUsers; 15884 15885 synchronized(mPackages) { 15886 oldPackage = mPackages.get(pkgName); 15887 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15888 15889 // don't allow upgrade to target a release SDK from a pre-release SDK 15890 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15891 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15892 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15893 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15894 if (oldTargetsPreRelease 15895 && !newTargetsPreRelease 15896 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15897 Slog.w(TAG, "Can't install package targeting released sdk"); 15898 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15899 return; 15900 } 15901 15902 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15903 15904 // verify signatures are valid 15905 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15906 if (!checkUpgradeKeySetLP(ps, pkg)) { 15907 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15908 "New package not signed by keys specified by upgrade-keysets: " 15909 + pkgName); 15910 return; 15911 } 15912 } else { 15913 // default to original signature matching 15914 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15915 != PackageManager.SIGNATURE_MATCH) { 15916 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15917 "New package has a different signature: " + pkgName); 15918 return; 15919 } 15920 } 15921 15922 // don't allow a system upgrade unless the upgrade hash matches 15923 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15924 byte[] digestBytes = null; 15925 try { 15926 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15927 updateDigest(digest, new File(pkg.baseCodePath)); 15928 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15929 for (String path : pkg.splitCodePaths) { 15930 updateDigest(digest, new File(path)); 15931 } 15932 } 15933 digestBytes = digest.digest(); 15934 } catch (NoSuchAlgorithmException | IOException e) { 15935 res.setError(INSTALL_FAILED_INVALID_APK, 15936 "Could not compute hash: " + pkgName); 15937 return; 15938 } 15939 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15940 res.setError(INSTALL_FAILED_INVALID_APK, 15941 "New package fails restrict-update check: " + pkgName); 15942 return; 15943 } 15944 // retain upgrade restriction 15945 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15946 } 15947 15948 // Check for shared user id changes 15949 String invalidPackageName = 15950 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15951 if (invalidPackageName != null) { 15952 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15953 "Package " + invalidPackageName + " tried to change user " 15954 + oldPackage.mSharedUserId); 15955 return; 15956 } 15957 15958 // In case of rollback, remember per-user/profile install state 15959 allUsers = sUserManager.getUserIds(); 15960 installedUsers = ps.queryInstalledUsers(allUsers, true); 15961 15962 // don't allow an upgrade from full to ephemeral 15963 if (isInstantApp) { 15964 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15965 for (int currentUser : allUsers) { 15966 if (!ps.getInstantApp(currentUser)) { 15967 // can't downgrade from full to instant 15968 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15969 + " for user: " + currentUser); 15970 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15971 return; 15972 } 15973 } 15974 } else if (!ps.getInstantApp(user.getIdentifier())) { 15975 // can't downgrade from full to instant 15976 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15977 + " for user: " + user.getIdentifier()); 15978 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15979 return; 15980 } 15981 } 15982 } 15983 15984 // Update what is removed 15985 res.removedInfo = new PackageRemovedInfo(); 15986 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15987 res.removedInfo.removedPackage = oldPackage.packageName; 15988 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15989 res.removedInfo.isUpdate = true; 15990 res.removedInfo.origUsers = installedUsers; 15991 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15992 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15993 for (int i = 0; i < installedUsers.length; i++) { 15994 final int userId = installedUsers[i]; 15995 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15996 } 15997 15998 final int childCount = (oldPackage.childPackages != null) 15999 ? oldPackage.childPackages.size() : 0; 16000 for (int i = 0; i < childCount; i++) { 16001 boolean childPackageUpdated = false; 16002 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16003 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16004 if (res.addedChildPackages != null) { 16005 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16006 if (childRes != null) { 16007 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16008 childRes.removedInfo.removedPackage = childPkg.packageName; 16009 childRes.removedInfo.isUpdate = true; 16010 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16011 childPackageUpdated = true; 16012 } 16013 } 16014 if (!childPackageUpdated) { 16015 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16016 childRemovedRes.removedPackage = childPkg.packageName; 16017 childRemovedRes.isUpdate = false; 16018 childRemovedRes.dataRemoved = true; 16019 synchronized (mPackages) { 16020 if (childPs != null) { 16021 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16022 } 16023 } 16024 if (res.removedInfo.removedChildPackages == null) { 16025 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16026 } 16027 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16028 } 16029 } 16030 16031 boolean sysPkg = (isSystemApp(oldPackage)); 16032 if (sysPkg) { 16033 // Set the system/privileged flags as needed 16034 final boolean privileged = 16035 (oldPackage.applicationInfo.privateFlags 16036 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16037 final int systemPolicyFlags = policyFlags 16038 | PackageParser.PARSE_IS_SYSTEM 16039 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16040 16041 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16042 user, allUsers, installerPackageName, res, installReason); 16043 } else { 16044 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16045 user, allUsers, installerPackageName, res, installReason); 16046 } 16047 } 16048 16049 public List<String> getPreviousCodePaths(String packageName) { 16050 final PackageSetting ps = mSettings.mPackages.get(packageName); 16051 final List<String> result = new ArrayList<String>(); 16052 if (ps != null && ps.oldCodePaths != null) { 16053 result.addAll(ps.oldCodePaths); 16054 } 16055 return result; 16056 } 16057 16058 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16059 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16060 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16061 int installReason) { 16062 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16063 + deletedPackage); 16064 16065 String pkgName = deletedPackage.packageName; 16066 boolean deletedPkg = true; 16067 boolean addedPkg = false; 16068 boolean updatedSettings = false; 16069 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16070 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16071 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16072 16073 final long origUpdateTime = (pkg.mExtras != null) 16074 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16075 16076 // First delete the existing package while retaining the data directory 16077 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16078 res.removedInfo, true, pkg)) { 16079 // If the existing package wasn't successfully deleted 16080 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16081 deletedPkg = false; 16082 } else { 16083 // Successfully deleted the old package; proceed with replace. 16084 16085 // If deleted package lived in a container, give users a chance to 16086 // relinquish resources before killing. 16087 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16088 if (DEBUG_INSTALL) { 16089 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16090 } 16091 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16092 final ArrayList<String> pkgList = new ArrayList<String>(1); 16093 pkgList.add(deletedPackage.applicationInfo.packageName); 16094 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16095 } 16096 16097 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16098 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16099 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16100 16101 try { 16102 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16103 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16104 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16105 installReason); 16106 16107 // Update the in-memory copy of the previous code paths. 16108 PackageSetting ps = mSettings.mPackages.get(pkgName); 16109 if (!killApp) { 16110 if (ps.oldCodePaths == null) { 16111 ps.oldCodePaths = new ArraySet<>(); 16112 } 16113 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16114 if (deletedPackage.splitCodePaths != null) { 16115 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16116 } 16117 } else { 16118 ps.oldCodePaths = null; 16119 } 16120 if (ps.childPackageNames != null) { 16121 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16122 final String childPkgName = ps.childPackageNames.get(i); 16123 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16124 childPs.oldCodePaths = ps.oldCodePaths; 16125 } 16126 } 16127 // set instant app status, but, only if it's explicitly specified 16128 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16129 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16130 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16131 prepareAppDataAfterInstallLIF(newPackage); 16132 addedPkg = true; 16133 mDexManager.notifyPackageUpdated(newPackage.packageName, 16134 newPackage.baseCodePath, newPackage.splitCodePaths); 16135 } catch (PackageManagerException e) { 16136 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16137 } 16138 } 16139 16140 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16141 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16142 16143 // Revert all internal state mutations and added folders for the failed install 16144 if (addedPkg) { 16145 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16146 res.removedInfo, true, null); 16147 } 16148 16149 // Restore the old package 16150 if (deletedPkg) { 16151 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16152 File restoreFile = new File(deletedPackage.codePath); 16153 // Parse old package 16154 boolean oldExternal = isExternal(deletedPackage); 16155 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16156 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16157 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16158 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16159 try { 16160 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16161 null); 16162 } catch (PackageManagerException e) { 16163 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16164 + e.getMessage()); 16165 return; 16166 } 16167 16168 synchronized (mPackages) { 16169 // Ensure the installer package name up to date 16170 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16171 16172 // Update permissions for restored package 16173 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16174 16175 mSettings.writeLPr(); 16176 } 16177 16178 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16179 } 16180 } else { 16181 synchronized (mPackages) { 16182 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16183 if (ps != null) { 16184 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16185 if (res.removedInfo.removedChildPackages != null) { 16186 final int childCount = res.removedInfo.removedChildPackages.size(); 16187 // Iterate in reverse as we may modify the collection 16188 for (int i = childCount - 1; i >= 0; i--) { 16189 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16190 if (res.addedChildPackages.containsKey(childPackageName)) { 16191 res.removedInfo.removedChildPackages.removeAt(i); 16192 } else { 16193 PackageRemovedInfo childInfo = res.removedInfo 16194 .removedChildPackages.valueAt(i); 16195 childInfo.removedForAllUsers = mPackages.get( 16196 childInfo.removedPackage) == null; 16197 } 16198 } 16199 } 16200 } 16201 } 16202 } 16203 } 16204 16205 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16206 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16207 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16208 int installReason) { 16209 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16210 + ", old=" + deletedPackage); 16211 16212 final boolean disabledSystem; 16213 16214 // Remove existing system package 16215 removePackageLI(deletedPackage, true); 16216 16217 synchronized (mPackages) { 16218 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16219 } 16220 if (!disabledSystem) { 16221 // We didn't need to disable the .apk as a current system package, 16222 // which means we are replacing another update that is already 16223 // installed. We need to make sure to delete the older one's .apk. 16224 res.removedInfo.args = createInstallArgsForExisting(0, 16225 deletedPackage.applicationInfo.getCodePath(), 16226 deletedPackage.applicationInfo.getResourcePath(), 16227 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16228 } else { 16229 res.removedInfo.args = null; 16230 } 16231 16232 // Successfully disabled the old package. Now proceed with re-installation 16233 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16234 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16235 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16236 16237 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16238 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16239 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16240 16241 PackageParser.Package newPackage = null; 16242 try { 16243 // Add the package to the internal data structures 16244 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16245 16246 // Set the update and install times 16247 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16248 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16249 System.currentTimeMillis()); 16250 16251 // Update the package dynamic state if succeeded 16252 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16253 // Now that the install succeeded make sure we remove data 16254 // directories for any child package the update removed. 16255 final int deletedChildCount = (deletedPackage.childPackages != null) 16256 ? deletedPackage.childPackages.size() : 0; 16257 final int newChildCount = (newPackage.childPackages != null) 16258 ? newPackage.childPackages.size() : 0; 16259 for (int i = 0; i < deletedChildCount; i++) { 16260 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16261 boolean childPackageDeleted = true; 16262 for (int j = 0; j < newChildCount; j++) { 16263 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16264 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16265 childPackageDeleted = false; 16266 break; 16267 } 16268 } 16269 if (childPackageDeleted) { 16270 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16271 deletedChildPkg.packageName); 16272 if (ps != null && res.removedInfo.removedChildPackages != null) { 16273 PackageRemovedInfo removedChildRes = res.removedInfo 16274 .removedChildPackages.get(deletedChildPkg.packageName); 16275 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16276 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16277 } 16278 } 16279 } 16280 16281 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16282 installReason); 16283 prepareAppDataAfterInstallLIF(newPackage); 16284 16285 mDexManager.notifyPackageUpdated(newPackage.packageName, 16286 newPackage.baseCodePath, newPackage.splitCodePaths); 16287 } 16288 } catch (PackageManagerException e) { 16289 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16290 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16291 } 16292 16293 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16294 // Re installation failed. Restore old information 16295 // Remove new pkg information 16296 if (newPackage != null) { 16297 removeInstalledPackageLI(newPackage, true); 16298 } 16299 // Add back the old system package 16300 try { 16301 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16302 } catch (PackageManagerException e) { 16303 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16304 } 16305 16306 synchronized (mPackages) { 16307 if (disabledSystem) { 16308 enableSystemPackageLPw(deletedPackage); 16309 } 16310 16311 // Ensure the installer package name up to date 16312 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16313 16314 // Update permissions for restored package 16315 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16316 16317 mSettings.writeLPr(); 16318 } 16319 16320 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16321 + " after failed upgrade"); 16322 } 16323 } 16324 16325 /** 16326 * Checks whether the parent or any of the child packages have a change shared 16327 * user. For a package to be a valid update the shred users of the parent and 16328 * the children should match. We may later support changing child shared users. 16329 * @param oldPkg The updated package. 16330 * @param newPkg The update package. 16331 * @return The shared user that change between the versions. 16332 */ 16333 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16334 PackageParser.Package newPkg) { 16335 // Check parent shared user 16336 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16337 return newPkg.packageName; 16338 } 16339 // Check child shared users 16340 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16341 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16342 for (int i = 0; i < newChildCount; i++) { 16343 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16344 // If this child was present, did it have the same shared user? 16345 for (int j = 0; j < oldChildCount; j++) { 16346 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16347 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16348 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16349 return newChildPkg.packageName; 16350 } 16351 } 16352 } 16353 return null; 16354 } 16355 16356 private void removeNativeBinariesLI(PackageSetting ps) { 16357 // Remove the lib path for the parent package 16358 if (ps != null) { 16359 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16360 // Remove the lib path for the child packages 16361 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16362 for (int i = 0; i < childCount; i++) { 16363 PackageSetting childPs = null; 16364 synchronized (mPackages) { 16365 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16366 } 16367 if (childPs != null) { 16368 NativeLibraryHelper.removeNativeBinariesLI(childPs 16369 .legacyNativeLibraryPathString); 16370 } 16371 } 16372 } 16373 } 16374 16375 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16376 // Enable the parent package 16377 mSettings.enableSystemPackageLPw(pkg.packageName); 16378 // Enable the child packages 16379 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16380 for (int i = 0; i < childCount; i++) { 16381 PackageParser.Package childPkg = pkg.childPackages.get(i); 16382 mSettings.enableSystemPackageLPw(childPkg.packageName); 16383 } 16384 } 16385 16386 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16387 PackageParser.Package newPkg) { 16388 // Disable the parent package (parent always replaced) 16389 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16390 // Disable the child packages 16391 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16392 for (int i = 0; i < childCount; i++) { 16393 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16394 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16395 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16396 } 16397 return disabled; 16398 } 16399 16400 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16401 String installerPackageName) { 16402 // Enable the parent package 16403 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16404 // Enable the child packages 16405 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16406 for (int i = 0; i < childCount; i++) { 16407 PackageParser.Package childPkg = pkg.childPackages.get(i); 16408 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16409 } 16410 } 16411 16412 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16413 // Collect all used permissions in the UID 16414 ArraySet<String> usedPermissions = new ArraySet<>(); 16415 final int packageCount = su.packages.size(); 16416 for (int i = 0; i < packageCount; i++) { 16417 PackageSetting ps = su.packages.valueAt(i); 16418 if (ps.pkg == null) { 16419 continue; 16420 } 16421 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16422 for (int j = 0; j < requestedPermCount; j++) { 16423 String permission = ps.pkg.requestedPermissions.get(j); 16424 BasePermission bp = mSettings.mPermissions.get(permission); 16425 if (bp != null) { 16426 usedPermissions.add(permission); 16427 } 16428 } 16429 } 16430 16431 PermissionsState permissionsState = su.getPermissionsState(); 16432 // Prune install permissions 16433 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16434 final int installPermCount = installPermStates.size(); 16435 for (int i = installPermCount - 1; i >= 0; i--) { 16436 PermissionState permissionState = installPermStates.get(i); 16437 if (!usedPermissions.contains(permissionState.getName())) { 16438 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16439 if (bp != null) { 16440 permissionsState.revokeInstallPermission(bp); 16441 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16442 PackageManager.MASK_PERMISSION_FLAGS, 0); 16443 } 16444 } 16445 } 16446 16447 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16448 16449 // Prune runtime permissions 16450 for (int userId : allUserIds) { 16451 List<PermissionState> runtimePermStates = permissionsState 16452 .getRuntimePermissionStates(userId); 16453 final int runtimePermCount = runtimePermStates.size(); 16454 for (int i = runtimePermCount - 1; i >= 0; i--) { 16455 PermissionState permissionState = runtimePermStates.get(i); 16456 if (!usedPermissions.contains(permissionState.getName())) { 16457 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16458 if (bp != null) { 16459 permissionsState.revokeRuntimePermission(bp, userId); 16460 permissionsState.updatePermissionFlags(bp, userId, 16461 PackageManager.MASK_PERMISSION_FLAGS, 0); 16462 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16463 runtimePermissionChangedUserIds, userId); 16464 } 16465 } 16466 } 16467 } 16468 16469 return runtimePermissionChangedUserIds; 16470 } 16471 16472 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16473 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16474 // Update the parent package setting 16475 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16476 res, user, installReason); 16477 // Update the child packages setting 16478 final int childCount = (newPackage.childPackages != null) 16479 ? newPackage.childPackages.size() : 0; 16480 for (int i = 0; i < childCount; i++) { 16481 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16482 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16483 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16484 childRes.origUsers, childRes, user, installReason); 16485 } 16486 } 16487 16488 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16489 String installerPackageName, int[] allUsers, int[] installedForUsers, 16490 PackageInstalledInfo res, UserHandle user, int installReason) { 16491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16492 16493 String pkgName = newPackage.packageName; 16494 synchronized (mPackages) { 16495 //write settings. the installStatus will be incomplete at this stage. 16496 //note that the new package setting would have already been 16497 //added to mPackages. It hasn't been persisted yet. 16498 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16499 // TODO: Remove this write? It's also written at the end of this method 16500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16501 mSettings.writeLPr(); 16502 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16503 } 16504 16505 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16506 synchronized (mPackages) { 16507 updatePermissionsLPw(newPackage.packageName, newPackage, 16508 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16509 ? UPDATE_PERMISSIONS_ALL : 0)); 16510 // For system-bundled packages, we assume that installing an upgraded version 16511 // of the package implies that the user actually wants to run that new code, 16512 // so we enable the package. 16513 PackageSetting ps = mSettings.mPackages.get(pkgName); 16514 final int userId = user.getIdentifier(); 16515 if (ps != null) { 16516 if (isSystemApp(newPackage)) { 16517 if (DEBUG_INSTALL) { 16518 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16519 } 16520 // Enable system package for requested users 16521 if (res.origUsers != null) { 16522 for (int origUserId : res.origUsers) { 16523 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16524 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16525 origUserId, installerPackageName); 16526 } 16527 } 16528 } 16529 // Also convey the prior install/uninstall state 16530 if (allUsers != null && installedForUsers != null) { 16531 for (int currentUserId : allUsers) { 16532 final boolean installed = ArrayUtils.contains( 16533 installedForUsers, currentUserId); 16534 if (DEBUG_INSTALL) { 16535 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16536 } 16537 ps.setInstalled(installed, currentUserId); 16538 } 16539 // these install state changes will be persisted in the 16540 // upcoming call to mSettings.writeLPr(). 16541 } 16542 } 16543 // It's implied that when a user requests installation, they want the app to be 16544 // installed and enabled. 16545 if (userId != UserHandle.USER_ALL) { 16546 ps.setInstalled(true, userId); 16547 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16548 } 16549 16550 // When replacing an existing package, preserve the original install reason for all 16551 // users that had the package installed before. 16552 final Set<Integer> previousUserIds = new ArraySet<>(); 16553 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16554 final int installReasonCount = res.removedInfo.installReasons.size(); 16555 for (int i = 0; i < installReasonCount; i++) { 16556 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16557 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16558 ps.setInstallReason(previousInstallReason, previousUserId); 16559 previousUserIds.add(previousUserId); 16560 } 16561 } 16562 16563 // Set install reason for users that are having the package newly installed. 16564 if (userId == UserHandle.USER_ALL) { 16565 for (int currentUserId : sUserManager.getUserIds()) { 16566 if (!previousUserIds.contains(currentUserId)) { 16567 ps.setInstallReason(installReason, currentUserId); 16568 } 16569 } 16570 } else if (!previousUserIds.contains(userId)) { 16571 ps.setInstallReason(installReason, userId); 16572 } 16573 mSettings.writeKernelMappingLPr(ps); 16574 } 16575 res.name = pkgName; 16576 res.uid = newPackage.applicationInfo.uid; 16577 res.pkg = newPackage; 16578 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16579 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16580 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16581 //to update install status 16582 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16583 mSettings.writeLPr(); 16584 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16585 } 16586 16587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16588 } 16589 16590 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16591 try { 16592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16593 installPackageLI(args, res); 16594 } finally { 16595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16596 } 16597 } 16598 16599 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16600 final int installFlags = args.installFlags; 16601 final String installerPackageName = args.installerPackageName; 16602 final String volumeUuid = args.volumeUuid; 16603 final File tmpPackageFile = new File(args.getCodePath()); 16604 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16605 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16606 || (args.volumeUuid != null)); 16607 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16608 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16609 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16610 boolean replace = false; 16611 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16612 if (args.move != null) { 16613 // moving a complete application; perform an initial scan on the new install location 16614 scanFlags |= SCAN_INITIAL; 16615 } 16616 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16617 scanFlags |= SCAN_DONT_KILL_APP; 16618 } 16619 if (instantApp) { 16620 scanFlags |= SCAN_AS_INSTANT_APP; 16621 } 16622 if (fullApp) { 16623 scanFlags |= SCAN_AS_FULL_APP; 16624 } 16625 16626 // Result object to be returned 16627 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16628 16629 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16630 16631 // Sanity check 16632 if (instantApp && (forwardLocked || onExternal)) { 16633 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16634 + " external=" + onExternal); 16635 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16636 return; 16637 } 16638 16639 // Retrieve PackageSettings and parse package 16640 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16641 | PackageParser.PARSE_ENFORCE_CODE 16642 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16643 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16644 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16645 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16646 PackageParser pp = new PackageParser(); 16647 pp.setSeparateProcesses(mSeparateProcesses); 16648 pp.setDisplayMetrics(mMetrics); 16649 pp.setCallback(mPackageParserCallback); 16650 16651 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16652 final PackageParser.Package pkg; 16653 try { 16654 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16655 } catch (PackageParserException e) { 16656 res.setError("Failed parse during installPackageLI", e); 16657 return; 16658 } finally { 16659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16660 } 16661 16662 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16663 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16664 Slog.w(TAG, "Instant app package " + pkg.packageName 16665 + " does not target O, this will be a fatal error."); 16666 // STOPSHIP: Make this a fatal error 16667 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16668 } 16669 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16670 Slog.w(TAG, "Instant app package " + pkg.packageName 16671 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16672 // STOPSHIP: Make this a fatal error 16673 pkg.applicationInfo.targetSandboxVersion = 2; 16674 } 16675 16676 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16677 // Static shared libraries have synthetic package names 16678 renameStaticSharedLibraryPackage(pkg); 16679 16680 // No static shared libs on external storage 16681 if (onExternal) { 16682 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16683 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16684 "Packages declaring static-shared libs cannot be updated"); 16685 return; 16686 } 16687 } 16688 16689 // If we are installing a clustered package add results for the children 16690 if (pkg.childPackages != null) { 16691 synchronized (mPackages) { 16692 final int childCount = pkg.childPackages.size(); 16693 for (int i = 0; i < childCount; i++) { 16694 PackageParser.Package childPkg = pkg.childPackages.get(i); 16695 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16696 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16697 childRes.pkg = childPkg; 16698 childRes.name = childPkg.packageName; 16699 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16700 if (childPs != null) { 16701 childRes.origUsers = childPs.queryInstalledUsers( 16702 sUserManager.getUserIds(), true); 16703 } 16704 if ((mPackages.containsKey(childPkg.packageName))) { 16705 childRes.removedInfo = new PackageRemovedInfo(); 16706 childRes.removedInfo.removedPackage = childPkg.packageName; 16707 } 16708 if (res.addedChildPackages == null) { 16709 res.addedChildPackages = new ArrayMap<>(); 16710 } 16711 res.addedChildPackages.put(childPkg.packageName, childRes); 16712 } 16713 } 16714 } 16715 16716 // If package doesn't declare API override, mark that we have an install 16717 // time CPU ABI override. 16718 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16719 pkg.cpuAbiOverride = args.abiOverride; 16720 } 16721 16722 String pkgName = res.name = pkg.packageName; 16723 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16724 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16725 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16726 return; 16727 } 16728 } 16729 16730 try { 16731 // either use what we've been given or parse directly from the APK 16732 if (args.certificates != null) { 16733 try { 16734 PackageParser.populateCertificates(pkg, args.certificates); 16735 } catch (PackageParserException e) { 16736 // there was something wrong with the certificates we were given; 16737 // try to pull them from the APK 16738 PackageParser.collectCertificates(pkg, parseFlags); 16739 } 16740 } else { 16741 PackageParser.collectCertificates(pkg, parseFlags); 16742 } 16743 } catch (PackageParserException e) { 16744 res.setError("Failed collect during installPackageLI", e); 16745 return; 16746 } 16747 16748 // Get rid of all references to package scan path via parser. 16749 pp = null; 16750 String oldCodePath = null; 16751 boolean systemApp = false; 16752 synchronized (mPackages) { 16753 // Check if installing already existing package 16754 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16755 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16756 if (pkg.mOriginalPackages != null 16757 && pkg.mOriginalPackages.contains(oldName) 16758 && mPackages.containsKey(oldName)) { 16759 // This package is derived from an original package, 16760 // and this device has been updating from that original 16761 // name. We must continue using the original name, so 16762 // rename the new package here. 16763 pkg.setPackageName(oldName); 16764 pkgName = pkg.packageName; 16765 replace = true; 16766 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16767 + oldName + " pkgName=" + pkgName); 16768 } else if (mPackages.containsKey(pkgName)) { 16769 // This package, under its official name, already exists 16770 // on the device; we should replace it. 16771 replace = true; 16772 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16773 } 16774 16775 // Child packages are installed through the parent package 16776 if (pkg.parentPackage != null) { 16777 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16778 "Package " + pkg.packageName + " is child of package " 16779 + pkg.parentPackage.parentPackage + ". Child packages " 16780 + "can be updated only through the parent package."); 16781 return; 16782 } 16783 16784 if (replace) { 16785 // Prevent apps opting out from runtime permissions 16786 PackageParser.Package oldPackage = mPackages.get(pkgName); 16787 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16788 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16789 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16790 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16791 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16792 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16793 + " doesn't support runtime permissions but the old" 16794 + " target SDK " + oldTargetSdk + " does."); 16795 return; 16796 } 16797 // Prevent apps from downgrading their targetSandbox. 16798 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16799 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16800 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16801 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16802 "Package " + pkg.packageName + " new target sandbox " 16803 + newTargetSandbox + " is incompatible with the previous value of" 16804 + oldTargetSandbox + "."); 16805 return; 16806 } 16807 16808 // Prevent installing of child packages 16809 if (oldPackage.parentPackage != null) { 16810 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16811 "Package " + pkg.packageName + " is child of package " 16812 + oldPackage.parentPackage + ". Child packages " 16813 + "can be updated only through the parent package."); 16814 return; 16815 } 16816 } 16817 } 16818 16819 PackageSetting ps = mSettings.mPackages.get(pkgName); 16820 if (ps != null) { 16821 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16822 16823 // Static shared libs have same package with different versions where 16824 // we internally use a synthetic package name to allow multiple versions 16825 // of the same package, therefore we need to compare signatures against 16826 // the package setting for the latest library version. 16827 PackageSetting signatureCheckPs = ps; 16828 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16829 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16830 if (libraryEntry != null) { 16831 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16832 } 16833 } 16834 16835 // Quick sanity check that we're signed correctly if updating; 16836 // we'll check this again later when scanning, but we want to 16837 // bail early here before tripping over redefined permissions. 16838 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16839 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16840 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16841 + pkg.packageName + " upgrade keys do not match the " 16842 + "previously installed version"); 16843 return; 16844 } 16845 } else { 16846 try { 16847 verifySignaturesLP(signatureCheckPs, pkg); 16848 } catch (PackageManagerException e) { 16849 res.setError(e.error, e.getMessage()); 16850 return; 16851 } 16852 } 16853 16854 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16855 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16856 systemApp = (ps.pkg.applicationInfo.flags & 16857 ApplicationInfo.FLAG_SYSTEM) != 0; 16858 } 16859 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16860 } 16861 16862 int N = pkg.permissions.size(); 16863 for (int i = N-1; i >= 0; i--) { 16864 PackageParser.Permission perm = pkg.permissions.get(i); 16865 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16866 16867 // Don't allow anyone but the platform to define ephemeral permissions. 16868 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16869 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16870 Slog.w(TAG, "Package " + pkg.packageName 16871 + " attempting to delcare ephemeral permission " 16872 + perm.info.name + "; Removing ephemeral."); 16873 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16874 } 16875 // Check whether the newly-scanned package wants to define an already-defined perm 16876 if (bp != null) { 16877 // If the defining package is signed with our cert, it's okay. This 16878 // also includes the "updating the same package" case, of course. 16879 // "updating same package" could also involve key-rotation. 16880 final boolean sigsOk; 16881 if (bp.sourcePackage.equals(pkg.packageName) 16882 && (bp.packageSetting instanceof PackageSetting) 16883 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16884 scanFlags))) { 16885 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16886 } else { 16887 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16888 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16889 } 16890 if (!sigsOk) { 16891 // If the owning package is the system itself, we log but allow 16892 // install to proceed; we fail the install on all other permission 16893 // redefinitions. 16894 if (!bp.sourcePackage.equals("android")) { 16895 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16896 + pkg.packageName + " attempting to redeclare permission " 16897 + perm.info.name + " already owned by " + bp.sourcePackage); 16898 res.origPermission = perm.info.name; 16899 res.origPackage = bp.sourcePackage; 16900 return; 16901 } else { 16902 Slog.w(TAG, "Package " + pkg.packageName 16903 + " attempting to redeclare system permission " 16904 + perm.info.name + "; ignoring new declaration"); 16905 pkg.permissions.remove(i); 16906 } 16907 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16908 // Prevent apps to change protection level to dangerous from any other 16909 // type as this would allow a privilege escalation where an app adds a 16910 // normal/signature permission in other app's group and later redefines 16911 // it as dangerous leading to the group auto-grant. 16912 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16913 == PermissionInfo.PROTECTION_DANGEROUS) { 16914 if (bp != null && !bp.isRuntime()) { 16915 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16916 + "non-runtime permission " + perm.info.name 16917 + " to runtime; keeping old protection level"); 16918 perm.info.protectionLevel = bp.protectionLevel; 16919 } 16920 } 16921 } 16922 } 16923 } 16924 } 16925 16926 if (systemApp) { 16927 if (onExternal) { 16928 // Abort update; system app can't be replaced with app on sdcard 16929 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16930 "Cannot install updates to system apps on sdcard"); 16931 return; 16932 } else if (instantApp) { 16933 // Abort update; system app can't be replaced with an instant app 16934 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16935 "Cannot update a system app with an instant app"); 16936 return; 16937 } 16938 } 16939 16940 if (args.move != null) { 16941 // We did an in-place move, so dex is ready to roll 16942 scanFlags |= SCAN_NO_DEX; 16943 scanFlags |= SCAN_MOVE; 16944 16945 synchronized (mPackages) { 16946 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16947 if (ps == null) { 16948 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16949 "Missing settings for moved package " + pkgName); 16950 } 16951 16952 // We moved the entire application as-is, so bring over the 16953 // previously derived ABI information. 16954 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16955 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16956 } 16957 16958 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16959 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16960 scanFlags |= SCAN_NO_DEX; 16961 16962 try { 16963 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16964 args.abiOverride : pkg.cpuAbiOverride); 16965 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16966 true /*extractLibs*/, mAppLib32InstallDir); 16967 } catch (PackageManagerException pme) { 16968 Slog.e(TAG, "Error deriving application ABI", pme); 16969 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16970 return; 16971 } 16972 16973 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16974 // Do not run PackageDexOptimizer through the local performDexOpt 16975 // method because `pkg` may not be in `mPackages` yet. 16976 // 16977 // Also, don't fail application installs if the dexopt step fails. 16978 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16979 null /* instructionSets */, false /* checkProfiles */, 16980 getCompilerFilterForReason(REASON_INSTALL), 16981 getOrCreateCompilerPackageStats(pkg), 16982 mDexManager.isUsedByOtherApps(pkg.packageName)); 16983 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16984 16985 // Notify BackgroundDexOptService that the package has been changed. 16986 // If this is an update of a package which used to fail to compile, 16987 // BDOS will remove it from its blacklist. 16988 // TODO: Layering violation 16989 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16990 } 16991 16992 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16993 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16994 return; 16995 } 16996 16997 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16998 16999 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17000 "installPackageLI")) { 17001 if (replace) { 17002 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17003 // Static libs have a synthetic package name containing the version 17004 // and cannot be updated as an update would get a new package name, 17005 // unless this is the exact same version code which is useful for 17006 // development. 17007 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17008 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17009 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17010 + "static-shared libs cannot be updated"); 17011 return; 17012 } 17013 } 17014 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17015 installerPackageName, res, args.installReason); 17016 } else { 17017 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17018 args.user, installerPackageName, volumeUuid, res, args.installReason); 17019 } 17020 } 17021 synchronized (mPackages) { 17022 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17023 if (ps != null) { 17024 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17025 ps.setUpdateAvailable(false /*updateAvailable*/); 17026 } 17027 17028 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17029 for (int i = 0; i < childCount; i++) { 17030 PackageParser.Package childPkg = pkg.childPackages.get(i); 17031 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17032 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17033 if (childPs != null) { 17034 childRes.newUsers = childPs.queryInstalledUsers( 17035 sUserManager.getUserIds(), true); 17036 } 17037 } 17038 17039 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17040 updateSequenceNumberLP(pkgName, res.newUsers); 17041 updateInstantAppInstallerLocked(); 17042 } 17043 } 17044 } 17045 17046 private void startIntentFilterVerifications(int userId, boolean replacing, 17047 PackageParser.Package pkg) { 17048 if (mIntentFilterVerifierComponent == null) { 17049 Slog.w(TAG, "No IntentFilter verification will not be done as " 17050 + "there is no IntentFilterVerifier available!"); 17051 return; 17052 } 17053 17054 final int verifierUid = getPackageUid( 17055 mIntentFilterVerifierComponent.getPackageName(), 17056 MATCH_DEBUG_TRIAGED_MISSING, 17057 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17058 17059 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17060 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17061 mHandler.sendMessage(msg); 17062 17063 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17064 for (int i = 0; i < childCount; i++) { 17065 PackageParser.Package childPkg = pkg.childPackages.get(i); 17066 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17067 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17068 mHandler.sendMessage(msg); 17069 } 17070 } 17071 17072 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17073 PackageParser.Package pkg) { 17074 int size = pkg.activities.size(); 17075 if (size == 0) { 17076 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17077 "No activity, so no need to verify any IntentFilter!"); 17078 return; 17079 } 17080 17081 final boolean hasDomainURLs = hasDomainURLs(pkg); 17082 if (!hasDomainURLs) { 17083 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17084 "No domain URLs, so no need to verify any IntentFilter!"); 17085 return; 17086 } 17087 17088 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17089 + " if any IntentFilter from the " + size 17090 + " Activities needs verification ..."); 17091 17092 int count = 0; 17093 final String packageName = pkg.packageName; 17094 17095 synchronized (mPackages) { 17096 // If this is a new install and we see that we've already run verification for this 17097 // package, we have nothing to do: it means the state was restored from backup. 17098 if (!replacing) { 17099 IntentFilterVerificationInfo ivi = 17100 mSettings.getIntentFilterVerificationLPr(packageName); 17101 if (ivi != null) { 17102 if (DEBUG_DOMAIN_VERIFICATION) { 17103 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17104 + ivi.getStatusString()); 17105 } 17106 return; 17107 } 17108 } 17109 17110 // If any filters need to be verified, then all need to be. 17111 boolean needToVerify = false; 17112 for (PackageParser.Activity a : pkg.activities) { 17113 for (ActivityIntentInfo filter : a.intents) { 17114 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17115 if (DEBUG_DOMAIN_VERIFICATION) { 17116 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17117 } 17118 needToVerify = true; 17119 break; 17120 } 17121 } 17122 } 17123 17124 if (needToVerify) { 17125 final int verificationId = mIntentFilterVerificationToken++; 17126 for (PackageParser.Activity a : pkg.activities) { 17127 for (ActivityIntentInfo filter : a.intents) { 17128 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17129 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17130 "Verification needed for IntentFilter:" + filter.toString()); 17131 mIntentFilterVerifier.addOneIntentFilterVerification( 17132 verifierUid, userId, verificationId, filter, packageName); 17133 count++; 17134 } 17135 } 17136 } 17137 } 17138 } 17139 17140 if (count > 0) { 17141 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17142 + " IntentFilter verification" + (count > 1 ? "s" : "") 17143 + " for userId:" + userId); 17144 mIntentFilterVerifier.startVerifications(userId); 17145 } else { 17146 if (DEBUG_DOMAIN_VERIFICATION) { 17147 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17148 } 17149 } 17150 } 17151 17152 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17153 final ComponentName cn = filter.activity.getComponentName(); 17154 final String packageName = cn.getPackageName(); 17155 17156 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17157 packageName); 17158 if (ivi == null) { 17159 return true; 17160 } 17161 int status = ivi.getStatus(); 17162 switch (status) { 17163 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17164 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17165 return true; 17166 17167 default: 17168 // Nothing to do 17169 return false; 17170 } 17171 } 17172 17173 private static boolean isMultiArch(ApplicationInfo info) { 17174 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17175 } 17176 17177 private static boolean isExternal(PackageParser.Package pkg) { 17178 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17179 } 17180 17181 private static boolean isExternal(PackageSetting ps) { 17182 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17183 } 17184 17185 private static boolean isSystemApp(PackageParser.Package pkg) { 17186 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17187 } 17188 17189 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17190 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17191 } 17192 17193 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17194 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17195 } 17196 17197 private static boolean isSystemApp(PackageSetting ps) { 17198 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17199 } 17200 17201 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17202 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17203 } 17204 17205 private int packageFlagsToInstallFlags(PackageSetting ps) { 17206 int installFlags = 0; 17207 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17208 // This existing package was an external ASEC install when we have 17209 // the external flag without a UUID 17210 installFlags |= PackageManager.INSTALL_EXTERNAL; 17211 } 17212 if (ps.isForwardLocked()) { 17213 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17214 } 17215 return installFlags; 17216 } 17217 17218 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17219 if (isExternal(pkg)) { 17220 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17221 return StorageManager.UUID_PRIMARY_PHYSICAL; 17222 } else { 17223 return pkg.volumeUuid; 17224 } 17225 } else { 17226 return StorageManager.UUID_PRIVATE_INTERNAL; 17227 } 17228 } 17229 17230 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17231 if (isExternal(pkg)) { 17232 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17233 return mSettings.getExternalVersion(); 17234 } else { 17235 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17236 } 17237 } else { 17238 return mSettings.getInternalVersion(); 17239 } 17240 } 17241 17242 private void deleteTempPackageFiles() { 17243 final FilenameFilter filter = new FilenameFilter() { 17244 public boolean accept(File dir, String name) { 17245 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17246 } 17247 }; 17248 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17249 file.delete(); 17250 } 17251 } 17252 17253 @Override 17254 public void deletePackageAsUser(String packageName, int versionCode, 17255 IPackageDeleteObserver observer, int userId, int flags) { 17256 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17257 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17258 } 17259 17260 @Override 17261 public void deletePackageVersioned(VersionedPackage versionedPackage, 17262 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17263 mContext.enforceCallingOrSelfPermission( 17264 android.Manifest.permission.DELETE_PACKAGES, null); 17265 Preconditions.checkNotNull(versionedPackage); 17266 Preconditions.checkNotNull(observer); 17267 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17268 PackageManager.VERSION_CODE_HIGHEST, 17269 Integer.MAX_VALUE, "versionCode must be >= -1"); 17270 17271 final String packageName = versionedPackage.getPackageName(); 17272 // TODO: We will change version code to long, so in the new API it is long 17273 final int versionCode = (int) versionedPackage.getVersionCode(); 17274 final String internalPackageName; 17275 synchronized (mPackages) { 17276 // Normalize package name to handle renamed packages and static libs 17277 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17278 // TODO: We will change version code to long, so in the new API it is long 17279 (int) versionedPackage.getVersionCode()); 17280 } 17281 17282 final int uid = Binder.getCallingUid(); 17283 if (!isOrphaned(internalPackageName) 17284 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17285 try { 17286 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17287 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17288 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17289 observer.onUserActionRequired(intent); 17290 } catch (RemoteException re) { 17291 } 17292 return; 17293 } 17294 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17295 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17296 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17297 mContext.enforceCallingOrSelfPermission( 17298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17299 "deletePackage for user " + userId); 17300 } 17301 17302 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17303 try { 17304 observer.onPackageDeleted(packageName, 17305 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17306 } catch (RemoteException re) { 17307 } 17308 return; 17309 } 17310 17311 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17312 try { 17313 observer.onPackageDeleted(packageName, 17314 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17315 } catch (RemoteException re) { 17316 } 17317 return; 17318 } 17319 17320 if (DEBUG_REMOVE) { 17321 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17322 + " deleteAllUsers: " + deleteAllUsers + " version=" 17323 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17324 ? "VERSION_CODE_HIGHEST" : versionCode)); 17325 } 17326 // Queue up an async operation since the package deletion may take a little while. 17327 mHandler.post(new Runnable() { 17328 public void run() { 17329 mHandler.removeCallbacks(this); 17330 int returnCode; 17331 if (!deleteAllUsers) { 17332 returnCode = deletePackageX(internalPackageName, versionCode, 17333 userId, deleteFlags); 17334 } else { 17335 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17336 internalPackageName, users); 17337 // If nobody is blocking uninstall, proceed with delete for all users 17338 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17339 returnCode = deletePackageX(internalPackageName, versionCode, 17340 userId, deleteFlags); 17341 } else { 17342 // Otherwise uninstall individually for users with blockUninstalls=false 17343 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17344 for (int userId : users) { 17345 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17346 returnCode = deletePackageX(internalPackageName, versionCode, 17347 userId, userFlags); 17348 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17349 Slog.w(TAG, "Package delete failed for user " + userId 17350 + ", returnCode " + returnCode); 17351 } 17352 } 17353 } 17354 // The app has only been marked uninstalled for certain users. 17355 // We still need to report that delete was blocked 17356 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17357 } 17358 } 17359 try { 17360 observer.onPackageDeleted(packageName, returnCode, null); 17361 } catch (RemoteException e) { 17362 Log.i(TAG, "Observer no longer exists."); 17363 } //end catch 17364 } //end run 17365 }); 17366 } 17367 17368 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17369 if (pkg.staticSharedLibName != null) { 17370 return pkg.manifestPackageName; 17371 } 17372 return pkg.packageName; 17373 } 17374 17375 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17376 // Handle renamed packages 17377 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17378 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17379 17380 // Is this a static library? 17381 SparseArray<SharedLibraryEntry> versionedLib = 17382 mStaticLibsByDeclaringPackage.get(packageName); 17383 if (versionedLib == null || versionedLib.size() <= 0) { 17384 return packageName; 17385 } 17386 17387 // Figure out which lib versions the caller can see 17388 SparseIntArray versionsCallerCanSee = null; 17389 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17390 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17391 && callingAppId != Process.ROOT_UID) { 17392 versionsCallerCanSee = new SparseIntArray(); 17393 String libName = versionedLib.valueAt(0).info.getName(); 17394 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17395 if (uidPackages != null) { 17396 for (String uidPackage : uidPackages) { 17397 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17398 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17399 if (libIdx >= 0) { 17400 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17401 versionsCallerCanSee.append(libVersion, libVersion); 17402 } 17403 } 17404 } 17405 } 17406 17407 // Caller can see nothing - done 17408 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17409 return packageName; 17410 } 17411 17412 // Find the version the caller can see and the app version code 17413 SharedLibraryEntry highestVersion = null; 17414 final int versionCount = versionedLib.size(); 17415 for (int i = 0; i < versionCount; i++) { 17416 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17417 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17418 libEntry.info.getVersion()) < 0) { 17419 continue; 17420 } 17421 // TODO: We will change version code to long, so in the new API it is long 17422 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17423 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17424 if (libVersionCode == versionCode) { 17425 return libEntry.apk; 17426 } 17427 } else if (highestVersion == null) { 17428 highestVersion = libEntry; 17429 } else if (libVersionCode > highestVersion.info 17430 .getDeclaringPackage().getVersionCode()) { 17431 highestVersion = libEntry; 17432 } 17433 } 17434 17435 if (highestVersion != null) { 17436 return highestVersion.apk; 17437 } 17438 17439 return packageName; 17440 } 17441 17442 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17443 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17444 || callingUid == Process.SYSTEM_UID) { 17445 return true; 17446 } 17447 final int callingUserId = UserHandle.getUserId(callingUid); 17448 // If the caller installed the pkgName, then allow it to silently uninstall. 17449 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17450 return true; 17451 } 17452 17453 // Allow package verifier to silently uninstall. 17454 if (mRequiredVerifierPackage != null && 17455 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17456 return true; 17457 } 17458 17459 // Allow package uninstaller to silently uninstall. 17460 if (mRequiredUninstallerPackage != null && 17461 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17462 return true; 17463 } 17464 17465 // Allow storage manager to silently uninstall. 17466 if (mStorageManagerPackage != null && 17467 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17468 return true; 17469 } 17470 return false; 17471 } 17472 17473 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17474 int[] result = EMPTY_INT_ARRAY; 17475 for (int userId : userIds) { 17476 if (getBlockUninstallForUser(packageName, userId)) { 17477 result = ArrayUtils.appendInt(result, userId); 17478 } 17479 } 17480 return result; 17481 } 17482 17483 @Override 17484 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17485 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17486 } 17487 17488 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17489 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17490 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17491 try { 17492 if (dpm != null) { 17493 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17494 /* callingUserOnly =*/ false); 17495 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17496 : deviceOwnerComponentName.getPackageName(); 17497 // Does the package contains the device owner? 17498 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17499 // this check is probably not needed, since DO should be registered as a device 17500 // admin on some user too. (Original bug for this: b/17657954) 17501 if (packageName.equals(deviceOwnerPackageName)) { 17502 return true; 17503 } 17504 // Does it contain a device admin for any user? 17505 int[] users; 17506 if (userId == UserHandle.USER_ALL) { 17507 users = sUserManager.getUserIds(); 17508 } else { 17509 users = new int[]{userId}; 17510 } 17511 for (int i = 0; i < users.length; ++i) { 17512 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17513 return true; 17514 } 17515 } 17516 } 17517 } catch (RemoteException e) { 17518 } 17519 return false; 17520 } 17521 17522 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17523 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17524 } 17525 17526 /** 17527 * This method is an internal method that could be get invoked either 17528 * to delete an installed package or to clean up a failed installation. 17529 * After deleting an installed package, a broadcast is sent to notify any 17530 * listeners that the package has been removed. For cleaning up a failed 17531 * installation, the broadcast is not necessary since the package's 17532 * installation wouldn't have sent the initial broadcast either 17533 * The key steps in deleting a package are 17534 * deleting the package information in internal structures like mPackages, 17535 * deleting the packages base directories through installd 17536 * updating mSettings to reflect current status 17537 * persisting settings for later use 17538 * sending a broadcast if necessary 17539 */ 17540 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17541 final PackageRemovedInfo info = new PackageRemovedInfo(); 17542 final boolean res; 17543 17544 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17545 ? UserHandle.USER_ALL : userId; 17546 17547 if (isPackageDeviceAdmin(packageName, removeUser)) { 17548 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17549 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17550 } 17551 17552 PackageSetting uninstalledPs = null; 17553 PackageParser.Package pkg = null; 17554 17555 // for the uninstall-updates case and restricted profiles, remember the per- 17556 // user handle installed state 17557 int[] allUsers; 17558 synchronized (mPackages) { 17559 uninstalledPs = mSettings.mPackages.get(packageName); 17560 if (uninstalledPs == null) { 17561 Slog.w(TAG, "Not removing non-existent package " + packageName); 17562 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17563 } 17564 17565 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17566 && uninstalledPs.versionCode != versionCode) { 17567 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17568 + uninstalledPs.versionCode + " != " + versionCode); 17569 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17570 } 17571 17572 // Static shared libs can be declared by any package, so let us not 17573 // allow removing a package if it provides a lib others depend on. 17574 pkg = mPackages.get(packageName); 17575 if (pkg != null && pkg.staticSharedLibName != null) { 17576 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17577 pkg.staticSharedLibVersion); 17578 if (libEntry != null) { 17579 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17580 libEntry.info, 0, userId); 17581 if (!ArrayUtils.isEmpty(libClientPackages)) { 17582 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17583 + " hosting lib " + libEntry.info.getName() + " version " 17584 + libEntry.info.getVersion() + " used by " + libClientPackages); 17585 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17586 } 17587 } 17588 } 17589 17590 allUsers = sUserManager.getUserIds(); 17591 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17592 } 17593 17594 final int freezeUser; 17595 if (isUpdatedSystemApp(uninstalledPs) 17596 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17597 // We're downgrading a system app, which will apply to all users, so 17598 // freeze them all during the downgrade 17599 freezeUser = UserHandle.USER_ALL; 17600 } else { 17601 freezeUser = removeUser; 17602 } 17603 17604 synchronized (mInstallLock) { 17605 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17606 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17607 deleteFlags, "deletePackageX")) { 17608 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17609 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17610 } 17611 synchronized (mPackages) { 17612 if (res) { 17613 if (pkg != null) { 17614 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17615 } 17616 updateSequenceNumberLP(packageName, info.removedUsers); 17617 updateInstantAppInstallerLocked(); 17618 } 17619 } 17620 } 17621 17622 if (res) { 17623 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17624 info.sendPackageRemovedBroadcasts(killApp); 17625 info.sendSystemPackageUpdatedBroadcasts(); 17626 info.sendSystemPackageAppearedBroadcasts(); 17627 } 17628 // Force a gc here. 17629 Runtime.getRuntime().gc(); 17630 // Delete the resources here after sending the broadcast to let 17631 // other processes clean up before deleting resources. 17632 if (info.args != null) { 17633 synchronized (mInstallLock) { 17634 info.args.doPostDeleteLI(true); 17635 } 17636 } 17637 17638 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17639 } 17640 17641 class PackageRemovedInfo { 17642 String removedPackage; 17643 int uid = -1; 17644 int removedAppId = -1; 17645 int[] origUsers; 17646 int[] removedUsers = null; 17647 SparseArray<Integer> installReasons; 17648 boolean isRemovedPackageSystemUpdate = false; 17649 boolean isUpdate; 17650 boolean dataRemoved; 17651 boolean removedForAllUsers; 17652 boolean isStaticSharedLib; 17653 // Clean up resources deleted packages. 17654 InstallArgs args = null; 17655 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17656 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17657 17658 void sendPackageRemovedBroadcasts(boolean killApp) { 17659 sendPackageRemovedBroadcastInternal(killApp); 17660 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17661 for (int i = 0; i < childCount; i++) { 17662 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17663 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17664 } 17665 } 17666 17667 void sendSystemPackageUpdatedBroadcasts() { 17668 if (isRemovedPackageSystemUpdate) { 17669 sendSystemPackageUpdatedBroadcastsInternal(); 17670 final int childCount = (removedChildPackages != null) 17671 ? removedChildPackages.size() : 0; 17672 for (int i = 0; i < childCount; i++) { 17673 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17674 if (childInfo.isRemovedPackageSystemUpdate) { 17675 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17676 } 17677 } 17678 } 17679 } 17680 17681 void sendSystemPackageAppearedBroadcasts() { 17682 final int packageCount = (appearedChildPackages != null) 17683 ? appearedChildPackages.size() : 0; 17684 for (int i = 0; i < packageCount; i++) { 17685 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17686 sendPackageAddedForNewUsers(installedInfo.name, true, 17687 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17688 } 17689 } 17690 17691 private void sendSystemPackageUpdatedBroadcastsInternal() { 17692 Bundle extras = new Bundle(2); 17693 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17694 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17695 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17696 extras, 0, null, null, null); 17697 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17698 extras, 0, null, null, null); 17699 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17700 null, 0, removedPackage, null, null); 17701 } 17702 17703 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17704 // Don't send static shared library removal broadcasts as these 17705 // libs are visible only the the apps that depend on them an one 17706 // cannot remove the library if it has a dependency. 17707 if (isStaticSharedLib) { 17708 return; 17709 } 17710 Bundle extras = new Bundle(2); 17711 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17712 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17713 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17714 if (isUpdate || isRemovedPackageSystemUpdate) { 17715 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17716 } 17717 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17718 if (removedPackage != null) { 17719 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17720 extras, 0, null, null, removedUsers); 17721 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17722 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17723 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17724 null, null, removedUsers); 17725 } 17726 } 17727 if (removedAppId >= 0) { 17728 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17729 removedUsers); 17730 } 17731 } 17732 } 17733 17734 /* 17735 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17736 * flag is not set, the data directory is removed as well. 17737 * make sure this flag is set for partially installed apps. If not its meaningless to 17738 * delete a partially installed application. 17739 */ 17740 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17741 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17742 String packageName = ps.name; 17743 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17744 // Retrieve object to delete permissions for shared user later on 17745 final PackageParser.Package deletedPkg; 17746 final PackageSetting deletedPs; 17747 // reader 17748 synchronized (mPackages) { 17749 deletedPkg = mPackages.get(packageName); 17750 deletedPs = mSettings.mPackages.get(packageName); 17751 if (outInfo != null) { 17752 outInfo.removedPackage = packageName; 17753 outInfo.isStaticSharedLib = deletedPkg != null 17754 && deletedPkg.staticSharedLibName != null; 17755 outInfo.removedUsers = deletedPs != null 17756 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17757 : null; 17758 } 17759 } 17760 17761 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17762 17763 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17764 final PackageParser.Package resolvedPkg; 17765 if (deletedPkg != null) { 17766 resolvedPkg = deletedPkg; 17767 } else { 17768 // We don't have a parsed package when it lives on an ejected 17769 // adopted storage device, so fake something together 17770 resolvedPkg = new PackageParser.Package(ps.name); 17771 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17772 } 17773 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17774 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17775 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17776 if (outInfo != null) { 17777 outInfo.dataRemoved = true; 17778 } 17779 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17780 } 17781 17782 int removedAppId = -1; 17783 17784 // writer 17785 synchronized (mPackages) { 17786 boolean installedStateChanged = false; 17787 if (deletedPs != null) { 17788 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17789 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17790 clearDefaultBrowserIfNeeded(packageName); 17791 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17792 removedAppId = mSettings.removePackageLPw(packageName); 17793 if (outInfo != null) { 17794 outInfo.removedAppId = removedAppId; 17795 } 17796 updatePermissionsLPw(deletedPs.name, null, 0); 17797 if (deletedPs.sharedUser != null) { 17798 // Remove permissions associated with package. Since runtime 17799 // permissions are per user we have to kill the removed package 17800 // or packages running under the shared user of the removed 17801 // package if revoking the permissions requested only by the removed 17802 // package is successful and this causes a change in gids. 17803 for (int userId : UserManagerService.getInstance().getUserIds()) { 17804 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17805 userId); 17806 if (userIdToKill == UserHandle.USER_ALL 17807 || userIdToKill >= UserHandle.USER_SYSTEM) { 17808 // If gids changed for this user, kill all affected packages. 17809 mHandler.post(new Runnable() { 17810 @Override 17811 public void run() { 17812 // This has to happen with no lock held. 17813 killApplication(deletedPs.name, deletedPs.appId, 17814 KILL_APP_REASON_GIDS_CHANGED); 17815 } 17816 }); 17817 break; 17818 } 17819 } 17820 } 17821 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17822 } 17823 // make sure to preserve per-user disabled state if this removal was just 17824 // a downgrade of a system app to the factory package 17825 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17826 if (DEBUG_REMOVE) { 17827 Slog.d(TAG, "Propagating install state across downgrade"); 17828 } 17829 for (int userId : allUserHandles) { 17830 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17831 if (DEBUG_REMOVE) { 17832 Slog.d(TAG, " user " + userId + " => " + installed); 17833 } 17834 if (installed != ps.getInstalled(userId)) { 17835 installedStateChanged = true; 17836 } 17837 ps.setInstalled(installed, userId); 17838 } 17839 } 17840 } 17841 // can downgrade to reader 17842 if (writeSettings) { 17843 // Save settings now 17844 mSettings.writeLPr(); 17845 } 17846 if (installedStateChanged) { 17847 mSettings.writeKernelMappingLPr(ps); 17848 } 17849 } 17850 if (removedAppId != -1) { 17851 // A user ID was deleted here. Go through all users and remove it 17852 // from KeyStore. 17853 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17854 } 17855 } 17856 17857 static boolean locationIsPrivileged(File path) { 17858 try { 17859 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17860 .getCanonicalPath(); 17861 return path.getCanonicalPath().startsWith(privilegedAppDir); 17862 } catch (IOException e) { 17863 Slog.e(TAG, "Unable to access code path " + path); 17864 } 17865 return false; 17866 } 17867 17868 /* 17869 * Tries to delete system package. 17870 */ 17871 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17872 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17873 boolean writeSettings) { 17874 if (deletedPs.parentPackageName != null) { 17875 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17876 return false; 17877 } 17878 17879 final boolean applyUserRestrictions 17880 = (allUserHandles != null) && (outInfo.origUsers != null); 17881 final PackageSetting disabledPs; 17882 // Confirm if the system package has been updated 17883 // An updated system app can be deleted. This will also have to restore 17884 // the system pkg from system partition 17885 // reader 17886 synchronized (mPackages) { 17887 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17888 } 17889 17890 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17891 + " disabledPs=" + disabledPs); 17892 17893 if (disabledPs == null) { 17894 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17895 return false; 17896 } else if (DEBUG_REMOVE) { 17897 Slog.d(TAG, "Deleting system pkg from data partition"); 17898 } 17899 17900 if (DEBUG_REMOVE) { 17901 if (applyUserRestrictions) { 17902 Slog.d(TAG, "Remembering install states:"); 17903 for (int userId : allUserHandles) { 17904 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17905 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17906 } 17907 } 17908 } 17909 17910 // Delete the updated package 17911 outInfo.isRemovedPackageSystemUpdate = true; 17912 if (outInfo.removedChildPackages != null) { 17913 final int childCount = (deletedPs.childPackageNames != null) 17914 ? deletedPs.childPackageNames.size() : 0; 17915 for (int i = 0; i < childCount; i++) { 17916 String childPackageName = deletedPs.childPackageNames.get(i); 17917 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17918 .contains(childPackageName)) { 17919 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17920 childPackageName); 17921 if (childInfo != null) { 17922 childInfo.isRemovedPackageSystemUpdate = true; 17923 } 17924 } 17925 } 17926 } 17927 17928 if (disabledPs.versionCode < deletedPs.versionCode) { 17929 // Delete data for downgrades 17930 flags &= ~PackageManager.DELETE_KEEP_DATA; 17931 } else { 17932 // Preserve data by setting flag 17933 flags |= PackageManager.DELETE_KEEP_DATA; 17934 } 17935 17936 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17937 outInfo, writeSettings, disabledPs.pkg); 17938 if (!ret) { 17939 return false; 17940 } 17941 17942 // writer 17943 synchronized (mPackages) { 17944 // Reinstate the old system package 17945 enableSystemPackageLPw(disabledPs.pkg); 17946 // Remove any native libraries from the upgraded package. 17947 removeNativeBinariesLI(deletedPs); 17948 } 17949 17950 // Install the system package 17951 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17952 int parseFlags = mDefParseFlags 17953 | PackageParser.PARSE_MUST_BE_APK 17954 | PackageParser.PARSE_IS_SYSTEM 17955 | PackageParser.PARSE_IS_SYSTEM_DIR; 17956 if (locationIsPrivileged(disabledPs.codePath)) { 17957 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17958 } 17959 17960 final PackageParser.Package newPkg; 17961 try { 17962 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17963 0 /* currentTime */, null); 17964 } catch (PackageManagerException e) { 17965 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17966 + e.getMessage()); 17967 return false; 17968 } 17969 17970 try { 17971 // update shared libraries for the newly re-installed system package 17972 updateSharedLibrariesLPr(newPkg, null); 17973 } catch (PackageManagerException e) { 17974 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17975 } 17976 17977 prepareAppDataAfterInstallLIF(newPkg); 17978 17979 // writer 17980 synchronized (mPackages) { 17981 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17982 17983 // Propagate the permissions state as we do not want to drop on the floor 17984 // runtime permissions. The update permissions method below will take 17985 // care of removing obsolete permissions and grant install permissions. 17986 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17987 updatePermissionsLPw(newPkg.packageName, newPkg, 17988 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17989 17990 if (applyUserRestrictions) { 17991 boolean installedStateChanged = false; 17992 if (DEBUG_REMOVE) { 17993 Slog.d(TAG, "Propagating install state across reinstall"); 17994 } 17995 for (int userId : allUserHandles) { 17996 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17997 if (DEBUG_REMOVE) { 17998 Slog.d(TAG, " user " + userId + " => " + installed); 17999 } 18000 if (installed != ps.getInstalled(userId)) { 18001 installedStateChanged = true; 18002 } 18003 ps.setInstalled(installed, userId); 18004 18005 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18006 } 18007 // Regardless of writeSettings we need to ensure that this restriction 18008 // state propagation is persisted 18009 mSettings.writeAllUsersPackageRestrictionsLPr(); 18010 if (installedStateChanged) { 18011 mSettings.writeKernelMappingLPr(ps); 18012 } 18013 } 18014 // can downgrade to reader here 18015 if (writeSettings) { 18016 mSettings.writeLPr(); 18017 } 18018 } 18019 return true; 18020 } 18021 18022 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18023 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18024 PackageRemovedInfo outInfo, boolean writeSettings, 18025 PackageParser.Package replacingPackage) { 18026 synchronized (mPackages) { 18027 if (outInfo != null) { 18028 outInfo.uid = ps.appId; 18029 } 18030 18031 if (outInfo != null && outInfo.removedChildPackages != null) { 18032 final int childCount = (ps.childPackageNames != null) 18033 ? ps.childPackageNames.size() : 0; 18034 for (int i = 0; i < childCount; i++) { 18035 String childPackageName = ps.childPackageNames.get(i); 18036 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18037 if (childPs == null) { 18038 return false; 18039 } 18040 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18041 childPackageName); 18042 if (childInfo != null) { 18043 childInfo.uid = childPs.appId; 18044 } 18045 } 18046 } 18047 } 18048 18049 // Delete package data from internal structures and also remove data if flag is set 18050 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18051 18052 // Delete the child packages data 18053 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18054 for (int i = 0; i < childCount; i++) { 18055 PackageSetting childPs; 18056 synchronized (mPackages) { 18057 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18058 } 18059 if (childPs != null) { 18060 PackageRemovedInfo childOutInfo = (outInfo != null 18061 && outInfo.removedChildPackages != null) 18062 ? outInfo.removedChildPackages.get(childPs.name) : null; 18063 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18064 && (replacingPackage != null 18065 && !replacingPackage.hasChildPackage(childPs.name)) 18066 ? flags & ~DELETE_KEEP_DATA : flags; 18067 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18068 deleteFlags, writeSettings); 18069 } 18070 } 18071 18072 // Delete application code and resources only for parent packages 18073 if (ps.parentPackageName == null) { 18074 if (deleteCodeAndResources && (outInfo != null)) { 18075 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18076 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18077 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18078 } 18079 } 18080 18081 return true; 18082 } 18083 18084 @Override 18085 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18086 int userId) { 18087 mContext.enforceCallingOrSelfPermission( 18088 android.Manifest.permission.DELETE_PACKAGES, null); 18089 synchronized (mPackages) { 18090 PackageSetting ps = mSettings.mPackages.get(packageName); 18091 if (ps == null) { 18092 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18093 return false; 18094 } 18095 // Cannot block uninstall of static shared libs as they are 18096 // considered a part of the using app (emulating static linking). 18097 // Also static libs are installed always on internal storage. 18098 PackageParser.Package pkg = mPackages.get(packageName); 18099 if (pkg != null && pkg.staticSharedLibName != null) { 18100 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18101 + " providing static shared library: " + pkg.staticSharedLibName); 18102 return false; 18103 } 18104 if (!ps.getInstalled(userId)) { 18105 // Can't block uninstall for an app that is not installed or enabled. 18106 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18107 return false; 18108 } 18109 ps.setBlockUninstall(blockUninstall, userId); 18110 mSettings.writePackageRestrictionsLPr(userId); 18111 } 18112 return true; 18113 } 18114 18115 @Override 18116 public boolean getBlockUninstallForUser(String packageName, int userId) { 18117 synchronized (mPackages) { 18118 PackageSetting ps = mSettings.mPackages.get(packageName); 18119 if (ps == null) { 18120 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18121 return false; 18122 } 18123 return ps.getBlockUninstall(userId); 18124 } 18125 } 18126 18127 @Override 18128 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18129 int callingUid = Binder.getCallingUid(); 18130 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18131 throw new SecurityException( 18132 "setRequiredForSystemUser can only be run by the system or root"); 18133 } 18134 synchronized (mPackages) { 18135 PackageSetting ps = mSettings.mPackages.get(packageName); 18136 if (ps == null) { 18137 Log.w(TAG, "Package doesn't exist: " + packageName); 18138 return false; 18139 } 18140 if (systemUserApp) { 18141 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18142 } else { 18143 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18144 } 18145 mSettings.writeLPr(); 18146 } 18147 return true; 18148 } 18149 18150 /* 18151 * This method handles package deletion in general 18152 */ 18153 private boolean deletePackageLIF(String packageName, UserHandle user, 18154 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18155 PackageRemovedInfo outInfo, boolean writeSettings, 18156 PackageParser.Package replacingPackage) { 18157 if (packageName == null) { 18158 Slog.w(TAG, "Attempt to delete null packageName."); 18159 return false; 18160 } 18161 18162 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18163 18164 PackageSetting ps; 18165 synchronized (mPackages) { 18166 ps = mSettings.mPackages.get(packageName); 18167 if (ps == null) { 18168 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18169 return false; 18170 } 18171 18172 if (ps.parentPackageName != null && (!isSystemApp(ps) 18173 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18174 if (DEBUG_REMOVE) { 18175 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18176 + ((user == null) ? UserHandle.USER_ALL : user)); 18177 } 18178 final int removedUserId = (user != null) ? user.getIdentifier() 18179 : UserHandle.USER_ALL; 18180 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18181 return false; 18182 } 18183 markPackageUninstalledForUserLPw(ps, user); 18184 scheduleWritePackageRestrictionsLocked(user); 18185 return true; 18186 } 18187 } 18188 18189 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18190 && user.getIdentifier() != UserHandle.USER_ALL)) { 18191 // The caller is asking that the package only be deleted for a single 18192 // user. To do this, we just mark its uninstalled state and delete 18193 // its data. If this is a system app, we only allow this to happen if 18194 // they have set the special DELETE_SYSTEM_APP which requests different 18195 // semantics than normal for uninstalling system apps. 18196 markPackageUninstalledForUserLPw(ps, user); 18197 18198 if (!isSystemApp(ps)) { 18199 // Do not uninstall the APK if an app should be cached 18200 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18201 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18202 // Other user still have this package installed, so all 18203 // we need to do is clear this user's data and save that 18204 // it is uninstalled. 18205 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18206 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18207 return false; 18208 } 18209 scheduleWritePackageRestrictionsLocked(user); 18210 return true; 18211 } else { 18212 // We need to set it back to 'installed' so the uninstall 18213 // broadcasts will be sent correctly. 18214 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18215 ps.setInstalled(true, user.getIdentifier()); 18216 mSettings.writeKernelMappingLPr(ps); 18217 } 18218 } else { 18219 // This is a system app, so we assume that the 18220 // other users still have this package installed, so all 18221 // we need to do is clear this user's data and save that 18222 // it is uninstalled. 18223 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18224 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18225 return false; 18226 } 18227 scheduleWritePackageRestrictionsLocked(user); 18228 return true; 18229 } 18230 } 18231 18232 // If we are deleting a composite package for all users, keep track 18233 // of result for each child. 18234 if (ps.childPackageNames != null && outInfo != null) { 18235 synchronized (mPackages) { 18236 final int childCount = ps.childPackageNames.size(); 18237 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18238 for (int i = 0; i < childCount; i++) { 18239 String childPackageName = ps.childPackageNames.get(i); 18240 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18241 childInfo.removedPackage = childPackageName; 18242 outInfo.removedChildPackages.put(childPackageName, childInfo); 18243 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18244 if (childPs != null) { 18245 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18246 } 18247 } 18248 } 18249 } 18250 18251 boolean ret = false; 18252 if (isSystemApp(ps)) { 18253 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18254 // When an updated system application is deleted we delete the existing resources 18255 // as well and fall back to existing code in system partition 18256 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18257 } else { 18258 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18259 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18260 outInfo, writeSettings, replacingPackage); 18261 } 18262 18263 // Take a note whether we deleted the package for all users 18264 if (outInfo != null) { 18265 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18266 if (outInfo.removedChildPackages != null) { 18267 synchronized (mPackages) { 18268 final int childCount = outInfo.removedChildPackages.size(); 18269 for (int i = 0; i < childCount; i++) { 18270 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18271 if (childInfo != null) { 18272 childInfo.removedForAllUsers = mPackages.get( 18273 childInfo.removedPackage) == null; 18274 } 18275 } 18276 } 18277 } 18278 // If we uninstalled an update to a system app there may be some 18279 // child packages that appeared as they are declared in the system 18280 // app but were not declared in the update. 18281 if (isSystemApp(ps)) { 18282 synchronized (mPackages) { 18283 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18284 final int childCount = (updatedPs.childPackageNames != null) 18285 ? updatedPs.childPackageNames.size() : 0; 18286 for (int i = 0; i < childCount; i++) { 18287 String childPackageName = updatedPs.childPackageNames.get(i); 18288 if (outInfo.removedChildPackages == null 18289 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18290 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18291 if (childPs == null) { 18292 continue; 18293 } 18294 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18295 installRes.name = childPackageName; 18296 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18297 installRes.pkg = mPackages.get(childPackageName); 18298 installRes.uid = childPs.pkg.applicationInfo.uid; 18299 if (outInfo.appearedChildPackages == null) { 18300 outInfo.appearedChildPackages = new ArrayMap<>(); 18301 } 18302 outInfo.appearedChildPackages.put(childPackageName, installRes); 18303 } 18304 } 18305 } 18306 } 18307 } 18308 18309 return ret; 18310 } 18311 18312 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18313 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18314 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18315 for (int nextUserId : userIds) { 18316 if (DEBUG_REMOVE) { 18317 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18318 } 18319 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18320 false /*installed*/, 18321 true /*stopped*/, 18322 true /*notLaunched*/, 18323 false /*hidden*/, 18324 false /*suspended*/, 18325 false /*instantApp*/, 18326 null /*lastDisableAppCaller*/, 18327 null /*enabledComponents*/, 18328 null /*disabledComponents*/, 18329 false /*blockUninstall*/, 18330 ps.readUserState(nextUserId).domainVerificationStatus, 18331 0, PackageManager.INSTALL_REASON_UNKNOWN); 18332 } 18333 mSettings.writeKernelMappingLPr(ps); 18334 } 18335 18336 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18337 PackageRemovedInfo outInfo) { 18338 final PackageParser.Package pkg; 18339 synchronized (mPackages) { 18340 pkg = mPackages.get(ps.name); 18341 } 18342 18343 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18344 : new int[] {userId}; 18345 for (int nextUserId : userIds) { 18346 if (DEBUG_REMOVE) { 18347 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18348 + nextUserId); 18349 } 18350 18351 destroyAppDataLIF(pkg, userId, 18352 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18353 destroyAppProfilesLIF(pkg, userId); 18354 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18355 schedulePackageCleaning(ps.name, nextUserId, false); 18356 synchronized (mPackages) { 18357 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18358 scheduleWritePackageRestrictionsLocked(nextUserId); 18359 } 18360 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18361 } 18362 } 18363 18364 if (outInfo != null) { 18365 outInfo.removedPackage = ps.name; 18366 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18367 outInfo.removedAppId = ps.appId; 18368 outInfo.removedUsers = userIds; 18369 } 18370 18371 return true; 18372 } 18373 18374 private final class ClearStorageConnection implements ServiceConnection { 18375 IMediaContainerService mContainerService; 18376 18377 @Override 18378 public void onServiceConnected(ComponentName name, IBinder service) { 18379 synchronized (this) { 18380 mContainerService = IMediaContainerService.Stub 18381 .asInterface(Binder.allowBlocking(service)); 18382 notifyAll(); 18383 } 18384 } 18385 18386 @Override 18387 public void onServiceDisconnected(ComponentName name) { 18388 } 18389 } 18390 18391 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18392 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18393 18394 final boolean mounted; 18395 if (Environment.isExternalStorageEmulated()) { 18396 mounted = true; 18397 } else { 18398 final String status = Environment.getExternalStorageState(); 18399 18400 mounted = status.equals(Environment.MEDIA_MOUNTED) 18401 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18402 } 18403 18404 if (!mounted) { 18405 return; 18406 } 18407 18408 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18409 int[] users; 18410 if (userId == UserHandle.USER_ALL) { 18411 users = sUserManager.getUserIds(); 18412 } else { 18413 users = new int[] { userId }; 18414 } 18415 final ClearStorageConnection conn = new ClearStorageConnection(); 18416 if (mContext.bindServiceAsUser( 18417 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18418 try { 18419 for (int curUser : users) { 18420 long timeout = SystemClock.uptimeMillis() + 5000; 18421 synchronized (conn) { 18422 long now; 18423 while (conn.mContainerService == null && 18424 (now = SystemClock.uptimeMillis()) < timeout) { 18425 try { 18426 conn.wait(timeout - now); 18427 } catch (InterruptedException e) { 18428 } 18429 } 18430 } 18431 if (conn.mContainerService == null) { 18432 return; 18433 } 18434 18435 final UserEnvironment userEnv = new UserEnvironment(curUser); 18436 clearDirectory(conn.mContainerService, 18437 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18438 if (allData) { 18439 clearDirectory(conn.mContainerService, 18440 userEnv.buildExternalStorageAppDataDirs(packageName)); 18441 clearDirectory(conn.mContainerService, 18442 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18443 } 18444 } 18445 } finally { 18446 mContext.unbindService(conn); 18447 } 18448 } 18449 } 18450 18451 @Override 18452 public void clearApplicationProfileData(String packageName) { 18453 enforceSystemOrRoot("Only the system can clear all profile data"); 18454 18455 final PackageParser.Package pkg; 18456 synchronized (mPackages) { 18457 pkg = mPackages.get(packageName); 18458 } 18459 18460 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18461 synchronized (mInstallLock) { 18462 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18463 } 18464 } 18465 } 18466 18467 @Override 18468 public void clearApplicationUserData(final String packageName, 18469 final IPackageDataObserver observer, final int userId) { 18470 mContext.enforceCallingOrSelfPermission( 18471 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18472 18473 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18474 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18475 18476 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18477 throw new SecurityException("Cannot clear data for a protected package: " 18478 + packageName); 18479 } 18480 // Queue up an async operation since the package deletion may take a little while. 18481 mHandler.post(new Runnable() { 18482 public void run() { 18483 mHandler.removeCallbacks(this); 18484 final boolean succeeded; 18485 try (PackageFreezer freezer = freezePackage(packageName, 18486 "clearApplicationUserData")) { 18487 synchronized (mInstallLock) { 18488 succeeded = clearApplicationUserDataLIF(packageName, userId); 18489 } 18490 clearExternalStorageDataSync(packageName, userId, true); 18491 synchronized (mPackages) { 18492 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18493 packageName, userId); 18494 } 18495 } 18496 if (succeeded) { 18497 // invoke DeviceStorageMonitor's update method to clear any notifications 18498 DeviceStorageMonitorInternal dsm = LocalServices 18499 .getService(DeviceStorageMonitorInternal.class); 18500 if (dsm != null) { 18501 dsm.checkMemory(); 18502 } 18503 } 18504 if(observer != null) { 18505 try { 18506 observer.onRemoveCompleted(packageName, succeeded); 18507 } catch (RemoteException e) { 18508 Log.i(TAG, "Observer no longer exists."); 18509 } 18510 } //end if observer 18511 } //end run 18512 }); 18513 } 18514 18515 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18516 if (packageName == null) { 18517 Slog.w(TAG, "Attempt to delete null packageName."); 18518 return false; 18519 } 18520 18521 // Try finding details about the requested package 18522 PackageParser.Package pkg; 18523 synchronized (mPackages) { 18524 pkg = mPackages.get(packageName); 18525 if (pkg == null) { 18526 final PackageSetting ps = mSettings.mPackages.get(packageName); 18527 if (ps != null) { 18528 pkg = ps.pkg; 18529 } 18530 } 18531 18532 if (pkg == null) { 18533 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18534 return false; 18535 } 18536 18537 PackageSetting ps = (PackageSetting) pkg.mExtras; 18538 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18539 } 18540 18541 clearAppDataLIF(pkg, userId, 18542 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18543 18544 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18545 removeKeystoreDataIfNeeded(userId, appId); 18546 18547 UserManagerInternal umInternal = getUserManagerInternal(); 18548 final int flags; 18549 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18550 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18551 } else if (umInternal.isUserRunning(userId)) { 18552 flags = StorageManager.FLAG_STORAGE_DE; 18553 } else { 18554 flags = 0; 18555 } 18556 prepareAppDataContentsLIF(pkg, userId, flags); 18557 18558 return true; 18559 } 18560 18561 /** 18562 * Reverts user permission state changes (permissions and flags) in 18563 * all packages for a given user. 18564 * 18565 * @param userId The device user for which to do a reset. 18566 */ 18567 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18568 final int packageCount = mPackages.size(); 18569 for (int i = 0; i < packageCount; i++) { 18570 PackageParser.Package pkg = mPackages.valueAt(i); 18571 PackageSetting ps = (PackageSetting) pkg.mExtras; 18572 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18573 } 18574 } 18575 18576 private void resetNetworkPolicies(int userId) { 18577 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18578 } 18579 18580 /** 18581 * Reverts user permission state changes (permissions and flags). 18582 * 18583 * @param ps The package for which to reset. 18584 * @param userId The device user for which to do a reset. 18585 */ 18586 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18587 final PackageSetting ps, final int userId) { 18588 if (ps.pkg == null) { 18589 return; 18590 } 18591 18592 // These are flags that can change base on user actions. 18593 final int userSettableMask = FLAG_PERMISSION_USER_SET 18594 | FLAG_PERMISSION_USER_FIXED 18595 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18596 | FLAG_PERMISSION_REVIEW_REQUIRED; 18597 18598 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18599 | FLAG_PERMISSION_POLICY_FIXED; 18600 18601 boolean writeInstallPermissions = false; 18602 boolean writeRuntimePermissions = false; 18603 18604 final int permissionCount = ps.pkg.requestedPermissions.size(); 18605 for (int i = 0; i < permissionCount; i++) { 18606 String permission = ps.pkg.requestedPermissions.get(i); 18607 18608 BasePermission bp = mSettings.mPermissions.get(permission); 18609 if (bp == null) { 18610 continue; 18611 } 18612 18613 // If shared user we just reset the state to which only this app contributed. 18614 if (ps.sharedUser != null) { 18615 boolean used = false; 18616 final int packageCount = ps.sharedUser.packages.size(); 18617 for (int j = 0; j < packageCount; j++) { 18618 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18619 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18620 && pkg.pkg.requestedPermissions.contains(permission)) { 18621 used = true; 18622 break; 18623 } 18624 } 18625 if (used) { 18626 continue; 18627 } 18628 } 18629 18630 PermissionsState permissionsState = ps.getPermissionsState(); 18631 18632 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18633 18634 // Always clear the user settable flags. 18635 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18636 bp.name) != null; 18637 // If permission review is enabled and this is a legacy app, mark the 18638 // permission as requiring a review as this is the initial state. 18639 int flags = 0; 18640 if (mPermissionReviewRequired 18641 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18642 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18643 } 18644 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18645 if (hasInstallState) { 18646 writeInstallPermissions = true; 18647 } else { 18648 writeRuntimePermissions = true; 18649 } 18650 } 18651 18652 // Below is only runtime permission handling. 18653 if (!bp.isRuntime()) { 18654 continue; 18655 } 18656 18657 // Never clobber system or policy. 18658 if ((oldFlags & policyOrSystemFlags) != 0) { 18659 continue; 18660 } 18661 18662 // If this permission was granted by default, make sure it is. 18663 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18664 if (permissionsState.grantRuntimePermission(bp, userId) 18665 != PERMISSION_OPERATION_FAILURE) { 18666 writeRuntimePermissions = true; 18667 } 18668 // If permission review is enabled the permissions for a legacy apps 18669 // are represented as constantly granted runtime ones, so don't revoke. 18670 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18671 // Otherwise, reset the permission. 18672 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18673 switch (revokeResult) { 18674 case PERMISSION_OPERATION_SUCCESS: 18675 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18676 writeRuntimePermissions = true; 18677 final int appId = ps.appId; 18678 mHandler.post(new Runnable() { 18679 @Override 18680 public void run() { 18681 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18682 } 18683 }); 18684 } break; 18685 } 18686 } 18687 } 18688 18689 // Synchronously write as we are taking permissions away. 18690 if (writeRuntimePermissions) { 18691 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18692 } 18693 18694 // Synchronously write as we are taking permissions away. 18695 if (writeInstallPermissions) { 18696 mSettings.writeLPr(); 18697 } 18698 } 18699 18700 /** 18701 * Remove entries from the keystore daemon. Will only remove it if the 18702 * {@code appId} is valid. 18703 */ 18704 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18705 if (appId < 0) { 18706 return; 18707 } 18708 18709 final KeyStore keyStore = KeyStore.getInstance(); 18710 if (keyStore != null) { 18711 if (userId == UserHandle.USER_ALL) { 18712 for (final int individual : sUserManager.getUserIds()) { 18713 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18714 } 18715 } else { 18716 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18717 } 18718 } else { 18719 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18720 } 18721 } 18722 18723 @Override 18724 public void deleteApplicationCacheFiles(final String packageName, 18725 final IPackageDataObserver observer) { 18726 final int userId = UserHandle.getCallingUserId(); 18727 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18728 } 18729 18730 @Override 18731 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18732 final IPackageDataObserver observer) { 18733 mContext.enforceCallingOrSelfPermission( 18734 android.Manifest.permission.DELETE_CACHE_FILES, null); 18735 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18736 /* requireFullPermission= */ true, /* checkShell= */ false, 18737 "delete application cache files"); 18738 18739 final PackageParser.Package pkg; 18740 synchronized (mPackages) { 18741 pkg = mPackages.get(packageName); 18742 } 18743 18744 // Queue up an async operation since the package deletion may take a little while. 18745 mHandler.post(new Runnable() { 18746 public void run() { 18747 synchronized (mInstallLock) { 18748 final int flags = StorageManager.FLAG_STORAGE_DE 18749 | StorageManager.FLAG_STORAGE_CE; 18750 // We're only clearing cache files, so we don't care if the 18751 // app is unfrozen and still able to run 18752 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18753 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18754 } 18755 clearExternalStorageDataSync(packageName, userId, false); 18756 if (observer != null) { 18757 try { 18758 observer.onRemoveCompleted(packageName, true); 18759 } catch (RemoteException e) { 18760 Log.i(TAG, "Observer no longer exists."); 18761 } 18762 } 18763 } 18764 }); 18765 } 18766 18767 @Override 18768 public void getPackageSizeInfo(final String packageName, int userHandle, 18769 final IPackageStatsObserver observer) { 18770 throw new UnsupportedOperationException( 18771 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18772 } 18773 18774 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18775 final PackageSetting ps; 18776 synchronized (mPackages) { 18777 ps = mSettings.mPackages.get(packageName); 18778 if (ps == null) { 18779 Slog.w(TAG, "Failed to find settings for " + packageName); 18780 return false; 18781 } 18782 } 18783 18784 final String[] packageNames = { packageName }; 18785 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18786 final String[] codePaths = { ps.codePathString }; 18787 18788 try { 18789 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18790 ps.appId, ceDataInodes, codePaths, stats); 18791 18792 // For now, ignore code size of packages on system partition 18793 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18794 stats.codeSize = 0; 18795 } 18796 18797 // External clients expect these to be tracked separately 18798 stats.dataSize -= stats.cacheSize; 18799 18800 } catch (InstallerException e) { 18801 Slog.w(TAG, String.valueOf(e)); 18802 return false; 18803 } 18804 18805 return true; 18806 } 18807 18808 private int getUidTargetSdkVersionLockedLPr(int uid) { 18809 Object obj = mSettings.getUserIdLPr(uid); 18810 if (obj instanceof SharedUserSetting) { 18811 final SharedUserSetting sus = (SharedUserSetting) obj; 18812 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18813 final Iterator<PackageSetting> it = sus.packages.iterator(); 18814 while (it.hasNext()) { 18815 final PackageSetting ps = it.next(); 18816 if (ps.pkg != null) { 18817 int v = ps.pkg.applicationInfo.targetSdkVersion; 18818 if (v < vers) vers = v; 18819 } 18820 } 18821 return vers; 18822 } else if (obj instanceof PackageSetting) { 18823 final PackageSetting ps = (PackageSetting) obj; 18824 if (ps.pkg != null) { 18825 return ps.pkg.applicationInfo.targetSdkVersion; 18826 } 18827 } 18828 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18829 } 18830 18831 @Override 18832 public void addPreferredActivity(IntentFilter filter, int match, 18833 ComponentName[] set, ComponentName activity, int userId) { 18834 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18835 "Adding preferred"); 18836 } 18837 18838 private void addPreferredActivityInternal(IntentFilter filter, int match, 18839 ComponentName[] set, ComponentName activity, boolean always, int userId, 18840 String opname) { 18841 // writer 18842 int callingUid = Binder.getCallingUid(); 18843 enforceCrossUserPermission(callingUid, userId, 18844 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18845 if (filter.countActions() == 0) { 18846 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18847 return; 18848 } 18849 synchronized (mPackages) { 18850 if (mContext.checkCallingOrSelfPermission( 18851 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18852 != PackageManager.PERMISSION_GRANTED) { 18853 if (getUidTargetSdkVersionLockedLPr(callingUid) 18854 < Build.VERSION_CODES.FROYO) { 18855 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18856 + callingUid); 18857 return; 18858 } 18859 mContext.enforceCallingOrSelfPermission( 18860 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18861 } 18862 18863 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18864 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18865 + userId + ":"); 18866 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18867 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18868 scheduleWritePackageRestrictionsLocked(userId); 18869 postPreferredActivityChangedBroadcast(userId); 18870 } 18871 } 18872 18873 private void postPreferredActivityChangedBroadcast(int userId) { 18874 mHandler.post(() -> { 18875 final IActivityManager am = ActivityManager.getService(); 18876 if (am == null) { 18877 return; 18878 } 18879 18880 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18881 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18882 try { 18883 am.broadcastIntent(null, intent, null, null, 18884 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18885 null, false, false, userId); 18886 } catch (RemoteException e) { 18887 } 18888 }); 18889 } 18890 18891 @Override 18892 public void replacePreferredActivity(IntentFilter filter, int match, 18893 ComponentName[] set, ComponentName activity, int userId) { 18894 if (filter.countActions() != 1) { 18895 throw new IllegalArgumentException( 18896 "replacePreferredActivity expects filter to have only 1 action."); 18897 } 18898 if (filter.countDataAuthorities() != 0 18899 || filter.countDataPaths() != 0 18900 || filter.countDataSchemes() > 1 18901 || filter.countDataTypes() != 0) { 18902 throw new IllegalArgumentException( 18903 "replacePreferredActivity expects filter to have no data authorities, " + 18904 "paths, or types; and at most one scheme."); 18905 } 18906 18907 final int callingUid = Binder.getCallingUid(); 18908 enforceCrossUserPermission(callingUid, userId, 18909 true /* requireFullPermission */, false /* checkShell */, 18910 "replace preferred activity"); 18911 synchronized (mPackages) { 18912 if (mContext.checkCallingOrSelfPermission( 18913 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18914 != PackageManager.PERMISSION_GRANTED) { 18915 if (getUidTargetSdkVersionLockedLPr(callingUid) 18916 < Build.VERSION_CODES.FROYO) { 18917 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18918 + Binder.getCallingUid()); 18919 return; 18920 } 18921 mContext.enforceCallingOrSelfPermission( 18922 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18923 } 18924 18925 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18926 if (pir != null) { 18927 // Get all of the existing entries that exactly match this filter. 18928 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18929 if (existing != null && existing.size() == 1) { 18930 PreferredActivity cur = existing.get(0); 18931 if (DEBUG_PREFERRED) { 18932 Slog.i(TAG, "Checking replace of preferred:"); 18933 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18934 if (!cur.mPref.mAlways) { 18935 Slog.i(TAG, " -- CUR; not mAlways!"); 18936 } else { 18937 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18938 Slog.i(TAG, " -- CUR: mSet=" 18939 + Arrays.toString(cur.mPref.mSetComponents)); 18940 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18941 Slog.i(TAG, " -- NEW: mMatch=" 18942 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18943 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18944 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18945 } 18946 } 18947 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18948 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18949 && cur.mPref.sameSet(set)) { 18950 // Setting the preferred activity to what it happens to be already 18951 if (DEBUG_PREFERRED) { 18952 Slog.i(TAG, "Replacing with same preferred activity " 18953 + cur.mPref.mShortComponent + " for user " 18954 + userId + ":"); 18955 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18956 } 18957 return; 18958 } 18959 } 18960 18961 if (existing != null) { 18962 if (DEBUG_PREFERRED) { 18963 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18964 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18965 } 18966 for (int i = 0; i < existing.size(); i++) { 18967 PreferredActivity pa = existing.get(i); 18968 if (DEBUG_PREFERRED) { 18969 Slog.i(TAG, "Removing existing preferred activity " 18970 + pa.mPref.mComponent + ":"); 18971 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18972 } 18973 pir.removeFilter(pa); 18974 } 18975 } 18976 } 18977 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18978 "Replacing preferred"); 18979 } 18980 } 18981 18982 @Override 18983 public void clearPackagePreferredActivities(String packageName) { 18984 final int uid = Binder.getCallingUid(); 18985 // writer 18986 synchronized (mPackages) { 18987 PackageParser.Package pkg = mPackages.get(packageName); 18988 if (pkg == null || pkg.applicationInfo.uid != uid) { 18989 if (mContext.checkCallingOrSelfPermission( 18990 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18991 != PackageManager.PERMISSION_GRANTED) { 18992 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18993 < Build.VERSION_CODES.FROYO) { 18994 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18995 + Binder.getCallingUid()); 18996 return; 18997 } 18998 mContext.enforceCallingOrSelfPermission( 18999 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19000 } 19001 } 19002 19003 int user = UserHandle.getCallingUserId(); 19004 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19005 scheduleWritePackageRestrictionsLocked(user); 19006 } 19007 } 19008 } 19009 19010 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19011 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19012 ArrayList<PreferredActivity> removed = null; 19013 boolean changed = false; 19014 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19015 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19016 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19017 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19018 continue; 19019 } 19020 Iterator<PreferredActivity> it = pir.filterIterator(); 19021 while (it.hasNext()) { 19022 PreferredActivity pa = it.next(); 19023 // Mark entry for removal only if it matches the package name 19024 // and the entry is of type "always". 19025 if (packageName == null || 19026 (pa.mPref.mComponent.getPackageName().equals(packageName) 19027 && pa.mPref.mAlways)) { 19028 if (removed == null) { 19029 removed = new ArrayList<PreferredActivity>(); 19030 } 19031 removed.add(pa); 19032 } 19033 } 19034 if (removed != null) { 19035 for (int j=0; j<removed.size(); j++) { 19036 PreferredActivity pa = removed.get(j); 19037 pir.removeFilter(pa); 19038 } 19039 changed = true; 19040 } 19041 } 19042 if (changed) { 19043 postPreferredActivityChangedBroadcast(userId); 19044 } 19045 return changed; 19046 } 19047 19048 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19049 private void clearIntentFilterVerificationsLPw(int userId) { 19050 final int packageCount = mPackages.size(); 19051 for (int i = 0; i < packageCount; i++) { 19052 PackageParser.Package pkg = mPackages.valueAt(i); 19053 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19054 } 19055 } 19056 19057 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19058 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19059 if (userId == UserHandle.USER_ALL) { 19060 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19061 sUserManager.getUserIds())) { 19062 for (int oneUserId : sUserManager.getUserIds()) { 19063 scheduleWritePackageRestrictionsLocked(oneUserId); 19064 } 19065 } 19066 } else { 19067 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19068 scheduleWritePackageRestrictionsLocked(userId); 19069 } 19070 } 19071 } 19072 19073 void clearDefaultBrowserIfNeeded(String packageName) { 19074 for (int oneUserId : sUserManager.getUserIds()) { 19075 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19076 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19077 if (packageName.equals(defaultBrowserPackageName)) { 19078 setDefaultBrowserPackageName(null, oneUserId); 19079 } 19080 } 19081 } 19082 19083 @Override 19084 public void resetApplicationPreferences(int userId) { 19085 mContext.enforceCallingOrSelfPermission( 19086 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19087 final long identity = Binder.clearCallingIdentity(); 19088 // writer 19089 try { 19090 synchronized (mPackages) { 19091 clearPackagePreferredActivitiesLPw(null, userId); 19092 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19093 // TODO: We have to reset the default SMS and Phone. This requires 19094 // significant refactoring to keep all default apps in the package 19095 // manager (cleaner but more work) or have the services provide 19096 // callbacks to the package manager to request a default app reset. 19097 applyFactoryDefaultBrowserLPw(userId); 19098 clearIntentFilterVerificationsLPw(userId); 19099 primeDomainVerificationsLPw(userId); 19100 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19101 scheduleWritePackageRestrictionsLocked(userId); 19102 } 19103 resetNetworkPolicies(userId); 19104 } finally { 19105 Binder.restoreCallingIdentity(identity); 19106 } 19107 } 19108 19109 @Override 19110 public int getPreferredActivities(List<IntentFilter> outFilters, 19111 List<ComponentName> outActivities, String packageName) { 19112 19113 int num = 0; 19114 final int userId = UserHandle.getCallingUserId(); 19115 // reader 19116 synchronized (mPackages) { 19117 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19118 if (pir != null) { 19119 final Iterator<PreferredActivity> it = pir.filterIterator(); 19120 while (it.hasNext()) { 19121 final PreferredActivity pa = it.next(); 19122 if (packageName == null 19123 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19124 && pa.mPref.mAlways)) { 19125 if (outFilters != null) { 19126 outFilters.add(new IntentFilter(pa)); 19127 } 19128 if (outActivities != null) { 19129 outActivities.add(pa.mPref.mComponent); 19130 } 19131 } 19132 } 19133 } 19134 } 19135 19136 return num; 19137 } 19138 19139 @Override 19140 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19141 int userId) { 19142 int callingUid = Binder.getCallingUid(); 19143 if (callingUid != Process.SYSTEM_UID) { 19144 throw new SecurityException( 19145 "addPersistentPreferredActivity can only be run by the system"); 19146 } 19147 if (filter.countActions() == 0) { 19148 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19149 return; 19150 } 19151 synchronized (mPackages) { 19152 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19153 ":"); 19154 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19155 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19156 new PersistentPreferredActivity(filter, activity)); 19157 scheduleWritePackageRestrictionsLocked(userId); 19158 postPreferredActivityChangedBroadcast(userId); 19159 } 19160 } 19161 19162 @Override 19163 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19164 int callingUid = Binder.getCallingUid(); 19165 if (callingUid != Process.SYSTEM_UID) { 19166 throw new SecurityException( 19167 "clearPackagePersistentPreferredActivities can only be run by the system"); 19168 } 19169 ArrayList<PersistentPreferredActivity> removed = null; 19170 boolean changed = false; 19171 synchronized (mPackages) { 19172 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19173 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19174 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19175 .valueAt(i); 19176 if (userId != thisUserId) { 19177 continue; 19178 } 19179 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19180 while (it.hasNext()) { 19181 PersistentPreferredActivity ppa = it.next(); 19182 // Mark entry for removal only if it matches the package name. 19183 if (ppa.mComponent.getPackageName().equals(packageName)) { 19184 if (removed == null) { 19185 removed = new ArrayList<PersistentPreferredActivity>(); 19186 } 19187 removed.add(ppa); 19188 } 19189 } 19190 if (removed != null) { 19191 for (int j=0; j<removed.size(); j++) { 19192 PersistentPreferredActivity ppa = removed.get(j); 19193 ppir.removeFilter(ppa); 19194 } 19195 changed = true; 19196 } 19197 } 19198 19199 if (changed) { 19200 scheduleWritePackageRestrictionsLocked(userId); 19201 postPreferredActivityChangedBroadcast(userId); 19202 } 19203 } 19204 } 19205 19206 /** 19207 * Common machinery for picking apart a restored XML blob and passing 19208 * it to a caller-supplied functor to be applied to the running system. 19209 */ 19210 private void restoreFromXml(XmlPullParser parser, int userId, 19211 String expectedStartTag, BlobXmlRestorer functor) 19212 throws IOException, XmlPullParserException { 19213 int type; 19214 while ((type = parser.next()) != XmlPullParser.START_TAG 19215 && type != XmlPullParser.END_DOCUMENT) { 19216 } 19217 if (type != XmlPullParser.START_TAG) { 19218 // oops didn't find a start tag?! 19219 if (DEBUG_BACKUP) { 19220 Slog.e(TAG, "Didn't find start tag during restore"); 19221 } 19222 return; 19223 } 19224Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19225 // this is supposed to be TAG_PREFERRED_BACKUP 19226 if (!expectedStartTag.equals(parser.getName())) { 19227 if (DEBUG_BACKUP) { 19228 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19229 } 19230 return; 19231 } 19232 19233 // skip interfering stuff, then we're aligned with the backing implementation 19234 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19235Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19236 functor.apply(parser, userId); 19237 } 19238 19239 private interface BlobXmlRestorer { 19240 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19241 } 19242 19243 /** 19244 * Non-Binder method, support for the backup/restore mechanism: write the 19245 * full set of preferred activities in its canonical XML format. Returns the 19246 * XML output as a byte array, or null if there is none. 19247 */ 19248 @Override 19249 public byte[] getPreferredActivityBackup(int userId) { 19250 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19251 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19252 } 19253 19254 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19255 try { 19256 final XmlSerializer serializer = new FastXmlSerializer(); 19257 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19258 serializer.startDocument(null, true); 19259 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19260 19261 synchronized (mPackages) { 19262 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19263 } 19264 19265 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19266 serializer.endDocument(); 19267 serializer.flush(); 19268 } catch (Exception e) { 19269 if (DEBUG_BACKUP) { 19270 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19271 } 19272 return null; 19273 } 19274 19275 return dataStream.toByteArray(); 19276 } 19277 19278 @Override 19279 public void restorePreferredActivities(byte[] backup, int userId) { 19280 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19281 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19282 } 19283 19284 try { 19285 final XmlPullParser parser = Xml.newPullParser(); 19286 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19287 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19288 new BlobXmlRestorer() { 19289 @Override 19290 public void apply(XmlPullParser parser, int userId) 19291 throws XmlPullParserException, IOException { 19292 synchronized (mPackages) { 19293 mSettings.readPreferredActivitiesLPw(parser, userId); 19294 } 19295 } 19296 } ); 19297 } catch (Exception e) { 19298 if (DEBUG_BACKUP) { 19299 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19300 } 19301 } 19302 } 19303 19304 /** 19305 * Non-Binder method, support for the backup/restore mechanism: write the 19306 * default browser (etc) settings in its canonical XML format. Returns the default 19307 * browser XML representation as a byte array, or null if there is none. 19308 */ 19309 @Override 19310 public byte[] getDefaultAppsBackup(int userId) { 19311 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19312 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19313 } 19314 19315 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19316 try { 19317 final XmlSerializer serializer = new FastXmlSerializer(); 19318 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19319 serializer.startDocument(null, true); 19320 serializer.startTag(null, TAG_DEFAULT_APPS); 19321 19322 synchronized (mPackages) { 19323 mSettings.writeDefaultAppsLPr(serializer, userId); 19324 } 19325 19326 serializer.endTag(null, TAG_DEFAULT_APPS); 19327 serializer.endDocument(); 19328 serializer.flush(); 19329 } catch (Exception e) { 19330 if (DEBUG_BACKUP) { 19331 Slog.e(TAG, "Unable to write default apps for backup", e); 19332 } 19333 return null; 19334 } 19335 19336 return dataStream.toByteArray(); 19337 } 19338 19339 @Override 19340 public void restoreDefaultApps(byte[] backup, int userId) { 19341 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19342 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19343 } 19344 19345 try { 19346 final XmlPullParser parser = Xml.newPullParser(); 19347 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19348 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19349 new BlobXmlRestorer() { 19350 @Override 19351 public void apply(XmlPullParser parser, int userId) 19352 throws XmlPullParserException, IOException { 19353 synchronized (mPackages) { 19354 mSettings.readDefaultAppsLPw(parser, userId); 19355 } 19356 } 19357 } ); 19358 } catch (Exception e) { 19359 if (DEBUG_BACKUP) { 19360 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19361 } 19362 } 19363 } 19364 19365 @Override 19366 public byte[] getIntentFilterVerificationBackup(int userId) { 19367 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19368 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19369 } 19370 19371 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19372 try { 19373 final XmlSerializer serializer = new FastXmlSerializer(); 19374 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19375 serializer.startDocument(null, true); 19376 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19377 19378 synchronized (mPackages) { 19379 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19380 } 19381 19382 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19383 serializer.endDocument(); 19384 serializer.flush(); 19385 } catch (Exception e) { 19386 if (DEBUG_BACKUP) { 19387 Slog.e(TAG, "Unable to write default apps for backup", e); 19388 } 19389 return null; 19390 } 19391 19392 return dataStream.toByteArray(); 19393 } 19394 19395 @Override 19396 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19397 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19398 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19399 } 19400 19401 try { 19402 final XmlPullParser parser = Xml.newPullParser(); 19403 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19404 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19405 new BlobXmlRestorer() { 19406 @Override 19407 public void apply(XmlPullParser parser, int userId) 19408 throws XmlPullParserException, IOException { 19409 synchronized (mPackages) { 19410 mSettings.readAllDomainVerificationsLPr(parser, userId); 19411 mSettings.writeLPr(); 19412 } 19413 } 19414 } ); 19415 } catch (Exception e) { 19416 if (DEBUG_BACKUP) { 19417 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19418 } 19419 } 19420 } 19421 19422 @Override 19423 public byte[] getPermissionGrantBackup(int userId) { 19424 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19425 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19426 } 19427 19428 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19429 try { 19430 final XmlSerializer serializer = new FastXmlSerializer(); 19431 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19432 serializer.startDocument(null, true); 19433 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19434 19435 synchronized (mPackages) { 19436 serializeRuntimePermissionGrantsLPr(serializer, userId); 19437 } 19438 19439 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19440 serializer.endDocument(); 19441 serializer.flush(); 19442 } catch (Exception e) { 19443 if (DEBUG_BACKUP) { 19444 Slog.e(TAG, "Unable to write default apps for backup", e); 19445 } 19446 return null; 19447 } 19448 19449 return dataStream.toByteArray(); 19450 } 19451 19452 @Override 19453 public void restorePermissionGrants(byte[] backup, int userId) { 19454 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19455 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19456 } 19457 19458 try { 19459 final XmlPullParser parser = Xml.newPullParser(); 19460 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19461 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19462 new BlobXmlRestorer() { 19463 @Override 19464 public void apply(XmlPullParser parser, int userId) 19465 throws XmlPullParserException, IOException { 19466 synchronized (mPackages) { 19467 processRestoredPermissionGrantsLPr(parser, userId); 19468 } 19469 } 19470 } ); 19471 } catch (Exception e) { 19472 if (DEBUG_BACKUP) { 19473 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19474 } 19475 } 19476 } 19477 19478 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19479 throws IOException { 19480 serializer.startTag(null, TAG_ALL_GRANTS); 19481 19482 final int N = mSettings.mPackages.size(); 19483 for (int i = 0; i < N; i++) { 19484 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19485 boolean pkgGrantsKnown = false; 19486 19487 PermissionsState packagePerms = ps.getPermissionsState(); 19488 19489 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19490 final int grantFlags = state.getFlags(); 19491 // only look at grants that are not system/policy fixed 19492 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19493 final boolean isGranted = state.isGranted(); 19494 // And only back up the user-twiddled state bits 19495 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19496 final String packageName = mSettings.mPackages.keyAt(i); 19497 if (!pkgGrantsKnown) { 19498 serializer.startTag(null, TAG_GRANT); 19499 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19500 pkgGrantsKnown = true; 19501 } 19502 19503 final boolean userSet = 19504 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19505 final boolean userFixed = 19506 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19507 final boolean revoke = 19508 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19509 19510 serializer.startTag(null, TAG_PERMISSION); 19511 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19512 if (isGranted) { 19513 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19514 } 19515 if (userSet) { 19516 serializer.attribute(null, ATTR_USER_SET, "true"); 19517 } 19518 if (userFixed) { 19519 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19520 } 19521 if (revoke) { 19522 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19523 } 19524 serializer.endTag(null, TAG_PERMISSION); 19525 } 19526 } 19527 } 19528 19529 if (pkgGrantsKnown) { 19530 serializer.endTag(null, TAG_GRANT); 19531 } 19532 } 19533 19534 serializer.endTag(null, TAG_ALL_GRANTS); 19535 } 19536 19537 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19538 throws XmlPullParserException, IOException { 19539 String pkgName = null; 19540 int outerDepth = parser.getDepth(); 19541 int type; 19542 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19543 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19544 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19545 continue; 19546 } 19547 19548 final String tagName = parser.getName(); 19549 if (tagName.equals(TAG_GRANT)) { 19550 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19551 if (DEBUG_BACKUP) { 19552 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19553 } 19554 } else if (tagName.equals(TAG_PERMISSION)) { 19555 19556 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19557 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19558 19559 int newFlagSet = 0; 19560 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19561 newFlagSet |= FLAG_PERMISSION_USER_SET; 19562 } 19563 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19564 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19565 } 19566 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19567 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19568 } 19569 if (DEBUG_BACKUP) { 19570 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19571 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19572 } 19573 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19574 if (ps != null) { 19575 // Already installed so we apply the grant immediately 19576 if (DEBUG_BACKUP) { 19577 Slog.v(TAG, " + already installed; applying"); 19578 } 19579 PermissionsState perms = ps.getPermissionsState(); 19580 BasePermission bp = mSettings.mPermissions.get(permName); 19581 if (bp != null) { 19582 if (isGranted) { 19583 perms.grantRuntimePermission(bp, userId); 19584 } 19585 if (newFlagSet != 0) { 19586 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19587 } 19588 } 19589 } else { 19590 // Need to wait for post-restore install to apply the grant 19591 if (DEBUG_BACKUP) { 19592 Slog.v(TAG, " - not yet installed; saving for later"); 19593 } 19594 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19595 isGranted, newFlagSet, userId); 19596 } 19597 } else { 19598 PackageManagerService.reportSettingsProblem(Log.WARN, 19599 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19600 XmlUtils.skipCurrentTag(parser); 19601 } 19602 } 19603 19604 scheduleWriteSettingsLocked(); 19605 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19606 } 19607 19608 @Override 19609 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19610 int sourceUserId, int targetUserId, int flags) { 19611 mContext.enforceCallingOrSelfPermission( 19612 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19613 int callingUid = Binder.getCallingUid(); 19614 enforceOwnerRights(ownerPackage, callingUid); 19615 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19616 if (intentFilter.countActions() == 0) { 19617 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19618 return; 19619 } 19620 synchronized (mPackages) { 19621 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19622 ownerPackage, targetUserId, flags); 19623 CrossProfileIntentResolver resolver = 19624 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19625 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19626 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19627 if (existing != null) { 19628 int size = existing.size(); 19629 for (int i = 0; i < size; i++) { 19630 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19631 return; 19632 } 19633 } 19634 } 19635 resolver.addFilter(newFilter); 19636 scheduleWritePackageRestrictionsLocked(sourceUserId); 19637 } 19638 } 19639 19640 @Override 19641 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19642 mContext.enforceCallingOrSelfPermission( 19643 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19644 int callingUid = Binder.getCallingUid(); 19645 enforceOwnerRights(ownerPackage, callingUid); 19646 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19647 synchronized (mPackages) { 19648 CrossProfileIntentResolver resolver = 19649 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19650 ArraySet<CrossProfileIntentFilter> set = 19651 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19652 for (CrossProfileIntentFilter filter : set) { 19653 if (filter.getOwnerPackage().equals(ownerPackage)) { 19654 resolver.removeFilter(filter); 19655 } 19656 } 19657 scheduleWritePackageRestrictionsLocked(sourceUserId); 19658 } 19659 } 19660 19661 // Enforcing that callingUid is owning pkg on userId 19662 private void enforceOwnerRights(String pkg, int callingUid) { 19663 // The system owns everything. 19664 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19665 return; 19666 } 19667 int callingUserId = UserHandle.getUserId(callingUid); 19668 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19669 if (pi == null) { 19670 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19671 + callingUserId); 19672 } 19673 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19674 throw new SecurityException("Calling uid " + callingUid 19675 + " does not own package " + pkg); 19676 } 19677 } 19678 19679 @Override 19680 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19681 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19682 } 19683 19684 /** 19685 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19686 * then reports the most likely home activity or null if there are more than one. 19687 */ 19688 public ComponentName getDefaultHomeActivity(int userId) { 19689 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19690 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19691 if (cn != null) { 19692 return cn; 19693 } 19694 19695 // Find the launcher with the highest priority and return that component if there are no 19696 // other home activity with the same priority. 19697 int lastPriority = Integer.MIN_VALUE; 19698 ComponentName lastComponent = null; 19699 final int size = allHomeCandidates.size(); 19700 for (int i = 0; i < size; i++) { 19701 final ResolveInfo ri = allHomeCandidates.get(i); 19702 if (ri.priority > lastPriority) { 19703 lastComponent = ri.activityInfo.getComponentName(); 19704 lastPriority = ri.priority; 19705 } else if (ri.priority == lastPriority) { 19706 // Two components found with same priority. 19707 lastComponent = null; 19708 } 19709 } 19710 return lastComponent; 19711 } 19712 19713 private Intent getHomeIntent() { 19714 Intent intent = new Intent(Intent.ACTION_MAIN); 19715 intent.addCategory(Intent.CATEGORY_HOME); 19716 intent.addCategory(Intent.CATEGORY_DEFAULT); 19717 return intent; 19718 } 19719 19720 private IntentFilter getHomeFilter() { 19721 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19722 filter.addCategory(Intent.CATEGORY_HOME); 19723 filter.addCategory(Intent.CATEGORY_DEFAULT); 19724 return filter; 19725 } 19726 19727 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19728 int userId) { 19729 Intent intent = getHomeIntent(); 19730 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19731 PackageManager.GET_META_DATA, userId); 19732 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19733 true, false, false, userId); 19734 19735 allHomeCandidates.clear(); 19736 if (list != null) { 19737 for (ResolveInfo ri : list) { 19738 allHomeCandidates.add(ri); 19739 } 19740 } 19741 return (preferred == null || preferred.activityInfo == null) 19742 ? null 19743 : new ComponentName(preferred.activityInfo.packageName, 19744 preferred.activityInfo.name); 19745 } 19746 19747 @Override 19748 public void setHomeActivity(ComponentName comp, int userId) { 19749 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19750 getHomeActivitiesAsUser(homeActivities, userId); 19751 19752 boolean found = false; 19753 19754 final int size = homeActivities.size(); 19755 final ComponentName[] set = new ComponentName[size]; 19756 for (int i = 0; i < size; i++) { 19757 final ResolveInfo candidate = homeActivities.get(i); 19758 final ActivityInfo info = candidate.activityInfo; 19759 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19760 set[i] = activityName; 19761 if (!found && activityName.equals(comp)) { 19762 found = true; 19763 } 19764 } 19765 if (!found) { 19766 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19767 + userId); 19768 } 19769 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19770 set, comp, userId); 19771 } 19772 19773 private @Nullable String getSetupWizardPackageName() { 19774 final Intent intent = new Intent(Intent.ACTION_MAIN); 19775 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19776 19777 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19778 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19779 | MATCH_DISABLED_COMPONENTS, 19780 UserHandle.myUserId()); 19781 if (matches.size() == 1) { 19782 return matches.get(0).getComponentInfo().packageName; 19783 } else { 19784 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19785 + ": matches=" + matches); 19786 return null; 19787 } 19788 } 19789 19790 private @Nullable String getStorageManagerPackageName() { 19791 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19792 19793 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19794 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19795 | MATCH_DISABLED_COMPONENTS, 19796 UserHandle.myUserId()); 19797 if (matches.size() == 1) { 19798 return matches.get(0).getComponentInfo().packageName; 19799 } else { 19800 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19801 + matches.size() + ": matches=" + matches); 19802 return null; 19803 } 19804 } 19805 19806 @Override 19807 public void setApplicationEnabledSetting(String appPackageName, 19808 int newState, int flags, int userId, String callingPackage) { 19809 if (!sUserManager.exists(userId)) return; 19810 if (callingPackage == null) { 19811 callingPackage = Integer.toString(Binder.getCallingUid()); 19812 } 19813 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19814 } 19815 19816 @Override 19817 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19818 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19819 synchronized (mPackages) { 19820 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19821 if (pkgSetting != null) { 19822 pkgSetting.setUpdateAvailable(updateAvailable); 19823 } 19824 } 19825 } 19826 19827 @Override 19828 public void setComponentEnabledSetting(ComponentName componentName, 19829 int newState, int flags, int userId) { 19830 if (!sUserManager.exists(userId)) return; 19831 setEnabledSetting(componentName.getPackageName(), 19832 componentName.getClassName(), newState, flags, userId, null); 19833 } 19834 19835 private void setEnabledSetting(final String packageName, String className, int newState, 19836 final int flags, int userId, String callingPackage) { 19837 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19838 || newState == COMPONENT_ENABLED_STATE_ENABLED 19839 || newState == COMPONENT_ENABLED_STATE_DISABLED 19840 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19841 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19842 throw new IllegalArgumentException("Invalid new component state: " 19843 + newState); 19844 } 19845 PackageSetting pkgSetting; 19846 final int uid = Binder.getCallingUid(); 19847 final int permission; 19848 if (uid == Process.SYSTEM_UID) { 19849 permission = PackageManager.PERMISSION_GRANTED; 19850 } else { 19851 permission = mContext.checkCallingOrSelfPermission( 19852 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19853 } 19854 enforceCrossUserPermission(uid, userId, 19855 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19856 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19857 boolean sendNow = false; 19858 boolean isApp = (className == null); 19859 String componentName = isApp ? packageName : className; 19860 int packageUid = -1; 19861 ArrayList<String> components; 19862 19863 // writer 19864 synchronized (mPackages) { 19865 pkgSetting = mSettings.mPackages.get(packageName); 19866 if (pkgSetting == null) { 19867 if (className == null) { 19868 throw new IllegalArgumentException("Unknown package: " + packageName); 19869 } 19870 throw new IllegalArgumentException( 19871 "Unknown component: " + packageName + "/" + className); 19872 } 19873 } 19874 19875 // Limit who can change which apps 19876 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19877 // Don't allow apps that don't have permission to modify other apps 19878 if (!allowedByPermission) { 19879 throw new SecurityException( 19880 "Permission Denial: attempt to change component state from pid=" 19881 + Binder.getCallingPid() 19882 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19883 } 19884 // Don't allow changing protected packages. 19885 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19886 throw new SecurityException("Cannot disable a protected package: " + packageName); 19887 } 19888 } 19889 19890 synchronized (mPackages) { 19891 if (uid == Process.SHELL_UID 19892 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19893 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19894 // unless it is a test package. 19895 int oldState = pkgSetting.getEnabled(userId); 19896 if (className == null 19897 && 19898 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19899 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19900 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19901 && 19902 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19903 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19904 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19905 // ok 19906 } else { 19907 throw new SecurityException( 19908 "Shell cannot change component state for " + packageName + "/" 19909 + className + " to " + newState); 19910 } 19911 } 19912 if (className == null) { 19913 // We're dealing with an application/package level state change 19914 if (pkgSetting.getEnabled(userId) == newState) { 19915 // Nothing to do 19916 return; 19917 } 19918 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19919 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19920 // Don't care about who enables an app. 19921 callingPackage = null; 19922 } 19923 pkgSetting.setEnabled(newState, userId, callingPackage); 19924 // pkgSetting.pkg.mSetEnabled = newState; 19925 } else { 19926 // We're dealing with a component level state change 19927 // First, verify that this is a valid class name. 19928 PackageParser.Package pkg = pkgSetting.pkg; 19929 if (pkg == null || !pkg.hasComponentClassName(className)) { 19930 if (pkg != null && 19931 pkg.applicationInfo.targetSdkVersion >= 19932 Build.VERSION_CODES.JELLY_BEAN) { 19933 throw new IllegalArgumentException("Component class " + className 19934 + " does not exist in " + packageName); 19935 } else { 19936 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19937 + className + " does not exist in " + packageName); 19938 } 19939 } 19940 switch (newState) { 19941 case COMPONENT_ENABLED_STATE_ENABLED: 19942 if (!pkgSetting.enableComponentLPw(className, userId)) { 19943 return; 19944 } 19945 break; 19946 case COMPONENT_ENABLED_STATE_DISABLED: 19947 if (!pkgSetting.disableComponentLPw(className, userId)) { 19948 return; 19949 } 19950 break; 19951 case COMPONENT_ENABLED_STATE_DEFAULT: 19952 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19953 return; 19954 } 19955 break; 19956 default: 19957 Slog.e(TAG, "Invalid new component state: " + newState); 19958 return; 19959 } 19960 } 19961 scheduleWritePackageRestrictionsLocked(userId); 19962 updateSequenceNumberLP(packageName, new int[] { userId }); 19963 final long callingId = Binder.clearCallingIdentity(); 19964 try { 19965 updateInstantAppInstallerLocked(); 19966 } finally { 19967 Binder.restoreCallingIdentity(callingId); 19968 } 19969 components = mPendingBroadcasts.get(userId, packageName); 19970 final boolean newPackage = components == null; 19971 if (newPackage) { 19972 components = new ArrayList<String>(); 19973 } 19974 if (!components.contains(componentName)) { 19975 components.add(componentName); 19976 } 19977 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19978 sendNow = true; 19979 // Purge entry from pending broadcast list if another one exists already 19980 // since we are sending one right away. 19981 mPendingBroadcasts.remove(userId, packageName); 19982 } else { 19983 if (newPackage) { 19984 mPendingBroadcasts.put(userId, packageName, components); 19985 } 19986 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19987 // Schedule a message 19988 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19989 } 19990 } 19991 } 19992 19993 long callingId = Binder.clearCallingIdentity(); 19994 try { 19995 if (sendNow) { 19996 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19997 sendPackageChangedBroadcast(packageName, 19998 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19999 } 20000 } finally { 20001 Binder.restoreCallingIdentity(callingId); 20002 } 20003 } 20004 20005 @Override 20006 public void flushPackageRestrictionsAsUser(int userId) { 20007 if (!sUserManager.exists(userId)) { 20008 return; 20009 } 20010 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20011 false /* checkShell */, "flushPackageRestrictions"); 20012 synchronized (mPackages) { 20013 mSettings.writePackageRestrictionsLPr(userId); 20014 mDirtyUsers.remove(userId); 20015 if (mDirtyUsers.isEmpty()) { 20016 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20017 } 20018 } 20019 } 20020 20021 private void sendPackageChangedBroadcast(String packageName, 20022 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20023 if (DEBUG_INSTALL) 20024 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20025 + componentNames); 20026 Bundle extras = new Bundle(4); 20027 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20028 String nameList[] = new String[componentNames.size()]; 20029 componentNames.toArray(nameList); 20030 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20031 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20032 extras.putInt(Intent.EXTRA_UID, packageUid); 20033 // If this is not reporting a change of the overall package, then only send it 20034 // to registered receivers. We don't want to launch a swath of apps for every 20035 // little component state change. 20036 final int flags = !componentNames.contains(packageName) 20037 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20038 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20039 new int[] {UserHandle.getUserId(packageUid)}); 20040 } 20041 20042 @Override 20043 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20044 if (!sUserManager.exists(userId)) return; 20045 final int uid = Binder.getCallingUid(); 20046 final int permission = mContext.checkCallingOrSelfPermission( 20047 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20048 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20049 enforceCrossUserPermission(uid, userId, 20050 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20051 // writer 20052 synchronized (mPackages) { 20053 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20054 allowedByPermission, uid, userId)) { 20055 scheduleWritePackageRestrictionsLocked(userId); 20056 } 20057 } 20058 } 20059 20060 @Override 20061 public String getInstallerPackageName(String packageName) { 20062 // reader 20063 synchronized (mPackages) { 20064 return mSettings.getInstallerPackageNameLPr(packageName); 20065 } 20066 } 20067 20068 public boolean isOrphaned(String packageName) { 20069 // reader 20070 synchronized (mPackages) { 20071 return mSettings.isOrphaned(packageName); 20072 } 20073 } 20074 20075 @Override 20076 public int getApplicationEnabledSetting(String packageName, int userId) { 20077 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20078 int uid = Binder.getCallingUid(); 20079 enforceCrossUserPermission(uid, userId, 20080 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20081 // reader 20082 synchronized (mPackages) { 20083 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20084 } 20085 } 20086 20087 @Override 20088 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20089 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20090 int uid = Binder.getCallingUid(); 20091 enforceCrossUserPermission(uid, userId, 20092 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20093 // reader 20094 synchronized (mPackages) { 20095 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20096 } 20097 } 20098 20099 @Override 20100 public void enterSafeMode() { 20101 enforceSystemOrRoot("Only the system can request entering safe mode"); 20102 20103 if (!mSystemReady) { 20104 mSafeMode = true; 20105 } 20106 } 20107 20108 @Override 20109 public void systemReady() { 20110 mSystemReady = true; 20111 20112 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20113 // disabled after already being started. 20114 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20115 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20116 20117 // Read the compatibilty setting when the system is ready. 20118 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20119 mContext.getContentResolver(), 20120 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20121 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20122 if (DEBUG_SETTINGS) { 20123 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20124 } 20125 20126 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20127 20128 synchronized (mPackages) { 20129 // Verify that all of the preferred activity components actually 20130 // exist. It is possible for applications to be updated and at 20131 // that point remove a previously declared activity component that 20132 // had been set as a preferred activity. We try to clean this up 20133 // the next time we encounter that preferred activity, but it is 20134 // possible for the user flow to never be able to return to that 20135 // situation so here we do a sanity check to make sure we haven't 20136 // left any junk around. 20137 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20138 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20139 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20140 removed.clear(); 20141 for (PreferredActivity pa : pir.filterSet()) { 20142 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20143 removed.add(pa); 20144 } 20145 } 20146 if (removed.size() > 0) { 20147 for (int r=0; r<removed.size(); r++) { 20148 PreferredActivity pa = removed.get(r); 20149 Slog.w(TAG, "Removing dangling preferred activity: " 20150 + pa.mPref.mComponent); 20151 pir.removeFilter(pa); 20152 } 20153 mSettings.writePackageRestrictionsLPr( 20154 mSettings.mPreferredActivities.keyAt(i)); 20155 } 20156 } 20157 20158 for (int userId : UserManagerService.getInstance().getUserIds()) { 20159 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20160 grantPermissionsUserIds = ArrayUtils.appendInt( 20161 grantPermissionsUserIds, userId); 20162 } 20163 } 20164 } 20165 sUserManager.systemReady(); 20166 20167 // If we upgraded grant all default permissions before kicking off. 20168 for (int userId : grantPermissionsUserIds) { 20169 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20170 } 20171 20172 // If we did not grant default permissions, we preload from this the 20173 // default permission exceptions lazily to ensure we don't hit the 20174 // disk on a new user creation. 20175 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20176 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20177 } 20178 20179 // Kick off any messages waiting for system ready 20180 if (mPostSystemReadyMessages != null) { 20181 for (Message msg : mPostSystemReadyMessages) { 20182 msg.sendToTarget(); 20183 } 20184 mPostSystemReadyMessages = null; 20185 } 20186 20187 // Watch for external volumes that come and go over time 20188 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20189 storage.registerListener(mStorageListener); 20190 20191 mInstallerService.systemReady(); 20192 mPackageDexOptimizer.systemReady(); 20193 20194 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20195 StorageManagerInternal.class); 20196 StorageManagerInternal.addExternalStoragePolicy( 20197 new StorageManagerInternal.ExternalStorageMountPolicy() { 20198 @Override 20199 public int getMountMode(int uid, String packageName) { 20200 if (Process.isIsolated(uid)) { 20201 return Zygote.MOUNT_EXTERNAL_NONE; 20202 } 20203 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20204 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20205 } 20206 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20207 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20208 } 20209 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20210 return Zygote.MOUNT_EXTERNAL_READ; 20211 } 20212 return Zygote.MOUNT_EXTERNAL_WRITE; 20213 } 20214 20215 @Override 20216 public boolean hasExternalStorage(int uid, String packageName) { 20217 return true; 20218 } 20219 }); 20220 20221 // Now that we're mostly running, clean up stale users and apps 20222 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20223 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20224 20225 if (mPrivappPermissionsViolations != null) { 20226 Slog.wtf(TAG,"Signature|privileged permissions not in " 20227 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20228 mPrivappPermissionsViolations = null; 20229 } 20230 } 20231 20232 public void waitForAppDataPrepared() { 20233 if (mPrepareAppDataFuture == null) { 20234 return; 20235 } 20236 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20237 mPrepareAppDataFuture = null; 20238 } 20239 20240 @Override 20241 public boolean isSafeMode() { 20242 return mSafeMode; 20243 } 20244 20245 @Override 20246 public boolean hasSystemUidErrors() { 20247 return mHasSystemUidErrors; 20248 } 20249 20250 static String arrayToString(int[] array) { 20251 StringBuffer buf = new StringBuffer(128); 20252 buf.append('['); 20253 if (array != null) { 20254 for (int i=0; i<array.length; i++) { 20255 if (i > 0) buf.append(", "); 20256 buf.append(array[i]); 20257 } 20258 } 20259 buf.append(']'); 20260 return buf.toString(); 20261 } 20262 20263 static class DumpState { 20264 public static final int DUMP_LIBS = 1 << 0; 20265 public static final int DUMP_FEATURES = 1 << 1; 20266 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20267 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20268 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20269 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20270 public static final int DUMP_PERMISSIONS = 1 << 6; 20271 public static final int DUMP_PACKAGES = 1 << 7; 20272 public static final int DUMP_SHARED_USERS = 1 << 8; 20273 public static final int DUMP_MESSAGES = 1 << 9; 20274 public static final int DUMP_PROVIDERS = 1 << 10; 20275 public static final int DUMP_VERIFIERS = 1 << 11; 20276 public static final int DUMP_PREFERRED = 1 << 12; 20277 public static final int DUMP_PREFERRED_XML = 1 << 13; 20278 public static final int DUMP_KEYSETS = 1 << 14; 20279 public static final int DUMP_VERSION = 1 << 15; 20280 public static final int DUMP_INSTALLS = 1 << 16; 20281 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20282 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20283 public static final int DUMP_FROZEN = 1 << 19; 20284 public static final int DUMP_DEXOPT = 1 << 20; 20285 public static final int DUMP_COMPILER_STATS = 1 << 21; 20286 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20287 20288 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20289 20290 private int mTypes; 20291 20292 private int mOptions; 20293 20294 private boolean mTitlePrinted; 20295 20296 private SharedUserSetting mSharedUser; 20297 20298 public boolean isDumping(int type) { 20299 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20300 return true; 20301 } 20302 20303 return (mTypes & type) != 0; 20304 } 20305 20306 public void setDump(int type) { 20307 mTypes |= type; 20308 } 20309 20310 public boolean isOptionEnabled(int option) { 20311 return (mOptions & option) != 0; 20312 } 20313 20314 public void setOptionEnabled(int option) { 20315 mOptions |= option; 20316 } 20317 20318 public boolean onTitlePrinted() { 20319 final boolean printed = mTitlePrinted; 20320 mTitlePrinted = true; 20321 return printed; 20322 } 20323 20324 public boolean getTitlePrinted() { 20325 return mTitlePrinted; 20326 } 20327 20328 public void setTitlePrinted(boolean enabled) { 20329 mTitlePrinted = enabled; 20330 } 20331 20332 public SharedUserSetting getSharedUser() { 20333 return mSharedUser; 20334 } 20335 20336 public void setSharedUser(SharedUserSetting user) { 20337 mSharedUser = user; 20338 } 20339 } 20340 20341 @Override 20342 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20343 FileDescriptor err, String[] args, ShellCallback callback, 20344 ResultReceiver resultReceiver) { 20345 (new PackageManagerShellCommand(this)).exec( 20346 this, in, out, err, args, callback, resultReceiver); 20347 } 20348 20349 @Override 20350 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20351 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20352 20353 DumpState dumpState = new DumpState(); 20354 boolean fullPreferred = false; 20355 boolean checkin = false; 20356 20357 String packageName = null; 20358 ArraySet<String> permissionNames = null; 20359 20360 int opti = 0; 20361 while (opti < args.length) { 20362 String opt = args[opti]; 20363 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20364 break; 20365 } 20366 opti++; 20367 20368 if ("-a".equals(opt)) { 20369 // Right now we only know how to print all. 20370 } else if ("-h".equals(opt)) { 20371 pw.println("Package manager dump options:"); 20372 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20373 pw.println(" --checkin: dump for a checkin"); 20374 pw.println(" -f: print details of intent filters"); 20375 pw.println(" -h: print this help"); 20376 pw.println(" cmd may be one of:"); 20377 pw.println(" l[ibraries]: list known shared libraries"); 20378 pw.println(" f[eatures]: list device features"); 20379 pw.println(" k[eysets]: print known keysets"); 20380 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20381 pw.println(" perm[issions]: dump permissions"); 20382 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20383 pw.println(" pref[erred]: print preferred package settings"); 20384 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20385 pw.println(" prov[iders]: dump content providers"); 20386 pw.println(" p[ackages]: dump installed packages"); 20387 pw.println(" s[hared-users]: dump shared user IDs"); 20388 pw.println(" m[essages]: print collected runtime messages"); 20389 pw.println(" v[erifiers]: print package verifier info"); 20390 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20391 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20392 pw.println(" version: print database version info"); 20393 pw.println(" write: write current settings now"); 20394 pw.println(" installs: details about install sessions"); 20395 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20396 pw.println(" dexopt: dump dexopt state"); 20397 pw.println(" compiler-stats: dump compiler statistics"); 20398 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20399 pw.println(" <package.name>: info about given package"); 20400 return; 20401 } else if ("--checkin".equals(opt)) { 20402 checkin = true; 20403 } else if ("-f".equals(opt)) { 20404 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20405 } else if ("--proto".equals(opt)) { 20406 dumpProto(fd); 20407 return; 20408 } else { 20409 pw.println("Unknown argument: " + opt + "; use -h for help"); 20410 } 20411 } 20412 20413 // Is the caller requesting to dump a particular piece of data? 20414 if (opti < args.length) { 20415 String cmd = args[opti]; 20416 opti++; 20417 // Is this a package name? 20418 if ("android".equals(cmd) || cmd.contains(".")) { 20419 packageName = cmd; 20420 // When dumping a single package, we always dump all of its 20421 // filter information since the amount of data will be reasonable. 20422 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20423 } else if ("check-permission".equals(cmd)) { 20424 if (opti >= args.length) { 20425 pw.println("Error: check-permission missing permission argument"); 20426 return; 20427 } 20428 String perm = args[opti]; 20429 opti++; 20430 if (opti >= args.length) { 20431 pw.println("Error: check-permission missing package argument"); 20432 return; 20433 } 20434 20435 String pkg = args[opti]; 20436 opti++; 20437 int user = UserHandle.getUserId(Binder.getCallingUid()); 20438 if (opti < args.length) { 20439 try { 20440 user = Integer.parseInt(args[opti]); 20441 } catch (NumberFormatException e) { 20442 pw.println("Error: check-permission user argument is not a number: " 20443 + args[opti]); 20444 return; 20445 } 20446 } 20447 20448 // Normalize package name to handle renamed packages and static libs 20449 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20450 20451 pw.println(checkPermission(perm, pkg, user)); 20452 return; 20453 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20454 dumpState.setDump(DumpState.DUMP_LIBS); 20455 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20456 dumpState.setDump(DumpState.DUMP_FEATURES); 20457 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20458 if (opti >= args.length) { 20459 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20460 | DumpState.DUMP_SERVICE_RESOLVERS 20461 | DumpState.DUMP_RECEIVER_RESOLVERS 20462 | DumpState.DUMP_CONTENT_RESOLVERS); 20463 } else { 20464 while (opti < args.length) { 20465 String name = args[opti]; 20466 if ("a".equals(name) || "activity".equals(name)) { 20467 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20468 } else if ("s".equals(name) || "service".equals(name)) { 20469 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20470 } else if ("r".equals(name) || "receiver".equals(name)) { 20471 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20472 } else if ("c".equals(name) || "content".equals(name)) { 20473 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20474 } else { 20475 pw.println("Error: unknown resolver table type: " + name); 20476 return; 20477 } 20478 opti++; 20479 } 20480 } 20481 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20482 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20483 } else if ("permission".equals(cmd)) { 20484 if (opti >= args.length) { 20485 pw.println("Error: permission requires permission name"); 20486 return; 20487 } 20488 permissionNames = new ArraySet<>(); 20489 while (opti < args.length) { 20490 permissionNames.add(args[opti]); 20491 opti++; 20492 } 20493 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20494 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20495 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20496 dumpState.setDump(DumpState.DUMP_PREFERRED); 20497 } else if ("preferred-xml".equals(cmd)) { 20498 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20499 if (opti < args.length && "--full".equals(args[opti])) { 20500 fullPreferred = true; 20501 opti++; 20502 } 20503 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20504 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20505 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20506 dumpState.setDump(DumpState.DUMP_PACKAGES); 20507 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20508 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20509 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20510 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20511 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20512 dumpState.setDump(DumpState.DUMP_MESSAGES); 20513 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20514 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20515 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20516 || "intent-filter-verifiers".equals(cmd)) { 20517 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20518 } else if ("version".equals(cmd)) { 20519 dumpState.setDump(DumpState.DUMP_VERSION); 20520 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20521 dumpState.setDump(DumpState.DUMP_KEYSETS); 20522 } else if ("installs".equals(cmd)) { 20523 dumpState.setDump(DumpState.DUMP_INSTALLS); 20524 } else if ("frozen".equals(cmd)) { 20525 dumpState.setDump(DumpState.DUMP_FROZEN); 20526 } else if ("dexopt".equals(cmd)) { 20527 dumpState.setDump(DumpState.DUMP_DEXOPT); 20528 } else if ("compiler-stats".equals(cmd)) { 20529 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20530 } else if ("enabled-overlays".equals(cmd)) { 20531 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20532 } else if ("write".equals(cmd)) { 20533 synchronized (mPackages) { 20534 mSettings.writeLPr(); 20535 pw.println("Settings written."); 20536 return; 20537 } 20538 } 20539 } 20540 20541 if (checkin) { 20542 pw.println("vers,1"); 20543 } 20544 20545 // reader 20546 synchronized (mPackages) { 20547 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20548 if (!checkin) { 20549 if (dumpState.onTitlePrinted()) 20550 pw.println(); 20551 pw.println("Database versions:"); 20552 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20553 } 20554 } 20555 20556 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20557 if (!checkin) { 20558 if (dumpState.onTitlePrinted()) 20559 pw.println(); 20560 pw.println("Verifiers:"); 20561 pw.print(" Required: "); 20562 pw.print(mRequiredVerifierPackage); 20563 pw.print(" (uid="); 20564 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20565 UserHandle.USER_SYSTEM)); 20566 pw.println(")"); 20567 } else if (mRequiredVerifierPackage != null) { 20568 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20569 pw.print(","); 20570 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20571 UserHandle.USER_SYSTEM)); 20572 } 20573 } 20574 20575 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20576 packageName == null) { 20577 if (mIntentFilterVerifierComponent != null) { 20578 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20579 if (!checkin) { 20580 if (dumpState.onTitlePrinted()) 20581 pw.println(); 20582 pw.println("Intent Filter Verifier:"); 20583 pw.print(" Using: "); 20584 pw.print(verifierPackageName); 20585 pw.print(" (uid="); 20586 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20587 UserHandle.USER_SYSTEM)); 20588 pw.println(")"); 20589 } else if (verifierPackageName != null) { 20590 pw.print("ifv,"); pw.print(verifierPackageName); 20591 pw.print(","); 20592 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20593 UserHandle.USER_SYSTEM)); 20594 } 20595 } else { 20596 pw.println(); 20597 pw.println("No Intent Filter Verifier available!"); 20598 } 20599 } 20600 20601 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20602 boolean printedHeader = false; 20603 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20604 while (it.hasNext()) { 20605 String libName = it.next(); 20606 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20607 if (versionedLib == null) { 20608 continue; 20609 } 20610 final int versionCount = versionedLib.size(); 20611 for (int i = 0; i < versionCount; i++) { 20612 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20613 if (!checkin) { 20614 if (!printedHeader) { 20615 if (dumpState.onTitlePrinted()) 20616 pw.println(); 20617 pw.println("Libraries:"); 20618 printedHeader = true; 20619 } 20620 pw.print(" "); 20621 } else { 20622 pw.print("lib,"); 20623 } 20624 pw.print(libEntry.info.getName()); 20625 if (libEntry.info.isStatic()) { 20626 pw.print(" version=" + libEntry.info.getVersion()); 20627 } 20628 if (!checkin) { 20629 pw.print(" -> "); 20630 } 20631 if (libEntry.path != null) { 20632 pw.print(" (jar) "); 20633 pw.print(libEntry.path); 20634 } else { 20635 pw.print(" (apk) "); 20636 pw.print(libEntry.apk); 20637 } 20638 pw.println(); 20639 } 20640 } 20641 } 20642 20643 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20644 if (dumpState.onTitlePrinted()) 20645 pw.println(); 20646 if (!checkin) { 20647 pw.println("Features:"); 20648 } 20649 20650 synchronized (mAvailableFeatures) { 20651 for (FeatureInfo feat : mAvailableFeatures.values()) { 20652 if (checkin) { 20653 pw.print("feat,"); 20654 pw.print(feat.name); 20655 pw.print(","); 20656 pw.println(feat.version); 20657 } else { 20658 pw.print(" "); 20659 pw.print(feat.name); 20660 if (feat.version > 0) { 20661 pw.print(" version="); 20662 pw.print(feat.version); 20663 } 20664 pw.println(); 20665 } 20666 } 20667 } 20668 } 20669 20670 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20671 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20672 : "Activity Resolver Table:", " ", packageName, 20673 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20674 dumpState.setTitlePrinted(true); 20675 } 20676 } 20677 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20678 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20679 : "Receiver Resolver Table:", " ", packageName, 20680 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20681 dumpState.setTitlePrinted(true); 20682 } 20683 } 20684 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20685 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20686 : "Service Resolver Table:", " ", packageName, 20687 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20688 dumpState.setTitlePrinted(true); 20689 } 20690 } 20691 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20692 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20693 : "Provider Resolver Table:", " ", packageName, 20694 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20695 dumpState.setTitlePrinted(true); 20696 } 20697 } 20698 20699 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20700 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20701 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20702 int user = mSettings.mPreferredActivities.keyAt(i); 20703 if (pir.dump(pw, 20704 dumpState.getTitlePrinted() 20705 ? "\nPreferred Activities User " + user + ":" 20706 : "Preferred Activities User " + user + ":", " ", 20707 packageName, true, false)) { 20708 dumpState.setTitlePrinted(true); 20709 } 20710 } 20711 } 20712 20713 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20714 pw.flush(); 20715 FileOutputStream fout = new FileOutputStream(fd); 20716 BufferedOutputStream str = new BufferedOutputStream(fout); 20717 XmlSerializer serializer = new FastXmlSerializer(); 20718 try { 20719 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20720 serializer.startDocument(null, true); 20721 serializer.setFeature( 20722 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20723 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20724 serializer.endDocument(); 20725 serializer.flush(); 20726 } catch (IllegalArgumentException e) { 20727 pw.println("Failed writing: " + e); 20728 } catch (IllegalStateException e) { 20729 pw.println("Failed writing: " + e); 20730 } catch (IOException e) { 20731 pw.println("Failed writing: " + e); 20732 } 20733 } 20734 20735 if (!checkin 20736 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20737 && packageName == null) { 20738 pw.println(); 20739 int count = mSettings.mPackages.size(); 20740 if (count == 0) { 20741 pw.println("No applications!"); 20742 pw.println(); 20743 } else { 20744 final String prefix = " "; 20745 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20746 if (allPackageSettings.size() == 0) { 20747 pw.println("No domain preferred apps!"); 20748 pw.println(); 20749 } else { 20750 pw.println("App verification status:"); 20751 pw.println(); 20752 count = 0; 20753 for (PackageSetting ps : allPackageSettings) { 20754 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20755 if (ivi == null || ivi.getPackageName() == null) continue; 20756 pw.println(prefix + "Package: " + ivi.getPackageName()); 20757 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20758 pw.println(prefix + "Status: " + ivi.getStatusString()); 20759 pw.println(); 20760 count++; 20761 } 20762 if (count == 0) { 20763 pw.println(prefix + "No app verification established."); 20764 pw.println(); 20765 } 20766 for (int userId : sUserManager.getUserIds()) { 20767 pw.println("App linkages for user " + userId + ":"); 20768 pw.println(); 20769 count = 0; 20770 for (PackageSetting ps : allPackageSettings) { 20771 final long status = ps.getDomainVerificationStatusForUser(userId); 20772 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20773 && !DEBUG_DOMAIN_VERIFICATION) { 20774 continue; 20775 } 20776 pw.println(prefix + "Package: " + ps.name); 20777 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20778 String statusStr = IntentFilterVerificationInfo. 20779 getStatusStringFromValue(status); 20780 pw.println(prefix + "Status: " + statusStr); 20781 pw.println(); 20782 count++; 20783 } 20784 if (count == 0) { 20785 pw.println(prefix + "No configured app linkages."); 20786 pw.println(); 20787 } 20788 } 20789 } 20790 } 20791 } 20792 20793 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20794 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20795 if (packageName == null && permissionNames == null) { 20796 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20797 if (iperm == 0) { 20798 if (dumpState.onTitlePrinted()) 20799 pw.println(); 20800 pw.println("AppOp Permissions:"); 20801 } 20802 pw.print(" AppOp Permission "); 20803 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20804 pw.println(":"); 20805 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20806 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20807 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20808 } 20809 } 20810 } 20811 } 20812 20813 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20814 boolean printedSomething = false; 20815 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20816 if (packageName != null && !packageName.equals(p.info.packageName)) { 20817 continue; 20818 } 20819 if (!printedSomething) { 20820 if (dumpState.onTitlePrinted()) 20821 pw.println(); 20822 pw.println("Registered ContentProviders:"); 20823 printedSomething = true; 20824 } 20825 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20826 pw.print(" "); pw.println(p.toString()); 20827 } 20828 printedSomething = false; 20829 for (Map.Entry<String, PackageParser.Provider> entry : 20830 mProvidersByAuthority.entrySet()) { 20831 PackageParser.Provider p = entry.getValue(); 20832 if (packageName != null && !packageName.equals(p.info.packageName)) { 20833 continue; 20834 } 20835 if (!printedSomething) { 20836 if (dumpState.onTitlePrinted()) 20837 pw.println(); 20838 pw.println("ContentProvider Authorities:"); 20839 printedSomething = true; 20840 } 20841 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20842 pw.print(" "); pw.println(p.toString()); 20843 if (p.info != null && p.info.applicationInfo != null) { 20844 final String appInfo = p.info.applicationInfo.toString(); 20845 pw.print(" applicationInfo="); pw.println(appInfo); 20846 } 20847 } 20848 } 20849 20850 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20851 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20852 } 20853 20854 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20855 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20856 } 20857 20858 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20859 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20860 } 20861 20862 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20863 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20864 } 20865 20866 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20867 // XXX should handle packageName != null by dumping only install data that 20868 // the given package is involved with. 20869 if (dumpState.onTitlePrinted()) pw.println(); 20870 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20871 } 20872 20873 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20874 // XXX should handle packageName != null by dumping only install data that 20875 // the given package is involved with. 20876 if (dumpState.onTitlePrinted()) pw.println(); 20877 20878 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20879 ipw.println(); 20880 ipw.println("Frozen packages:"); 20881 ipw.increaseIndent(); 20882 if (mFrozenPackages.size() == 0) { 20883 ipw.println("(none)"); 20884 } else { 20885 for (int i = 0; i < mFrozenPackages.size(); i++) { 20886 ipw.println(mFrozenPackages.valueAt(i)); 20887 } 20888 } 20889 ipw.decreaseIndent(); 20890 } 20891 20892 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20893 if (dumpState.onTitlePrinted()) pw.println(); 20894 dumpDexoptStateLPr(pw, packageName); 20895 } 20896 20897 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20898 if (dumpState.onTitlePrinted()) pw.println(); 20899 dumpCompilerStatsLPr(pw, packageName); 20900 } 20901 20902 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20903 if (dumpState.onTitlePrinted()) pw.println(); 20904 dumpEnabledOverlaysLPr(pw); 20905 } 20906 20907 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20908 if (dumpState.onTitlePrinted()) pw.println(); 20909 mSettings.dumpReadMessagesLPr(pw, dumpState); 20910 20911 pw.println(); 20912 pw.println("Package warning messages:"); 20913 BufferedReader in = null; 20914 String line = null; 20915 try { 20916 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20917 while ((line = in.readLine()) != null) { 20918 if (line.contains("ignored: updated version")) continue; 20919 pw.println(line); 20920 } 20921 } catch (IOException ignored) { 20922 } finally { 20923 IoUtils.closeQuietly(in); 20924 } 20925 } 20926 20927 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20928 BufferedReader in = null; 20929 String line = null; 20930 try { 20931 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20932 while ((line = in.readLine()) != null) { 20933 if (line.contains("ignored: updated version")) continue; 20934 pw.print("msg,"); 20935 pw.println(line); 20936 } 20937 } catch (IOException ignored) { 20938 } finally { 20939 IoUtils.closeQuietly(in); 20940 } 20941 } 20942 } 20943 } 20944 20945 private void dumpProto(FileDescriptor fd) { 20946 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20947 20948 synchronized (mPackages) { 20949 final long requiredVerifierPackageToken = 20950 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20951 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20952 proto.write( 20953 PackageServiceDumpProto.PackageShortProto.UID, 20954 getPackageUid( 20955 mRequiredVerifierPackage, 20956 MATCH_DEBUG_TRIAGED_MISSING, 20957 UserHandle.USER_SYSTEM)); 20958 proto.end(requiredVerifierPackageToken); 20959 20960 if (mIntentFilterVerifierComponent != null) { 20961 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20962 final long verifierPackageToken = 20963 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20964 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20965 proto.write( 20966 PackageServiceDumpProto.PackageShortProto.UID, 20967 getPackageUid( 20968 verifierPackageName, 20969 MATCH_DEBUG_TRIAGED_MISSING, 20970 UserHandle.USER_SYSTEM)); 20971 proto.end(verifierPackageToken); 20972 } 20973 20974 dumpSharedLibrariesProto(proto); 20975 dumpFeaturesProto(proto); 20976 mSettings.dumpPackagesProto(proto); 20977 mSettings.dumpSharedUsersProto(proto); 20978 dumpMessagesProto(proto); 20979 } 20980 proto.flush(); 20981 } 20982 20983 private void dumpMessagesProto(ProtoOutputStream proto) { 20984 BufferedReader in = null; 20985 String line = null; 20986 try { 20987 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20988 while ((line = in.readLine()) != null) { 20989 if (line.contains("ignored: updated version")) continue; 20990 proto.write(PackageServiceDumpProto.MESSAGES, line); 20991 } 20992 } catch (IOException ignored) { 20993 } finally { 20994 IoUtils.closeQuietly(in); 20995 } 20996 } 20997 20998 private void dumpFeaturesProto(ProtoOutputStream proto) { 20999 synchronized (mAvailableFeatures) { 21000 final int count = mAvailableFeatures.size(); 21001 for (int i = 0; i < count; i++) { 21002 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21003 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21004 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21005 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21006 proto.end(featureToken); 21007 } 21008 } 21009 } 21010 21011 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21012 final int count = mSharedLibraries.size(); 21013 for (int i = 0; i < count; i++) { 21014 final String libName = mSharedLibraries.keyAt(i); 21015 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21016 if (versionedLib == null) { 21017 continue; 21018 } 21019 final int versionCount = versionedLib.size(); 21020 for (int j = 0; j < versionCount; j++) { 21021 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21022 final long sharedLibraryToken = 21023 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21024 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21025 final boolean isJar = (libEntry.path != null); 21026 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21027 if (isJar) { 21028 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21029 } else { 21030 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21031 } 21032 proto.end(sharedLibraryToken); 21033 } 21034 } 21035 } 21036 21037 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21038 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21039 ipw.println(); 21040 ipw.println("Dexopt state:"); 21041 ipw.increaseIndent(); 21042 Collection<PackageParser.Package> packages = null; 21043 if (packageName != null) { 21044 PackageParser.Package targetPackage = mPackages.get(packageName); 21045 if (targetPackage != null) { 21046 packages = Collections.singletonList(targetPackage); 21047 } else { 21048 ipw.println("Unable to find package: " + packageName); 21049 return; 21050 } 21051 } else { 21052 packages = mPackages.values(); 21053 } 21054 21055 for (PackageParser.Package pkg : packages) { 21056 ipw.println("[" + pkg.packageName + "]"); 21057 ipw.increaseIndent(); 21058 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21059 ipw.decreaseIndent(); 21060 } 21061 } 21062 21063 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21064 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21065 ipw.println(); 21066 ipw.println("Compiler stats:"); 21067 ipw.increaseIndent(); 21068 Collection<PackageParser.Package> packages = null; 21069 if (packageName != null) { 21070 PackageParser.Package targetPackage = mPackages.get(packageName); 21071 if (targetPackage != null) { 21072 packages = Collections.singletonList(targetPackage); 21073 } else { 21074 ipw.println("Unable to find package: " + packageName); 21075 return; 21076 } 21077 } else { 21078 packages = mPackages.values(); 21079 } 21080 21081 for (PackageParser.Package pkg : packages) { 21082 ipw.println("[" + pkg.packageName + "]"); 21083 ipw.increaseIndent(); 21084 21085 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21086 if (stats == null) { 21087 ipw.println("(No recorded stats)"); 21088 } else { 21089 stats.dump(ipw); 21090 } 21091 ipw.decreaseIndent(); 21092 } 21093 } 21094 21095 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21096 pw.println("Enabled overlay paths:"); 21097 final int N = mEnabledOverlayPaths.size(); 21098 for (int i = 0; i < N; i++) { 21099 final int userId = mEnabledOverlayPaths.keyAt(i); 21100 pw.println(String.format(" User %d:", userId)); 21101 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21102 mEnabledOverlayPaths.valueAt(i); 21103 final int M = userSpecificOverlays.size(); 21104 for (int j = 0; j < M; j++) { 21105 final String targetPackageName = userSpecificOverlays.keyAt(j); 21106 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21107 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21108 } 21109 } 21110 } 21111 21112 private String dumpDomainString(String packageName) { 21113 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21114 .getList(); 21115 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21116 21117 ArraySet<String> result = new ArraySet<>(); 21118 if (iviList.size() > 0) { 21119 for (IntentFilterVerificationInfo ivi : iviList) { 21120 for (String host : ivi.getDomains()) { 21121 result.add(host); 21122 } 21123 } 21124 } 21125 if (filters != null && filters.size() > 0) { 21126 for (IntentFilter filter : filters) { 21127 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21128 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21129 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21130 result.addAll(filter.getHostsList()); 21131 } 21132 } 21133 } 21134 21135 StringBuilder sb = new StringBuilder(result.size() * 16); 21136 for (String domain : result) { 21137 if (sb.length() > 0) sb.append(" "); 21138 sb.append(domain); 21139 } 21140 return sb.toString(); 21141 } 21142 21143 // ------- apps on sdcard specific code ------- 21144 static final boolean DEBUG_SD_INSTALL = false; 21145 21146 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21147 21148 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21149 21150 private boolean mMediaMounted = false; 21151 21152 static String getEncryptKey() { 21153 try { 21154 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21155 SD_ENCRYPTION_KEYSTORE_NAME); 21156 if (sdEncKey == null) { 21157 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21158 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21159 if (sdEncKey == null) { 21160 Slog.e(TAG, "Failed to create encryption keys"); 21161 return null; 21162 } 21163 } 21164 return sdEncKey; 21165 } catch (NoSuchAlgorithmException nsae) { 21166 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21167 return null; 21168 } catch (IOException ioe) { 21169 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21170 return null; 21171 } 21172 } 21173 21174 /* 21175 * Update media status on PackageManager. 21176 */ 21177 @Override 21178 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21179 int callingUid = Binder.getCallingUid(); 21180 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21181 throw new SecurityException("Media status can only be updated by the system"); 21182 } 21183 // reader; this apparently protects mMediaMounted, but should probably 21184 // be a different lock in that case. 21185 synchronized (mPackages) { 21186 Log.i(TAG, "Updating external media status from " 21187 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21188 + (mediaStatus ? "mounted" : "unmounted")); 21189 if (DEBUG_SD_INSTALL) 21190 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21191 + ", mMediaMounted=" + mMediaMounted); 21192 if (mediaStatus == mMediaMounted) { 21193 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21194 : 0, -1); 21195 mHandler.sendMessage(msg); 21196 return; 21197 } 21198 mMediaMounted = mediaStatus; 21199 } 21200 // Queue up an async operation since the package installation may take a 21201 // little while. 21202 mHandler.post(new Runnable() { 21203 public void run() { 21204 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21205 } 21206 }); 21207 } 21208 21209 /** 21210 * Called by StorageManagerService when the initial ASECs to scan are available. 21211 * Should block until all the ASEC containers are finished being scanned. 21212 */ 21213 public void scanAvailableAsecs() { 21214 updateExternalMediaStatusInner(true, false, false); 21215 } 21216 21217 /* 21218 * Collect information of applications on external media, map them against 21219 * existing containers and update information based on current mount status. 21220 * Please note that we always have to report status if reportStatus has been 21221 * set to true especially when unloading packages. 21222 */ 21223 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21224 boolean externalStorage) { 21225 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21226 int[] uidArr = EmptyArray.INT; 21227 21228 final String[] list = PackageHelper.getSecureContainerList(); 21229 if (ArrayUtils.isEmpty(list)) { 21230 Log.i(TAG, "No secure containers found"); 21231 } else { 21232 // Process list of secure containers and categorize them 21233 // as active or stale based on their package internal state. 21234 21235 // reader 21236 synchronized (mPackages) { 21237 for (String cid : list) { 21238 // Leave stages untouched for now; installer service owns them 21239 if (PackageInstallerService.isStageName(cid)) continue; 21240 21241 if (DEBUG_SD_INSTALL) 21242 Log.i(TAG, "Processing container " + cid); 21243 String pkgName = getAsecPackageName(cid); 21244 if (pkgName == null) { 21245 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21246 continue; 21247 } 21248 if (DEBUG_SD_INSTALL) 21249 Log.i(TAG, "Looking for pkg : " + pkgName); 21250 21251 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21252 if (ps == null) { 21253 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21254 continue; 21255 } 21256 21257 /* 21258 * Skip packages that are not external if we're unmounting 21259 * external storage. 21260 */ 21261 if (externalStorage && !isMounted && !isExternal(ps)) { 21262 continue; 21263 } 21264 21265 final AsecInstallArgs args = new AsecInstallArgs(cid, 21266 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21267 // The package status is changed only if the code path 21268 // matches between settings and the container id. 21269 if (ps.codePathString != null 21270 && ps.codePathString.startsWith(args.getCodePath())) { 21271 if (DEBUG_SD_INSTALL) { 21272 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21273 + " at code path: " + ps.codePathString); 21274 } 21275 21276 // We do have a valid package installed on sdcard 21277 processCids.put(args, ps.codePathString); 21278 final int uid = ps.appId; 21279 if (uid != -1) { 21280 uidArr = ArrayUtils.appendInt(uidArr, uid); 21281 } 21282 } else { 21283 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21284 + ps.codePathString); 21285 } 21286 } 21287 } 21288 21289 Arrays.sort(uidArr); 21290 } 21291 21292 // Process packages with valid entries. 21293 if (isMounted) { 21294 if (DEBUG_SD_INSTALL) 21295 Log.i(TAG, "Loading packages"); 21296 loadMediaPackages(processCids, uidArr, externalStorage); 21297 startCleaningPackages(); 21298 mInstallerService.onSecureContainersAvailable(); 21299 } else { 21300 if (DEBUG_SD_INSTALL) 21301 Log.i(TAG, "Unloading packages"); 21302 unloadMediaPackages(processCids, uidArr, reportStatus); 21303 } 21304 } 21305 21306 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21307 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21308 final int size = infos.size(); 21309 final String[] packageNames = new String[size]; 21310 final int[] packageUids = new int[size]; 21311 for (int i = 0; i < size; i++) { 21312 final ApplicationInfo info = infos.get(i); 21313 packageNames[i] = info.packageName; 21314 packageUids[i] = info.uid; 21315 } 21316 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21317 finishedReceiver); 21318 } 21319 21320 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21321 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21322 sendResourcesChangedBroadcast(mediaStatus, replacing, 21323 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21324 } 21325 21326 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21327 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21328 int size = pkgList.length; 21329 if (size > 0) { 21330 // Send broadcasts here 21331 Bundle extras = new Bundle(); 21332 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21333 if (uidArr != null) { 21334 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21335 } 21336 if (replacing) { 21337 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21338 } 21339 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21340 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21341 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21342 } 21343 } 21344 21345 /* 21346 * Look at potentially valid container ids from processCids If package 21347 * information doesn't match the one on record or package scanning fails, 21348 * the cid is added to list of removeCids. We currently don't delete stale 21349 * containers. 21350 */ 21351 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21352 boolean externalStorage) { 21353 ArrayList<String> pkgList = new ArrayList<String>(); 21354 Set<AsecInstallArgs> keys = processCids.keySet(); 21355 21356 for (AsecInstallArgs args : keys) { 21357 String codePath = processCids.get(args); 21358 if (DEBUG_SD_INSTALL) 21359 Log.i(TAG, "Loading container : " + args.cid); 21360 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21361 try { 21362 // Make sure there are no container errors first. 21363 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21364 Slog.e(TAG, "Failed to mount cid : " + args.cid 21365 + " when installing from sdcard"); 21366 continue; 21367 } 21368 // Check code path here. 21369 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21370 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21371 + " does not match one in settings " + codePath); 21372 continue; 21373 } 21374 // Parse package 21375 int parseFlags = mDefParseFlags; 21376 if (args.isExternalAsec()) { 21377 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21378 } 21379 if (args.isFwdLocked()) { 21380 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21381 } 21382 21383 synchronized (mInstallLock) { 21384 PackageParser.Package pkg = null; 21385 try { 21386 // Sadly we don't know the package name yet to freeze it 21387 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21388 SCAN_IGNORE_FROZEN, 0, null); 21389 } catch (PackageManagerException e) { 21390 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21391 } 21392 // Scan the package 21393 if (pkg != null) { 21394 /* 21395 * TODO why is the lock being held? doPostInstall is 21396 * called in other places without the lock. This needs 21397 * to be straightened out. 21398 */ 21399 // writer 21400 synchronized (mPackages) { 21401 retCode = PackageManager.INSTALL_SUCCEEDED; 21402 pkgList.add(pkg.packageName); 21403 // Post process args 21404 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21405 pkg.applicationInfo.uid); 21406 } 21407 } else { 21408 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21409 } 21410 } 21411 21412 } finally { 21413 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21414 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21415 } 21416 } 21417 } 21418 // writer 21419 synchronized (mPackages) { 21420 // If the platform SDK has changed since the last time we booted, 21421 // we need to re-grant app permission to catch any new ones that 21422 // appear. This is really a hack, and means that apps can in some 21423 // cases get permissions that the user didn't initially explicitly 21424 // allow... it would be nice to have some better way to handle 21425 // this situation. 21426 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21427 : mSettings.getInternalVersion(); 21428 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21429 : StorageManager.UUID_PRIVATE_INTERNAL; 21430 21431 int updateFlags = UPDATE_PERMISSIONS_ALL; 21432 if (ver.sdkVersion != mSdkVersion) { 21433 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21434 + mSdkVersion + "; regranting permissions for external"); 21435 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21436 } 21437 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21438 21439 // Yay, everything is now upgraded 21440 ver.forceCurrent(); 21441 21442 // can downgrade to reader 21443 // Persist settings 21444 mSettings.writeLPr(); 21445 } 21446 // Send a broadcast to let everyone know we are done processing 21447 if (pkgList.size() > 0) { 21448 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21449 } 21450 } 21451 21452 /* 21453 * Utility method to unload a list of specified containers 21454 */ 21455 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21456 // Just unmount all valid containers. 21457 for (AsecInstallArgs arg : cidArgs) { 21458 synchronized (mInstallLock) { 21459 arg.doPostDeleteLI(false); 21460 } 21461 } 21462 } 21463 21464 /* 21465 * Unload packages mounted on external media. This involves deleting package 21466 * data from internal structures, sending broadcasts about disabled packages, 21467 * gc'ing to free up references, unmounting all secure containers 21468 * corresponding to packages on external media, and posting a 21469 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21470 * that we always have to post this message if status has been requested no 21471 * matter what. 21472 */ 21473 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21474 final boolean reportStatus) { 21475 if (DEBUG_SD_INSTALL) 21476 Log.i(TAG, "unloading media packages"); 21477 ArrayList<String> pkgList = new ArrayList<String>(); 21478 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21479 final Set<AsecInstallArgs> keys = processCids.keySet(); 21480 for (AsecInstallArgs args : keys) { 21481 String pkgName = args.getPackageName(); 21482 if (DEBUG_SD_INSTALL) 21483 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21484 // Delete package internally 21485 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21486 synchronized (mInstallLock) { 21487 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21488 final boolean res; 21489 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21490 "unloadMediaPackages")) { 21491 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21492 null); 21493 } 21494 if (res) { 21495 pkgList.add(pkgName); 21496 } else { 21497 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21498 failedList.add(args); 21499 } 21500 } 21501 } 21502 21503 // reader 21504 synchronized (mPackages) { 21505 // We didn't update the settings after removing each package; 21506 // write them now for all packages. 21507 mSettings.writeLPr(); 21508 } 21509 21510 // We have to absolutely send UPDATED_MEDIA_STATUS only 21511 // after confirming that all the receivers processed the ordered 21512 // broadcast when packages get disabled, force a gc to clean things up. 21513 // and unload all the containers. 21514 if (pkgList.size() > 0) { 21515 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21516 new IIntentReceiver.Stub() { 21517 public void performReceive(Intent intent, int resultCode, String data, 21518 Bundle extras, boolean ordered, boolean sticky, 21519 int sendingUser) throws RemoteException { 21520 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21521 reportStatus ? 1 : 0, 1, keys); 21522 mHandler.sendMessage(msg); 21523 } 21524 }); 21525 } else { 21526 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21527 keys); 21528 mHandler.sendMessage(msg); 21529 } 21530 } 21531 21532 private void loadPrivatePackages(final VolumeInfo vol) { 21533 mHandler.post(new Runnable() { 21534 @Override 21535 public void run() { 21536 loadPrivatePackagesInner(vol); 21537 } 21538 }); 21539 } 21540 21541 private void loadPrivatePackagesInner(VolumeInfo vol) { 21542 final String volumeUuid = vol.fsUuid; 21543 if (TextUtils.isEmpty(volumeUuid)) { 21544 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21545 return; 21546 } 21547 21548 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21549 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21550 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21551 21552 final VersionInfo ver; 21553 final List<PackageSetting> packages; 21554 synchronized (mPackages) { 21555 ver = mSettings.findOrCreateVersion(volumeUuid); 21556 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21557 } 21558 21559 for (PackageSetting ps : packages) { 21560 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21561 synchronized (mInstallLock) { 21562 final PackageParser.Package pkg; 21563 try { 21564 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21565 loaded.add(pkg.applicationInfo); 21566 21567 } catch (PackageManagerException e) { 21568 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21569 } 21570 21571 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21572 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21573 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21574 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21575 } 21576 } 21577 } 21578 21579 // Reconcile app data for all started/unlocked users 21580 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21581 final UserManager um = mContext.getSystemService(UserManager.class); 21582 UserManagerInternal umInternal = getUserManagerInternal(); 21583 for (UserInfo user : um.getUsers()) { 21584 final int flags; 21585 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21586 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21587 } else if (umInternal.isUserRunning(user.id)) { 21588 flags = StorageManager.FLAG_STORAGE_DE; 21589 } else { 21590 continue; 21591 } 21592 21593 try { 21594 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21595 synchronized (mInstallLock) { 21596 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21597 } 21598 } catch (IllegalStateException e) { 21599 // Device was probably ejected, and we'll process that event momentarily 21600 Slog.w(TAG, "Failed to prepare storage: " + e); 21601 } 21602 } 21603 21604 synchronized (mPackages) { 21605 int updateFlags = UPDATE_PERMISSIONS_ALL; 21606 if (ver.sdkVersion != mSdkVersion) { 21607 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21608 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21609 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21610 } 21611 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21612 21613 // Yay, everything is now upgraded 21614 ver.forceCurrent(); 21615 21616 mSettings.writeLPr(); 21617 } 21618 21619 for (PackageFreezer freezer : freezers) { 21620 freezer.close(); 21621 } 21622 21623 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21624 sendResourcesChangedBroadcast(true, false, loaded, null); 21625 } 21626 21627 private void unloadPrivatePackages(final VolumeInfo vol) { 21628 mHandler.post(new Runnable() { 21629 @Override 21630 public void run() { 21631 unloadPrivatePackagesInner(vol); 21632 } 21633 }); 21634 } 21635 21636 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21637 final String volumeUuid = vol.fsUuid; 21638 if (TextUtils.isEmpty(volumeUuid)) { 21639 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21640 return; 21641 } 21642 21643 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21644 synchronized (mInstallLock) { 21645 synchronized (mPackages) { 21646 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21647 for (PackageSetting ps : packages) { 21648 if (ps.pkg == null) continue; 21649 21650 final ApplicationInfo info = ps.pkg.applicationInfo; 21651 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21652 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21653 21654 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21655 "unloadPrivatePackagesInner")) { 21656 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21657 false, null)) { 21658 unloaded.add(info); 21659 } else { 21660 Slog.w(TAG, "Failed to unload " + ps.codePath); 21661 } 21662 } 21663 21664 // Try very hard to release any references to this package 21665 // so we don't risk the system server being killed due to 21666 // open FDs 21667 AttributeCache.instance().removePackage(ps.name); 21668 } 21669 21670 mSettings.writeLPr(); 21671 } 21672 } 21673 21674 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21675 sendResourcesChangedBroadcast(false, false, unloaded, null); 21676 21677 // Try very hard to release any references to this path so we don't risk 21678 // the system server being killed due to open FDs 21679 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21680 21681 for (int i = 0; i < 3; i++) { 21682 System.gc(); 21683 System.runFinalization(); 21684 } 21685 } 21686 21687 private void assertPackageKnown(String volumeUuid, String packageName) 21688 throws PackageManagerException { 21689 synchronized (mPackages) { 21690 // Normalize package name to handle renamed packages 21691 packageName = normalizePackageNameLPr(packageName); 21692 21693 final PackageSetting ps = mSettings.mPackages.get(packageName); 21694 if (ps == null) { 21695 throw new PackageManagerException("Package " + packageName + " is unknown"); 21696 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21697 throw new PackageManagerException( 21698 "Package " + packageName + " found on unknown volume " + volumeUuid 21699 + "; expected volume " + ps.volumeUuid); 21700 } 21701 } 21702 } 21703 21704 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21705 throws PackageManagerException { 21706 synchronized (mPackages) { 21707 // Normalize package name to handle renamed packages 21708 packageName = normalizePackageNameLPr(packageName); 21709 21710 final PackageSetting ps = mSettings.mPackages.get(packageName); 21711 if (ps == null) { 21712 throw new PackageManagerException("Package " + packageName + " is unknown"); 21713 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21714 throw new PackageManagerException( 21715 "Package " + packageName + " found on unknown volume " + volumeUuid 21716 + "; expected volume " + ps.volumeUuid); 21717 } else if (!ps.getInstalled(userId)) { 21718 throw new PackageManagerException( 21719 "Package " + packageName + " not installed for user " + userId); 21720 } 21721 } 21722 } 21723 21724 private List<String> collectAbsoluteCodePaths() { 21725 synchronized (mPackages) { 21726 List<String> codePaths = new ArrayList<>(); 21727 final int packageCount = mSettings.mPackages.size(); 21728 for (int i = 0; i < packageCount; i++) { 21729 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21730 codePaths.add(ps.codePath.getAbsolutePath()); 21731 } 21732 return codePaths; 21733 } 21734 } 21735 21736 /** 21737 * Examine all apps present on given mounted volume, and destroy apps that 21738 * aren't expected, either due to uninstallation or reinstallation on 21739 * another volume. 21740 */ 21741 private void reconcileApps(String volumeUuid) { 21742 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21743 List<File> filesToDelete = null; 21744 21745 final File[] files = FileUtils.listFilesOrEmpty( 21746 Environment.getDataAppDirectory(volumeUuid)); 21747 for (File file : files) { 21748 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21749 && !PackageInstallerService.isStageName(file.getName()); 21750 if (!isPackage) { 21751 // Ignore entries which are not packages 21752 continue; 21753 } 21754 21755 String absolutePath = file.getAbsolutePath(); 21756 21757 boolean pathValid = false; 21758 final int absoluteCodePathCount = absoluteCodePaths.size(); 21759 for (int i = 0; i < absoluteCodePathCount; i++) { 21760 String absoluteCodePath = absoluteCodePaths.get(i); 21761 if (absolutePath.startsWith(absoluteCodePath)) { 21762 pathValid = true; 21763 break; 21764 } 21765 } 21766 21767 if (!pathValid) { 21768 if (filesToDelete == null) { 21769 filesToDelete = new ArrayList<>(); 21770 } 21771 filesToDelete.add(file); 21772 } 21773 } 21774 21775 if (filesToDelete != null) { 21776 final int fileToDeleteCount = filesToDelete.size(); 21777 for (int i = 0; i < fileToDeleteCount; i++) { 21778 File fileToDelete = filesToDelete.get(i); 21779 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21780 synchronized (mInstallLock) { 21781 removeCodePathLI(fileToDelete); 21782 } 21783 } 21784 } 21785 } 21786 21787 /** 21788 * Reconcile all app data for the given user. 21789 * <p> 21790 * Verifies that directories exist and that ownership and labeling is 21791 * correct for all installed apps on all mounted volumes. 21792 */ 21793 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21794 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21795 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21796 final String volumeUuid = vol.getFsUuid(); 21797 synchronized (mInstallLock) { 21798 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21799 } 21800 } 21801 } 21802 21803 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21804 boolean migrateAppData) { 21805 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21806 } 21807 21808 /** 21809 * Reconcile all app data on given mounted volume. 21810 * <p> 21811 * Destroys app data that isn't expected, either due to uninstallation or 21812 * reinstallation on another volume. 21813 * <p> 21814 * Verifies that directories exist and that ownership and labeling is 21815 * correct for all installed apps. 21816 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21817 */ 21818 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21819 boolean migrateAppData, boolean onlyCoreApps) { 21820 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21821 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21822 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21823 21824 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21825 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21826 21827 // First look for stale data that doesn't belong, and check if things 21828 // have changed since we did our last restorecon 21829 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21830 if (StorageManager.isFileEncryptedNativeOrEmulated() 21831 && !StorageManager.isUserKeyUnlocked(userId)) { 21832 throw new RuntimeException( 21833 "Yikes, someone asked us to reconcile CE storage while " + userId 21834 + " was still locked; this would have caused massive data loss!"); 21835 } 21836 21837 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21838 for (File file : files) { 21839 final String packageName = file.getName(); 21840 try { 21841 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21842 } catch (PackageManagerException e) { 21843 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21844 try { 21845 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21846 StorageManager.FLAG_STORAGE_CE, 0); 21847 } catch (InstallerException e2) { 21848 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21849 } 21850 } 21851 } 21852 } 21853 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21854 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21855 for (File file : files) { 21856 final String packageName = file.getName(); 21857 try { 21858 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21859 } catch (PackageManagerException e) { 21860 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21861 try { 21862 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21863 StorageManager.FLAG_STORAGE_DE, 0); 21864 } catch (InstallerException e2) { 21865 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21866 } 21867 } 21868 } 21869 } 21870 21871 // Ensure that data directories are ready to roll for all packages 21872 // installed for this volume and user 21873 final List<PackageSetting> packages; 21874 synchronized (mPackages) { 21875 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21876 } 21877 int preparedCount = 0; 21878 for (PackageSetting ps : packages) { 21879 final String packageName = ps.name; 21880 if (ps.pkg == null) { 21881 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21882 // TODO: might be due to legacy ASEC apps; we should circle back 21883 // and reconcile again once they're scanned 21884 continue; 21885 } 21886 // Skip non-core apps if requested 21887 if (onlyCoreApps && !ps.pkg.coreApp) { 21888 result.add(packageName); 21889 continue; 21890 } 21891 21892 if (ps.getInstalled(userId)) { 21893 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21894 preparedCount++; 21895 } 21896 } 21897 21898 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21899 return result; 21900 } 21901 21902 /** 21903 * Prepare app data for the given app just after it was installed or 21904 * upgraded. This method carefully only touches users that it's installed 21905 * for, and it forces a restorecon to handle any seinfo changes. 21906 * <p> 21907 * Verifies that directories exist and that ownership and labeling is 21908 * correct for all installed apps. If there is an ownership mismatch, it 21909 * will try recovering system apps by wiping data; third-party app data is 21910 * left intact. 21911 * <p> 21912 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21913 */ 21914 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21915 final PackageSetting ps; 21916 synchronized (mPackages) { 21917 ps = mSettings.mPackages.get(pkg.packageName); 21918 mSettings.writeKernelMappingLPr(ps); 21919 } 21920 21921 final UserManager um = mContext.getSystemService(UserManager.class); 21922 UserManagerInternal umInternal = getUserManagerInternal(); 21923 for (UserInfo user : um.getUsers()) { 21924 final int flags; 21925 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21926 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21927 } else if (umInternal.isUserRunning(user.id)) { 21928 flags = StorageManager.FLAG_STORAGE_DE; 21929 } else { 21930 continue; 21931 } 21932 21933 if (ps.getInstalled(user.id)) { 21934 // TODO: when user data is locked, mark that we're still dirty 21935 prepareAppDataLIF(pkg, user.id, flags); 21936 } 21937 } 21938 } 21939 21940 /** 21941 * Prepare app data for the given app. 21942 * <p> 21943 * Verifies that directories exist and that ownership and labeling is 21944 * correct for all installed apps. If there is an ownership mismatch, this 21945 * will try recovering system apps by wiping data; third-party app data is 21946 * left intact. 21947 */ 21948 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21949 if (pkg == null) { 21950 Slog.wtf(TAG, "Package was null!", new Throwable()); 21951 return; 21952 } 21953 prepareAppDataLeafLIF(pkg, userId, flags); 21954 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21955 for (int i = 0; i < childCount; i++) { 21956 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21957 } 21958 } 21959 21960 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21961 boolean maybeMigrateAppData) { 21962 prepareAppDataLIF(pkg, userId, flags); 21963 21964 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21965 // We may have just shuffled around app data directories, so 21966 // prepare them one more time 21967 prepareAppDataLIF(pkg, userId, flags); 21968 } 21969 } 21970 21971 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21972 if (DEBUG_APP_DATA) { 21973 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21974 + Integer.toHexString(flags)); 21975 } 21976 21977 final String volumeUuid = pkg.volumeUuid; 21978 final String packageName = pkg.packageName; 21979 final ApplicationInfo app = pkg.applicationInfo; 21980 final int appId = UserHandle.getAppId(app.uid); 21981 21982 Preconditions.checkNotNull(app.seInfo); 21983 21984 long ceDataInode = -1; 21985 try { 21986 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21987 appId, app.seInfo, app.targetSdkVersion); 21988 } catch (InstallerException e) { 21989 if (app.isSystemApp()) { 21990 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21991 + ", but trying to recover: " + e); 21992 destroyAppDataLeafLIF(pkg, userId, flags); 21993 try { 21994 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21995 appId, app.seInfo, app.targetSdkVersion); 21996 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21997 } catch (InstallerException e2) { 21998 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21999 } 22000 } else { 22001 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22002 } 22003 } 22004 22005 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22006 // TODO: mark this structure as dirty so we persist it! 22007 synchronized (mPackages) { 22008 final PackageSetting ps = mSettings.mPackages.get(packageName); 22009 if (ps != null) { 22010 ps.setCeDataInode(ceDataInode, userId); 22011 } 22012 } 22013 } 22014 22015 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22016 } 22017 22018 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22019 if (pkg == null) { 22020 Slog.wtf(TAG, "Package was null!", new Throwable()); 22021 return; 22022 } 22023 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22024 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22025 for (int i = 0; i < childCount; i++) { 22026 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22027 } 22028 } 22029 22030 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22031 final String volumeUuid = pkg.volumeUuid; 22032 final String packageName = pkg.packageName; 22033 final ApplicationInfo app = pkg.applicationInfo; 22034 22035 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22036 // Create a native library symlink only if we have native libraries 22037 // and if the native libraries are 32 bit libraries. We do not provide 22038 // this symlink for 64 bit libraries. 22039 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22040 final String nativeLibPath = app.nativeLibraryDir; 22041 try { 22042 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22043 nativeLibPath, userId); 22044 } catch (InstallerException e) { 22045 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22046 } 22047 } 22048 } 22049 } 22050 22051 /** 22052 * For system apps on non-FBE devices, this method migrates any existing 22053 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22054 * requested by the app. 22055 */ 22056 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22057 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22058 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22059 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22060 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22061 try { 22062 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22063 storageTarget); 22064 } catch (InstallerException e) { 22065 logCriticalInfo(Log.WARN, 22066 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22067 } 22068 return true; 22069 } else { 22070 return false; 22071 } 22072 } 22073 22074 public PackageFreezer freezePackage(String packageName, String killReason) { 22075 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22076 } 22077 22078 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22079 return new PackageFreezer(packageName, userId, killReason); 22080 } 22081 22082 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22083 String killReason) { 22084 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22085 } 22086 22087 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22088 String killReason) { 22089 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22090 return new PackageFreezer(); 22091 } else { 22092 return freezePackage(packageName, userId, killReason); 22093 } 22094 } 22095 22096 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22097 String killReason) { 22098 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22099 } 22100 22101 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22102 String killReason) { 22103 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22104 return new PackageFreezer(); 22105 } else { 22106 return freezePackage(packageName, userId, killReason); 22107 } 22108 } 22109 22110 /** 22111 * Class that freezes and kills the given package upon creation, and 22112 * unfreezes it upon closing. This is typically used when doing surgery on 22113 * app code/data to prevent the app from running while you're working. 22114 */ 22115 private class PackageFreezer implements AutoCloseable { 22116 private final String mPackageName; 22117 private final PackageFreezer[] mChildren; 22118 22119 private final boolean mWeFroze; 22120 22121 private final AtomicBoolean mClosed = new AtomicBoolean(); 22122 private final CloseGuard mCloseGuard = CloseGuard.get(); 22123 22124 /** 22125 * Create and return a stub freezer that doesn't actually do anything, 22126 * typically used when someone requested 22127 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22128 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22129 */ 22130 public PackageFreezer() { 22131 mPackageName = null; 22132 mChildren = null; 22133 mWeFroze = false; 22134 mCloseGuard.open("close"); 22135 } 22136 22137 public PackageFreezer(String packageName, int userId, String killReason) { 22138 synchronized (mPackages) { 22139 mPackageName = packageName; 22140 mWeFroze = mFrozenPackages.add(mPackageName); 22141 22142 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22143 if (ps != null) { 22144 killApplication(ps.name, ps.appId, userId, killReason); 22145 } 22146 22147 final PackageParser.Package p = mPackages.get(packageName); 22148 if (p != null && p.childPackages != null) { 22149 final int N = p.childPackages.size(); 22150 mChildren = new PackageFreezer[N]; 22151 for (int i = 0; i < N; i++) { 22152 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22153 userId, killReason); 22154 } 22155 } else { 22156 mChildren = null; 22157 } 22158 } 22159 mCloseGuard.open("close"); 22160 } 22161 22162 @Override 22163 protected void finalize() throws Throwable { 22164 try { 22165 mCloseGuard.warnIfOpen(); 22166 close(); 22167 } finally { 22168 super.finalize(); 22169 } 22170 } 22171 22172 @Override 22173 public void close() { 22174 mCloseGuard.close(); 22175 if (mClosed.compareAndSet(false, true)) { 22176 synchronized (mPackages) { 22177 if (mWeFroze) { 22178 mFrozenPackages.remove(mPackageName); 22179 } 22180 22181 if (mChildren != null) { 22182 for (PackageFreezer freezer : mChildren) { 22183 freezer.close(); 22184 } 22185 } 22186 } 22187 } 22188 } 22189 } 22190 22191 /** 22192 * Verify that given package is currently frozen. 22193 */ 22194 private void checkPackageFrozen(String packageName) { 22195 synchronized (mPackages) { 22196 if (!mFrozenPackages.contains(packageName)) { 22197 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22198 } 22199 } 22200 } 22201 22202 @Override 22203 public int movePackage(final String packageName, final String volumeUuid) { 22204 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22205 22206 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22207 final int moveId = mNextMoveId.getAndIncrement(); 22208 mHandler.post(new Runnable() { 22209 @Override 22210 public void run() { 22211 try { 22212 movePackageInternal(packageName, volumeUuid, moveId, user); 22213 } catch (PackageManagerException e) { 22214 Slog.w(TAG, "Failed to move " + packageName, e); 22215 mMoveCallbacks.notifyStatusChanged(moveId, 22216 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22217 } 22218 } 22219 }); 22220 return moveId; 22221 } 22222 22223 private void movePackageInternal(final String packageName, final String volumeUuid, 22224 final int moveId, UserHandle user) throws PackageManagerException { 22225 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22226 final PackageManager pm = mContext.getPackageManager(); 22227 22228 final boolean currentAsec; 22229 final String currentVolumeUuid; 22230 final File codeFile; 22231 final String installerPackageName; 22232 final String packageAbiOverride; 22233 final int appId; 22234 final String seinfo; 22235 final String label; 22236 final int targetSdkVersion; 22237 final PackageFreezer freezer; 22238 final int[] installedUserIds; 22239 22240 // reader 22241 synchronized (mPackages) { 22242 final PackageParser.Package pkg = mPackages.get(packageName); 22243 final PackageSetting ps = mSettings.mPackages.get(packageName); 22244 if (pkg == null || ps == null) { 22245 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22246 } 22247 22248 if (pkg.applicationInfo.isSystemApp()) { 22249 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22250 "Cannot move system application"); 22251 } 22252 22253 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22254 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22255 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22256 if (isInternalStorage && !allow3rdPartyOnInternal) { 22257 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22258 "3rd party apps are not allowed on internal storage"); 22259 } 22260 22261 if (pkg.applicationInfo.isExternalAsec()) { 22262 currentAsec = true; 22263 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22264 } else if (pkg.applicationInfo.isForwardLocked()) { 22265 currentAsec = true; 22266 currentVolumeUuid = "forward_locked"; 22267 } else { 22268 currentAsec = false; 22269 currentVolumeUuid = ps.volumeUuid; 22270 22271 final File probe = new File(pkg.codePath); 22272 final File probeOat = new File(probe, "oat"); 22273 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22274 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22275 "Move only supported for modern cluster style installs"); 22276 } 22277 } 22278 22279 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22280 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22281 "Package already moved to " + volumeUuid); 22282 } 22283 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22284 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22285 "Device admin cannot be moved"); 22286 } 22287 22288 if (mFrozenPackages.contains(packageName)) { 22289 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22290 "Failed to move already frozen package"); 22291 } 22292 22293 codeFile = new File(pkg.codePath); 22294 installerPackageName = ps.installerPackageName; 22295 packageAbiOverride = ps.cpuAbiOverrideString; 22296 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22297 seinfo = pkg.applicationInfo.seInfo; 22298 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22299 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22300 freezer = freezePackage(packageName, "movePackageInternal"); 22301 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22302 } 22303 22304 final Bundle extras = new Bundle(); 22305 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22306 extras.putString(Intent.EXTRA_TITLE, label); 22307 mMoveCallbacks.notifyCreated(moveId, extras); 22308 22309 int installFlags; 22310 final boolean moveCompleteApp; 22311 final File measurePath; 22312 22313 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22314 installFlags = INSTALL_INTERNAL; 22315 moveCompleteApp = !currentAsec; 22316 measurePath = Environment.getDataAppDirectory(volumeUuid); 22317 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22318 installFlags = INSTALL_EXTERNAL; 22319 moveCompleteApp = false; 22320 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22321 } else { 22322 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22323 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22324 || !volume.isMountedWritable()) { 22325 freezer.close(); 22326 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22327 "Move location not mounted private volume"); 22328 } 22329 22330 Preconditions.checkState(!currentAsec); 22331 22332 installFlags = INSTALL_INTERNAL; 22333 moveCompleteApp = true; 22334 measurePath = Environment.getDataAppDirectory(volumeUuid); 22335 } 22336 22337 final PackageStats stats = new PackageStats(null, -1); 22338 synchronized (mInstaller) { 22339 for (int userId : installedUserIds) { 22340 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22341 freezer.close(); 22342 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22343 "Failed to measure package size"); 22344 } 22345 } 22346 } 22347 22348 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22349 + stats.dataSize); 22350 22351 final long startFreeBytes = measurePath.getUsableSpace(); 22352 final long sizeBytes; 22353 if (moveCompleteApp) { 22354 sizeBytes = stats.codeSize + stats.dataSize; 22355 } else { 22356 sizeBytes = stats.codeSize; 22357 } 22358 22359 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22360 freezer.close(); 22361 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22362 "Not enough free space to move"); 22363 } 22364 22365 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22366 22367 final CountDownLatch installedLatch = new CountDownLatch(1); 22368 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22369 @Override 22370 public void onUserActionRequired(Intent intent) throws RemoteException { 22371 throw new IllegalStateException(); 22372 } 22373 22374 @Override 22375 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22376 Bundle extras) throws RemoteException { 22377 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22378 + PackageManager.installStatusToString(returnCode, msg)); 22379 22380 installedLatch.countDown(); 22381 freezer.close(); 22382 22383 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22384 switch (status) { 22385 case PackageInstaller.STATUS_SUCCESS: 22386 mMoveCallbacks.notifyStatusChanged(moveId, 22387 PackageManager.MOVE_SUCCEEDED); 22388 break; 22389 case PackageInstaller.STATUS_FAILURE_STORAGE: 22390 mMoveCallbacks.notifyStatusChanged(moveId, 22391 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22392 break; 22393 default: 22394 mMoveCallbacks.notifyStatusChanged(moveId, 22395 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22396 break; 22397 } 22398 } 22399 }; 22400 22401 final MoveInfo move; 22402 if (moveCompleteApp) { 22403 // Kick off a thread to report progress estimates 22404 new Thread() { 22405 @Override 22406 public void run() { 22407 while (true) { 22408 try { 22409 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22410 break; 22411 } 22412 } catch (InterruptedException ignored) { 22413 } 22414 22415 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22416 final int progress = 10 + (int) MathUtils.constrain( 22417 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22418 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22419 } 22420 } 22421 }.start(); 22422 22423 final String dataAppName = codeFile.getName(); 22424 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22425 dataAppName, appId, seinfo, targetSdkVersion); 22426 } else { 22427 move = null; 22428 } 22429 22430 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22431 22432 final Message msg = mHandler.obtainMessage(INIT_COPY); 22433 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22434 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22435 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22436 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22437 PackageManager.INSTALL_REASON_UNKNOWN); 22438 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22439 msg.obj = params; 22440 22441 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22442 System.identityHashCode(msg.obj)); 22443 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22444 System.identityHashCode(msg.obj)); 22445 22446 mHandler.sendMessage(msg); 22447 } 22448 22449 @Override 22450 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22451 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22452 22453 final int realMoveId = mNextMoveId.getAndIncrement(); 22454 final Bundle extras = new Bundle(); 22455 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22456 mMoveCallbacks.notifyCreated(realMoveId, extras); 22457 22458 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22459 @Override 22460 public void onCreated(int moveId, Bundle extras) { 22461 // Ignored 22462 } 22463 22464 @Override 22465 public void onStatusChanged(int moveId, int status, long estMillis) { 22466 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22467 } 22468 }; 22469 22470 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22471 storage.setPrimaryStorageUuid(volumeUuid, callback); 22472 return realMoveId; 22473 } 22474 22475 @Override 22476 public int getMoveStatus(int moveId) { 22477 mContext.enforceCallingOrSelfPermission( 22478 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22479 return mMoveCallbacks.mLastStatus.get(moveId); 22480 } 22481 22482 @Override 22483 public void registerMoveCallback(IPackageMoveObserver callback) { 22484 mContext.enforceCallingOrSelfPermission( 22485 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22486 mMoveCallbacks.register(callback); 22487 } 22488 22489 @Override 22490 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22491 mContext.enforceCallingOrSelfPermission( 22492 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22493 mMoveCallbacks.unregister(callback); 22494 } 22495 22496 @Override 22497 public boolean setInstallLocation(int loc) { 22498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22499 null); 22500 if (getInstallLocation() == loc) { 22501 return true; 22502 } 22503 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22504 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22505 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22506 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22507 return true; 22508 } 22509 return false; 22510 } 22511 22512 @Override 22513 public int getInstallLocation() { 22514 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22515 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22516 PackageHelper.APP_INSTALL_AUTO); 22517 } 22518 22519 /** Called by UserManagerService */ 22520 void cleanUpUser(UserManagerService userManager, int userHandle) { 22521 synchronized (mPackages) { 22522 mDirtyUsers.remove(userHandle); 22523 mUserNeedsBadging.delete(userHandle); 22524 mSettings.removeUserLPw(userHandle); 22525 mPendingBroadcasts.remove(userHandle); 22526 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22527 removeUnusedPackagesLPw(userManager, userHandle); 22528 } 22529 } 22530 22531 /** 22532 * We're removing userHandle and would like to remove any downloaded packages 22533 * that are no longer in use by any other user. 22534 * @param userHandle the user being removed 22535 */ 22536 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22537 final boolean DEBUG_CLEAN_APKS = false; 22538 int [] users = userManager.getUserIds(); 22539 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22540 while (psit.hasNext()) { 22541 PackageSetting ps = psit.next(); 22542 if (ps.pkg == null) { 22543 continue; 22544 } 22545 final String packageName = ps.pkg.packageName; 22546 // Skip over if system app 22547 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22548 continue; 22549 } 22550 if (DEBUG_CLEAN_APKS) { 22551 Slog.i(TAG, "Checking package " + packageName); 22552 } 22553 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22554 if (keep) { 22555 if (DEBUG_CLEAN_APKS) { 22556 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22557 } 22558 } else { 22559 for (int i = 0; i < users.length; i++) { 22560 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22561 keep = true; 22562 if (DEBUG_CLEAN_APKS) { 22563 Slog.i(TAG, " Keeping package " + packageName + " for user " 22564 + users[i]); 22565 } 22566 break; 22567 } 22568 } 22569 } 22570 if (!keep) { 22571 if (DEBUG_CLEAN_APKS) { 22572 Slog.i(TAG, " Removing package " + packageName); 22573 } 22574 mHandler.post(new Runnable() { 22575 public void run() { 22576 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22577 userHandle, 0); 22578 } //end run 22579 }); 22580 } 22581 } 22582 } 22583 22584 /** Called by UserManagerService */ 22585 void createNewUser(int userId, String[] disallowedPackages) { 22586 synchronized (mInstallLock) { 22587 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22588 } 22589 synchronized (mPackages) { 22590 scheduleWritePackageRestrictionsLocked(userId); 22591 scheduleWritePackageListLocked(userId); 22592 applyFactoryDefaultBrowserLPw(userId); 22593 primeDomainVerificationsLPw(userId); 22594 } 22595 } 22596 22597 void onNewUserCreated(final int userId) { 22598 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22599 // If permission review for legacy apps is required, we represent 22600 // dagerous permissions for such apps as always granted runtime 22601 // permissions to keep per user flag state whether review is needed. 22602 // Hence, if a new user is added we have to propagate dangerous 22603 // permission grants for these legacy apps. 22604 if (mPermissionReviewRequired) { 22605 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22606 | UPDATE_PERMISSIONS_REPLACE_ALL); 22607 } 22608 } 22609 22610 @Override 22611 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22612 mContext.enforceCallingOrSelfPermission( 22613 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22614 "Only package verification agents can read the verifier device identity"); 22615 22616 synchronized (mPackages) { 22617 return mSettings.getVerifierDeviceIdentityLPw(); 22618 } 22619 } 22620 22621 @Override 22622 public void setPermissionEnforced(String permission, boolean enforced) { 22623 // TODO: Now that we no longer change GID for storage, this should to away. 22624 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22625 "setPermissionEnforced"); 22626 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22627 synchronized (mPackages) { 22628 if (mSettings.mReadExternalStorageEnforced == null 22629 || mSettings.mReadExternalStorageEnforced != enforced) { 22630 mSettings.mReadExternalStorageEnforced = enforced; 22631 mSettings.writeLPr(); 22632 } 22633 } 22634 // kill any non-foreground processes so we restart them and 22635 // grant/revoke the GID. 22636 final IActivityManager am = ActivityManager.getService(); 22637 if (am != null) { 22638 final long token = Binder.clearCallingIdentity(); 22639 try { 22640 am.killProcessesBelowForeground("setPermissionEnforcement"); 22641 } catch (RemoteException e) { 22642 } finally { 22643 Binder.restoreCallingIdentity(token); 22644 } 22645 } 22646 } else { 22647 throw new IllegalArgumentException("No selective enforcement for " + permission); 22648 } 22649 } 22650 22651 @Override 22652 @Deprecated 22653 public boolean isPermissionEnforced(String permission) { 22654 return true; 22655 } 22656 22657 @Override 22658 public boolean isStorageLow() { 22659 final long token = Binder.clearCallingIdentity(); 22660 try { 22661 final DeviceStorageMonitorInternal 22662 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22663 if (dsm != null) { 22664 return dsm.isMemoryLow(); 22665 } else { 22666 return false; 22667 } 22668 } finally { 22669 Binder.restoreCallingIdentity(token); 22670 } 22671 } 22672 22673 @Override 22674 public IPackageInstaller getPackageInstaller() { 22675 return mInstallerService; 22676 } 22677 22678 private boolean userNeedsBadging(int userId) { 22679 int index = mUserNeedsBadging.indexOfKey(userId); 22680 if (index < 0) { 22681 final UserInfo userInfo; 22682 final long token = Binder.clearCallingIdentity(); 22683 try { 22684 userInfo = sUserManager.getUserInfo(userId); 22685 } finally { 22686 Binder.restoreCallingIdentity(token); 22687 } 22688 final boolean b; 22689 if (userInfo != null && userInfo.isManagedProfile()) { 22690 b = true; 22691 } else { 22692 b = false; 22693 } 22694 mUserNeedsBadging.put(userId, b); 22695 return b; 22696 } 22697 return mUserNeedsBadging.valueAt(index); 22698 } 22699 22700 @Override 22701 public KeySet getKeySetByAlias(String packageName, String alias) { 22702 if (packageName == null || alias == null) { 22703 return null; 22704 } 22705 synchronized(mPackages) { 22706 final PackageParser.Package pkg = mPackages.get(packageName); 22707 if (pkg == null) { 22708 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22709 throw new IllegalArgumentException("Unknown package: " + packageName); 22710 } 22711 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22712 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22713 } 22714 } 22715 22716 @Override 22717 public KeySet getSigningKeySet(String packageName) { 22718 if (packageName == null) { 22719 return null; 22720 } 22721 synchronized(mPackages) { 22722 final PackageParser.Package pkg = mPackages.get(packageName); 22723 if (pkg == null) { 22724 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22725 throw new IllegalArgumentException("Unknown package: " + packageName); 22726 } 22727 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22728 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22729 throw new SecurityException("May not access signing KeySet of other apps."); 22730 } 22731 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22732 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22733 } 22734 } 22735 22736 @Override 22737 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22738 if (packageName == null || ks == null) { 22739 return false; 22740 } 22741 synchronized(mPackages) { 22742 final PackageParser.Package pkg = mPackages.get(packageName); 22743 if (pkg == null) { 22744 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22745 throw new IllegalArgumentException("Unknown package: " + packageName); 22746 } 22747 IBinder ksh = ks.getToken(); 22748 if (ksh instanceof KeySetHandle) { 22749 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22750 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22751 } 22752 return false; 22753 } 22754 } 22755 22756 @Override 22757 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22758 if (packageName == null || ks == null) { 22759 return false; 22760 } 22761 synchronized(mPackages) { 22762 final PackageParser.Package pkg = mPackages.get(packageName); 22763 if (pkg == null) { 22764 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22765 throw new IllegalArgumentException("Unknown package: " + packageName); 22766 } 22767 IBinder ksh = ks.getToken(); 22768 if (ksh instanceof KeySetHandle) { 22769 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22770 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22771 } 22772 return false; 22773 } 22774 } 22775 22776 private void deletePackageIfUnusedLPr(final String packageName) { 22777 PackageSetting ps = mSettings.mPackages.get(packageName); 22778 if (ps == null) { 22779 return; 22780 } 22781 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22782 // TODO Implement atomic delete if package is unused 22783 // It is currently possible that the package will be deleted even if it is installed 22784 // after this method returns. 22785 mHandler.post(new Runnable() { 22786 public void run() { 22787 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22788 0, PackageManager.DELETE_ALL_USERS); 22789 } 22790 }); 22791 } 22792 } 22793 22794 /** 22795 * Check and throw if the given before/after packages would be considered a 22796 * downgrade. 22797 */ 22798 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22799 throws PackageManagerException { 22800 if (after.versionCode < before.mVersionCode) { 22801 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22802 "Update version code " + after.versionCode + " is older than current " 22803 + before.mVersionCode); 22804 } else if (after.versionCode == before.mVersionCode) { 22805 if (after.baseRevisionCode < before.baseRevisionCode) { 22806 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22807 "Update base revision code " + after.baseRevisionCode 22808 + " is older than current " + before.baseRevisionCode); 22809 } 22810 22811 if (!ArrayUtils.isEmpty(after.splitNames)) { 22812 for (int i = 0; i < after.splitNames.length; i++) { 22813 final String splitName = after.splitNames[i]; 22814 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22815 if (j != -1) { 22816 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22817 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22818 "Update split " + splitName + " revision code " 22819 + after.splitRevisionCodes[i] + " is older than current " 22820 + before.splitRevisionCodes[j]); 22821 } 22822 } 22823 } 22824 } 22825 } 22826 } 22827 22828 private static class MoveCallbacks extends Handler { 22829 private static final int MSG_CREATED = 1; 22830 private static final int MSG_STATUS_CHANGED = 2; 22831 22832 private final RemoteCallbackList<IPackageMoveObserver> 22833 mCallbacks = new RemoteCallbackList<>(); 22834 22835 private final SparseIntArray mLastStatus = new SparseIntArray(); 22836 22837 public MoveCallbacks(Looper looper) { 22838 super(looper); 22839 } 22840 22841 public void register(IPackageMoveObserver callback) { 22842 mCallbacks.register(callback); 22843 } 22844 22845 public void unregister(IPackageMoveObserver callback) { 22846 mCallbacks.unregister(callback); 22847 } 22848 22849 @Override 22850 public void handleMessage(Message msg) { 22851 final SomeArgs args = (SomeArgs) msg.obj; 22852 final int n = mCallbacks.beginBroadcast(); 22853 for (int i = 0; i < n; i++) { 22854 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22855 try { 22856 invokeCallback(callback, msg.what, args); 22857 } catch (RemoteException ignored) { 22858 } 22859 } 22860 mCallbacks.finishBroadcast(); 22861 args.recycle(); 22862 } 22863 22864 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22865 throws RemoteException { 22866 switch (what) { 22867 case MSG_CREATED: { 22868 callback.onCreated(args.argi1, (Bundle) args.arg2); 22869 break; 22870 } 22871 case MSG_STATUS_CHANGED: { 22872 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22873 break; 22874 } 22875 } 22876 } 22877 22878 private void notifyCreated(int moveId, Bundle extras) { 22879 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22880 22881 final SomeArgs args = SomeArgs.obtain(); 22882 args.argi1 = moveId; 22883 args.arg2 = extras; 22884 obtainMessage(MSG_CREATED, args).sendToTarget(); 22885 } 22886 22887 private void notifyStatusChanged(int moveId, int status) { 22888 notifyStatusChanged(moveId, status, -1); 22889 } 22890 22891 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22892 Slog.v(TAG, "Move " + moveId + " status " + status); 22893 22894 final SomeArgs args = SomeArgs.obtain(); 22895 args.argi1 = moveId; 22896 args.argi2 = status; 22897 args.arg3 = estMillis; 22898 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22899 22900 synchronized (mLastStatus) { 22901 mLastStatus.put(moveId, status); 22902 } 22903 } 22904 } 22905 22906 private final static class OnPermissionChangeListeners extends Handler { 22907 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22908 22909 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22910 new RemoteCallbackList<>(); 22911 22912 public OnPermissionChangeListeners(Looper looper) { 22913 super(looper); 22914 } 22915 22916 @Override 22917 public void handleMessage(Message msg) { 22918 switch (msg.what) { 22919 case MSG_ON_PERMISSIONS_CHANGED: { 22920 final int uid = msg.arg1; 22921 handleOnPermissionsChanged(uid); 22922 } break; 22923 } 22924 } 22925 22926 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22927 mPermissionListeners.register(listener); 22928 22929 } 22930 22931 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22932 mPermissionListeners.unregister(listener); 22933 } 22934 22935 public void onPermissionsChanged(int uid) { 22936 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22937 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22938 } 22939 } 22940 22941 private void handleOnPermissionsChanged(int uid) { 22942 final int count = mPermissionListeners.beginBroadcast(); 22943 try { 22944 for (int i = 0; i < count; i++) { 22945 IOnPermissionsChangeListener callback = mPermissionListeners 22946 .getBroadcastItem(i); 22947 try { 22948 callback.onPermissionsChanged(uid); 22949 } catch (RemoteException e) { 22950 Log.e(TAG, "Permission listener is dead", e); 22951 } 22952 } 22953 } finally { 22954 mPermissionListeners.finishBroadcast(); 22955 } 22956 } 22957 } 22958 22959 private class PackageManagerInternalImpl extends PackageManagerInternal { 22960 @Override 22961 public void setLocationPackagesProvider(PackagesProvider provider) { 22962 synchronized (mPackages) { 22963 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22964 } 22965 } 22966 22967 @Override 22968 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22969 synchronized (mPackages) { 22970 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22971 } 22972 } 22973 22974 @Override 22975 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22976 synchronized (mPackages) { 22977 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22978 } 22979 } 22980 22981 @Override 22982 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22983 synchronized (mPackages) { 22984 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22985 } 22986 } 22987 22988 @Override 22989 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22990 synchronized (mPackages) { 22991 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22992 } 22993 } 22994 22995 @Override 22996 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22997 synchronized (mPackages) { 22998 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22999 } 23000 } 23001 23002 @Override 23003 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23004 synchronized (mPackages) { 23005 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23006 packageName, userId); 23007 } 23008 } 23009 23010 @Override 23011 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23012 synchronized (mPackages) { 23013 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23014 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23015 packageName, userId); 23016 } 23017 } 23018 23019 @Override 23020 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23021 synchronized (mPackages) { 23022 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23023 packageName, userId); 23024 } 23025 } 23026 23027 @Override 23028 public void setKeepUninstalledPackages(final List<String> packageList) { 23029 Preconditions.checkNotNull(packageList); 23030 List<String> removedFromList = null; 23031 synchronized (mPackages) { 23032 if (mKeepUninstalledPackages != null) { 23033 final int packagesCount = mKeepUninstalledPackages.size(); 23034 for (int i = 0; i < packagesCount; i++) { 23035 String oldPackage = mKeepUninstalledPackages.get(i); 23036 if (packageList != null && packageList.contains(oldPackage)) { 23037 continue; 23038 } 23039 if (removedFromList == null) { 23040 removedFromList = new ArrayList<>(); 23041 } 23042 removedFromList.add(oldPackage); 23043 } 23044 } 23045 mKeepUninstalledPackages = new ArrayList<>(packageList); 23046 if (removedFromList != null) { 23047 final int removedCount = removedFromList.size(); 23048 for (int i = 0; i < removedCount; i++) { 23049 deletePackageIfUnusedLPr(removedFromList.get(i)); 23050 } 23051 } 23052 } 23053 } 23054 23055 @Override 23056 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23057 synchronized (mPackages) { 23058 // If we do not support permission review, done. 23059 if (!mPermissionReviewRequired) { 23060 return false; 23061 } 23062 23063 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23064 if (packageSetting == null) { 23065 return false; 23066 } 23067 23068 // Permission review applies only to apps not supporting the new permission model. 23069 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23070 return false; 23071 } 23072 23073 // Legacy apps have the permission and get user consent on launch. 23074 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23075 return permissionsState.isPermissionReviewRequired(userId); 23076 } 23077 } 23078 23079 @Override 23080 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23081 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23082 } 23083 23084 @Override 23085 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23086 int userId) { 23087 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23088 } 23089 23090 @Override 23091 public void setDeviceAndProfileOwnerPackages( 23092 int deviceOwnerUserId, String deviceOwnerPackage, 23093 SparseArray<String> profileOwnerPackages) { 23094 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23095 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23096 } 23097 23098 @Override 23099 public boolean isPackageDataProtected(int userId, String packageName) { 23100 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23101 } 23102 23103 @Override 23104 public boolean isPackageEphemeral(int userId, String packageName) { 23105 synchronized (mPackages) { 23106 final PackageSetting ps = mSettings.mPackages.get(packageName); 23107 return ps != null ? ps.getInstantApp(userId) : false; 23108 } 23109 } 23110 23111 @Override 23112 public boolean wasPackageEverLaunched(String packageName, int userId) { 23113 synchronized (mPackages) { 23114 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23115 } 23116 } 23117 23118 @Override 23119 public void grantRuntimePermission(String packageName, String name, int userId, 23120 boolean overridePolicy) { 23121 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23122 overridePolicy); 23123 } 23124 23125 @Override 23126 public void revokeRuntimePermission(String packageName, String name, int userId, 23127 boolean overridePolicy) { 23128 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23129 overridePolicy); 23130 } 23131 23132 @Override 23133 public String getNameForUid(int uid) { 23134 return PackageManagerService.this.getNameForUid(uid); 23135 } 23136 23137 @Override 23138 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23139 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23140 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23141 responseObj, origIntent, resolvedType, callingPackage, userId); 23142 } 23143 23144 @Override 23145 public void grantEphemeralAccess(int userId, Intent intent, 23146 int targetAppId, int ephemeralAppId) { 23147 synchronized (mPackages) { 23148 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23149 targetAppId, ephemeralAppId); 23150 } 23151 } 23152 23153 @Override 23154 public boolean isInstantAppInstallerComponent(ComponentName component) { 23155 synchronized (mPackages) { 23156 return component != null && component.equals(mInstantAppInstallerComponent); 23157 } 23158 } 23159 23160 @Override 23161 public void pruneInstantApps() { 23162 synchronized (mPackages) { 23163 mInstantAppRegistry.pruneInstantAppsLPw(); 23164 } 23165 } 23166 23167 @Override 23168 public String getSetupWizardPackageName() { 23169 return mSetupWizardPackage; 23170 } 23171 23172 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23173 if (policy != null) { 23174 mExternalSourcesPolicy = policy; 23175 } 23176 } 23177 23178 @Override 23179 public boolean isPackagePersistent(String packageName) { 23180 synchronized (mPackages) { 23181 PackageParser.Package pkg = mPackages.get(packageName); 23182 return pkg != null 23183 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23184 | ApplicationInfo.FLAG_PERSISTENT)) == 23185 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23186 : false; 23187 } 23188 } 23189 23190 @Override 23191 public List<PackageInfo> getOverlayPackages(int userId) { 23192 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23193 synchronized (mPackages) { 23194 for (PackageParser.Package p : mPackages.values()) { 23195 if (p.mOverlayTarget != null) { 23196 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23197 if (pkg != null) { 23198 overlayPackages.add(pkg); 23199 } 23200 } 23201 } 23202 } 23203 return overlayPackages; 23204 } 23205 23206 @Override 23207 public List<String> getTargetPackageNames(int userId) { 23208 List<String> targetPackages = new ArrayList<>(); 23209 synchronized (mPackages) { 23210 for (PackageParser.Package p : mPackages.values()) { 23211 if (p.mOverlayTarget == null) { 23212 targetPackages.add(p.packageName); 23213 } 23214 } 23215 } 23216 return targetPackages; 23217 } 23218 23219 @Override 23220 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23221 @Nullable List<String> overlayPackageNames) { 23222 synchronized (mPackages) { 23223 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23224 Slog.e(TAG, "failed to find package " + targetPackageName); 23225 return false; 23226 } 23227 23228 ArrayList<String> paths = null; 23229 if (overlayPackageNames != null) { 23230 final int N = overlayPackageNames.size(); 23231 paths = new ArrayList<>(N); 23232 for (int i = 0; i < N; i++) { 23233 final String packageName = overlayPackageNames.get(i); 23234 final PackageParser.Package pkg = mPackages.get(packageName); 23235 if (pkg == null) { 23236 Slog.e(TAG, "failed to find package " + packageName); 23237 return false; 23238 } 23239 paths.add(pkg.baseCodePath); 23240 } 23241 } 23242 23243 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23244 mEnabledOverlayPaths.get(userId); 23245 if (userSpecificOverlays == null) { 23246 userSpecificOverlays = new ArrayMap<>(); 23247 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23248 } 23249 23250 if (paths != null && paths.size() > 0) { 23251 userSpecificOverlays.put(targetPackageName, paths); 23252 } else { 23253 userSpecificOverlays.remove(targetPackageName); 23254 } 23255 return true; 23256 } 23257 } 23258 23259 @Override 23260 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23261 int flags, int userId) { 23262 return resolveIntentInternal( 23263 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23264 } 23265 23266 @Override 23267 public ResolveInfo resolveService(Intent intent, String resolvedType, 23268 int flags, int userId, int callingUid) { 23269 return resolveServiceInternal( 23270 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23271 } 23272 23273 23274 @Override 23275 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23276 synchronized (mPackages) { 23277 mIsolatedOwners.put(isolatedUid, ownerUid); 23278 } 23279 } 23280 23281 @Override 23282 public void removeIsolatedUid(int isolatedUid) { 23283 synchronized (mPackages) { 23284 mIsolatedOwners.delete(isolatedUid); 23285 } 23286 } 23287 } 23288 23289 @Override 23290 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23291 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23292 synchronized (mPackages) { 23293 final long identity = Binder.clearCallingIdentity(); 23294 try { 23295 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23296 packageNames, userId); 23297 } finally { 23298 Binder.restoreCallingIdentity(identity); 23299 } 23300 } 23301 } 23302 23303 @Override 23304 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23305 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23306 synchronized (mPackages) { 23307 final long identity = Binder.clearCallingIdentity(); 23308 try { 23309 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23310 packageNames, userId); 23311 } finally { 23312 Binder.restoreCallingIdentity(identity); 23313 } 23314 } 23315 } 23316 23317 private static void enforceSystemOrPhoneCaller(String tag) { 23318 int callingUid = Binder.getCallingUid(); 23319 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23320 throw new SecurityException( 23321 "Cannot call " + tag + " from UID " + callingUid); 23322 } 23323 } 23324 23325 boolean isHistoricalPackageUsageAvailable() { 23326 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23327 } 23328 23329 /** 23330 * Return a <b>copy</b> of the collection of packages known to the package manager. 23331 * @return A copy of the values of mPackages. 23332 */ 23333 Collection<PackageParser.Package> getPackages() { 23334 synchronized (mPackages) { 23335 return new ArrayList<>(mPackages.values()); 23336 } 23337 } 23338 23339 /** 23340 * Logs process start information (including base APK hash) to the security log. 23341 * @hide 23342 */ 23343 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23344 String apkFile, int pid) { 23345 if (!SecurityLog.isLoggingEnabled()) { 23346 return; 23347 } 23348 Bundle data = new Bundle(); 23349 data.putLong("startTimestamp", System.currentTimeMillis()); 23350 data.putString("processName", processName); 23351 data.putInt("uid", uid); 23352 data.putString("seinfo", seinfo); 23353 data.putString("apkFile", apkFile); 23354 data.putInt("pid", pid); 23355 Message msg = mProcessLoggingHandler.obtainMessage( 23356 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23357 msg.setData(data); 23358 mProcessLoggingHandler.sendMessage(msg); 23359 } 23360 23361 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23362 return mCompilerStats.getPackageStats(pkgName); 23363 } 23364 23365 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23366 return getOrCreateCompilerPackageStats(pkg.packageName); 23367 } 23368 23369 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23370 return mCompilerStats.getOrCreatePackageStats(pkgName); 23371 } 23372 23373 public void deleteCompilerPackageStats(String pkgName) { 23374 mCompilerStats.deletePackageStats(pkgName); 23375 } 23376 23377 @Override 23378 public int getInstallReason(String packageName, int userId) { 23379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23380 true /* requireFullPermission */, false /* checkShell */, 23381 "get install reason"); 23382 synchronized (mPackages) { 23383 final PackageSetting ps = mSettings.mPackages.get(packageName); 23384 if (ps != null) { 23385 return ps.getInstallReason(userId); 23386 } 23387 } 23388 return PackageManager.INSTALL_REASON_UNKNOWN; 23389 } 23390 23391 @Override 23392 public boolean canRequestPackageInstalls(String packageName, int userId) { 23393 int callingUid = Binder.getCallingUid(); 23394 int uid = getPackageUid(packageName, 0, userId); 23395 if (callingUid != uid && callingUid != Process.ROOT_UID 23396 && callingUid != Process.SYSTEM_UID) { 23397 throw new SecurityException( 23398 "Caller uid " + callingUid + " does not own package " + packageName); 23399 } 23400 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23401 if (info == null) { 23402 return false; 23403 } 23404 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23405 throw new UnsupportedOperationException( 23406 "Operation only supported on apps targeting Android O or higher"); 23407 } 23408 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23409 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23410 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23411 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23412 } 23413 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23414 return false; 23415 } 23416 if (mExternalSourcesPolicy != null) { 23417 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23418 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23419 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23420 } 23421 } 23422 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23423 } 23424 23425 @Override 23426 public ComponentName getInstantAppResolverSettingsComponent() { 23427 return mInstantAppResolverSettingsComponent; 23428 } 23429} 23430