PackageManagerService.java revision 72bb1c61c57705df3b3ea7626ef408126d0817f1
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_NUMBERS, 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 // Have we told the Activity Manager to whitelist the default container service by uid yet? 612 @GuardedBy("mPackages") 613 boolean mDefaultContainerWhitelisted = false; 614 615 @GuardedBy("mPackages") 616 private boolean mDexOptDialogShown; 617 618 /** The location for ASEC container files on internal storage. */ 619 final String mAsecInternalPath; 620 621 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 622 // LOCK HELD. Can be called with mInstallLock held. 623 @GuardedBy("mInstallLock") 624 final Installer mInstaller; 625 626 /** Directory where installed third-party apps stored */ 627 final File mAppInstallDir; 628 629 /** 630 * Directory to which applications installed internally have their 631 * 32 bit native libraries copied. 632 */ 633 private File mAppLib32InstallDir; 634 635 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 636 // apps. 637 final File mDrmAppPrivateInstallDir; 638 639 // ---------------------------------------------------------------- 640 641 // Lock for state used when installing and doing other long running 642 // operations. Methods that must be called with this lock held have 643 // the suffix "LI". 644 final Object mInstallLock = new Object(); 645 646 // ---------------------------------------------------------------- 647 648 // Keys are String (package name), values are Package. This also serves 649 // as the lock for the global state. Methods that must be called with 650 // this lock held have the prefix "LP". 651 @GuardedBy("mPackages") 652 final ArrayMap<String, PackageParser.Package> mPackages = 653 new ArrayMap<String, PackageParser.Package>(); 654 655 final ArrayMap<String, Set<String>> mKnownCodebase = 656 new ArrayMap<String, Set<String>>(); 657 658 // Keys are isolated uids and values are the uid of the application 659 // that created the isolated proccess. 660 @GuardedBy("mPackages") 661 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 662 663 // List of APK paths to load for each user and package. This data is never 664 // persisted by the package manager. Instead, the overlay manager will 665 // ensure the data is up-to-date in runtime. 666 @GuardedBy("mPackages") 667 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 668 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 669 670 /** 671 * Tracks new system packages [received in an OTA] that we expect to 672 * find updated user-installed versions. Keys are package name, values 673 * are package location. 674 */ 675 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 676 /** 677 * Tracks high priority intent filters for protected actions. During boot, certain 678 * filter actions are protected and should never be allowed to have a high priority 679 * intent filter for them. However, there is one, and only one exception -- the 680 * setup wizard. It must be able to define a high priority intent filter for these 681 * actions to ensure there are no escapes from the wizard. We need to delay processing 682 * of these during boot as we need to look at all of the system packages in order 683 * to know which component is the setup wizard. 684 */ 685 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 686 /** 687 * Whether or not processing protected filters should be deferred. 688 */ 689 private boolean mDeferProtectedFilters = true; 690 691 /** 692 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 693 */ 694 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 695 /** 696 * Whether or not system app permissions should be promoted from install to runtime. 697 */ 698 boolean mPromoteSystemApps; 699 700 @GuardedBy("mPackages") 701 final Settings mSettings; 702 703 /** 704 * Set of package names that are currently "frozen", which means active 705 * surgery is being done on the code/data for that package. The platform 706 * will refuse to launch frozen packages to avoid race conditions. 707 * 708 * @see PackageFreezer 709 */ 710 @GuardedBy("mPackages") 711 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 712 713 final ProtectedPackages mProtectedPackages; 714 715 boolean mFirstBoot; 716 717 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 718 719 // System configuration read by SystemConfig. 720 final int[] mGlobalGids; 721 final SparseArray<ArraySet<String>> mSystemPermissions; 722 @GuardedBy("mAvailableFeatures") 723 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 724 725 // If mac_permissions.xml was found for seinfo labeling. 726 boolean mFoundPolicyFile; 727 728 private final InstantAppRegistry mInstantAppRegistry; 729 730 @GuardedBy("mPackages") 731 int mChangedPackagesSequenceNumber; 732 /** 733 * List of changed [installed, removed or updated] packages. 734 * mapping from user id -> sequence number -> package name 735 */ 736 @GuardedBy("mPackages") 737 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 738 /** 739 * The sequence number of the last change to a package. 740 * mapping from user id -> package name -> sequence number 741 */ 742 @GuardedBy("mPackages") 743 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 744 745 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 746 @Override public boolean hasFeature(String feature) { 747 return PackageManagerService.this.hasSystemFeature(feature, 0); 748 } 749 }; 750 751 public static final class SharedLibraryEntry { 752 public final String path; 753 public final String apk; 754 public final SharedLibraryInfo info; 755 756 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 757 String declaringPackageName, int declaringPackageVersionCode) { 758 path = _path; 759 apk = _apk; 760 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 761 declaringPackageName, declaringPackageVersionCode), null); 762 } 763 } 764 765 // Currently known shared libraries. 766 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 767 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 768 new ArrayMap<>(); 769 770 // All available activities, for your resolving pleasure. 771 final ActivityIntentResolver mActivities = 772 new ActivityIntentResolver(); 773 774 // All available receivers, for your resolving pleasure. 775 final ActivityIntentResolver mReceivers = 776 new ActivityIntentResolver(); 777 778 // All available services, for your resolving pleasure. 779 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 780 781 // All available providers, for your resolving pleasure. 782 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 783 784 // Mapping from provider base names (first directory in content URI codePath) 785 // to the provider information. 786 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 787 new ArrayMap<String, PackageParser.Provider>(); 788 789 // Mapping from instrumentation class names to info about them. 790 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 791 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 792 793 // Mapping from permission names to info about them. 794 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 795 new ArrayMap<String, PackageParser.PermissionGroup>(); 796 797 // Packages whose data we have transfered into another package, thus 798 // should no longer exist. 799 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 800 801 // Broadcast actions that are only available to the system. 802 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 803 804 /** List of packages waiting for verification. */ 805 final SparseArray<PackageVerificationState> mPendingVerification 806 = new SparseArray<PackageVerificationState>(); 807 808 /** Set of packages associated with each app op permission. */ 809 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 810 811 final PackageInstallerService mInstallerService; 812 813 private final PackageDexOptimizer mPackageDexOptimizer; 814 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 815 // is used by other apps). 816 private final DexManager mDexManager; 817 818 private AtomicInteger mNextMoveId = new AtomicInteger(); 819 private final MoveCallbacks mMoveCallbacks; 820 821 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 822 823 // Cache of users who need badging. 824 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 825 826 /** Token for keys in mPendingVerification. */ 827 private int mPendingVerificationToken = 0; 828 829 volatile boolean mSystemReady; 830 volatile boolean mSafeMode; 831 volatile boolean mHasSystemUidErrors; 832 833 ApplicationInfo mAndroidApplication; 834 final ActivityInfo mResolveActivity = new ActivityInfo(); 835 final ResolveInfo mResolveInfo = new ResolveInfo(); 836 ComponentName mResolveComponentName; 837 PackageParser.Package mPlatformPackage; 838 ComponentName mCustomResolverComponentName; 839 840 boolean mResolverReplaced = false; 841 842 private final @Nullable ComponentName mIntentFilterVerifierComponent; 843 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 844 845 private int mIntentFilterVerificationToken = 0; 846 847 /** The service connection to the ephemeral resolver */ 848 final EphemeralResolverConnection mInstantAppResolverConnection; 849 /** Component used to show resolver settings for Instant Apps */ 850 final ComponentName mInstantAppResolverSettingsComponent; 851 852 /** Component used to install ephemeral applications */ 853 ComponentName mInstantAppInstallerComponent; 854 ActivityInfo mInstantAppInstallerActivity; 855 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 856 857 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 858 = new SparseArray<IntentFilterVerificationState>(); 859 860 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 861 862 // List of packages names to keep cached, even if they are uninstalled for all users 863 private List<String> mKeepUninstalledPackages; 864 865 private UserManagerInternal mUserManagerInternal; 866 867 private DeviceIdleController.LocalService mDeviceIdleController; 868 869 private File mCacheDir; 870 871 private ArraySet<String> mPrivappPermissionsViolations; 872 873 private Future<?> mPrepareAppDataFuture; 874 875 private static class IFVerificationParams { 876 PackageParser.Package pkg; 877 boolean replacing; 878 int userId; 879 int verifierUid; 880 881 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 882 int _userId, int _verifierUid) { 883 pkg = _pkg; 884 replacing = _replacing; 885 userId = _userId; 886 replacing = _replacing; 887 verifierUid = _verifierUid; 888 } 889 } 890 891 private interface IntentFilterVerifier<T extends IntentFilter> { 892 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 893 T filter, String packageName); 894 void startVerifications(int userId); 895 void receiveVerificationResponse(int verificationId); 896 } 897 898 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 899 private Context mContext; 900 private ComponentName mIntentFilterVerifierComponent; 901 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 902 903 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 904 mContext = context; 905 mIntentFilterVerifierComponent = verifierComponent; 906 } 907 908 private String getDefaultScheme() { 909 return IntentFilter.SCHEME_HTTPS; 910 } 911 912 @Override 913 public void startVerifications(int userId) { 914 // Launch verifications requests 915 int count = mCurrentIntentFilterVerifications.size(); 916 for (int n=0; n<count; n++) { 917 int verificationId = mCurrentIntentFilterVerifications.get(n); 918 final IntentFilterVerificationState ivs = 919 mIntentFilterVerificationStates.get(verificationId); 920 921 String packageName = ivs.getPackageName(); 922 923 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 924 final int filterCount = filters.size(); 925 ArraySet<String> domainsSet = new ArraySet<>(); 926 for (int m=0; m<filterCount; m++) { 927 PackageParser.ActivityIntentInfo filter = filters.get(m); 928 domainsSet.addAll(filter.getHostsList()); 929 } 930 synchronized (mPackages) { 931 if (mSettings.createIntentFilterVerificationIfNeededLPw( 932 packageName, domainsSet) != null) { 933 scheduleWriteSettingsLocked(); 934 } 935 } 936 sendVerificationRequest(userId, verificationId, ivs); 937 } 938 mCurrentIntentFilterVerifications.clear(); 939 } 940 941 private void sendVerificationRequest(int userId, int verificationId, 942 IntentFilterVerificationState ivs) { 943 944 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 945 verificationIntent.putExtra( 946 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 947 verificationId); 948 verificationIntent.putExtra( 949 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 950 getDefaultScheme()); 951 verificationIntent.putExtra( 952 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 953 ivs.getHostsString()); 954 verificationIntent.putExtra( 955 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 956 ivs.getPackageName()); 957 verificationIntent.setComponent(mIntentFilterVerifierComponent); 958 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 959 960 UserHandle user = new UserHandle(userId); 961 mContext.sendBroadcastAsUser(verificationIntent, user); 962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 963 "Sending IntentFilter verification broadcast"); 964 } 965 966 public void receiveVerificationResponse(int verificationId) { 967 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 968 969 final boolean verified = ivs.isVerified(); 970 971 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 972 final int count = filters.size(); 973 if (DEBUG_DOMAIN_VERIFICATION) { 974 Slog.i(TAG, "Received verification response " + verificationId 975 + " for " + count + " filters, verified=" + verified); 976 } 977 for (int n=0; n<count; n++) { 978 PackageParser.ActivityIntentInfo filter = filters.get(n); 979 filter.setVerified(verified); 980 981 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 982 + " verified with result:" + verified + " and hosts:" 983 + ivs.getHostsString()); 984 } 985 986 mIntentFilterVerificationStates.remove(verificationId); 987 988 final String packageName = ivs.getPackageName(); 989 IntentFilterVerificationInfo ivi = null; 990 991 synchronized (mPackages) { 992 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 993 } 994 if (ivi == null) { 995 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 996 + verificationId + " packageName:" + packageName); 997 return; 998 } 999 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1000 "Updating IntentFilterVerificationInfo for package " + packageName 1001 +" verificationId:" + verificationId); 1002 1003 synchronized (mPackages) { 1004 if (verified) { 1005 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1006 } else { 1007 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1008 } 1009 scheduleWriteSettingsLocked(); 1010 1011 final int userId = ivs.getUserId(); 1012 if (userId != UserHandle.USER_ALL) { 1013 final int userStatus = 1014 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1015 1016 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1017 boolean needUpdate = false; 1018 1019 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1020 // already been set by the User thru the Disambiguation dialog 1021 switch (userStatus) { 1022 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1023 if (verified) { 1024 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1025 } else { 1026 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1027 } 1028 needUpdate = true; 1029 break; 1030 1031 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1032 if (verified) { 1033 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1034 needUpdate = true; 1035 } 1036 break; 1037 1038 default: 1039 // Nothing to do 1040 } 1041 1042 if (needUpdate) { 1043 mSettings.updateIntentFilterVerificationStatusLPw( 1044 packageName, updatedStatus, userId); 1045 scheduleWritePackageRestrictionsLocked(userId); 1046 } 1047 } 1048 } 1049 } 1050 1051 @Override 1052 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1053 ActivityIntentInfo filter, String packageName) { 1054 if (!hasValidDomains(filter)) { 1055 return false; 1056 } 1057 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1058 if (ivs == null) { 1059 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1060 packageName); 1061 } 1062 if (DEBUG_DOMAIN_VERIFICATION) { 1063 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1064 } 1065 ivs.addFilter(filter); 1066 return true; 1067 } 1068 1069 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1070 int userId, int verificationId, String packageName) { 1071 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1072 verifierUid, userId, packageName); 1073 ivs.setPendingState(); 1074 synchronized (mPackages) { 1075 mIntentFilterVerificationStates.append(verificationId, ivs); 1076 mCurrentIntentFilterVerifications.add(verificationId); 1077 } 1078 return ivs; 1079 } 1080 } 1081 1082 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1083 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1084 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1085 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1086 } 1087 1088 // Set of pending broadcasts for aggregating enable/disable of components. 1089 static class PendingPackageBroadcasts { 1090 // for each user id, a map of <package name -> components within that package> 1091 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1092 1093 public PendingPackageBroadcasts() { 1094 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1095 } 1096 1097 public ArrayList<String> get(int userId, String packageName) { 1098 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1099 return packages.get(packageName); 1100 } 1101 1102 public void put(int userId, String packageName, ArrayList<String> components) { 1103 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1104 packages.put(packageName, components); 1105 } 1106 1107 public void remove(int userId, String packageName) { 1108 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1109 if (packages != null) { 1110 packages.remove(packageName); 1111 } 1112 } 1113 1114 public void remove(int userId) { 1115 mUidMap.remove(userId); 1116 } 1117 1118 public int userIdCount() { 1119 return mUidMap.size(); 1120 } 1121 1122 public int userIdAt(int n) { 1123 return mUidMap.keyAt(n); 1124 } 1125 1126 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1127 return mUidMap.get(userId); 1128 } 1129 1130 public int size() { 1131 // total number of pending broadcast entries across all userIds 1132 int num = 0; 1133 for (int i = 0; i< mUidMap.size(); i++) { 1134 num += mUidMap.valueAt(i).size(); 1135 } 1136 return num; 1137 } 1138 1139 public void clear() { 1140 mUidMap.clear(); 1141 } 1142 1143 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1144 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1145 if (map == null) { 1146 map = new ArrayMap<String, ArrayList<String>>(); 1147 mUidMap.put(userId, map); 1148 } 1149 return map; 1150 } 1151 } 1152 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1153 1154 // Service Connection to remote media container service to copy 1155 // package uri's from external media onto secure containers 1156 // or internal storage. 1157 private IMediaContainerService mContainerService = null; 1158 1159 static final int SEND_PENDING_BROADCAST = 1; 1160 static final int MCS_BOUND = 3; 1161 static final int END_COPY = 4; 1162 static final int INIT_COPY = 5; 1163 static final int MCS_UNBIND = 6; 1164 static final int START_CLEANING_PACKAGE = 7; 1165 static final int FIND_INSTALL_LOC = 8; 1166 static final int POST_INSTALL = 9; 1167 static final int MCS_RECONNECT = 10; 1168 static final int MCS_GIVE_UP = 11; 1169 static final int UPDATED_MEDIA_STATUS = 12; 1170 static final int WRITE_SETTINGS = 13; 1171 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1172 static final int PACKAGE_VERIFIED = 15; 1173 static final int CHECK_PENDING_VERIFICATION = 16; 1174 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1175 static final int INTENT_FILTER_VERIFIED = 18; 1176 static final int WRITE_PACKAGE_LIST = 19; 1177 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1178 1179 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1180 1181 // Delay time in millisecs 1182 static final int BROADCAST_DELAY = 10 * 1000; 1183 1184 static UserManagerService sUserManager; 1185 1186 // Stores a list of users whose package restrictions file needs to be updated 1187 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1188 1189 final private DefaultContainerConnection mDefContainerConn = 1190 new DefaultContainerConnection(); 1191 class DefaultContainerConnection implements ServiceConnection { 1192 public void onServiceConnected(ComponentName name, IBinder service) { 1193 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1194 final IMediaContainerService imcs = IMediaContainerService.Stub 1195 .asInterface(Binder.allowBlocking(service)); 1196 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1197 } 1198 1199 public void onServiceDisconnected(ComponentName name) { 1200 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1201 } 1202 } 1203 1204 // Recordkeeping of restore-after-install operations that are currently in flight 1205 // between the Package Manager and the Backup Manager 1206 static class PostInstallData { 1207 public InstallArgs args; 1208 public PackageInstalledInfo res; 1209 1210 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1211 args = _a; 1212 res = _r; 1213 } 1214 } 1215 1216 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1217 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1218 1219 // XML tags for backup/restore of various bits of state 1220 private static final String TAG_PREFERRED_BACKUP = "pa"; 1221 private static final String TAG_DEFAULT_APPS = "da"; 1222 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1223 1224 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1225 private static final String TAG_ALL_GRANTS = "rt-grants"; 1226 private static final String TAG_GRANT = "grant"; 1227 private static final String ATTR_PACKAGE_NAME = "pkg"; 1228 1229 private static final String TAG_PERMISSION = "perm"; 1230 private static final String ATTR_PERMISSION_NAME = "name"; 1231 private static final String ATTR_IS_GRANTED = "g"; 1232 private static final String ATTR_USER_SET = "set"; 1233 private static final String ATTR_USER_FIXED = "fixed"; 1234 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1235 1236 // System/policy permission grants are not backed up 1237 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1238 FLAG_PERMISSION_POLICY_FIXED 1239 | FLAG_PERMISSION_SYSTEM_FIXED 1240 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1241 1242 // And we back up these user-adjusted states 1243 private static final int USER_RUNTIME_GRANT_MASK = 1244 FLAG_PERMISSION_USER_SET 1245 | FLAG_PERMISSION_USER_FIXED 1246 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1247 1248 final @Nullable String mRequiredVerifierPackage; 1249 final @NonNull String mRequiredInstallerPackage; 1250 final @NonNull String mRequiredUninstallerPackage; 1251 final @Nullable String mSetupWizardPackage; 1252 final @Nullable String mStorageManagerPackage; 1253 final @NonNull String mServicesSystemSharedLibraryPackageName; 1254 final @NonNull String mSharedSystemSharedLibraryPackageName; 1255 1256 final boolean mPermissionReviewRequired; 1257 1258 private final PackageUsage mPackageUsage = new PackageUsage(); 1259 private final CompilerStats mCompilerStats = new CompilerStats(); 1260 1261 class PackageHandler extends Handler { 1262 private boolean mBound = false; 1263 final ArrayList<HandlerParams> mPendingInstalls = 1264 new ArrayList<HandlerParams>(); 1265 1266 private boolean connectToService() { 1267 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1268 " DefaultContainerService"); 1269 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1272 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 mBound = true; 1275 return true; 1276 } 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1278 return false; 1279 } 1280 1281 private void disconnectService() { 1282 mContainerService = null; 1283 mBound = false; 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1285 mContext.unbindService(mDefContainerConn); 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1287 } 1288 1289 PackageHandler(Looper looper) { 1290 super(looper); 1291 } 1292 1293 public void handleMessage(Message msg) { 1294 try { 1295 doHandleMessage(msg); 1296 } finally { 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1298 } 1299 } 1300 1301 void doHandleMessage(Message msg) { 1302 switch (msg.what) { 1303 case INIT_COPY: { 1304 HandlerParams params = (HandlerParams) msg.obj; 1305 int idx = mPendingInstalls.size(); 1306 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1307 // If a bind was already initiated we dont really 1308 // need to do anything. The pending install 1309 // will be processed later on. 1310 if (!mBound) { 1311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1312 System.identityHashCode(mHandler)); 1313 // If this is the only one pending we might 1314 // have to bind to the service again. 1315 if (!connectToService()) { 1316 Slog.e(TAG, "Failed to bind to media container service"); 1317 params.serviceError(); 1318 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1319 System.identityHashCode(mHandler)); 1320 if (params.traceMethod != null) { 1321 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1322 params.traceCookie); 1323 } 1324 return; 1325 } else { 1326 // Once we bind to the service, the first 1327 // pending request will be processed. 1328 mPendingInstalls.add(idx, params); 1329 } 1330 } else { 1331 mPendingInstalls.add(idx, params); 1332 // Already bound to the service. Just make 1333 // sure we trigger off processing the first request. 1334 if (idx == 0) { 1335 mHandler.sendEmptyMessage(MCS_BOUND); 1336 } 1337 } 1338 break; 1339 } 1340 case MCS_BOUND: { 1341 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1342 if (msg.obj != null) { 1343 mContainerService = (IMediaContainerService) msg.obj; 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1345 System.identityHashCode(mHandler)); 1346 } 1347 if (mContainerService == null) { 1348 if (!mBound) { 1349 // Something seriously wrong since we are not bound and we are not 1350 // waiting for connection. Bail out. 1351 Slog.e(TAG, "Cannot bind to media container service"); 1352 for (HandlerParams params : mPendingInstalls) { 1353 // Indicate service bind error 1354 params.serviceError(); 1355 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1356 System.identityHashCode(params)); 1357 if (params.traceMethod != null) { 1358 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1359 params.traceMethod, params.traceCookie); 1360 } 1361 return; 1362 } 1363 mPendingInstalls.clear(); 1364 } else { 1365 Slog.w(TAG, "Waiting to connect to media container service"); 1366 } 1367 } else if (mPendingInstalls.size() > 0) { 1368 HandlerParams params = mPendingInstalls.get(0); 1369 if (params != null) { 1370 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1371 System.identityHashCode(params)); 1372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1373 if (params.startCopy()) { 1374 // We are done... look for more work or to 1375 // go idle. 1376 if (DEBUG_SD_INSTALL) Log.i(TAG, 1377 "Checking for more work or unbind..."); 1378 // Delete pending install 1379 if (mPendingInstalls.size() > 0) { 1380 mPendingInstalls.remove(0); 1381 } 1382 if (mPendingInstalls.size() == 0) { 1383 if (mBound) { 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, 1385 "Posting delayed MCS_UNBIND"); 1386 removeMessages(MCS_UNBIND); 1387 Message ubmsg = obtainMessage(MCS_UNBIND); 1388 // Unbind after a little delay, to avoid 1389 // continual thrashing. 1390 sendMessageDelayed(ubmsg, 10000); 1391 } 1392 } else { 1393 // There are more pending requests in queue. 1394 // Just post MCS_BOUND message to trigger processing 1395 // of next pending install. 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, 1397 "Posting MCS_BOUND for next work"); 1398 mHandler.sendEmptyMessage(MCS_BOUND); 1399 } 1400 } 1401 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1402 } 1403 } else { 1404 // Should never happen ideally. 1405 Slog.w(TAG, "Empty queue"); 1406 } 1407 break; 1408 } 1409 case MCS_RECONNECT: { 1410 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1411 if (mPendingInstalls.size() > 0) { 1412 if (mBound) { 1413 disconnectService(); 1414 } 1415 if (!connectToService()) { 1416 Slog.e(TAG, "Failed to bind to media container service"); 1417 for (HandlerParams params : mPendingInstalls) { 1418 // Indicate service bind error 1419 params.serviceError(); 1420 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1421 System.identityHashCode(params)); 1422 } 1423 mPendingInstalls.clear(); 1424 } 1425 } 1426 break; 1427 } 1428 case MCS_UNBIND: { 1429 // If there is no actual work left, then time to unbind. 1430 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1431 1432 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1433 if (mBound) { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1435 1436 disconnectService(); 1437 } 1438 } else if (mPendingInstalls.size() > 0) { 1439 // There are more pending requests in queue. 1440 // Just post MCS_BOUND message to trigger processing 1441 // of next pending install. 1442 mHandler.sendEmptyMessage(MCS_BOUND); 1443 } 1444 1445 break; 1446 } 1447 case MCS_GIVE_UP: { 1448 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1449 HandlerParams params = mPendingInstalls.remove(0); 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1451 System.identityHashCode(params)); 1452 break; 1453 } 1454 case SEND_PENDING_BROADCAST: { 1455 String packages[]; 1456 ArrayList<String> components[]; 1457 int size = 0; 1458 int uids[]; 1459 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1460 synchronized (mPackages) { 1461 if (mPendingBroadcasts == null) { 1462 return; 1463 } 1464 size = mPendingBroadcasts.size(); 1465 if (size <= 0) { 1466 // Nothing to be done. Just return 1467 return; 1468 } 1469 packages = new String[size]; 1470 components = new ArrayList[size]; 1471 uids = new int[size]; 1472 int i = 0; // filling out the above arrays 1473 1474 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1475 int packageUserId = mPendingBroadcasts.userIdAt(n); 1476 Iterator<Map.Entry<String, ArrayList<String>>> it 1477 = mPendingBroadcasts.packagesForUserId(packageUserId) 1478 .entrySet().iterator(); 1479 while (it.hasNext() && i < size) { 1480 Map.Entry<String, ArrayList<String>> ent = it.next(); 1481 packages[i] = ent.getKey(); 1482 components[i] = ent.getValue(); 1483 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1484 uids[i] = (ps != null) 1485 ? UserHandle.getUid(packageUserId, ps.appId) 1486 : -1; 1487 i++; 1488 } 1489 } 1490 size = i; 1491 mPendingBroadcasts.clear(); 1492 } 1493 // Send broadcasts 1494 for (int i = 0; i < size; i++) { 1495 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1496 } 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1498 break; 1499 } 1500 case START_CLEANING_PACKAGE: { 1501 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1502 final String packageName = (String)msg.obj; 1503 final int userId = msg.arg1; 1504 final boolean andCode = msg.arg2 != 0; 1505 synchronized (mPackages) { 1506 if (userId == UserHandle.USER_ALL) { 1507 int[] users = sUserManager.getUserIds(); 1508 for (int user : users) { 1509 mSettings.addPackageToCleanLPw( 1510 new PackageCleanItem(user, packageName, andCode)); 1511 } 1512 } else { 1513 mSettings.addPackageToCleanLPw( 1514 new PackageCleanItem(userId, packageName, andCode)); 1515 } 1516 } 1517 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1518 startCleaningPackages(); 1519 } break; 1520 case POST_INSTALL: { 1521 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1522 1523 PostInstallData data = mRunningInstalls.get(msg.arg1); 1524 final boolean didRestore = (msg.arg2 != 0); 1525 mRunningInstalls.delete(msg.arg1); 1526 1527 if (data != null) { 1528 InstallArgs args = data.args; 1529 PackageInstalledInfo parentRes = data.res; 1530 1531 final boolean grantPermissions = (args.installFlags 1532 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1533 final boolean killApp = (args.installFlags 1534 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1535 final String[] grantedPermissions = args.installGrantPermissions; 1536 1537 // Handle the parent package 1538 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1539 grantedPermissions, didRestore, args.installerPackageName, 1540 args.observer); 1541 1542 // Handle the child packages 1543 final int childCount = (parentRes.addedChildPackages != null) 1544 ? parentRes.addedChildPackages.size() : 0; 1545 for (int i = 0; i < childCount; i++) { 1546 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1547 handlePackagePostInstall(childRes, grantPermissions, killApp, 1548 grantedPermissions, false, args.installerPackageName, 1549 args.observer); 1550 } 1551 1552 // Log tracing if needed 1553 if (args.traceMethod != null) { 1554 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1555 args.traceCookie); 1556 } 1557 } else { 1558 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1559 } 1560 1561 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1562 } break; 1563 case UPDATED_MEDIA_STATUS: { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1565 boolean reportStatus = msg.arg1 == 1; 1566 boolean doGc = msg.arg2 == 1; 1567 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1568 if (doGc) { 1569 // Force a gc to clear up stale containers. 1570 Runtime.getRuntime().gc(); 1571 } 1572 if (msg.obj != null) { 1573 @SuppressWarnings("unchecked") 1574 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1575 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1576 // Unload containers 1577 unloadAllContainers(args); 1578 } 1579 if (reportStatus) { 1580 try { 1581 if (DEBUG_SD_INSTALL) Log.i(TAG, 1582 "Invoking StorageManagerService call back"); 1583 PackageHelper.getStorageManager().finishMediaUpdate(); 1584 } catch (RemoteException e) { 1585 Log.e(TAG, "StorageManagerService not running?"); 1586 } 1587 } 1588 } break; 1589 case WRITE_SETTINGS: { 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 removeMessages(WRITE_SETTINGS); 1593 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1594 mSettings.writeLPr(); 1595 mDirtyUsers.clear(); 1596 } 1597 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1598 } break; 1599 case WRITE_PACKAGE_RESTRICTIONS: { 1600 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1601 synchronized (mPackages) { 1602 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1603 for (int userId : mDirtyUsers) { 1604 mSettings.writePackageRestrictionsLPr(userId); 1605 } 1606 mDirtyUsers.clear(); 1607 } 1608 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1609 } break; 1610 case WRITE_PACKAGE_LIST: { 1611 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1612 synchronized (mPackages) { 1613 removeMessages(WRITE_PACKAGE_LIST); 1614 mSettings.writePackageListLPr(msg.arg1); 1615 } 1616 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1617 } break; 1618 case CHECK_PENDING_VERIFICATION: { 1619 final int verificationId = msg.arg1; 1620 final PackageVerificationState state = mPendingVerification.get(verificationId); 1621 1622 if ((state != null) && !state.timeoutExtended()) { 1623 final InstallArgs args = state.getInstallArgs(); 1624 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1625 1626 Slog.i(TAG, "Verification timed out for " + originUri); 1627 mPendingVerification.remove(verificationId); 1628 1629 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1630 1631 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1632 Slog.i(TAG, "Continuing with installation of " + originUri); 1633 state.setVerifierResponse(Binder.getCallingUid(), 1634 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1635 broadcastPackageVerified(verificationId, originUri, 1636 PackageManager.VERIFICATION_ALLOW, 1637 state.getInstallArgs().getUser()); 1638 try { 1639 ret = args.copyApk(mContainerService, true); 1640 } catch (RemoteException e) { 1641 Slog.e(TAG, "Could not contact the ContainerService"); 1642 } 1643 } else { 1644 broadcastPackageVerified(verificationId, originUri, 1645 PackageManager.VERIFICATION_REJECT, 1646 state.getInstallArgs().getUser()); 1647 } 1648 1649 Trace.asyncTraceEnd( 1650 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1651 1652 processPendingInstall(args, ret); 1653 mHandler.sendEmptyMessage(MCS_UNBIND); 1654 } 1655 break; 1656 } 1657 case PACKAGE_VERIFIED: { 1658 final int verificationId = msg.arg1; 1659 1660 final PackageVerificationState state = mPendingVerification.get(verificationId); 1661 if (state == null) { 1662 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1663 break; 1664 } 1665 1666 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1667 1668 state.setVerifierResponse(response.callerUid, response.code); 1669 1670 if (state.isVerificationComplete()) { 1671 mPendingVerification.remove(verificationId); 1672 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 int ret; 1677 if (state.isInstallAllowed()) { 1678 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1679 broadcastPackageVerified(verificationId, originUri, 1680 response.code, state.getInstallArgs().getUser()); 1681 try { 1682 ret = args.copyApk(mContainerService, true); 1683 } catch (RemoteException e) { 1684 Slog.e(TAG, "Could not contact the ContainerService"); 1685 } 1686 } else { 1687 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1688 } 1689 1690 Trace.asyncTraceEnd( 1691 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1692 1693 processPendingInstall(args, ret); 1694 mHandler.sendEmptyMessage(MCS_UNBIND); 1695 } 1696 1697 break; 1698 } 1699 case START_INTENT_FILTER_VERIFICATIONS: { 1700 IFVerificationParams params = (IFVerificationParams) msg.obj; 1701 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1702 params.replacing, params.pkg); 1703 break; 1704 } 1705 case INTENT_FILTER_VERIFIED: { 1706 final int verificationId = msg.arg1; 1707 1708 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1709 verificationId); 1710 if (state == null) { 1711 Slog.w(TAG, "Invalid IntentFilter verification token " 1712 + verificationId + " received"); 1713 break; 1714 } 1715 1716 final int userId = state.getUserId(); 1717 1718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1719 "Processing IntentFilter verification with token:" 1720 + verificationId + " and userId:" + userId); 1721 1722 final IntentFilterVerificationResponse response = 1723 (IntentFilterVerificationResponse) msg.obj; 1724 1725 state.setVerifierResponse(response.callerUid, response.code); 1726 1727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1728 "IntentFilter verification with token:" + verificationId 1729 + " and userId:" + userId 1730 + " is settings verifier response with response code:" 1731 + response.code); 1732 1733 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1735 + response.getFailedDomainsString()); 1736 } 1737 1738 if (state.isVerificationComplete()) { 1739 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1740 } else { 1741 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1742 "IntentFilter verification with token:" + verificationId 1743 + " was not said to be complete"); 1744 } 1745 1746 break; 1747 } 1748 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1749 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1750 mInstantAppResolverConnection, 1751 (InstantAppRequest) msg.obj, 1752 mInstantAppInstallerActivity, 1753 mHandler); 1754 } 1755 } 1756 } 1757 } 1758 1759 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1760 boolean killApp, String[] grantedPermissions, 1761 boolean launchedForRestore, String installerPackage, 1762 IPackageInstallObserver2 installObserver) { 1763 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1764 // Send the removed broadcasts 1765 if (res.removedInfo != null) { 1766 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1767 } 1768 1769 // Now that we successfully installed the package, grant runtime 1770 // permissions if requested before broadcasting the install. Also 1771 // for legacy apps in permission review mode we clear the permission 1772 // review flag which is used to emulate runtime permissions for 1773 // legacy apps. 1774 if (grantPermissions) { 1775 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1776 } 1777 1778 final boolean update = res.removedInfo != null 1779 && res.removedInfo.removedPackage != null; 1780 1781 // If this is the first time we have child packages for a disabled privileged 1782 // app that had no children, we grant requested runtime permissions to the new 1783 // children if the parent on the system image had them already granted. 1784 if (res.pkg.parentPackage != null) { 1785 synchronized (mPackages) { 1786 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1787 } 1788 } 1789 1790 synchronized (mPackages) { 1791 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1792 } 1793 1794 final String packageName = res.pkg.applicationInfo.packageName; 1795 1796 // Determine the set of users who are adding this package for 1797 // the first time vs. those who are seeing an update. 1798 int[] firstUsers = EMPTY_INT_ARRAY; 1799 int[] updateUsers = EMPTY_INT_ARRAY; 1800 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1801 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1802 for (int newUser : res.newUsers) { 1803 if (ps.getInstantApp(newUser)) { 1804 continue; 1805 } 1806 if (allNewUsers) { 1807 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1808 continue; 1809 } 1810 boolean isNew = true; 1811 for (int origUser : res.origUsers) { 1812 if (origUser == newUser) { 1813 isNew = false; 1814 break; 1815 } 1816 } 1817 if (isNew) { 1818 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1819 } else { 1820 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1821 } 1822 } 1823 1824 // Send installed broadcasts if the package is not a static shared lib. 1825 if (res.pkg.staticSharedLibName == null) { 1826 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1827 1828 // Send added for users that see the package for the first time 1829 // sendPackageAddedForNewUsers also deals with system apps 1830 int appId = UserHandle.getAppId(res.uid); 1831 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1832 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1833 1834 // Send added for users that don't see the package for the first time 1835 Bundle extras = new Bundle(1); 1836 extras.putInt(Intent.EXTRA_UID, res.uid); 1837 if (update) { 1838 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1839 } 1840 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1841 extras, 0 /*flags*/, null /*targetPackage*/, 1842 null /*finishedReceiver*/, updateUsers); 1843 1844 // Send replaced for users that don't see the package for the first time 1845 if (update) { 1846 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1847 packageName, extras, 0 /*flags*/, 1848 null /*targetPackage*/, null /*finishedReceiver*/, 1849 updateUsers); 1850 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1851 null /*package*/, null /*extras*/, 0 /*flags*/, 1852 packageName /*targetPackage*/, 1853 null /*finishedReceiver*/, updateUsers); 1854 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1855 // First-install and we did a restore, so we're responsible for the 1856 // first-launch broadcast. 1857 if (DEBUG_BACKUP) { 1858 Slog.i(TAG, "Post-restore of " + packageName 1859 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1860 } 1861 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1862 } 1863 1864 // Send broadcast package appeared if forward locked/external for all users 1865 // treat asec-hosted packages like removable media on upgrade 1866 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1867 if (DEBUG_INSTALL) { 1868 Slog.i(TAG, "upgrading pkg " + res.pkg 1869 + " is ASEC-hosted -> AVAILABLE"); 1870 } 1871 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1872 ArrayList<String> pkgList = new ArrayList<>(1); 1873 pkgList.add(packageName); 1874 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1875 } 1876 } 1877 1878 // Work that needs to happen on first install within each user 1879 if (firstUsers != null && firstUsers.length > 0) { 1880 synchronized (mPackages) { 1881 for (int userId : firstUsers) { 1882 // If this app is a browser and it's newly-installed for some 1883 // users, clear any default-browser state in those users. The 1884 // app's nature doesn't depend on the user, so we can just check 1885 // its browser nature in any user and generalize. 1886 if (packageIsBrowser(packageName, userId)) { 1887 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1888 } 1889 1890 // We may also need to apply pending (restored) runtime 1891 // permission grants within these users. 1892 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1893 } 1894 } 1895 } 1896 1897 // Log current value of "unknown sources" setting 1898 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1899 getUnknownSourcesSettings()); 1900 1901 // Force a gc to clear up things 1902 Runtime.getRuntime().gc(); 1903 1904 // Remove the replaced package's older resources safely now 1905 // We delete after a gc for applications on sdcard. 1906 if (res.removedInfo != null && res.removedInfo.args != null) { 1907 synchronized (mInstallLock) { 1908 res.removedInfo.args.doPostDeleteLI(true); 1909 } 1910 } 1911 1912 // Notify DexManager that the package was installed for new users. 1913 // The updated users should already be indexed and the package code paths 1914 // should not change. 1915 // Don't notify the manager for ephemeral apps as they are not expected to 1916 // survive long enough to benefit of background optimizations. 1917 for (int userId : firstUsers) { 1918 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1919 // There's a race currently where some install events may interleave with an uninstall. 1920 // This can lead to package info being null (b/36642664). 1921 if (info != null) { 1922 mDexManager.notifyPackageInstalled(info, userId); 1923 } 1924 } 1925 } 1926 1927 // If someone is watching installs - notify them 1928 if (installObserver != null) { 1929 try { 1930 Bundle extras = extrasForInstallResult(res); 1931 installObserver.onPackageInstalled(res.name, res.returnCode, 1932 res.returnMsg, extras); 1933 } catch (RemoteException e) { 1934 Slog.i(TAG, "Observer no longer exists."); 1935 } 1936 } 1937 } 1938 1939 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1940 PackageParser.Package pkg) { 1941 if (pkg.parentPackage == null) { 1942 return; 1943 } 1944 if (pkg.requestedPermissions == null) { 1945 return; 1946 } 1947 final PackageSetting disabledSysParentPs = mSettings 1948 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1949 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1950 || !disabledSysParentPs.isPrivileged() 1951 || (disabledSysParentPs.childPackageNames != null 1952 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1953 return; 1954 } 1955 final int[] allUserIds = sUserManager.getUserIds(); 1956 final int permCount = pkg.requestedPermissions.size(); 1957 for (int i = 0; i < permCount; i++) { 1958 String permission = pkg.requestedPermissions.get(i); 1959 BasePermission bp = mSettings.mPermissions.get(permission); 1960 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1961 continue; 1962 } 1963 for (int userId : allUserIds) { 1964 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1965 permission, userId)) { 1966 grantRuntimePermission(pkg.packageName, permission, userId); 1967 } 1968 } 1969 } 1970 } 1971 1972 private StorageEventListener mStorageListener = new StorageEventListener() { 1973 @Override 1974 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1975 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1976 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1977 final String volumeUuid = vol.getFsUuid(); 1978 1979 // Clean up any users or apps that were removed or recreated 1980 // while this volume was missing 1981 sUserManager.reconcileUsers(volumeUuid); 1982 reconcileApps(volumeUuid); 1983 1984 // Clean up any install sessions that expired or were 1985 // cancelled while this volume was missing 1986 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1987 1988 loadPrivatePackages(vol); 1989 1990 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1991 unloadPrivatePackages(vol); 1992 } 1993 } 1994 1995 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1996 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1997 updateExternalMediaStatus(true, false); 1998 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1999 updateExternalMediaStatus(false, false); 2000 } 2001 } 2002 } 2003 2004 @Override 2005 public void onVolumeForgotten(String fsUuid) { 2006 if (TextUtils.isEmpty(fsUuid)) { 2007 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2008 return; 2009 } 2010 2011 // Remove any apps installed on the forgotten volume 2012 synchronized (mPackages) { 2013 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2014 for (PackageSetting ps : packages) { 2015 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2016 deletePackageVersioned(new VersionedPackage(ps.name, 2017 PackageManager.VERSION_CODE_HIGHEST), 2018 new LegacyPackageDeleteObserver(null).getBinder(), 2019 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2020 // Try very hard to release any references to this package 2021 // so we don't risk the system server being killed due to 2022 // open FDs 2023 AttributeCache.instance().removePackage(ps.name); 2024 } 2025 2026 mSettings.onVolumeForgotten(fsUuid); 2027 mSettings.writeLPr(); 2028 } 2029 } 2030 }; 2031 2032 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2033 String[] grantedPermissions) { 2034 for (int userId : userIds) { 2035 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2036 } 2037 } 2038 2039 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2040 String[] grantedPermissions) { 2041 SettingBase sb = (SettingBase) pkg.mExtras; 2042 if (sb == null) { 2043 return; 2044 } 2045 2046 PermissionsState permissionsState = sb.getPermissionsState(); 2047 2048 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2049 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2050 2051 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2052 >= Build.VERSION_CODES.M; 2053 2054 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2055 2056 for (String permission : pkg.requestedPermissions) { 2057 final BasePermission bp; 2058 synchronized (mPackages) { 2059 bp = mSettings.mPermissions.get(permission); 2060 } 2061 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2062 && (!instantApp || bp.isInstant()) 2063 && (grantedPermissions == null 2064 || ArrayUtils.contains(grantedPermissions, permission))) { 2065 final int flags = permissionsState.getPermissionFlags(permission, userId); 2066 if (supportsRuntimePermissions) { 2067 // Installer cannot change immutable permissions. 2068 if ((flags & immutableFlags) == 0) { 2069 grantRuntimePermission(pkg.packageName, permission, userId); 2070 } 2071 } else if (mPermissionReviewRequired) { 2072 // In permission review mode we clear the review flag when we 2073 // are asked to install the app with all permissions granted. 2074 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2075 updatePermissionFlags(permission, pkg.packageName, 2076 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2077 } 2078 } 2079 } 2080 } 2081 } 2082 2083 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2084 Bundle extras = null; 2085 switch (res.returnCode) { 2086 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2087 extras = new Bundle(); 2088 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2089 res.origPermission); 2090 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2091 res.origPackage); 2092 break; 2093 } 2094 case PackageManager.INSTALL_SUCCEEDED: { 2095 extras = new Bundle(); 2096 extras.putBoolean(Intent.EXTRA_REPLACING, 2097 res.removedInfo != null && res.removedInfo.removedPackage != null); 2098 break; 2099 } 2100 } 2101 return extras; 2102 } 2103 2104 void scheduleWriteSettingsLocked() { 2105 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2106 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2107 } 2108 } 2109 2110 void scheduleWritePackageListLocked(int userId) { 2111 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2112 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2113 msg.arg1 = userId; 2114 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2115 } 2116 } 2117 2118 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2119 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2120 scheduleWritePackageRestrictionsLocked(userId); 2121 } 2122 2123 void scheduleWritePackageRestrictionsLocked(int userId) { 2124 final int[] userIds = (userId == UserHandle.USER_ALL) 2125 ? sUserManager.getUserIds() : new int[]{userId}; 2126 for (int nextUserId : userIds) { 2127 if (!sUserManager.exists(nextUserId)) return; 2128 mDirtyUsers.add(nextUserId); 2129 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2130 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2131 } 2132 } 2133 } 2134 2135 public static PackageManagerService main(Context context, Installer installer, 2136 boolean factoryTest, boolean onlyCore) { 2137 // Self-check for initial settings. 2138 PackageManagerServiceCompilerMapping.checkProperties(); 2139 2140 PackageManagerService m = new PackageManagerService(context, installer, 2141 factoryTest, onlyCore); 2142 m.enableSystemUserPackages(); 2143 ServiceManager.addService("package", m); 2144 return m; 2145 } 2146 2147 private void enableSystemUserPackages() { 2148 if (!UserManager.isSplitSystemUser()) { 2149 return; 2150 } 2151 // For system user, enable apps based on the following conditions: 2152 // - app is whitelisted or belong to one of these groups: 2153 // -- system app which has no launcher icons 2154 // -- system app which has INTERACT_ACROSS_USERS permission 2155 // -- system IME app 2156 // - app is not in the blacklist 2157 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2158 Set<String> enableApps = new ArraySet<>(); 2159 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2160 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2161 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2162 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2163 enableApps.addAll(wlApps); 2164 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2165 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2166 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2167 enableApps.removeAll(blApps); 2168 Log.i(TAG, "Applications installed for system user: " + enableApps); 2169 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2170 UserHandle.SYSTEM); 2171 final int allAppsSize = allAps.size(); 2172 synchronized (mPackages) { 2173 for (int i = 0; i < allAppsSize; i++) { 2174 String pName = allAps.get(i); 2175 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2176 // Should not happen, but we shouldn't be failing if it does 2177 if (pkgSetting == null) { 2178 continue; 2179 } 2180 boolean install = enableApps.contains(pName); 2181 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2182 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2183 + " for system user"); 2184 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2185 } 2186 } 2187 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2188 } 2189 } 2190 2191 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2192 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2193 Context.DISPLAY_SERVICE); 2194 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2195 } 2196 2197 /** 2198 * Requests that files preopted on a secondary system partition be copied to the data partition 2199 * if possible. Note that the actual copying of the files is accomplished by init for security 2200 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2201 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2202 */ 2203 private static void requestCopyPreoptedFiles() { 2204 final int WAIT_TIME_MS = 100; 2205 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2206 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2207 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2208 // We will wait for up to 100 seconds. 2209 final long timeStart = SystemClock.uptimeMillis(); 2210 final long timeEnd = timeStart + 100 * 1000; 2211 long timeNow = timeStart; 2212 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2213 try { 2214 Thread.sleep(WAIT_TIME_MS); 2215 } catch (InterruptedException e) { 2216 // Do nothing 2217 } 2218 timeNow = SystemClock.uptimeMillis(); 2219 if (timeNow > timeEnd) { 2220 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2221 Slog.wtf(TAG, "cppreopt did not finish!"); 2222 break; 2223 } 2224 } 2225 2226 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2227 } 2228 } 2229 2230 public PackageManagerService(Context context, Installer installer, 2231 boolean factoryTest, boolean onlyCore) { 2232 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2234 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2235 SystemClock.uptimeMillis()); 2236 2237 if (mSdkVersion <= 0) { 2238 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2239 } 2240 2241 mContext = context; 2242 2243 mPermissionReviewRequired = context.getResources().getBoolean( 2244 R.bool.config_permissionReviewRequired); 2245 2246 mFactoryTest = factoryTest; 2247 mOnlyCore = onlyCore; 2248 mMetrics = new DisplayMetrics(); 2249 mSettings = new Settings(mPackages); 2250 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2251 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2252 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2253 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2254 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2255 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2256 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2257 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2258 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2259 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2260 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2261 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2262 2263 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2264 if (separateProcesses != null && separateProcesses.length() > 0) { 2265 if ("*".equals(separateProcesses)) { 2266 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2267 mSeparateProcesses = null; 2268 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2269 } else { 2270 mDefParseFlags = 0; 2271 mSeparateProcesses = separateProcesses.split(","); 2272 Slog.w(TAG, "Running with debug.separate_processes: " 2273 + separateProcesses); 2274 } 2275 } else { 2276 mDefParseFlags = 0; 2277 mSeparateProcesses = null; 2278 } 2279 2280 mInstaller = installer; 2281 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2282 "*dexopt*"); 2283 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2284 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2285 2286 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2287 FgThread.get().getLooper()); 2288 2289 getDefaultDisplayMetrics(context, mMetrics); 2290 2291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2292 SystemConfig systemConfig = SystemConfig.getInstance(); 2293 mGlobalGids = systemConfig.getGlobalGids(); 2294 mSystemPermissions = systemConfig.getSystemPermissions(); 2295 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2297 2298 mProtectedPackages = new ProtectedPackages(mContext); 2299 2300 synchronized (mInstallLock) { 2301 // writer 2302 synchronized (mPackages) { 2303 mHandlerThread = new ServiceThread(TAG, 2304 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2305 mHandlerThread.start(); 2306 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2307 mProcessLoggingHandler = new ProcessLoggingHandler(); 2308 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2309 2310 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2311 mInstantAppRegistry = new InstantAppRegistry(this); 2312 2313 File dataDir = Environment.getDataDirectory(); 2314 mAppInstallDir = new File(dataDir, "app"); 2315 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2316 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2317 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2318 sUserManager = new UserManagerService(context, this, 2319 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2320 2321 // Propagate permission configuration in to package manager. 2322 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2323 = systemConfig.getPermissions(); 2324 for (int i=0; i<permConfig.size(); i++) { 2325 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2326 BasePermission bp = mSettings.mPermissions.get(perm.name); 2327 if (bp == null) { 2328 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2329 mSettings.mPermissions.put(perm.name, bp); 2330 } 2331 if (perm.gids != null) { 2332 bp.setGids(perm.gids, perm.perUser); 2333 } 2334 } 2335 2336 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2337 final int builtInLibCount = libConfig.size(); 2338 for (int i = 0; i < builtInLibCount; i++) { 2339 String name = libConfig.keyAt(i); 2340 String path = libConfig.valueAt(i); 2341 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2342 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2343 } 2344 2345 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2346 2347 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2348 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2349 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2350 2351 // Clean up orphaned packages for which the code path doesn't exist 2352 // and they are an update to a system app - caused by bug/32321269 2353 final int packageSettingCount = mSettings.mPackages.size(); 2354 for (int i = packageSettingCount - 1; i >= 0; i--) { 2355 PackageSetting ps = mSettings.mPackages.valueAt(i); 2356 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2357 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2358 mSettings.mPackages.removeAt(i); 2359 mSettings.enableSystemPackageLPw(ps.name); 2360 } 2361 } 2362 2363 if (mFirstBoot) { 2364 requestCopyPreoptedFiles(); 2365 } 2366 2367 String customResolverActivity = Resources.getSystem().getString( 2368 R.string.config_customResolverActivity); 2369 if (TextUtils.isEmpty(customResolverActivity)) { 2370 customResolverActivity = null; 2371 } else { 2372 mCustomResolverComponentName = ComponentName.unflattenFromString( 2373 customResolverActivity); 2374 } 2375 2376 long startTime = SystemClock.uptimeMillis(); 2377 2378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2379 startTime); 2380 2381 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2382 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2383 2384 if (bootClassPath == null) { 2385 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2386 } 2387 2388 if (systemServerClassPath == null) { 2389 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2390 } 2391 2392 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2393 2394 final VersionInfo ver = mSettings.getInternalVersion(); 2395 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2396 if (mIsUpgrade) { 2397 logCriticalInfo(Log.INFO, 2398 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2399 } 2400 2401 // when upgrading from pre-M, promote system app permissions from install to runtime 2402 mPromoteSystemApps = 2403 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2404 2405 // When upgrading from pre-N, we need to handle package extraction like first boot, 2406 // as there is no profiling data available. 2407 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2408 2409 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2410 2411 // save off the names of pre-existing system packages prior to scanning; we don't 2412 // want to automatically grant runtime permissions for new system apps 2413 if (mPromoteSystemApps) { 2414 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2415 while (pkgSettingIter.hasNext()) { 2416 PackageSetting ps = pkgSettingIter.next(); 2417 if (isSystemApp(ps)) { 2418 mExistingSystemPackages.add(ps.name); 2419 } 2420 } 2421 } 2422 2423 mCacheDir = preparePackageParserCache(mIsUpgrade); 2424 2425 // Set flag to monitor and not change apk file paths when 2426 // scanning install directories. 2427 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2428 2429 if (mIsUpgrade || mFirstBoot) { 2430 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2431 } 2432 2433 // Collect vendor overlay packages. (Do this before scanning any apps.) 2434 // For security and version matching reason, only consider 2435 // overlay packages if they reside in the right directory. 2436 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2440 2441 // Find base frameworks (resource packages without code). 2442 scanDirTracedLI(frameworkDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR 2445 | PackageParser.PARSE_IS_PRIVILEGED, 2446 scanFlags | SCAN_NO_DEX, 0); 2447 2448 // Collected privileged system packages. 2449 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2450 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2451 | PackageParser.PARSE_IS_SYSTEM 2452 | PackageParser.PARSE_IS_SYSTEM_DIR 2453 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2454 2455 // Collect ordinary system packages. 2456 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2457 scanDirTracedLI(systemAppDir, mDefParseFlags 2458 | PackageParser.PARSE_IS_SYSTEM 2459 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2460 2461 // Collect all vendor packages. 2462 File vendorAppDir = new File("/vendor/app"); 2463 try { 2464 vendorAppDir = vendorAppDir.getCanonicalFile(); 2465 } catch (IOException e) { 2466 // failed to look up canonical path, continue with original one 2467 } 2468 scanDirTracedLI(vendorAppDir, mDefParseFlags 2469 | PackageParser.PARSE_IS_SYSTEM 2470 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2471 2472 // Collect all OEM packages. 2473 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2474 scanDirTracedLI(oemAppDir, mDefParseFlags 2475 | PackageParser.PARSE_IS_SYSTEM 2476 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2477 2478 // Prune any system packages that no longer exist. 2479 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2480 if (!mOnlyCore) { 2481 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2482 while (psit.hasNext()) { 2483 PackageSetting ps = psit.next(); 2484 2485 /* 2486 * If this is not a system app, it can't be a 2487 * disable system app. 2488 */ 2489 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2490 continue; 2491 } 2492 2493 /* 2494 * If the package is scanned, it's not erased. 2495 */ 2496 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2497 if (scannedPkg != null) { 2498 /* 2499 * If the system app is both scanned and in the 2500 * disabled packages list, then it must have been 2501 * added via OTA. Remove it from the currently 2502 * scanned package so the previously user-installed 2503 * application can be scanned. 2504 */ 2505 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2506 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2507 + ps.name + "; removing system app. Last known codePath=" 2508 + ps.codePathString + ", installStatus=" + ps.installStatus 2509 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2510 + scannedPkg.mVersionCode); 2511 removePackageLI(scannedPkg, true); 2512 mExpectingBetter.put(ps.name, ps.codePath); 2513 } 2514 2515 continue; 2516 } 2517 2518 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2519 psit.remove(); 2520 logCriticalInfo(Log.WARN, "System package " + ps.name 2521 + " no longer exists; it's data will be wiped"); 2522 // Actual deletion of code and data will be handled by later 2523 // reconciliation step 2524 } else { 2525 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2526 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2527 possiblyDeletedUpdatedSystemApps.add(ps.name); 2528 } 2529 } 2530 } 2531 } 2532 2533 //look for any incomplete package installations 2534 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2535 for (int i = 0; i < deletePkgsList.size(); i++) { 2536 // Actual deletion of code and data will be handled by later 2537 // reconciliation step 2538 final String packageName = deletePkgsList.get(i).name; 2539 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2540 synchronized (mPackages) { 2541 mSettings.removePackageLPw(packageName); 2542 } 2543 } 2544 2545 //delete tmp files 2546 deleteTempPackageFiles(); 2547 2548 // Remove any shared userIDs that have no associated packages 2549 mSettings.pruneSharedUsersLPw(); 2550 2551 if (!mOnlyCore) { 2552 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2553 SystemClock.uptimeMillis()); 2554 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2555 2556 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2557 | PackageParser.PARSE_FORWARD_LOCK, 2558 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2559 2560 /** 2561 * Remove disable package settings for any updated system 2562 * apps that were removed via an OTA. If they're not a 2563 * previously-updated app, remove them completely. 2564 * Otherwise, just revoke their system-level permissions. 2565 */ 2566 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2567 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2568 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2569 2570 String msg; 2571 if (deletedPkg == null) { 2572 msg = "Updated system package " + deletedAppName 2573 + " no longer exists; it's data will be wiped"; 2574 // Actual deletion of code and data will be handled by later 2575 // reconciliation step 2576 } else { 2577 msg = "Updated system app + " + deletedAppName 2578 + " no longer present; removing system privileges for " 2579 + deletedAppName; 2580 2581 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2582 2583 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2584 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2585 } 2586 logCriticalInfo(Log.WARN, msg); 2587 } 2588 2589 /** 2590 * Make sure all system apps that we expected to appear on 2591 * the userdata partition actually showed up. If they never 2592 * appeared, crawl back and revive the system version. 2593 */ 2594 for (int i = 0; i < mExpectingBetter.size(); i++) { 2595 final String packageName = mExpectingBetter.keyAt(i); 2596 if (!mPackages.containsKey(packageName)) { 2597 final File scanFile = mExpectingBetter.valueAt(i); 2598 2599 logCriticalInfo(Log.WARN, "Expected better " + packageName 2600 + " but never showed up; reverting to system"); 2601 2602 int reparseFlags = mDefParseFlags; 2603 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR 2606 | PackageParser.PARSE_IS_PRIVILEGED; 2607 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2608 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2609 | PackageParser.PARSE_IS_SYSTEM_DIR; 2610 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2611 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2612 | PackageParser.PARSE_IS_SYSTEM_DIR; 2613 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2614 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2615 | PackageParser.PARSE_IS_SYSTEM_DIR; 2616 } else { 2617 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2618 continue; 2619 } 2620 2621 mSettings.enableSystemPackageLPw(packageName); 2622 2623 try { 2624 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2625 } catch (PackageManagerException e) { 2626 Slog.e(TAG, "Failed to parse original system package: " 2627 + e.getMessage()); 2628 } 2629 } 2630 } 2631 } 2632 mExpectingBetter.clear(); 2633 2634 // Resolve the storage manager. 2635 mStorageManagerPackage = getStorageManagerPackageName(); 2636 2637 // Resolve protected action filters. Only the setup wizard is allowed to 2638 // have a high priority filter for these actions. 2639 mSetupWizardPackage = getSetupWizardPackageName(); 2640 if (mProtectedFilters.size() > 0) { 2641 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2642 Slog.i(TAG, "No setup wizard;" 2643 + " All protected intents capped to priority 0"); 2644 } 2645 for (ActivityIntentInfo filter : mProtectedFilters) { 2646 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2647 if (DEBUG_FILTERS) { 2648 Slog.i(TAG, "Found setup wizard;" 2649 + " allow priority " + filter.getPriority() + ";" 2650 + " package: " + filter.activity.info.packageName 2651 + " activity: " + filter.activity.className 2652 + " priority: " + filter.getPriority()); 2653 } 2654 // skip setup wizard; allow it to keep the high priority filter 2655 continue; 2656 } 2657 Slog.w(TAG, "Protected action; cap priority to 0;" 2658 + " package: " + filter.activity.info.packageName 2659 + " activity: " + filter.activity.className 2660 + " origPrio: " + filter.getPriority()); 2661 filter.setPriority(0); 2662 } 2663 } 2664 mDeferProtectedFilters = false; 2665 mProtectedFilters.clear(); 2666 2667 // Now that we know all of the shared libraries, update all clients to have 2668 // the correct library paths. 2669 updateAllSharedLibrariesLPw(null); 2670 2671 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2672 // NOTE: We ignore potential failures here during a system scan (like 2673 // the rest of the commands above) because there's precious little we 2674 // can do about it. A settings error is reported, though. 2675 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2676 } 2677 2678 // Now that we know all the packages we are keeping, 2679 // read and update their last usage times. 2680 mPackageUsage.read(mPackages); 2681 mCompilerStats.read(); 2682 2683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2684 SystemClock.uptimeMillis()); 2685 Slog.i(TAG, "Time to scan packages: " 2686 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2687 + " seconds"); 2688 2689 // If the platform SDK has changed since the last time we booted, 2690 // we need to re-grant app permission to catch any new ones that 2691 // appear. This is really a hack, and means that apps can in some 2692 // cases get permissions that the user didn't initially explicitly 2693 // allow... it would be nice to have some better way to handle 2694 // this situation. 2695 int updateFlags = UPDATE_PERMISSIONS_ALL; 2696 if (ver.sdkVersion != mSdkVersion) { 2697 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2698 + mSdkVersion + "; regranting permissions for internal storage"); 2699 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2700 } 2701 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2702 ver.sdkVersion = mSdkVersion; 2703 2704 // If this is the first boot or an update from pre-M, and it is a normal 2705 // boot, then we need to initialize the default preferred apps across 2706 // all defined users. 2707 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2708 for (UserInfo user : sUserManager.getUsers(true)) { 2709 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2710 applyFactoryDefaultBrowserLPw(user.id); 2711 primeDomainVerificationsLPw(user.id); 2712 } 2713 } 2714 2715 // Prepare storage for system user really early during boot, 2716 // since core system apps like SettingsProvider and SystemUI 2717 // can't wait for user to start 2718 final int storageFlags; 2719 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2720 storageFlags = StorageManager.FLAG_STORAGE_DE; 2721 } else { 2722 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2723 } 2724 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2725 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2726 true /* onlyCoreApps */); 2727 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "fixup"); 2729 try { 2730 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2731 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2732 } catch (InstallerException e) { 2733 Slog.w(TAG, "Trouble fixing GIDs", e); 2734 } 2735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2736 2737 if (deferPackages == null || deferPackages.isEmpty()) { 2738 return; 2739 } 2740 int count = 0; 2741 for (String pkgName : deferPackages) { 2742 PackageParser.Package pkg = null; 2743 synchronized (mPackages) { 2744 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2745 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2746 pkg = ps.pkg; 2747 } 2748 } 2749 if (pkg != null) { 2750 synchronized (mInstallLock) { 2751 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2752 true /* maybeMigrateAppData */); 2753 } 2754 count++; 2755 } 2756 } 2757 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2758 }, "prepareAppData"); 2759 2760 // If this is first boot after an OTA, and a normal boot, then 2761 // we need to clear code cache directories. 2762 // Note that we do *not* clear the application profiles. These remain valid 2763 // across OTAs and are used to drive profile verification (post OTA) and 2764 // profile compilation (without waiting to collect a fresh set of profiles). 2765 if (mIsUpgrade && !onlyCore) { 2766 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2767 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2768 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2769 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2770 // No apps are running this early, so no need to freeze 2771 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2772 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2773 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2774 } 2775 } 2776 ver.fingerprint = Build.FINGERPRINT; 2777 } 2778 2779 checkDefaultBrowser(); 2780 2781 // clear only after permissions and other defaults have been updated 2782 mExistingSystemPackages.clear(); 2783 mPromoteSystemApps = false; 2784 2785 // All the changes are done during package scanning. 2786 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2787 2788 // can downgrade to reader 2789 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2790 mSettings.writeLPr(); 2791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2792 2793 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2794 SystemClock.uptimeMillis()); 2795 2796 if (!mOnlyCore) { 2797 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2798 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2799 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2800 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2801 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2802 mIntentFilterVerifierComponent); 2803 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2804 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2805 SharedLibraryInfo.VERSION_UNDEFINED); 2806 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2807 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2808 SharedLibraryInfo.VERSION_UNDEFINED); 2809 } else { 2810 mRequiredVerifierPackage = null; 2811 mRequiredInstallerPackage = null; 2812 mRequiredUninstallerPackage = null; 2813 mIntentFilterVerifierComponent = null; 2814 mIntentFilterVerifier = null; 2815 mServicesSystemSharedLibraryPackageName = null; 2816 mSharedSystemSharedLibraryPackageName = null; 2817 } 2818 2819 mInstallerService = new PackageInstallerService(context, this); 2820 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2821 if (ephemeralResolverComponent != null) { 2822 if (DEBUG_EPHEMERAL) { 2823 Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent); 2824 } 2825 mInstantAppResolverConnection = 2826 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2827 mInstantAppResolverSettingsComponent = 2828 getEphemeralResolverSettingsLPr(ephemeralResolverComponent); 2829 } else { 2830 mInstantAppResolverConnection = null; 2831 mInstantAppResolverSettingsComponent = null; 2832 } 2833 updateInstantAppInstallerLocked(); 2834 2835 // Read and update the usage of dex files. 2836 // Do this at the end of PM init so that all the packages have their 2837 // data directory reconciled. 2838 // At this point we know the code paths of the packages, so we can validate 2839 // the disk file and build the internal cache. 2840 // The usage file is expected to be small so loading and verifying it 2841 // should take a fairly small time compare to the other activities (e.g. package 2842 // scanning). 2843 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2844 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2845 for (int userId : currentUserIds) { 2846 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2847 } 2848 mDexManager.load(userPackages); 2849 } // synchronized (mPackages) 2850 } // synchronized (mInstallLock) 2851 2852 // Now after opening every single application zip, make sure they 2853 // are all flushed. Not really needed, but keeps things nice and 2854 // tidy. 2855 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2856 Runtime.getRuntime().gc(); 2857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2858 2859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2860 FallbackCategoryProvider.loadFallbacks(); 2861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2862 2863 // The initial scanning above does many calls into installd while 2864 // holding the mPackages lock, but we're mostly interested in yelling 2865 // once we have a booted system. 2866 mInstaller.setWarnIfHeld(mPackages); 2867 2868 // Expose private service for system components to use. 2869 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2870 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2871 } 2872 2873 private void updateInstantAppInstallerLocked() { 2874 final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent; 2875 final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr(); 2876 ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null 2877 ? null : newInstantAppInstaller.getComponentName(); 2878 2879 if (newInstantAppInstallerComponent != null 2880 && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) { 2881 if (DEBUG_EPHEMERAL) { 2882 Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent); 2883 } 2884 setUpInstantAppInstallerActivityLP(newInstantAppInstaller); 2885 } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) { 2886 Slog.d(TAG, "Unset ephemeral installer; none available"); 2887 } 2888 mInstantAppInstallerComponent = newInstantAppInstallerComponent; 2889 } 2890 2891 private static File preparePackageParserCache(boolean isUpgrade) { 2892 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2893 return null; 2894 } 2895 2896 // Disable package parsing on eng builds to allow for faster incremental development. 2897 if ("eng".equals(Build.TYPE)) { 2898 return null; 2899 } 2900 2901 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2902 Slog.i(TAG, "Disabling package parser cache due to system property."); 2903 return null; 2904 } 2905 2906 // The base directory for the package parser cache lives under /data/system/. 2907 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2908 "package_cache"); 2909 if (cacheBaseDir == null) { 2910 return null; 2911 } 2912 2913 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2914 // This also serves to "GC" unused entries when the package cache version changes (which 2915 // can only happen during upgrades). 2916 if (isUpgrade) { 2917 FileUtils.deleteContents(cacheBaseDir); 2918 } 2919 2920 2921 // Return the versioned package cache directory. This is something like 2922 // "/data/system/package_cache/1" 2923 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2924 2925 // The following is a workaround to aid development on non-numbered userdebug 2926 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2927 // the system partition is newer. 2928 // 2929 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2930 // that starts with "eng." to signify that this is an engineering build and not 2931 // destined for release. 2932 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2933 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2934 2935 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2936 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2937 // in general and should not be used for production changes. In this specific case, 2938 // we know that they will work. 2939 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2940 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2941 FileUtils.deleteContents(cacheBaseDir); 2942 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2943 } 2944 } 2945 2946 return cacheDir; 2947 } 2948 2949 @Override 2950 public boolean isFirstBoot() { 2951 return mFirstBoot; 2952 } 2953 2954 @Override 2955 public boolean isOnlyCoreApps() { 2956 return mOnlyCore; 2957 } 2958 2959 @Override 2960 public boolean isUpgrade() { 2961 return mIsUpgrade; 2962 } 2963 2964 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2965 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2966 2967 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2968 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2969 UserHandle.USER_SYSTEM); 2970 if (matches.size() == 1) { 2971 return matches.get(0).getComponentInfo().packageName; 2972 } else if (matches.size() == 0) { 2973 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2974 return null; 2975 } 2976 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2977 } 2978 2979 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2980 synchronized (mPackages) { 2981 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2982 if (libraryEntry == null) { 2983 throw new IllegalStateException("Missing required shared library:" + name); 2984 } 2985 return libraryEntry.apk; 2986 } 2987 } 2988 2989 private @NonNull String getRequiredInstallerLPr() { 2990 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2991 intent.addCategory(Intent.CATEGORY_DEFAULT); 2992 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2993 2994 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2995 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2996 UserHandle.USER_SYSTEM); 2997 if (matches.size() == 1) { 2998 ResolveInfo resolveInfo = matches.get(0); 2999 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3000 throw new RuntimeException("The installer must be a privileged app"); 3001 } 3002 return matches.get(0).getComponentInfo().packageName; 3003 } else { 3004 throw new RuntimeException("There must be exactly one installer; found " + matches); 3005 } 3006 } 3007 3008 private @NonNull String getRequiredUninstallerLPr() { 3009 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3010 intent.addCategory(Intent.CATEGORY_DEFAULT); 3011 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3012 3013 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3014 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3015 UserHandle.USER_SYSTEM); 3016 if (resolveInfo == null || 3017 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3018 throw new RuntimeException("There must be exactly one uninstaller; found " 3019 + resolveInfo); 3020 } 3021 return resolveInfo.getComponentInfo().packageName; 3022 } 3023 3024 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3025 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3026 3027 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3028 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3029 UserHandle.USER_SYSTEM); 3030 ResolveInfo best = null; 3031 final int N = matches.size(); 3032 for (int i = 0; i < N; i++) { 3033 final ResolveInfo cur = matches.get(i); 3034 final String packageName = cur.getComponentInfo().packageName; 3035 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3036 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3037 continue; 3038 } 3039 3040 if (best == null || cur.priority > best.priority) { 3041 best = cur; 3042 } 3043 } 3044 3045 if (best != null) { 3046 return best.getComponentInfo().getComponentName(); 3047 } else { 3048 throw new RuntimeException("There must be at least one intent filter verifier"); 3049 } 3050 } 3051 3052 private @Nullable ComponentName getEphemeralResolverLPr() { 3053 final String[] packageArray = 3054 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3055 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3056 if (DEBUG_EPHEMERAL) { 3057 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3058 } 3059 return null; 3060 } 3061 3062 final int callingUid = Binder.getCallingUid(); 3063 final int resolveFlags = 3064 MATCH_DIRECT_BOOT_AWARE 3065 | MATCH_DIRECT_BOOT_UNAWARE 3066 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3067 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE); 3068 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3069 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3070 // temporarily look for the old action 3071 if (resolvers.size() == 0) { 3072 if (DEBUG_EPHEMERAL) { 3073 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3074 } 3075 resolverIntent.setAction(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3076 resolvers = queryIntentServicesInternal(resolverIntent, null, 3077 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3078 } 3079 final int N = resolvers.size(); 3080 if (N == 0) { 3081 if (DEBUG_EPHEMERAL) { 3082 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3083 } 3084 return null; 3085 } 3086 3087 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3088 for (int i = 0; i < N; i++) { 3089 final ResolveInfo info = resolvers.get(i); 3090 3091 if (info.serviceInfo == null) { 3092 continue; 3093 } 3094 3095 final String packageName = info.serviceInfo.packageName; 3096 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3097 if (DEBUG_EPHEMERAL) { 3098 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3099 + " pkg: " + packageName + ", info:" + info); 3100 } 3101 continue; 3102 } 3103 3104 if (DEBUG_EPHEMERAL) { 3105 Slog.v(TAG, "Ephemeral resolver found;" 3106 + " pkg: " + packageName + ", info:" + info); 3107 } 3108 return new ComponentName(packageName, info.serviceInfo.name); 3109 } 3110 if (DEBUG_EPHEMERAL) { 3111 Slog.v(TAG, "Ephemeral resolver NOT found"); 3112 } 3113 return null; 3114 } 3115 3116 private @Nullable ActivityInfo getEphemeralInstallerLPr() { 3117 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3118 intent.addCategory(Intent.CATEGORY_DEFAULT); 3119 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3120 3121 final int resolveFlags = 3122 MATCH_DIRECT_BOOT_AWARE 3123 | MATCH_DIRECT_BOOT_UNAWARE 3124 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3125 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3126 resolveFlags, UserHandle.USER_SYSTEM); 3127 // temporarily look for the old action 3128 if (matches.isEmpty()) { 3129 if (DEBUG_EPHEMERAL) { 3130 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3131 } 3132 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3133 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3134 resolveFlags, UserHandle.USER_SYSTEM); 3135 } 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.INSTALL_PACKAGES, 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 (ActivityInfo) matches.get(0).getComponentInfo(); 3152 } else { 3153 throw new RuntimeException( 3154 "There must be at most one ephemeral installer; found " + matches); 3155 } 3156 } 3157 3158 private @Nullable ComponentName getEphemeralResolverSettingsLPr( 3159 @NonNull ComponentName resolver) { 3160 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3161 .addCategory(Intent.CATEGORY_DEFAULT) 3162 .setPackage(resolver.getPackageName()); 3163 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3164 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3165 UserHandle.USER_SYSTEM); 3166 // temporarily look for the old action 3167 if (matches.isEmpty()) { 3168 if (DEBUG_EPHEMERAL) { 3169 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3170 } 3171 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3172 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3173 UserHandle.USER_SYSTEM); 3174 } 3175 if (matches.isEmpty()) { 3176 return null; 3177 } 3178 return matches.get(0).getComponentInfo().getComponentName(); 3179 } 3180 3181 private void primeDomainVerificationsLPw(int userId) { 3182 if (DEBUG_DOMAIN_VERIFICATION) { 3183 Slog.d(TAG, "Priming domain verifications in user " + userId); 3184 } 3185 3186 SystemConfig systemConfig = SystemConfig.getInstance(); 3187 ArraySet<String> packages = systemConfig.getLinkedApps(); 3188 3189 for (String packageName : packages) { 3190 PackageParser.Package pkg = mPackages.get(packageName); 3191 if (pkg != null) { 3192 if (!pkg.isSystemApp()) { 3193 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3194 continue; 3195 } 3196 3197 ArraySet<String> domains = null; 3198 for (PackageParser.Activity a : pkg.activities) { 3199 for (ActivityIntentInfo filter : a.intents) { 3200 if (hasValidDomains(filter)) { 3201 if (domains == null) { 3202 domains = new ArraySet<String>(); 3203 } 3204 domains.addAll(filter.getHostsList()); 3205 } 3206 } 3207 } 3208 3209 if (domains != null && domains.size() > 0) { 3210 if (DEBUG_DOMAIN_VERIFICATION) { 3211 Slog.v(TAG, " + " + packageName); 3212 } 3213 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3214 // state w.r.t. the formal app-linkage "no verification attempted" state; 3215 // and then 'always' in the per-user state actually used for intent resolution. 3216 final IntentFilterVerificationInfo ivi; 3217 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3218 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3219 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3220 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3221 } else { 3222 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3223 + "' does not handle web links"); 3224 } 3225 } else { 3226 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3227 } 3228 } 3229 3230 scheduleWritePackageRestrictionsLocked(userId); 3231 scheduleWriteSettingsLocked(); 3232 } 3233 3234 private void applyFactoryDefaultBrowserLPw(int userId) { 3235 // The default browser app's package name is stored in a string resource, 3236 // with a product-specific overlay used for vendor customization. 3237 String browserPkg = mContext.getResources().getString( 3238 com.android.internal.R.string.default_browser); 3239 if (!TextUtils.isEmpty(browserPkg)) { 3240 // non-empty string => required to be a known package 3241 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3242 if (ps == null) { 3243 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3244 browserPkg = null; 3245 } else { 3246 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3247 } 3248 } 3249 3250 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3251 // default. If there's more than one, just leave everything alone. 3252 if (browserPkg == null) { 3253 calculateDefaultBrowserLPw(userId); 3254 } 3255 } 3256 3257 private void calculateDefaultBrowserLPw(int userId) { 3258 List<String> allBrowsers = resolveAllBrowserApps(userId); 3259 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3260 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3261 } 3262 3263 private List<String> resolveAllBrowserApps(int userId) { 3264 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3265 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3266 PackageManager.MATCH_ALL, userId); 3267 3268 final int count = list.size(); 3269 List<String> result = new ArrayList<String>(count); 3270 for (int i=0; i<count; i++) { 3271 ResolveInfo info = list.get(i); 3272 if (info.activityInfo == null 3273 || !info.handleAllWebDataURI 3274 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3275 || result.contains(info.activityInfo.packageName)) { 3276 continue; 3277 } 3278 result.add(info.activityInfo.packageName); 3279 } 3280 3281 return result; 3282 } 3283 3284 private boolean packageIsBrowser(String packageName, int userId) { 3285 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3286 PackageManager.MATCH_ALL, userId); 3287 final int N = list.size(); 3288 for (int i = 0; i < N; i++) { 3289 ResolveInfo info = list.get(i); 3290 if (packageName.equals(info.activityInfo.packageName)) { 3291 return true; 3292 } 3293 } 3294 return false; 3295 } 3296 3297 private void checkDefaultBrowser() { 3298 final int myUserId = UserHandle.myUserId(); 3299 final String packageName = getDefaultBrowserPackageName(myUserId); 3300 if (packageName != null) { 3301 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3302 if (info == null) { 3303 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3304 synchronized (mPackages) { 3305 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3306 } 3307 } 3308 } 3309 } 3310 3311 @Override 3312 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3313 throws RemoteException { 3314 try { 3315 return super.onTransact(code, data, reply, flags); 3316 } catch (RuntimeException e) { 3317 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3318 Slog.wtf(TAG, "Package Manager Crash", e); 3319 } 3320 throw e; 3321 } 3322 } 3323 3324 static int[] appendInts(int[] cur, int[] add) { 3325 if (add == null) return cur; 3326 if (cur == null) return add; 3327 final int N = add.length; 3328 for (int i=0; i<N; i++) { 3329 cur = appendInt(cur, add[i]); 3330 } 3331 return cur; 3332 } 3333 3334 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3335 if (!sUserManager.exists(userId)) return null; 3336 if (ps == null) { 3337 return null; 3338 } 3339 final PackageParser.Package p = ps.pkg; 3340 if (p == null) { 3341 return null; 3342 } 3343 // Filter out ephemeral app metadata: 3344 // * The system/shell/root can see metadata for any app 3345 // * An installed app can see metadata for 1) other installed apps 3346 // and 2) ephemeral apps that have explicitly interacted with it 3347 // * Ephemeral apps can only see their own data and exposed installed apps 3348 // * Holding a signature permission allows seeing instant apps 3349 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3350 if (callingAppId != Process.SYSTEM_UID 3351 && callingAppId != Process.SHELL_UID 3352 && callingAppId != Process.ROOT_UID 3353 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3354 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3355 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3356 if (instantAppPackageName != null) { 3357 // ephemeral apps can only get information on themselves or 3358 // installed apps that are exposed. 3359 if (!instantAppPackageName.equals(p.packageName) 3360 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3361 return null; 3362 } 3363 } else { 3364 if (ps.getInstantApp(userId)) { 3365 // only get access to the ephemeral app if we've been granted access 3366 if (!mInstantAppRegistry.isInstantAccessGranted( 3367 userId, callingAppId, ps.appId)) { 3368 return null; 3369 } 3370 } 3371 } 3372 } 3373 3374 final PermissionsState permissionsState = ps.getPermissionsState(); 3375 3376 // Compute GIDs only if requested 3377 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3378 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3379 // Compute granted permissions only if package has requested permissions 3380 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3381 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3382 final PackageUserState state = ps.readUserState(userId); 3383 3384 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3385 && ps.isSystem()) { 3386 flags |= MATCH_ANY_USER; 3387 } 3388 3389 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3390 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3391 3392 if (packageInfo == null) { 3393 return null; 3394 } 3395 3396 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3397 3398 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3399 resolveExternalPackageNameLPr(p); 3400 3401 return packageInfo; 3402 } 3403 3404 @Override 3405 public void checkPackageStartable(String packageName, int userId) { 3406 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3407 3408 synchronized (mPackages) { 3409 final PackageSetting ps = mSettings.mPackages.get(packageName); 3410 if (ps == null) { 3411 throw new SecurityException("Package " + packageName + " was not found!"); 3412 } 3413 3414 if (!ps.getInstalled(userId)) { 3415 throw new SecurityException( 3416 "Package " + packageName + " was not installed for user " + userId + "!"); 3417 } 3418 3419 if (mSafeMode && !ps.isSystem()) { 3420 throw new SecurityException("Package " + packageName + " not a system app!"); 3421 } 3422 3423 if (mFrozenPackages.contains(packageName)) { 3424 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3425 } 3426 3427 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3428 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3429 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3430 } 3431 } 3432 } 3433 3434 @Override 3435 public boolean isPackageAvailable(String packageName, int userId) { 3436 if (!sUserManager.exists(userId)) return false; 3437 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3438 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3439 synchronized (mPackages) { 3440 PackageParser.Package p = mPackages.get(packageName); 3441 if (p != null) { 3442 final PackageSetting ps = (PackageSetting) p.mExtras; 3443 if (ps != null) { 3444 final PackageUserState state = ps.readUserState(userId); 3445 if (state != null) { 3446 return PackageParser.isAvailable(state); 3447 } 3448 } 3449 } 3450 } 3451 return false; 3452 } 3453 3454 @Override 3455 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3456 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3457 flags, userId); 3458 } 3459 3460 @Override 3461 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3462 int flags, int userId) { 3463 return getPackageInfoInternal(versionedPackage.getPackageName(), 3464 // TODO: We will change version code to long, so in the new API it is long 3465 (int) versionedPackage.getVersionCode(), flags, userId); 3466 } 3467 3468 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3469 int flags, int userId) { 3470 if (!sUserManager.exists(userId)) return null; 3471 flags = updateFlagsForPackage(flags, userId, packageName); 3472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3473 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3474 3475 // reader 3476 synchronized (mPackages) { 3477 // Normalize package name to handle renamed packages and static libs 3478 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3479 3480 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3481 if (matchFactoryOnly) { 3482 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3483 if (ps != null) { 3484 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3485 return null; 3486 } 3487 return generatePackageInfo(ps, flags, userId); 3488 } 3489 } 3490 3491 PackageParser.Package p = mPackages.get(packageName); 3492 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3493 return null; 3494 } 3495 if (DEBUG_PACKAGE_INFO) 3496 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3497 if (p != null) { 3498 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3499 Binder.getCallingUid(), userId)) { 3500 return null; 3501 } 3502 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3503 } 3504 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3505 final PackageSetting ps = mSettings.mPackages.get(packageName); 3506 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3507 return null; 3508 } 3509 return generatePackageInfo(ps, flags, userId); 3510 } 3511 } 3512 return null; 3513 } 3514 3515 3516 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3517 // System/shell/root get to see all static libs 3518 final int appId = UserHandle.getAppId(uid); 3519 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3520 || appId == Process.ROOT_UID) { 3521 return false; 3522 } 3523 3524 // No package means no static lib as it is always on internal storage 3525 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3526 return false; 3527 } 3528 3529 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3530 ps.pkg.staticSharedLibVersion); 3531 if (libEntry == null) { 3532 return false; 3533 } 3534 3535 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3536 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3537 if (uidPackageNames == null) { 3538 return true; 3539 } 3540 3541 for (String uidPackageName : uidPackageNames) { 3542 if (ps.name.equals(uidPackageName)) { 3543 return false; 3544 } 3545 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3546 if (uidPs != null) { 3547 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3548 libEntry.info.getName()); 3549 if (index < 0) { 3550 continue; 3551 } 3552 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3553 return false; 3554 } 3555 } 3556 } 3557 return true; 3558 } 3559 3560 @Override 3561 public String[] currentToCanonicalPackageNames(String[] names) { 3562 String[] out = new String[names.length]; 3563 // reader 3564 synchronized (mPackages) { 3565 for (int i=names.length-1; i>=0; i--) { 3566 PackageSetting ps = mSettings.mPackages.get(names[i]); 3567 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3568 } 3569 } 3570 return out; 3571 } 3572 3573 @Override 3574 public String[] canonicalToCurrentPackageNames(String[] names) { 3575 String[] out = new String[names.length]; 3576 // reader 3577 synchronized (mPackages) { 3578 for (int i=names.length-1; i>=0; i--) { 3579 String cur = mSettings.getRenamedPackageLPr(names[i]); 3580 out[i] = cur != null ? cur : names[i]; 3581 } 3582 } 3583 return out; 3584 } 3585 3586 @Override 3587 public int getPackageUid(String packageName, int flags, int userId) { 3588 if (!sUserManager.exists(userId)) return -1; 3589 flags = updateFlagsForPackage(flags, userId, packageName); 3590 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3591 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3592 3593 // reader 3594 synchronized (mPackages) { 3595 final PackageParser.Package p = mPackages.get(packageName); 3596 if (p != null && p.isMatch(flags)) { 3597 return UserHandle.getUid(userId, p.applicationInfo.uid); 3598 } 3599 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3600 final PackageSetting ps = mSettings.mPackages.get(packageName); 3601 if (ps != null && ps.isMatch(flags)) { 3602 return UserHandle.getUid(userId, ps.appId); 3603 } 3604 } 3605 } 3606 3607 return -1; 3608 } 3609 3610 @Override 3611 public int[] getPackageGids(String packageName, int flags, int userId) { 3612 if (!sUserManager.exists(userId)) return null; 3613 flags = updateFlagsForPackage(flags, userId, packageName); 3614 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3615 false /* requireFullPermission */, false /* checkShell */, 3616 "getPackageGids"); 3617 3618 // reader 3619 synchronized (mPackages) { 3620 final PackageParser.Package p = mPackages.get(packageName); 3621 if (p != null && p.isMatch(flags)) { 3622 PackageSetting ps = (PackageSetting) p.mExtras; 3623 // TODO: Shouldn't this be checking for package installed state for userId and 3624 // return null? 3625 return ps.getPermissionsState().computeGids(userId); 3626 } 3627 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3628 final PackageSetting ps = mSettings.mPackages.get(packageName); 3629 if (ps != null && ps.isMatch(flags)) { 3630 return ps.getPermissionsState().computeGids(userId); 3631 } 3632 } 3633 } 3634 3635 return null; 3636 } 3637 3638 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3639 if (bp.perm != null) { 3640 return PackageParser.generatePermissionInfo(bp.perm, flags); 3641 } 3642 PermissionInfo pi = new PermissionInfo(); 3643 pi.name = bp.name; 3644 pi.packageName = bp.sourcePackage; 3645 pi.nonLocalizedLabel = bp.name; 3646 pi.protectionLevel = bp.protectionLevel; 3647 return pi; 3648 } 3649 3650 @Override 3651 public PermissionInfo getPermissionInfo(String name, int flags) { 3652 // reader 3653 synchronized (mPackages) { 3654 final BasePermission p = mSettings.mPermissions.get(name); 3655 if (p != null) { 3656 return generatePermissionInfo(p, flags); 3657 } 3658 return null; 3659 } 3660 } 3661 3662 @Override 3663 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3664 int flags) { 3665 // reader 3666 synchronized (mPackages) { 3667 if (group != null && !mPermissionGroups.containsKey(group)) { 3668 // This is thrown as NameNotFoundException 3669 return null; 3670 } 3671 3672 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3673 for (BasePermission p : mSettings.mPermissions.values()) { 3674 if (group == null) { 3675 if (p.perm == null || p.perm.info.group == null) { 3676 out.add(generatePermissionInfo(p, flags)); 3677 } 3678 } else { 3679 if (p.perm != null && group.equals(p.perm.info.group)) { 3680 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3681 } 3682 } 3683 } 3684 return new ParceledListSlice<>(out); 3685 } 3686 } 3687 3688 @Override 3689 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3690 // reader 3691 synchronized (mPackages) { 3692 return PackageParser.generatePermissionGroupInfo( 3693 mPermissionGroups.get(name), flags); 3694 } 3695 } 3696 3697 @Override 3698 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3699 // reader 3700 synchronized (mPackages) { 3701 final int N = mPermissionGroups.size(); 3702 ArrayList<PermissionGroupInfo> out 3703 = new ArrayList<PermissionGroupInfo>(N); 3704 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3705 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3706 } 3707 return new ParceledListSlice<>(out); 3708 } 3709 } 3710 3711 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3712 int uid, int userId) { 3713 if (!sUserManager.exists(userId)) return null; 3714 PackageSetting ps = mSettings.mPackages.get(packageName); 3715 if (ps != null) { 3716 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3717 return null; 3718 } 3719 if (ps.pkg == null) { 3720 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3721 if (pInfo != null) { 3722 return pInfo.applicationInfo; 3723 } 3724 return null; 3725 } 3726 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3727 ps.readUserState(userId), userId); 3728 if (ai != null) { 3729 rebaseEnabledOverlays(ai, userId); 3730 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3731 } 3732 return ai; 3733 } 3734 return null; 3735 } 3736 3737 @Override 3738 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3739 if (!sUserManager.exists(userId)) return null; 3740 flags = updateFlagsForApplication(flags, userId, packageName); 3741 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3742 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3743 3744 // writer 3745 synchronized (mPackages) { 3746 // Normalize package name to handle renamed packages and static libs 3747 packageName = resolveInternalPackageNameLPr(packageName, 3748 PackageManager.VERSION_CODE_HIGHEST); 3749 3750 PackageParser.Package p = mPackages.get(packageName); 3751 if (DEBUG_PACKAGE_INFO) Log.v( 3752 TAG, "getApplicationInfo " + packageName 3753 + ": " + p); 3754 if (p != null) { 3755 PackageSetting ps = mSettings.mPackages.get(packageName); 3756 if (ps == null) return null; 3757 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3758 return null; 3759 } 3760 // Note: isEnabledLP() does not apply here - always return info 3761 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3762 p, flags, ps.readUserState(userId), userId); 3763 if (ai != null) { 3764 rebaseEnabledOverlays(ai, userId); 3765 ai.packageName = resolveExternalPackageNameLPr(p); 3766 } 3767 return ai; 3768 } 3769 if ("android".equals(packageName)||"system".equals(packageName)) { 3770 return mAndroidApplication; 3771 } 3772 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3773 // Already generates the external package name 3774 return generateApplicationInfoFromSettingsLPw(packageName, 3775 Binder.getCallingUid(), flags, userId); 3776 } 3777 } 3778 return null; 3779 } 3780 3781 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3782 List<String> paths = new ArrayList<>(); 3783 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3784 mEnabledOverlayPaths.get(userId); 3785 if (userSpecificOverlays != null) { 3786 if (!"android".equals(ai.packageName)) { 3787 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3788 if (frameworkOverlays != null) { 3789 paths.addAll(frameworkOverlays); 3790 } 3791 } 3792 3793 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3794 if (appOverlays != null) { 3795 paths.addAll(appOverlays); 3796 } 3797 } 3798 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3799 } 3800 3801 private String normalizePackageNameLPr(String packageName) { 3802 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3803 return normalizedPackageName != null ? normalizedPackageName : packageName; 3804 } 3805 3806 @Override 3807 public void deletePreloadsFileCache() { 3808 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3809 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3810 } 3811 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3812 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3813 FileUtils.deleteContents(dir); 3814 } 3815 3816 @Override 3817 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3818 final IPackageDataObserver observer) { 3819 mContext.enforceCallingOrSelfPermission( 3820 android.Manifest.permission.CLEAR_APP_CACHE, null); 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 (observer != null) { 3830 try { 3831 observer.onRemoveCompleted(null, success); 3832 } catch (RemoteException e) { 3833 Slog.w(TAG, e); 3834 } 3835 } 3836 }); 3837 } 3838 3839 @Override 3840 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3841 final IntentSender pi) { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3844 mHandler.post(() -> { 3845 boolean success = false; 3846 try { 3847 freeStorage(volumeUuid, freeStorageSize, 0); 3848 success = true; 3849 } catch (IOException e) { 3850 Slog.w(TAG, e); 3851 } 3852 if (pi != null) { 3853 try { 3854 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3855 } catch (SendIntentException e) { 3856 Slog.w(TAG, e); 3857 } 3858 } 3859 }); 3860 } 3861 3862 /** 3863 * Blocking call to clear various types of cached data across the system 3864 * until the requested bytes are available. 3865 */ 3866 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3867 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3868 final File file = storage.findPathForUuid(volumeUuid); 3869 if (file.getUsableSpace() >= bytes) return; 3870 3871 if (ENABLE_FREE_CACHE_V2) { 3872 final boolean aggressive = (storageFlags 3873 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3874 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3875 volumeUuid); 3876 3877 // 1. Pre-flight to determine if we have any chance to succeed 3878 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3879 if (internalVolume && (aggressive || SystemProperties 3880 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3881 deletePreloadsFileCache(); 3882 if (file.getUsableSpace() >= bytes) return; 3883 } 3884 3885 // 3. Consider parsed APK data (aggressive only) 3886 if (internalVolume && aggressive) { 3887 FileUtils.deleteContents(mCacheDir); 3888 if (file.getUsableSpace() >= bytes) return; 3889 } 3890 3891 // 4. Consider cached app data (above quotas) 3892 try { 3893 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3894 } catch (InstallerException ignored) { 3895 } 3896 if (file.getUsableSpace() >= bytes) return; 3897 3898 // 5. Consider shared libraries with refcount=0 and age>2h 3899 // 6. Consider dexopt output (aggressive only) 3900 // 7. Consider ephemeral apps not used in last week 3901 3902 // 8. Consider cached app data (below quotas) 3903 try { 3904 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3905 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3906 } catch (InstallerException ignored) { 3907 } 3908 if (file.getUsableSpace() >= bytes) return; 3909 3910 // 9. Consider DropBox entries 3911 // 10. Consider ephemeral cookies 3912 3913 } else { 3914 try { 3915 mInstaller.freeCache(volumeUuid, bytes, 0); 3916 } catch (InstallerException ignored) { 3917 } 3918 if (file.getUsableSpace() >= bytes) return; 3919 } 3920 3921 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3922 } 3923 3924 /** 3925 * Update given flags based on encryption status of current user. 3926 */ 3927 private int updateFlags(int flags, int userId) { 3928 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3929 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3930 // Caller expressed an explicit opinion about what encryption 3931 // aware/unaware components they want to see, so fall through and 3932 // give them what they want 3933 } else { 3934 // Caller expressed no opinion, so match based on user state 3935 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3936 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3937 } else { 3938 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3939 } 3940 } 3941 return flags; 3942 } 3943 3944 private UserManagerInternal getUserManagerInternal() { 3945 if (mUserManagerInternal == null) { 3946 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3947 } 3948 return mUserManagerInternal; 3949 } 3950 3951 private DeviceIdleController.LocalService getDeviceIdleController() { 3952 if (mDeviceIdleController == null) { 3953 mDeviceIdleController = 3954 LocalServices.getService(DeviceIdleController.LocalService.class); 3955 } 3956 return mDeviceIdleController; 3957 } 3958 3959 /** 3960 * Update given flags when being used to request {@link PackageInfo}. 3961 */ 3962 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3963 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3964 boolean triaged = true; 3965 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3966 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3967 // Caller is asking for component details, so they'd better be 3968 // asking for specific encryption matching behavior, or be triaged 3969 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3970 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3971 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3972 triaged = false; 3973 } 3974 } 3975 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3976 | PackageManager.MATCH_SYSTEM_ONLY 3977 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3978 triaged = false; 3979 } 3980 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3981 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3982 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3983 + Debug.getCallers(5)); 3984 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3985 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3986 // If the caller wants all packages and has a restricted profile associated with it, 3987 // then match all users. This is to make sure that launchers that need to access work 3988 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3989 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3990 flags |= PackageManager.MATCH_ANY_USER; 3991 } 3992 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3993 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3994 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3995 } 3996 return updateFlags(flags, userId); 3997 } 3998 3999 /** 4000 * Update given flags when being used to request {@link ApplicationInfo}. 4001 */ 4002 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4003 return updateFlagsForPackage(flags, userId, cookie); 4004 } 4005 4006 /** 4007 * Update given flags when being used to request {@link ComponentInfo}. 4008 */ 4009 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4010 if (cookie instanceof Intent) { 4011 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4012 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4013 } 4014 } 4015 4016 boolean triaged = true; 4017 // Caller is asking for component details, so they'd better be 4018 // asking for specific encryption matching behavior, or be triaged 4019 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4020 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4021 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4022 triaged = false; 4023 } 4024 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4025 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4026 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4027 } 4028 4029 return updateFlags(flags, userId); 4030 } 4031 4032 /** 4033 * Update given intent when being used to request {@link ResolveInfo}. 4034 */ 4035 private Intent updateIntentForResolve(Intent intent) { 4036 if (intent.getSelector() != null) { 4037 intent = intent.getSelector(); 4038 } 4039 if (DEBUG_PREFERRED) { 4040 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4041 } 4042 return intent; 4043 } 4044 4045 /** 4046 * Update given flags when being used to request {@link ResolveInfo}. 4047 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4048 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4049 * flag set. However, this flag is only honoured in three circumstances: 4050 * <ul> 4051 * <li>when called from a system process</li> 4052 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4053 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4054 * action and a {@code android.intent.category.BROWSABLE} category</li> 4055 * </ul> 4056 */ 4057 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4058 boolean includeInstantApps) { 4059 // Safe mode means we shouldn't match any third-party components 4060 if (mSafeMode) { 4061 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4062 } 4063 if (getInstantAppPackageName(callingUid) != null) { 4064 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4065 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4066 flags |= PackageManager.MATCH_INSTANT; 4067 } else { 4068 // Otherwise, prevent leaking ephemeral components 4069 final boolean isSpecialProcess = 4070 callingUid == Process.SYSTEM_UID 4071 || callingUid == Process.SHELL_UID 4072 || callingUid == 0; 4073 final boolean allowMatchInstant = 4074 (includeInstantApps 4075 && Intent.ACTION_VIEW.equals(intent.getAction()) 4076 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4077 && hasWebURI(intent)) 4078 || isSpecialProcess 4079 || mContext.checkCallingOrSelfPermission( 4080 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4081 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4082 if (!allowMatchInstant) { 4083 flags &= ~PackageManager.MATCH_INSTANT; 4084 } 4085 } 4086 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4087 } 4088 4089 @Override 4090 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4091 if (!sUserManager.exists(userId)) return null; 4092 flags = updateFlagsForComponent(flags, userId, component); 4093 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4094 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4095 synchronized (mPackages) { 4096 PackageParser.Activity a = mActivities.mActivities.get(component); 4097 4098 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4099 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4100 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4101 if (ps == null) return null; 4102 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4103 userId); 4104 } 4105 if (mResolveComponentName.equals(component)) { 4106 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4107 new PackageUserState(), userId); 4108 } 4109 } 4110 return null; 4111 } 4112 4113 @Override 4114 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4115 String resolvedType) { 4116 synchronized (mPackages) { 4117 if (component.equals(mResolveComponentName)) { 4118 // The resolver supports EVERYTHING! 4119 return true; 4120 } 4121 PackageParser.Activity a = mActivities.mActivities.get(component); 4122 if (a == null) { 4123 return false; 4124 } 4125 for (int i=0; i<a.intents.size(); i++) { 4126 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4127 intent.getData(), intent.getCategories(), TAG) >= 0) { 4128 return true; 4129 } 4130 } 4131 return false; 4132 } 4133 } 4134 4135 @Override 4136 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4137 if (!sUserManager.exists(userId)) return null; 4138 flags = updateFlagsForComponent(flags, userId, component); 4139 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4140 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4141 synchronized (mPackages) { 4142 PackageParser.Activity a = mReceivers.mActivities.get(component); 4143 if (DEBUG_PACKAGE_INFO) Log.v( 4144 TAG, "getReceiverInfo " + component + ": " + a); 4145 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4146 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4147 if (ps == null) return null; 4148 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4149 ps.readUserState(userId), userId); 4150 if (ri != null) { 4151 rebaseEnabledOverlays(ri.applicationInfo, userId); 4152 } 4153 return ri; 4154 } 4155 } 4156 return null; 4157 } 4158 4159 @Override 4160 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4161 if (!sUserManager.exists(userId)) return null; 4162 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4163 4164 flags = updateFlagsForPackage(flags, userId, null); 4165 4166 final boolean canSeeStaticLibraries = 4167 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4168 == PERMISSION_GRANTED 4169 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4170 == PERMISSION_GRANTED 4171 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4172 == PERMISSION_GRANTED 4173 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4174 == PERMISSION_GRANTED; 4175 4176 synchronized (mPackages) { 4177 List<SharedLibraryInfo> result = null; 4178 4179 final int libCount = mSharedLibraries.size(); 4180 for (int i = 0; i < libCount; i++) { 4181 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4182 if (versionedLib == null) { 4183 continue; 4184 } 4185 4186 final int versionCount = versionedLib.size(); 4187 for (int j = 0; j < versionCount; j++) { 4188 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4189 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4190 break; 4191 } 4192 final long identity = Binder.clearCallingIdentity(); 4193 try { 4194 // TODO: We will change version code to long, so in the new API it is long 4195 PackageInfo packageInfo = getPackageInfoVersioned( 4196 libInfo.getDeclaringPackage(), flags, userId); 4197 if (packageInfo == null) { 4198 continue; 4199 } 4200 } finally { 4201 Binder.restoreCallingIdentity(identity); 4202 } 4203 4204 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4205 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4206 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4207 4208 if (result == null) { 4209 result = new ArrayList<>(); 4210 } 4211 result.add(resLibInfo); 4212 } 4213 } 4214 4215 return result != null ? new ParceledListSlice<>(result) : null; 4216 } 4217 } 4218 4219 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4220 SharedLibraryInfo libInfo, int flags, int userId) { 4221 List<VersionedPackage> versionedPackages = null; 4222 final int packageCount = mSettings.mPackages.size(); 4223 for (int i = 0; i < packageCount; i++) { 4224 PackageSetting ps = mSettings.mPackages.valueAt(i); 4225 4226 if (ps == null) { 4227 continue; 4228 } 4229 4230 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4231 continue; 4232 } 4233 4234 final String libName = libInfo.getName(); 4235 if (libInfo.isStatic()) { 4236 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4237 if (libIdx < 0) { 4238 continue; 4239 } 4240 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4241 continue; 4242 } 4243 if (versionedPackages == null) { 4244 versionedPackages = new ArrayList<>(); 4245 } 4246 // If the dependent is a static shared lib, use the public package name 4247 String dependentPackageName = ps.name; 4248 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4249 dependentPackageName = ps.pkg.manifestPackageName; 4250 } 4251 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4252 } else if (ps.pkg != null) { 4253 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4254 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4255 if (versionedPackages == null) { 4256 versionedPackages = new ArrayList<>(); 4257 } 4258 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4259 } 4260 } 4261 } 4262 4263 return versionedPackages; 4264 } 4265 4266 @Override 4267 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4268 if (!sUserManager.exists(userId)) return null; 4269 flags = updateFlagsForComponent(flags, userId, component); 4270 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4271 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4272 synchronized (mPackages) { 4273 PackageParser.Service s = mServices.mServices.get(component); 4274 if (DEBUG_PACKAGE_INFO) Log.v( 4275 TAG, "getServiceInfo " + component + ": " + s); 4276 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4277 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4278 if (ps == null) return null; 4279 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4280 ps.readUserState(userId), userId); 4281 if (si != null) { 4282 rebaseEnabledOverlays(si.applicationInfo, userId); 4283 } 4284 return si; 4285 } 4286 } 4287 return null; 4288 } 4289 4290 @Override 4291 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4292 if (!sUserManager.exists(userId)) return null; 4293 flags = updateFlagsForComponent(flags, userId, component); 4294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4295 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4296 synchronized (mPackages) { 4297 PackageParser.Provider p = mProviders.mProviders.get(component); 4298 if (DEBUG_PACKAGE_INFO) Log.v( 4299 TAG, "getProviderInfo " + component + ": " + p); 4300 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4301 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4302 if (ps == null) return null; 4303 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4304 ps.readUserState(userId), userId); 4305 if (pi != null) { 4306 rebaseEnabledOverlays(pi.applicationInfo, userId); 4307 } 4308 return pi; 4309 } 4310 } 4311 return null; 4312 } 4313 4314 @Override 4315 public String[] getSystemSharedLibraryNames() { 4316 synchronized (mPackages) { 4317 Set<String> libs = null; 4318 final int libCount = mSharedLibraries.size(); 4319 for (int i = 0; i < libCount; i++) { 4320 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4321 if (versionedLib == null) { 4322 continue; 4323 } 4324 final int versionCount = versionedLib.size(); 4325 for (int j = 0; j < versionCount; j++) { 4326 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4327 if (!libEntry.info.isStatic()) { 4328 if (libs == null) { 4329 libs = new ArraySet<>(); 4330 } 4331 libs.add(libEntry.info.getName()); 4332 break; 4333 } 4334 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4335 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4336 UserHandle.getUserId(Binder.getCallingUid()))) { 4337 if (libs == null) { 4338 libs = new ArraySet<>(); 4339 } 4340 libs.add(libEntry.info.getName()); 4341 break; 4342 } 4343 } 4344 } 4345 4346 if (libs != null) { 4347 String[] libsArray = new String[libs.size()]; 4348 libs.toArray(libsArray); 4349 return libsArray; 4350 } 4351 4352 return null; 4353 } 4354 } 4355 4356 @Override 4357 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4358 synchronized (mPackages) { 4359 return mServicesSystemSharedLibraryPackageName; 4360 } 4361 } 4362 4363 @Override 4364 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4365 synchronized (mPackages) { 4366 return mSharedSystemSharedLibraryPackageName; 4367 } 4368 } 4369 4370 private void updateSequenceNumberLP(String packageName, int[] userList) { 4371 for (int i = userList.length - 1; i >= 0; --i) { 4372 final int userId = userList[i]; 4373 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4374 if (changedPackages == null) { 4375 changedPackages = new SparseArray<>(); 4376 mChangedPackages.put(userId, changedPackages); 4377 } 4378 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4379 if (sequenceNumbers == null) { 4380 sequenceNumbers = new HashMap<>(); 4381 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4382 } 4383 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4384 if (sequenceNumber != null) { 4385 changedPackages.remove(sequenceNumber); 4386 } 4387 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4388 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4389 } 4390 mChangedPackagesSequenceNumber++; 4391 } 4392 4393 @Override 4394 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4395 synchronized (mPackages) { 4396 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4397 return null; 4398 } 4399 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4400 if (changedPackages == null) { 4401 return null; 4402 } 4403 final List<String> packageNames = 4404 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4405 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4406 final String packageName = changedPackages.get(i); 4407 if (packageName != null) { 4408 packageNames.add(packageName); 4409 } 4410 } 4411 return packageNames.isEmpty() 4412 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4413 } 4414 } 4415 4416 @Override 4417 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4418 ArrayList<FeatureInfo> res; 4419 synchronized (mAvailableFeatures) { 4420 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4421 res.addAll(mAvailableFeatures.values()); 4422 } 4423 final FeatureInfo fi = new FeatureInfo(); 4424 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4425 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4426 res.add(fi); 4427 4428 return new ParceledListSlice<>(res); 4429 } 4430 4431 @Override 4432 public boolean hasSystemFeature(String name, int version) { 4433 synchronized (mAvailableFeatures) { 4434 final FeatureInfo feat = mAvailableFeatures.get(name); 4435 if (feat == null) { 4436 return false; 4437 } else { 4438 return feat.version >= version; 4439 } 4440 } 4441 } 4442 4443 @Override 4444 public int checkPermission(String permName, String pkgName, int userId) { 4445 if (!sUserManager.exists(userId)) { 4446 return PackageManager.PERMISSION_DENIED; 4447 } 4448 4449 synchronized (mPackages) { 4450 final PackageParser.Package p = mPackages.get(pkgName); 4451 if (p != null && p.mExtras != null) { 4452 final PackageSetting ps = (PackageSetting) p.mExtras; 4453 final PermissionsState permissionsState = ps.getPermissionsState(); 4454 if (permissionsState.hasPermission(permName, userId)) { 4455 return PackageManager.PERMISSION_GRANTED; 4456 } 4457 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4458 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4459 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4460 return PackageManager.PERMISSION_GRANTED; 4461 } 4462 } 4463 } 4464 4465 return PackageManager.PERMISSION_DENIED; 4466 } 4467 4468 @Override 4469 public int checkUidPermission(String permName, int uid) { 4470 final int userId = UserHandle.getUserId(uid); 4471 4472 if (!sUserManager.exists(userId)) { 4473 return PackageManager.PERMISSION_DENIED; 4474 } 4475 4476 synchronized (mPackages) { 4477 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4478 if (obj != null) { 4479 final SettingBase ps = (SettingBase) obj; 4480 final PermissionsState permissionsState = ps.getPermissionsState(); 4481 if (permissionsState.hasPermission(permName, userId)) { 4482 return PackageManager.PERMISSION_GRANTED; 4483 } 4484 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4485 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4486 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4487 return PackageManager.PERMISSION_GRANTED; 4488 } 4489 } else { 4490 ArraySet<String> perms = mSystemPermissions.get(uid); 4491 if (perms != null) { 4492 if (perms.contains(permName)) { 4493 return PackageManager.PERMISSION_GRANTED; 4494 } 4495 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4496 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4497 return PackageManager.PERMISSION_GRANTED; 4498 } 4499 } 4500 } 4501 } 4502 4503 return PackageManager.PERMISSION_DENIED; 4504 } 4505 4506 @Override 4507 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4508 if (UserHandle.getCallingUserId() != userId) { 4509 mContext.enforceCallingPermission( 4510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4511 "isPermissionRevokedByPolicy for user " + userId); 4512 } 4513 4514 if (checkPermission(permission, packageName, userId) 4515 == PackageManager.PERMISSION_GRANTED) { 4516 return false; 4517 } 4518 4519 final long identity = Binder.clearCallingIdentity(); 4520 try { 4521 final int flags = getPermissionFlags(permission, packageName, userId); 4522 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4523 } finally { 4524 Binder.restoreCallingIdentity(identity); 4525 } 4526 } 4527 4528 @Override 4529 public String getPermissionControllerPackageName() { 4530 synchronized (mPackages) { 4531 return mRequiredInstallerPackage; 4532 } 4533 } 4534 4535 /** 4536 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4537 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4538 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4539 * @param message the message to log on security exception 4540 */ 4541 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4542 boolean checkShell, String message) { 4543 if (userId < 0) { 4544 throw new IllegalArgumentException("Invalid userId " + userId); 4545 } 4546 if (checkShell) { 4547 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4548 } 4549 if (userId == UserHandle.getUserId(callingUid)) return; 4550 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4551 if (requireFullPermission) { 4552 mContext.enforceCallingOrSelfPermission( 4553 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4554 } else { 4555 try { 4556 mContext.enforceCallingOrSelfPermission( 4557 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4558 } catch (SecurityException se) { 4559 mContext.enforceCallingOrSelfPermission( 4560 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4561 } 4562 } 4563 } 4564 } 4565 4566 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4567 if (callingUid == Process.SHELL_UID) { 4568 if (userHandle >= 0 4569 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4570 throw new SecurityException("Shell does not have permission to access user " 4571 + userHandle); 4572 } else if (userHandle < 0) { 4573 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4574 + Debug.getCallers(3)); 4575 } 4576 } 4577 } 4578 4579 private BasePermission findPermissionTreeLP(String permName) { 4580 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4581 if (permName.startsWith(bp.name) && 4582 permName.length() > bp.name.length() && 4583 permName.charAt(bp.name.length()) == '.') { 4584 return bp; 4585 } 4586 } 4587 return null; 4588 } 4589 4590 private BasePermission checkPermissionTreeLP(String permName) { 4591 if (permName != null) { 4592 BasePermission bp = findPermissionTreeLP(permName); 4593 if (bp != null) { 4594 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4595 return bp; 4596 } 4597 throw new SecurityException("Calling uid " 4598 + Binder.getCallingUid() 4599 + " is not allowed to add to permission tree " 4600 + bp.name + " owned by uid " + bp.uid); 4601 } 4602 } 4603 throw new SecurityException("No permission tree found for " + permName); 4604 } 4605 4606 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4607 if (s1 == null) { 4608 return s2 == null; 4609 } 4610 if (s2 == null) { 4611 return false; 4612 } 4613 if (s1.getClass() != s2.getClass()) { 4614 return false; 4615 } 4616 return s1.equals(s2); 4617 } 4618 4619 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4620 if (pi1.icon != pi2.icon) return false; 4621 if (pi1.logo != pi2.logo) return false; 4622 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4623 if (!compareStrings(pi1.name, pi2.name)) return false; 4624 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4625 // We'll take care of setting this one. 4626 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4627 // These are not currently stored in settings. 4628 //if (!compareStrings(pi1.group, pi2.group)) return false; 4629 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4630 //if (pi1.labelRes != pi2.labelRes) return false; 4631 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4632 return true; 4633 } 4634 4635 int permissionInfoFootprint(PermissionInfo info) { 4636 int size = info.name.length(); 4637 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4638 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4639 return size; 4640 } 4641 4642 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4643 int size = 0; 4644 for (BasePermission perm : mSettings.mPermissions.values()) { 4645 if (perm.uid == tree.uid) { 4646 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4647 } 4648 } 4649 return size; 4650 } 4651 4652 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4653 // We calculate the max size of permissions defined by this uid and throw 4654 // if that plus the size of 'info' would exceed our stated maximum. 4655 if (tree.uid != Process.SYSTEM_UID) { 4656 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4657 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4658 throw new SecurityException("Permission tree size cap exceeded"); 4659 } 4660 } 4661 } 4662 4663 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4664 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4665 throw new SecurityException("Label must be specified in permission"); 4666 } 4667 BasePermission tree = checkPermissionTreeLP(info.name); 4668 BasePermission bp = mSettings.mPermissions.get(info.name); 4669 boolean added = bp == null; 4670 boolean changed = true; 4671 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4672 if (added) { 4673 enforcePermissionCapLocked(info, tree); 4674 bp = new BasePermission(info.name, tree.sourcePackage, 4675 BasePermission.TYPE_DYNAMIC); 4676 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4677 throw new SecurityException( 4678 "Not allowed to modify non-dynamic permission " 4679 + info.name); 4680 } else { 4681 if (bp.protectionLevel == fixedLevel 4682 && bp.perm.owner.equals(tree.perm.owner) 4683 && bp.uid == tree.uid 4684 && comparePermissionInfos(bp.perm.info, info)) { 4685 changed = false; 4686 } 4687 } 4688 bp.protectionLevel = fixedLevel; 4689 info = new PermissionInfo(info); 4690 info.protectionLevel = fixedLevel; 4691 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4692 bp.perm.info.packageName = tree.perm.info.packageName; 4693 bp.uid = tree.uid; 4694 if (added) { 4695 mSettings.mPermissions.put(info.name, bp); 4696 } 4697 if (changed) { 4698 if (!async) { 4699 mSettings.writeLPr(); 4700 } else { 4701 scheduleWriteSettingsLocked(); 4702 } 4703 } 4704 return added; 4705 } 4706 4707 @Override 4708 public boolean addPermission(PermissionInfo info) { 4709 synchronized (mPackages) { 4710 return addPermissionLocked(info, false); 4711 } 4712 } 4713 4714 @Override 4715 public boolean addPermissionAsync(PermissionInfo info) { 4716 synchronized (mPackages) { 4717 return addPermissionLocked(info, true); 4718 } 4719 } 4720 4721 @Override 4722 public void removePermission(String name) { 4723 synchronized (mPackages) { 4724 checkPermissionTreeLP(name); 4725 BasePermission bp = mSettings.mPermissions.get(name); 4726 if (bp != null) { 4727 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4728 throw new SecurityException( 4729 "Not allowed to modify non-dynamic permission " 4730 + name); 4731 } 4732 mSettings.mPermissions.remove(name); 4733 mSettings.writeLPr(); 4734 } 4735 } 4736 } 4737 4738 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4739 BasePermission bp) { 4740 int index = pkg.requestedPermissions.indexOf(bp.name); 4741 if (index == -1) { 4742 throw new SecurityException("Package " + pkg.packageName 4743 + " has not requested permission " + bp.name); 4744 } 4745 if (!bp.isRuntime() && !bp.isDevelopment()) { 4746 throw new SecurityException("Permission " + bp.name 4747 + " is not a changeable permission type"); 4748 } 4749 } 4750 4751 @Override 4752 public void grantRuntimePermission(String packageName, String name, final int userId) { 4753 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4754 } 4755 4756 private void grantRuntimePermission(String packageName, String name, final int userId, 4757 boolean overridePolicy) { 4758 if (!sUserManager.exists(userId)) { 4759 Log.e(TAG, "No such user:" + userId); 4760 return; 4761 } 4762 4763 mContext.enforceCallingOrSelfPermission( 4764 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4765 "grantRuntimePermission"); 4766 4767 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4768 true /* requireFullPermission */, true /* checkShell */, 4769 "grantRuntimePermission"); 4770 4771 final int uid; 4772 final SettingBase sb; 4773 4774 synchronized (mPackages) { 4775 final PackageParser.Package pkg = mPackages.get(packageName); 4776 if (pkg == null) { 4777 throw new IllegalArgumentException("Unknown package: " + packageName); 4778 } 4779 4780 final BasePermission bp = mSettings.mPermissions.get(name); 4781 if (bp == null) { 4782 throw new IllegalArgumentException("Unknown permission: " + name); 4783 } 4784 4785 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4786 4787 // If a permission review is required for legacy apps we represent 4788 // their permissions as always granted runtime ones since we need 4789 // to keep the review required permission flag per user while an 4790 // install permission's state is shared across all users. 4791 if (mPermissionReviewRequired 4792 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4793 && bp.isRuntime()) { 4794 return; 4795 } 4796 4797 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4798 sb = (SettingBase) pkg.mExtras; 4799 if (sb == null) { 4800 throw new IllegalArgumentException("Unknown package: " + packageName); 4801 } 4802 4803 final PermissionsState permissionsState = sb.getPermissionsState(); 4804 4805 final int flags = permissionsState.getPermissionFlags(name, userId); 4806 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4807 throw new SecurityException("Cannot grant system fixed permission " 4808 + name + " for package " + packageName); 4809 } 4810 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4811 throw new SecurityException("Cannot grant policy fixed permission " 4812 + name + " for package " + packageName); 4813 } 4814 4815 if (bp.isDevelopment()) { 4816 // Development permissions must be handled specially, since they are not 4817 // normal runtime permissions. For now they apply to all users. 4818 if (permissionsState.grantInstallPermission(bp) != 4819 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4820 scheduleWriteSettingsLocked(); 4821 } 4822 return; 4823 } 4824 4825 final PackageSetting ps = mSettings.mPackages.get(packageName); 4826 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4827 throw new SecurityException("Cannot grant non-ephemeral permission" 4828 + name + " for package " + packageName); 4829 } 4830 4831 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4832 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4833 return; 4834 } 4835 4836 final int result = permissionsState.grantRuntimePermission(bp, userId); 4837 switch (result) { 4838 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4839 return; 4840 } 4841 4842 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4843 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4844 mHandler.post(new Runnable() { 4845 @Override 4846 public void run() { 4847 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4848 } 4849 }); 4850 } 4851 break; 4852 } 4853 4854 if (bp.isRuntime()) { 4855 logPermissionGranted(mContext, name, packageName); 4856 } 4857 4858 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4859 4860 // Not critical if that is lost - app has to request again. 4861 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4862 } 4863 4864 // Only need to do this if user is initialized. Otherwise it's a new user 4865 // and there are no processes running as the user yet and there's no need 4866 // to make an expensive call to remount processes for the changed permissions. 4867 if (READ_EXTERNAL_STORAGE.equals(name) 4868 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4869 final long token = Binder.clearCallingIdentity(); 4870 try { 4871 if (sUserManager.isInitialized(userId)) { 4872 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4873 StorageManagerInternal.class); 4874 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4875 } 4876 } finally { 4877 Binder.restoreCallingIdentity(token); 4878 } 4879 } 4880 } 4881 4882 @Override 4883 public void revokeRuntimePermission(String packageName, String name, int userId) { 4884 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4885 } 4886 4887 private void revokeRuntimePermission(String packageName, String name, int userId, 4888 boolean overridePolicy) { 4889 if (!sUserManager.exists(userId)) { 4890 Log.e(TAG, "No such user:" + userId); 4891 return; 4892 } 4893 4894 mContext.enforceCallingOrSelfPermission( 4895 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4896 "revokeRuntimePermission"); 4897 4898 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4899 true /* requireFullPermission */, true /* checkShell */, 4900 "revokeRuntimePermission"); 4901 4902 final int appId; 4903 4904 synchronized (mPackages) { 4905 final PackageParser.Package pkg = mPackages.get(packageName); 4906 if (pkg == null) { 4907 throw new IllegalArgumentException("Unknown package: " + packageName); 4908 } 4909 4910 final BasePermission bp = mSettings.mPermissions.get(name); 4911 if (bp == null) { 4912 throw new IllegalArgumentException("Unknown permission: " + name); 4913 } 4914 4915 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4916 4917 // If a permission review is required for legacy apps we represent 4918 // their permissions as always granted runtime ones since we need 4919 // to keep the review required permission flag per user while an 4920 // install permission's state is shared across all users. 4921 if (mPermissionReviewRequired 4922 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4923 && bp.isRuntime()) { 4924 return; 4925 } 4926 4927 SettingBase sb = (SettingBase) pkg.mExtras; 4928 if (sb == null) { 4929 throw new IllegalArgumentException("Unknown package: " + packageName); 4930 } 4931 4932 final PermissionsState permissionsState = sb.getPermissionsState(); 4933 4934 final int flags = permissionsState.getPermissionFlags(name, userId); 4935 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4936 throw new SecurityException("Cannot revoke system fixed permission " 4937 + name + " for package " + packageName); 4938 } 4939 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4940 throw new SecurityException("Cannot revoke policy fixed permission " 4941 + name + " for package " + packageName); 4942 } 4943 4944 if (bp.isDevelopment()) { 4945 // Development permissions must be handled specially, since they are not 4946 // normal runtime permissions. For now they apply to all users. 4947 if (permissionsState.revokeInstallPermission(bp) != 4948 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4949 scheduleWriteSettingsLocked(); 4950 } 4951 return; 4952 } 4953 4954 if (permissionsState.revokeRuntimePermission(bp, userId) == 4955 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4956 return; 4957 } 4958 4959 if (bp.isRuntime()) { 4960 logPermissionRevoked(mContext, name, packageName); 4961 } 4962 4963 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4964 4965 // Critical, after this call app should never have the permission. 4966 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4967 4968 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4969 } 4970 4971 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4972 } 4973 4974 /** 4975 * Get the first event id for the permission. 4976 * 4977 * <p>There are four events for each permission: <ul> 4978 * <li>Request permission: first id + 0</li> 4979 * <li>Grant permission: first id + 1</li> 4980 * <li>Request for permission denied: first id + 2</li> 4981 * <li>Revoke permission: first id + 3</li> 4982 * </ul></p> 4983 * 4984 * @param name name of the permission 4985 * 4986 * @return The first event id for the permission 4987 */ 4988 private static int getBaseEventId(@NonNull String name) { 4989 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4990 4991 if (eventIdIndex == -1) { 4992 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4993 || "user".equals(Build.TYPE)) { 4994 Log.i(TAG, "Unknown permission " + name); 4995 4996 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4997 } else { 4998 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4999 // 5000 // Also update 5001 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5002 // - metrics_constants.proto 5003 throw new IllegalStateException("Unknown permission " + name); 5004 } 5005 } 5006 5007 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5008 } 5009 5010 /** 5011 * Log that a permission was revoked. 5012 * 5013 * @param context Context of the caller 5014 * @param name name of the permission 5015 * @param packageName package permission if for 5016 */ 5017 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5018 @NonNull String packageName) { 5019 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5020 } 5021 5022 /** 5023 * Log that a permission request was granted. 5024 * 5025 * @param context Context of the caller 5026 * @param name name of the permission 5027 * @param packageName package permission if for 5028 */ 5029 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5030 @NonNull String packageName) { 5031 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5032 } 5033 5034 @Override 5035 public void resetRuntimePermissions() { 5036 mContext.enforceCallingOrSelfPermission( 5037 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5038 "revokeRuntimePermission"); 5039 5040 int callingUid = Binder.getCallingUid(); 5041 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5042 mContext.enforceCallingOrSelfPermission( 5043 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5044 "resetRuntimePermissions"); 5045 } 5046 5047 synchronized (mPackages) { 5048 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5049 for (int userId : UserManagerService.getInstance().getUserIds()) { 5050 final int packageCount = mPackages.size(); 5051 for (int i = 0; i < packageCount; i++) { 5052 PackageParser.Package pkg = mPackages.valueAt(i); 5053 if (!(pkg.mExtras instanceof PackageSetting)) { 5054 continue; 5055 } 5056 PackageSetting ps = (PackageSetting) pkg.mExtras; 5057 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5058 } 5059 } 5060 } 5061 } 5062 5063 @Override 5064 public int getPermissionFlags(String name, String packageName, int userId) { 5065 if (!sUserManager.exists(userId)) { 5066 return 0; 5067 } 5068 5069 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5070 5071 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5072 true /* requireFullPermission */, false /* checkShell */, 5073 "getPermissionFlags"); 5074 5075 synchronized (mPackages) { 5076 final PackageParser.Package pkg = mPackages.get(packageName); 5077 if (pkg == null) { 5078 return 0; 5079 } 5080 5081 final BasePermission bp = mSettings.mPermissions.get(name); 5082 if (bp == null) { 5083 return 0; 5084 } 5085 5086 SettingBase sb = (SettingBase) pkg.mExtras; 5087 if (sb == null) { 5088 return 0; 5089 } 5090 5091 PermissionsState permissionsState = sb.getPermissionsState(); 5092 return permissionsState.getPermissionFlags(name, userId); 5093 } 5094 } 5095 5096 @Override 5097 public void updatePermissionFlags(String name, String packageName, int flagMask, 5098 int flagValues, int userId) { 5099 if (!sUserManager.exists(userId)) { 5100 return; 5101 } 5102 5103 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5104 5105 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5106 true /* requireFullPermission */, true /* checkShell */, 5107 "updatePermissionFlags"); 5108 5109 // Only the system can change these flags and nothing else. 5110 if (getCallingUid() != Process.SYSTEM_UID) { 5111 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5112 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5113 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5114 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5115 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5116 } 5117 5118 synchronized (mPackages) { 5119 final PackageParser.Package pkg = mPackages.get(packageName); 5120 if (pkg == null) { 5121 throw new IllegalArgumentException("Unknown package: " + packageName); 5122 } 5123 5124 final BasePermission bp = mSettings.mPermissions.get(name); 5125 if (bp == null) { 5126 throw new IllegalArgumentException("Unknown permission: " + name); 5127 } 5128 5129 SettingBase sb = (SettingBase) pkg.mExtras; 5130 if (sb == null) { 5131 throw new IllegalArgumentException("Unknown package: " + packageName); 5132 } 5133 5134 PermissionsState permissionsState = sb.getPermissionsState(); 5135 5136 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5137 5138 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5139 // Install and runtime permissions are stored in different places, 5140 // so figure out what permission changed and persist the change. 5141 if (permissionsState.getInstallPermissionState(name) != null) { 5142 scheduleWriteSettingsLocked(); 5143 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5144 || hadState) { 5145 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5146 } 5147 } 5148 } 5149 } 5150 5151 /** 5152 * Update the permission flags for all packages and runtime permissions of a user in order 5153 * to allow device or profile owner to remove POLICY_FIXED. 5154 */ 5155 @Override 5156 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5157 if (!sUserManager.exists(userId)) { 5158 return; 5159 } 5160 5161 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5162 5163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5164 true /* requireFullPermission */, true /* checkShell */, 5165 "updatePermissionFlagsForAllApps"); 5166 5167 // Only the system can change system fixed flags. 5168 if (getCallingUid() != Process.SYSTEM_UID) { 5169 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5170 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5171 } 5172 5173 synchronized (mPackages) { 5174 boolean changed = false; 5175 final int packageCount = mPackages.size(); 5176 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5177 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5178 SettingBase sb = (SettingBase) pkg.mExtras; 5179 if (sb == null) { 5180 continue; 5181 } 5182 PermissionsState permissionsState = sb.getPermissionsState(); 5183 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5184 userId, flagMask, flagValues); 5185 } 5186 if (changed) { 5187 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5188 } 5189 } 5190 } 5191 5192 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5193 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5194 != PackageManager.PERMISSION_GRANTED 5195 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5196 != PackageManager.PERMISSION_GRANTED) { 5197 throw new SecurityException(message + " requires " 5198 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5199 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5200 } 5201 } 5202 5203 @Override 5204 public boolean shouldShowRequestPermissionRationale(String permissionName, 5205 String packageName, int userId) { 5206 if (UserHandle.getCallingUserId() != userId) { 5207 mContext.enforceCallingPermission( 5208 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5209 "canShowRequestPermissionRationale for user " + userId); 5210 } 5211 5212 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5213 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5214 return false; 5215 } 5216 5217 if (checkPermission(permissionName, packageName, userId) 5218 == PackageManager.PERMISSION_GRANTED) { 5219 return false; 5220 } 5221 5222 final int flags; 5223 5224 final long identity = Binder.clearCallingIdentity(); 5225 try { 5226 flags = getPermissionFlags(permissionName, 5227 packageName, userId); 5228 } finally { 5229 Binder.restoreCallingIdentity(identity); 5230 } 5231 5232 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5233 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5234 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5235 5236 if ((flags & fixedFlags) != 0) { 5237 return false; 5238 } 5239 5240 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5241 } 5242 5243 @Override 5244 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5245 mContext.enforceCallingOrSelfPermission( 5246 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5247 "addOnPermissionsChangeListener"); 5248 5249 synchronized (mPackages) { 5250 mOnPermissionChangeListeners.addListenerLocked(listener); 5251 } 5252 } 5253 5254 @Override 5255 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5256 synchronized (mPackages) { 5257 mOnPermissionChangeListeners.removeListenerLocked(listener); 5258 } 5259 } 5260 5261 @Override 5262 public boolean isProtectedBroadcast(String actionName) { 5263 synchronized (mPackages) { 5264 if (mProtectedBroadcasts.contains(actionName)) { 5265 return true; 5266 } else if (actionName != null) { 5267 // TODO: remove these terrible hacks 5268 if (actionName.startsWith("android.net.netmon.lingerExpired") 5269 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5270 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5271 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5272 return true; 5273 } 5274 } 5275 } 5276 return false; 5277 } 5278 5279 @Override 5280 public int checkSignatures(String pkg1, String pkg2) { 5281 synchronized (mPackages) { 5282 final PackageParser.Package p1 = mPackages.get(pkg1); 5283 final PackageParser.Package p2 = mPackages.get(pkg2); 5284 if (p1 == null || p1.mExtras == null 5285 || p2 == null || p2.mExtras == null) { 5286 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5287 } 5288 return compareSignatures(p1.mSignatures, p2.mSignatures); 5289 } 5290 } 5291 5292 @Override 5293 public int checkUidSignatures(int uid1, int uid2) { 5294 // Map to base uids. 5295 uid1 = UserHandle.getAppId(uid1); 5296 uid2 = UserHandle.getAppId(uid2); 5297 // reader 5298 synchronized (mPackages) { 5299 Signature[] s1; 5300 Signature[] s2; 5301 Object obj = mSettings.getUserIdLPr(uid1); 5302 if (obj != null) { 5303 if (obj instanceof SharedUserSetting) { 5304 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5305 } else if (obj instanceof PackageSetting) { 5306 s1 = ((PackageSetting)obj).signatures.mSignatures; 5307 } else { 5308 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5309 } 5310 } else { 5311 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5312 } 5313 obj = mSettings.getUserIdLPr(uid2); 5314 if (obj != null) { 5315 if (obj instanceof SharedUserSetting) { 5316 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5317 } else if (obj instanceof PackageSetting) { 5318 s2 = ((PackageSetting)obj).signatures.mSignatures; 5319 } else { 5320 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5321 } 5322 } else { 5323 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5324 } 5325 return compareSignatures(s1, s2); 5326 } 5327 } 5328 5329 /** 5330 * This method should typically only be used when granting or revoking 5331 * permissions, since the app may immediately restart after this call. 5332 * <p> 5333 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5334 * guard your work against the app being relaunched. 5335 */ 5336 private void killUid(int appId, int userId, String reason) { 5337 final long identity = Binder.clearCallingIdentity(); 5338 try { 5339 IActivityManager am = ActivityManager.getService(); 5340 if (am != null) { 5341 try { 5342 am.killUid(appId, userId, reason); 5343 } catch (RemoteException e) { 5344 /* ignore - same process */ 5345 } 5346 } 5347 } finally { 5348 Binder.restoreCallingIdentity(identity); 5349 } 5350 } 5351 5352 /** 5353 * Compares two sets of signatures. Returns: 5354 * <br /> 5355 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5356 * <br /> 5357 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5358 * <br /> 5359 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5360 * <br /> 5361 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5362 * <br /> 5363 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5364 */ 5365 static int compareSignatures(Signature[] s1, Signature[] s2) { 5366 if (s1 == null) { 5367 return s2 == null 5368 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5369 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5370 } 5371 5372 if (s2 == null) { 5373 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5374 } 5375 5376 if (s1.length != s2.length) { 5377 return PackageManager.SIGNATURE_NO_MATCH; 5378 } 5379 5380 // Since both signature sets are of size 1, we can compare without HashSets. 5381 if (s1.length == 1) { 5382 return s1[0].equals(s2[0]) ? 5383 PackageManager.SIGNATURE_MATCH : 5384 PackageManager.SIGNATURE_NO_MATCH; 5385 } 5386 5387 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5388 for (Signature sig : s1) { 5389 set1.add(sig); 5390 } 5391 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5392 for (Signature sig : s2) { 5393 set2.add(sig); 5394 } 5395 // Make sure s2 contains all signatures in s1. 5396 if (set1.equals(set2)) { 5397 return PackageManager.SIGNATURE_MATCH; 5398 } 5399 return PackageManager.SIGNATURE_NO_MATCH; 5400 } 5401 5402 /** 5403 * If the database version for this type of package (internal storage or 5404 * external storage) is less than the version where package signatures 5405 * were updated, return true. 5406 */ 5407 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5408 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5409 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5410 } 5411 5412 /** 5413 * Used for backward compatibility to make sure any packages with 5414 * certificate chains get upgraded to the new style. {@code existingSigs} 5415 * will be in the old format (since they were stored on disk from before the 5416 * system upgrade) and {@code scannedSigs} will be in the newer format. 5417 */ 5418 private int compareSignaturesCompat(PackageSignatures existingSigs, 5419 PackageParser.Package scannedPkg) { 5420 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5421 return PackageManager.SIGNATURE_NO_MATCH; 5422 } 5423 5424 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5425 for (Signature sig : existingSigs.mSignatures) { 5426 existingSet.add(sig); 5427 } 5428 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5429 for (Signature sig : scannedPkg.mSignatures) { 5430 try { 5431 Signature[] chainSignatures = sig.getChainSignatures(); 5432 for (Signature chainSig : chainSignatures) { 5433 scannedCompatSet.add(chainSig); 5434 } 5435 } catch (CertificateEncodingException e) { 5436 scannedCompatSet.add(sig); 5437 } 5438 } 5439 /* 5440 * Make sure the expanded scanned set contains all signatures in the 5441 * existing one. 5442 */ 5443 if (scannedCompatSet.equals(existingSet)) { 5444 // Migrate the old signatures to the new scheme. 5445 existingSigs.assignSignatures(scannedPkg.mSignatures); 5446 // The new KeySets will be re-added later in the scanning process. 5447 synchronized (mPackages) { 5448 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5449 } 5450 return PackageManager.SIGNATURE_MATCH; 5451 } 5452 return PackageManager.SIGNATURE_NO_MATCH; 5453 } 5454 5455 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5456 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5457 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5458 } 5459 5460 private int compareSignaturesRecover(PackageSignatures existingSigs, 5461 PackageParser.Package scannedPkg) { 5462 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5463 return PackageManager.SIGNATURE_NO_MATCH; 5464 } 5465 5466 String msg = null; 5467 try { 5468 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5469 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5470 + scannedPkg.packageName); 5471 return PackageManager.SIGNATURE_MATCH; 5472 } 5473 } catch (CertificateException e) { 5474 msg = e.getMessage(); 5475 } 5476 5477 logCriticalInfo(Log.INFO, 5478 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5479 return PackageManager.SIGNATURE_NO_MATCH; 5480 } 5481 5482 @Override 5483 public List<String> getAllPackages() { 5484 synchronized (mPackages) { 5485 return new ArrayList<String>(mPackages.keySet()); 5486 } 5487 } 5488 5489 @Override 5490 public String[] getPackagesForUid(int uid) { 5491 final int userId = UserHandle.getUserId(uid); 5492 uid = UserHandle.getAppId(uid); 5493 // reader 5494 synchronized (mPackages) { 5495 Object obj = mSettings.getUserIdLPr(uid); 5496 if (obj instanceof SharedUserSetting) { 5497 final SharedUserSetting sus = (SharedUserSetting) obj; 5498 final int N = sus.packages.size(); 5499 String[] res = new String[N]; 5500 final Iterator<PackageSetting> it = sus.packages.iterator(); 5501 int i = 0; 5502 while (it.hasNext()) { 5503 PackageSetting ps = it.next(); 5504 if (ps.getInstalled(userId)) { 5505 res[i++] = ps.name; 5506 } else { 5507 res = ArrayUtils.removeElement(String.class, res, res[i]); 5508 } 5509 } 5510 return res; 5511 } else if (obj instanceof PackageSetting) { 5512 final PackageSetting ps = (PackageSetting) obj; 5513 if (ps.getInstalled(userId)) { 5514 return new String[]{ps.name}; 5515 } 5516 } 5517 } 5518 return null; 5519 } 5520 5521 @Override 5522 public String getNameForUid(int uid) { 5523 // reader 5524 synchronized (mPackages) { 5525 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5526 if (obj instanceof SharedUserSetting) { 5527 final SharedUserSetting sus = (SharedUserSetting) obj; 5528 return sus.name + ":" + sus.userId; 5529 } else if (obj instanceof PackageSetting) { 5530 final PackageSetting ps = (PackageSetting) obj; 5531 return ps.name; 5532 } 5533 } 5534 return null; 5535 } 5536 5537 @Override 5538 public int getUidForSharedUser(String sharedUserName) { 5539 if(sharedUserName == null) { 5540 return -1; 5541 } 5542 // reader 5543 synchronized (mPackages) { 5544 SharedUserSetting suid; 5545 try { 5546 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5547 if (suid != null) { 5548 return suid.userId; 5549 } 5550 } catch (PackageManagerException ignore) { 5551 // can't happen, but, still need to catch it 5552 } 5553 return -1; 5554 } 5555 } 5556 5557 @Override 5558 public int getFlagsForUid(int uid) { 5559 synchronized (mPackages) { 5560 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5561 if (obj instanceof SharedUserSetting) { 5562 final SharedUserSetting sus = (SharedUserSetting) obj; 5563 return sus.pkgFlags; 5564 } else if (obj instanceof PackageSetting) { 5565 final PackageSetting ps = (PackageSetting) obj; 5566 return ps.pkgFlags; 5567 } 5568 } 5569 return 0; 5570 } 5571 5572 @Override 5573 public int getPrivateFlagsForUid(int uid) { 5574 synchronized (mPackages) { 5575 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5576 if (obj instanceof SharedUserSetting) { 5577 final SharedUserSetting sus = (SharedUserSetting) obj; 5578 return sus.pkgPrivateFlags; 5579 } else if (obj instanceof PackageSetting) { 5580 final PackageSetting ps = (PackageSetting) obj; 5581 return ps.pkgPrivateFlags; 5582 } 5583 } 5584 return 0; 5585 } 5586 5587 @Override 5588 public boolean isUidPrivileged(int uid) { 5589 uid = UserHandle.getAppId(uid); 5590 // reader 5591 synchronized (mPackages) { 5592 Object obj = mSettings.getUserIdLPr(uid); 5593 if (obj instanceof SharedUserSetting) { 5594 final SharedUserSetting sus = (SharedUserSetting) obj; 5595 final Iterator<PackageSetting> it = sus.packages.iterator(); 5596 while (it.hasNext()) { 5597 if (it.next().isPrivileged()) { 5598 return true; 5599 } 5600 } 5601 } else if (obj instanceof PackageSetting) { 5602 final PackageSetting ps = (PackageSetting) obj; 5603 return ps.isPrivileged(); 5604 } 5605 } 5606 return false; 5607 } 5608 5609 @Override 5610 public String[] getAppOpPermissionPackages(String permissionName) { 5611 synchronized (mPackages) { 5612 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5613 if (pkgs == null) { 5614 return null; 5615 } 5616 return pkgs.toArray(new String[pkgs.size()]); 5617 } 5618 } 5619 5620 @Override 5621 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5622 int flags, int userId) { 5623 return resolveIntentInternal( 5624 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5625 } 5626 5627 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5628 int flags, int userId, boolean includeInstantApps) { 5629 try { 5630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5631 5632 if (!sUserManager.exists(userId)) return null; 5633 final int callingUid = Binder.getCallingUid(); 5634 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5635 enforceCrossUserPermission(callingUid, userId, 5636 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5637 5638 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5639 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5640 flags, userId, includeInstantApps); 5641 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5642 5643 final ResolveInfo bestChoice = 5644 chooseBestActivity(intent, resolvedType, flags, query, userId); 5645 return bestChoice; 5646 } finally { 5647 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5648 } 5649 } 5650 5651 @Override 5652 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5653 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5654 throw new SecurityException( 5655 "findPersistentPreferredActivity can only be run by the system"); 5656 } 5657 if (!sUserManager.exists(userId)) { 5658 return null; 5659 } 5660 final int callingUid = Binder.getCallingUid(); 5661 intent = updateIntentForResolve(intent); 5662 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5663 final int flags = updateFlagsForResolve( 5664 0, userId, intent, callingUid, false /*includeInstantApps*/); 5665 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5666 userId); 5667 synchronized (mPackages) { 5668 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5669 userId); 5670 } 5671 } 5672 5673 @Override 5674 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5675 IntentFilter filter, int match, ComponentName activity) { 5676 final int userId = UserHandle.getCallingUserId(); 5677 if (DEBUG_PREFERRED) { 5678 Log.v(TAG, "setLastChosenActivity intent=" + intent 5679 + " resolvedType=" + resolvedType 5680 + " flags=" + flags 5681 + " filter=" + filter 5682 + " match=" + match 5683 + " activity=" + activity); 5684 filter.dump(new PrintStreamPrinter(System.out), " "); 5685 } 5686 intent.setComponent(null); 5687 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5688 userId); 5689 // Find any earlier preferred or last chosen entries and nuke them 5690 findPreferredActivity(intent, resolvedType, 5691 flags, query, 0, false, true, false, userId); 5692 // Add the new activity as the last chosen for this filter 5693 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5694 "Setting last chosen"); 5695 } 5696 5697 @Override 5698 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5699 final int userId = UserHandle.getCallingUserId(); 5700 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5701 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5702 userId); 5703 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5704 false, false, false, userId); 5705 } 5706 5707 /** 5708 * Returns whether or not instant apps have been disabled remotely. 5709 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5710 * held. Otherwise we run the risk of deadlock. 5711 */ 5712 private boolean isEphemeralDisabled() { 5713 // ephemeral apps have been disabled across the board 5714 if (DISABLE_EPHEMERAL_APPS) { 5715 return true; 5716 } 5717 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5718 if (!mSystemReady) { 5719 return true; 5720 } 5721 // we can't get a content resolver until the system is ready; these checks must happen last 5722 final ContentResolver resolver = mContext.getContentResolver(); 5723 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5724 return true; 5725 } 5726 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5727 } 5728 5729 private boolean isEphemeralAllowed( 5730 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5731 boolean skipPackageCheck) { 5732 final int callingUser = UserHandle.getCallingUserId(); 5733 if (callingUser != UserHandle.USER_SYSTEM) { 5734 return false; 5735 } 5736 if (mInstantAppResolverConnection == null) { 5737 return false; 5738 } 5739 if (mInstantAppInstallerComponent == null) { 5740 return false; 5741 } 5742 if (intent.getComponent() != null) { 5743 return false; 5744 } 5745 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5746 return false; 5747 } 5748 if (!skipPackageCheck && intent.getPackage() != null) { 5749 return false; 5750 } 5751 final boolean isWebUri = hasWebURI(intent); 5752 if (!isWebUri || intent.getData().getHost() == null) { 5753 return false; 5754 } 5755 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5756 // Or if there's already an ephemeral app installed that handles the action 5757 synchronized (mPackages) { 5758 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5759 for (int n = 0; n < count; n++) { 5760 final ResolveInfo info = resolvedActivities.get(n); 5761 final String packageName = info.activityInfo.packageName; 5762 final PackageSetting ps = mSettings.mPackages.get(packageName); 5763 if (ps != null) { 5764 // only check domain verification status if the app is not a browser 5765 if (!info.handleAllWebDataURI) { 5766 // Try to get the status from User settings first 5767 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5768 final int status = (int) (packedStatus >> 32); 5769 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5770 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5771 if (DEBUG_EPHEMERAL) { 5772 Slog.v(TAG, "DENY instant app;" 5773 + " pkg: " + packageName + ", status: " + status); 5774 } 5775 return false; 5776 } 5777 } 5778 if (ps.getInstantApp(userId)) { 5779 if (DEBUG_EPHEMERAL) { 5780 Slog.v(TAG, "DENY instant app installed;" 5781 + " pkg: " + packageName); 5782 } 5783 return false; 5784 } 5785 } 5786 } 5787 } 5788 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5789 return true; 5790 } 5791 5792 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5793 Intent origIntent, String resolvedType, String callingPackage, 5794 int userId) { 5795 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5796 new InstantAppRequest(responseObj, origIntent, resolvedType, 5797 callingPackage, userId)); 5798 mHandler.sendMessage(msg); 5799 } 5800 5801 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5802 int flags, List<ResolveInfo> query, int userId) { 5803 if (query != null) { 5804 final int N = query.size(); 5805 if (N == 1) { 5806 return query.get(0); 5807 } else if (N > 1) { 5808 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5809 // If there is more than one activity with the same priority, 5810 // then let the user decide between them. 5811 ResolveInfo r0 = query.get(0); 5812 ResolveInfo r1 = query.get(1); 5813 if (DEBUG_INTENT_MATCHING || debug) { 5814 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5815 + r1.activityInfo.name + "=" + r1.priority); 5816 } 5817 // If the first activity has a higher priority, or a different 5818 // default, then it is always desirable to pick it. 5819 if (r0.priority != r1.priority 5820 || r0.preferredOrder != r1.preferredOrder 5821 || r0.isDefault != r1.isDefault) { 5822 return query.get(0); 5823 } 5824 // If we have saved a preference for a preferred activity for 5825 // this Intent, use that. 5826 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5827 flags, query, r0.priority, true, false, debug, userId); 5828 if (ri != null) { 5829 return ri; 5830 } 5831 // If we have an ephemeral app, use it 5832 for (int i = 0; i < N; i++) { 5833 ri = query.get(i); 5834 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5835 return ri; 5836 } 5837 } 5838 ri = new ResolveInfo(mResolveInfo); 5839 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5840 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5841 // If all of the options come from the same package, show the application's 5842 // label and icon instead of the generic resolver's. 5843 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5844 // and then throw away the ResolveInfo itself, meaning that the caller loses 5845 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5846 // a fallback for this case; we only set the target package's resources on 5847 // the ResolveInfo, not the ActivityInfo. 5848 final String intentPackage = intent.getPackage(); 5849 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5850 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5851 ri.resolvePackageName = intentPackage; 5852 if (userNeedsBadging(userId)) { 5853 ri.noResourceId = true; 5854 } else { 5855 ri.icon = appi.icon; 5856 } 5857 ri.iconResourceId = appi.icon; 5858 ri.labelRes = appi.labelRes; 5859 } 5860 ri.activityInfo.applicationInfo = new ApplicationInfo( 5861 ri.activityInfo.applicationInfo); 5862 if (userId != 0) { 5863 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5864 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5865 } 5866 // Make sure that the resolver is displayable in car mode 5867 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5868 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5869 return ri; 5870 } 5871 } 5872 return null; 5873 } 5874 5875 /** 5876 * Return true if the given list is not empty and all of its contents have 5877 * an activityInfo with the given package name. 5878 */ 5879 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5880 if (ArrayUtils.isEmpty(list)) { 5881 return false; 5882 } 5883 for (int i = 0, N = list.size(); i < N; i++) { 5884 final ResolveInfo ri = list.get(i); 5885 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5886 if (ai == null || !packageName.equals(ai.packageName)) { 5887 return false; 5888 } 5889 } 5890 return true; 5891 } 5892 5893 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5894 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5895 final int N = query.size(); 5896 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5897 .get(userId); 5898 // Get the list of persistent preferred activities that handle the intent 5899 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5900 List<PersistentPreferredActivity> pprefs = ppir != null 5901 ? ppir.queryIntent(intent, resolvedType, 5902 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5903 userId) 5904 : null; 5905 if (pprefs != null && pprefs.size() > 0) { 5906 final int M = pprefs.size(); 5907 for (int i=0; i<M; i++) { 5908 final PersistentPreferredActivity ppa = pprefs.get(i); 5909 if (DEBUG_PREFERRED || debug) { 5910 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5911 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5912 + "\n component=" + ppa.mComponent); 5913 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5914 } 5915 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5916 flags | MATCH_DISABLED_COMPONENTS, userId); 5917 if (DEBUG_PREFERRED || debug) { 5918 Slog.v(TAG, "Found persistent preferred activity:"); 5919 if (ai != null) { 5920 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5921 } else { 5922 Slog.v(TAG, " null"); 5923 } 5924 } 5925 if (ai == null) { 5926 // This previously registered persistent preferred activity 5927 // component is no longer known. Ignore it and do NOT remove it. 5928 continue; 5929 } 5930 for (int j=0; j<N; j++) { 5931 final ResolveInfo ri = query.get(j); 5932 if (!ri.activityInfo.applicationInfo.packageName 5933 .equals(ai.applicationInfo.packageName)) { 5934 continue; 5935 } 5936 if (!ri.activityInfo.name.equals(ai.name)) { 5937 continue; 5938 } 5939 // Found a persistent preference that can handle the intent. 5940 if (DEBUG_PREFERRED || debug) { 5941 Slog.v(TAG, "Returning persistent preferred activity: " + 5942 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5943 } 5944 return ri; 5945 } 5946 } 5947 } 5948 return null; 5949 } 5950 5951 // TODO: handle preferred activities missing while user has amnesia 5952 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5953 List<ResolveInfo> query, int priority, boolean always, 5954 boolean removeMatches, boolean debug, int userId) { 5955 if (!sUserManager.exists(userId)) return null; 5956 final int callingUid = Binder.getCallingUid(); 5957 flags = updateFlagsForResolve( 5958 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5959 intent = updateIntentForResolve(intent); 5960 // writer 5961 synchronized (mPackages) { 5962 // Try to find a matching persistent preferred activity. 5963 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5964 debug, userId); 5965 5966 // If a persistent preferred activity matched, use it. 5967 if (pri != null) { 5968 return pri; 5969 } 5970 5971 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5972 // Get the list of preferred activities that handle the intent 5973 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5974 List<PreferredActivity> prefs = pir != null 5975 ? pir.queryIntent(intent, resolvedType, 5976 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5977 userId) 5978 : null; 5979 if (prefs != null && prefs.size() > 0) { 5980 boolean changed = false; 5981 try { 5982 // First figure out how good the original match set is. 5983 // We will only allow preferred activities that came 5984 // from the same match quality. 5985 int match = 0; 5986 5987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5988 5989 final int N = query.size(); 5990 for (int j=0; j<N; j++) { 5991 final ResolveInfo ri = query.get(j); 5992 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5993 + ": 0x" + Integer.toHexString(match)); 5994 if (ri.match > match) { 5995 match = ri.match; 5996 } 5997 } 5998 5999 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6000 + Integer.toHexString(match)); 6001 6002 match &= IntentFilter.MATCH_CATEGORY_MASK; 6003 final int M = prefs.size(); 6004 for (int i=0; i<M; i++) { 6005 final PreferredActivity pa = prefs.get(i); 6006 if (DEBUG_PREFERRED || debug) { 6007 Slog.v(TAG, "Checking PreferredActivity ds=" 6008 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6009 + "\n component=" + pa.mPref.mComponent); 6010 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6011 } 6012 if (pa.mPref.mMatch != match) { 6013 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6014 + Integer.toHexString(pa.mPref.mMatch)); 6015 continue; 6016 } 6017 // If it's not an "always" type preferred activity and that's what we're 6018 // looking for, skip it. 6019 if (always && !pa.mPref.mAlways) { 6020 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6021 continue; 6022 } 6023 final ActivityInfo ai = getActivityInfo( 6024 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6025 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6026 userId); 6027 if (DEBUG_PREFERRED || debug) { 6028 Slog.v(TAG, "Found preferred activity:"); 6029 if (ai != null) { 6030 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6031 } else { 6032 Slog.v(TAG, " null"); 6033 } 6034 } 6035 if (ai == null) { 6036 // This previously registered preferred activity 6037 // component is no longer known. Most likely an update 6038 // to the app was installed and in the new version this 6039 // component no longer exists. Clean it up by removing 6040 // it from the preferred activities list, and skip it. 6041 Slog.w(TAG, "Removing dangling preferred activity: " 6042 + pa.mPref.mComponent); 6043 pir.removeFilter(pa); 6044 changed = true; 6045 continue; 6046 } 6047 for (int j=0; j<N; j++) { 6048 final ResolveInfo ri = query.get(j); 6049 if (!ri.activityInfo.applicationInfo.packageName 6050 .equals(ai.applicationInfo.packageName)) { 6051 continue; 6052 } 6053 if (!ri.activityInfo.name.equals(ai.name)) { 6054 continue; 6055 } 6056 6057 if (removeMatches) { 6058 pir.removeFilter(pa); 6059 changed = true; 6060 if (DEBUG_PREFERRED) { 6061 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6062 } 6063 break; 6064 } 6065 6066 // Okay we found a previously set preferred or last chosen app. 6067 // If the result set is different from when this 6068 // was created, we need to clear it and re-ask the 6069 // user their preference, if we're looking for an "always" type entry. 6070 if (always && !pa.mPref.sameSet(query)) { 6071 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6072 + intent + " type " + resolvedType); 6073 if (DEBUG_PREFERRED) { 6074 Slog.v(TAG, "Removing preferred activity since set changed " 6075 + pa.mPref.mComponent); 6076 } 6077 pir.removeFilter(pa); 6078 // Re-add the filter as a "last chosen" entry (!always) 6079 PreferredActivity lastChosen = new PreferredActivity( 6080 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6081 pir.addFilter(lastChosen); 6082 changed = true; 6083 return null; 6084 } 6085 6086 // Yay! Either the set matched or we're looking for the last chosen 6087 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6088 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6089 return ri; 6090 } 6091 } 6092 } finally { 6093 if (changed) { 6094 if (DEBUG_PREFERRED) { 6095 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6096 } 6097 scheduleWritePackageRestrictionsLocked(userId); 6098 } 6099 } 6100 } 6101 } 6102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6103 return null; 6104 } 6105 6106 /* 6107 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6108 */ 6109 @Override 6110 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6111 int targetUserId) { 6112 mContext.enforceCallingOrSelfPermission( 6113 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6114 List<CrossProfileIntentFilter> matches = 6115 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6116 if (matches != null) { 6117 int size = matches.size(); 6118 for (int i = 0; i < size; i++) { 6119 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6120 } 6121 } 6122 if (hasWebURI(intent)) { 6123 // cross-profile app linking works only towards the parent. 6124 final int callingUid = Binder.getCallingUid(); 6125 final UserInfo parent = getProfileParent(sourceUserId); 6126 synchronized(mPackages) { 6127 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6128 false /*includeInstantApps*/); 6129 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6130 intent, resolvedType, flags, sourceUserId, parent.id); 6131 return xpDomainInfo != null; 6132 } 6133 } 6134 return false; 6135 } 6136 6137 private UserInfo getProfileParent(int userId) { 6138 final long identity = Binder.clearCallingIdentity(); 6139 try { 6140 return sUserManager.getProfileParent(userId); 6141 } finally { 6142 Binder.restoreCallingIdentity(identity); 6143 } 6144 } 6145 6146 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6147 String resolvedType, int userId) { 6148 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6149 if (resolver != null) { 6150 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6151 } 6152 return null; 6153 } 6154 6155 @Override 6156 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6157 String resolvedType, int flags, int userId) { 6158 try { 6159 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6160 6161 return new ParceledListSlice<>( 6162 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6163 } finally { 6164 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6165 } 6166 } 6167 6168 /** 6169 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6170 * instant, returns {@code null}. 6171 */ 6172 private String getInstantAppPackageName(int callingUid) { 6173 // If the caller is an isolated app use the owner's uid for the lookup. 6174 if (Process.isIsolated(callingUid)) { 6175 callingUid = mIsolatedOwners.get(callingUid); 6176 } 6177 final int appId = UserHandle.getAppId(callingUid); 6178 synchronized (mPackages) { 6179 final Object obj = mSettings.getUserIdLPr(appId); 6180 if (obj instanceof PackageSetting) { 6181 final PackageSetting ps = (PackageSetting) obj; 6182 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6183 return isInstantApp ? ps.pkg.packageName : null; 6184 } 6185 } 6186 return null; 6187 } 6188 6189 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6190 String resolvedType, int flags, int userId) { 6191 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6192 } 6193 6194 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6195 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6196 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6197 final int callingUid = Binder.getCallingUid(); 6198 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6199 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6200 enforceCrossUserPermission(callingUid, userId, 6201 false /* requireFullPermission */, false /* checkShell */, 6202 "query intent activities"); 6203 ComponentName comp = intent.getComponent(); 6204 if (comp == null) { 6205 if (intent.getSelector() != null) { 6206 intent = intent.getSelector(); 6207 comp = intent.getComponent(); 6208 } 6209 } 6210 6211 if (comp != null) { 6212 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6213 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6214 if (ai != null) { 6215 // When specifying an explicit component, we prevent the activity from being 6216 // used when either 1) the calling package is normal and the activity is within 6217 // an ephemeral application or 2) the calling package is ephemeral and the 6218 // activity is not visible to ephemeral applications. 6219 final boolean matchInstantApp = 6220 (flags & PackageManager.MATCH_INSTANT) != 0; 6221 final boolean matchVisibleToInstantAppOnly = 6222 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6223 final boolean isCallerInstantApp = 6224 instantAppPkgName != null; 6225 final boolean isTargetSameInstantApp = 6226 comp.getPackageName().equals(instantAppPkgName); 6227 final boolean isTargetInstantApp = 6228 (ai.applicationInfo.privateFlags 6229 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6230 final boolean isTargetHiddenFromInstantApp = 6231 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6232 final boolean blockResolution = 6233 !isTargetSameInstantApp 6234 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6235 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6236 && isTargetHiddenFromInstantApp)); 6237 if (!blockResolution) { 6238 final ResolveInfo ri = new ResolveInfo(); 6239 ri.activityInfo = ai; 6240 list.add(ri); 6241 } 6242 } 6243 return applyPostResolutionFilter(list, instantAppPkgName); 6244 } 6245 6246 // reader 6247 boolean sortResult = false; 6248 boolean addEphemeral = false; 6249 List<ResolveInfo> result; 6250 final String pkgName = intent.getPackage(); 6251 final boolean ephemeralDisabled = isEphemeralDisabled(); 6252 synchronized (mPackages) { 6253 if (pkgName == null) { 6254 List<CrossProfileIntentFilter> matchingFilters = 6255 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6256 // Check for results that need to skip the current profile. 6257 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6258 resolvedType, flags, userId); 6259 if (xpResolveInfo != null) { 6260 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6261 xpResult.add(xpResolveInfo); 6262 return applyPostResolutionFilter( 6263 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6264 } 6265 6266 // Check for results in the current profile. 6267 result = filterIfNotSystemUser(mActivities.queryIntent( 6268 intent, resolvedType, flags, userId), userId); 6269 addEphemeral = !ephemeralDisabled 6270 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6271 // Check for cross profile results. 6272 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6273 xpResolveInfo = queryCrossProfileIntents( 6274 matchingFilters, intent, resolvedType, flags, userId, 6275 hasNonNegativePriorityResult); 6276 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6277 boolean isVisibleToUser = filterIfNotSystemUser( 6278 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6279 if (isVisibleToUser) { 6280 result.add(xpResolveInfo); 6281 sortResult = true; 6282 } 6283 } 6284 if (hasWebURI(intent)) { 6285 CrossProfileDomainInfo xpDomainInfo = null; 6286 final UserInfo parent = getProfileParent(userId); 6287 if (parent != null) { 6288 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6289 flags, userId, parent.id); 6290 } 6291 if (xpDomainInfo != null) { 6292 if (xpResolveInfo != null) { 6293 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6294 // in the result. 6295 result.remove(xpResolveInfo); 6296 } 6297 if (result.size() == 0 && !addEphemeral) { 6298 // No result in current profile, but found candidate in parent user. 6299 // And we are not going to add emphemeral app, so we can return the 6300 // result straight away. 6301 result.add(xpDomainInfo.resolveInfo); 6302 return applyPostResolutionFilter(result, instantAppPkgName); 6303 } 6304 } else if (result.size() <= 1 && !addEphemeral) { 6305 // No result in parent user and <= 1 result in current profile, and we 6306 // are not going to add emphemeral app, so we can return the result without 6307 // further processing. 6308 return applyPostResolutionFilter(result, instantAppPkgName); 6309 } 6310 // We have more than one candidate (combining results from current and parent 6311 // profile), so we need filtering and sorting. 6312 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6313 intent, flags, result, xpDomainInfo, userId); 6314 sortResult = true; 6315 } 6316 } else { 6317 final PackageParser.Package pkg = mPackages.get(pkgName); 6318 if (pkg != null) { 6319 return applyPostResolutionFilter(filterIfNotSystemUser( 6320 mActivities.queryIntentForPackage( 6321 intent, resolvedType, flags, pkg.activities, userId), 6322 userId), instantAppPkgName); 6323 } else { 6324 // the caller wants to resolve for a particular package; however, there 6325 // were no installed results, so, try to find an ephemeral result 6326 addEphemeral = !ephemeralDisabled 6327 && isEphemeralAllowed( 6328 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6329 result = new ArrayList<ResolveInfo>(); 6330 } 6331 } 6332 } 6333 if (addEphemeral) { 6334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6335 final InstantAppRequest requestObject = new InstantAppRequest( 6336 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6337 null /*callingPackage*/, userId); 6338 final AuxiliaryResolveInfo auxiliaryResponse = 6339 InstantAppResolver.doInstantAppResolutionPhaseOne( 6340 mContext, mInstantAppResolverConnection, requestObject); 6341 if (auxiliaryResponse != null) { 6342 if (DEBUG_EPHEMERAL) { 6343 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6344 } 6345 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6346 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6347 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6348 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6349 // make sure this resolver is the default 6350 ephemeralInstaller.isDefault = true; 6351 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6352 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6353 // add a non-generic filter 6354 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6355 ephemeralInstaller.filter.addDataPath( 6356 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6357 ephemeralInstaller.instantAppAvailable = true; 6358 result.add(ephemeralInstaller); 6359 } 6360 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6361 } 6362 if (sortResult) { 6363 Collections.sort(result, mResolvePrioritySorter); 6364 } 6365 return applyPostResolutionFilter(result, instantAppPkgName); 6366 } 6367 6368 private static class CrossProfileDomainInfo { 6369 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6370 ResolveInfo resolveInfo; 6371 /* Best domain verification status of the activities found in the other profile */ 6372 int bestDomainVerificationStatus; 6373 } 6374 6375 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6376 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6377 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6378 sourceUserId)) { 6379 return null; 6380 } 6381 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6382 resolvedType, flags, parentUserId); 6383 6384 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6385 return null; 6386 } 6387 CrossProfileDomainInfo result = null; 6388 int size = resultTargetUser.size(); 6389 for (int i = 0; i < size; i++) { 6390 ResolveInfo riTargetUser = resultTargetUser.get(i); 6391 // Intent filter verification is only for filters that specify a host. So don't return 6392 // those that handle all web uris. 6393 if (riTargetUser.handleAllWebDataURI) { 6394 continue; 6395 } 6396 String packageName = riTargetUser.activityInfo.packageName; 6397 PackageSetting ps = mSettings.mPackages.get(packageName); 6398 if (ps == null) { 6399 continue; 6400 } 6401 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6402 int status = (int)(verificationState >> 32); 6403 if (result == null) { 6404 result = new CrossProfileDomainInfo(); 6405 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6406 sourceUserId, parentUserId); 6407 result.bestDomainVerificationStatus = status; 6408 } else { 6409 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6410 result.bestDomainVerificationStatus); 6411 } 6412 } 6413 // Don't consider matches with status NEVER across profiles. 6414 if (result != null && result.bestDomainVerificationStatus 6415 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6416 return null; 6417 } 6418 return result; 6419 } 6420 6421 /** 6422 * Verification statuses are ordered from the worse to the best, except for 6423 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6424 */ 6425 private int bestDomainVerificationStatus(int status1, int status2) { 6426 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6427 return status2; 6428 } 6429 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6430 return status1; 6431 } 6432 return (int) MathUtils.max(status1, status2); 6433 } 6434 6435 private boolean isUserEnabled(int userId) { 6436 long callingId = Binder.clearCallingIdentity(); 6437 try { 6438 UserInfo userInfo = sUserManager.getUserInfo(userId); 6439 return userInfo != null && userInfo.isEnabled(); 6440 } finally { 6441 Binder.restoreCallingIdentity(callingId); 6442 } 6443 } 6444 6445 /** 6446 * Filter out activities with systemUserOnly flag set, when current user is not System. 6447 * 6448 * @return filtered list 6449 */ 6450 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6451 if (userId == UserHandle.USER_SYSTEM) { 6452 return resolveInfos; 6453 } 6454 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6455 ResolveInfo info = resolveInfos.get(i); 6456 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6457 resolveInfos.remove(i); 6458 } 6459 } 6460 return resolveInfos; 6461 } 6462 6463 /** 6464 * Filters out ephemeral activities. 6465 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6466 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6467 * 6468 * @param resolveInfos The pre-filtered list of resolved activities 6469 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6470 * is performed. 6471 * @return A filtered list of resolved activities. 6472 */ 6473 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6474 String ephemeralPkgName) { 6475 // TODO: When adding on-demand split support for non-instant apps, remove this check 6476 // and always apply post filtering 6477 if (ephemeralPkgName == null) { 6478 return resolveInfos; 6479 } 6480 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6481 final ResolveInfo info = resolveInfos.get(i); 6482 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6483 // allow activities that are defined in the provided package 6484 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6485 if (info.activityInfo.splitName != null 6486 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6487 info.activityInfo.splitName)) { 6488 // requested activity is defined in a split that hasn't been installed yet. 6489 // add the installer to the resolve list 6490 if (DEBUG_EPHEMERAL) { 6491 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6492 } 6493 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6494 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6495 info.activityInfo.packageName, info.activityInfo.splitName, 6496 info.activityInfo.applicationInfo.versionCode); 6497 // make sure this resolver is the default 6498 installerInfo.isDefault = true; 6499 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6500 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6501 // add a non-generic filter 6502 installerInfo.filter = new IntentFilter(); 6503 // load resources from the correct package 6504 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6505 resolveInfos.set(i, installerInfo); 6506 } 6507 continue; 6508 } 6509 // allow activities that have been explicitly exposed to ephemeral apps 6510 if (!isEphemeralApp 6511 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6512 continue; 6513 } 6514 resolveInfos.remove(i); 6515 } 6516 return resolveInfos; 6517 } 6518 6519 /** 6520 * @param resolveInfos list of resolve infos in descending priority order 6521 * @return if the list contains a resolve info with non-negative priority 6522 */ 6523 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6524 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6525 } 6526 6527 private static boolean hasWebURI(Intent intent) { 6528 if (intent.getData() == null) { 6529 return false; 6530 } 6531 final String scheme = intent.getScheme(); 6532 if (TextUtils.isEmpty(scheme)) { 6533 return false; 6534 } 6535 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6536 } 6537 6538 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6539 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6540 int userId) { 6541 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6542 6543 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6544 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6545 candidates.size()); 6546 } 6547 6548 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6549 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6550 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6551 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6552 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6553 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6554 6555 synchronized (mPackages) { 6556 final int count = candidates.size(); 6557 // First, try to use linked apps. Partition the candidates into four lists: 6558 // one for the final results, one for the "do not use ever", one for "undefined status" 6559 // and finally one for "browser app type". 6560 for (int n=0; n<count; n++) { 6561 ResolveInfo info = candidates.get(n); 6562 String packageName = info.activityInfo.packageName; 6563 PackageSetting ps = mSettings.mPackages.get(packageName); 6564 if (ps != null) { 6565 // Add to the special match all list (Browser use case) 6566 if (info.handleAllWebDataURI) { 6567 matchAllList.add(info); 6568 continue; 6569 } 6570 // Try to get the status from User settings first 6571 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6572 int status = (int)(packedStatus >> 32); 6573 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6574 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6575 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6576 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6577 + " : linkgen=" + linkGeneration); 6578 } 6579 // Use link-enabled generation as preferredOrder, i.e. 6580 // prefer newly-enabled over earlier-enabled. 6581 info.preferredOrder = linkGeneration; 6582 alwaysList.add(info); 6583 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6584 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6585 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6586 } 6587 neverList.add(info); 6588 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6589 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6590 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6591 } 6592 alwaysAskList.add(info); 6593 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6594 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6595 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6596 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6597 } 6598 undefinedList.add(info); 6599 } 6600 } 6601 } 6602 6603 // We'll want to include browser possibilities in a few cases 6604 boolean includeBrowser = false; 6605 6606 // First try to add the "always" resolution(s) for the current user, if any 6607 if (alwaysList.size() > 0) { 6608 result.addAll(alwaysList); 6609 } else { 6610 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6611 result.addAll(undefinedList); 6612 // Maybe add one for the other profile. 6613 if (xpDomainInfo != null && ( 6614 xpDomainInfo.bestDomainVerificationStatus 6615 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6616 result.add(xpDomainInfo.resolveInfo); 6617 } 6618 includeBrowser = true; 6619 } 6620 6621 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6622 // If there were 'always' entries their preferred order has been set, so we also 6623 // back that off to make the alternatives equivalent 6624 if (alwaysAskList.size() > 0) { 6625 for (ResolveInfo i : result) { 6626 i.preferredOrder = 0; 6627 } 6628 result.addAll(alwaysAskList); 6629 includeBrowser = true; 6630 } 6631 6632 if (includeBrowser) { 6633 // Also add browsers (all of them or only the default one) 6634 if (DEBUG_DOMAIN_VERIFICATION) { 6635 Slog.v(TAG, " ...including browsers in candidate set"); 6636 } 6637 if ((matchFlags & MATCH_ALL) != 0) { 6638 result.addAll(matchAllList); 6639 } else { 6640 // Browser/generic handling case. If there's a default browser, go straight 6641 // to that (but only if there is no other higher-priority match). 6642 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6643 int maxMatchPrio = 0; 6644 ResolveInfo defaultBrowserMatch = null; 6645 final int numCandidates = matchAllList.size(); 6646 for (int n = 0; n < numCandidates; n++) { 6647 ResolveInfo info = matchAllList.get(n); 6648 // track the highest overall match priority... 6649 if (info.priority > maxMatchPrio) { 6650 maxMatchPrio = info.priority; 6651 } 6652 // ...and the highest-priority default browser match 6653 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6654 if (defaultBrowserMatch == null 6655 || (defaultBrowserMatch.priority < info.priority)) { 6656 if (debug) { 6657 Slog.v(TAG, "Considering default browser match " + info); 6658 } 6659 defaultBrowserMatch = info; 6660 } 6661 } 6662 } 6663 if (defaultBrowserMatch != null 6664 && defaultBrowserMatch.priority >= maxMatchPrio 6665 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6666 { 6667 if (debug) { 6668 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6669 } 6670 result.add(defaultBrowserMatch); 6671 } else { 6672 result.addAll(matchAllList); 6673 } 6674 } 6675 6676 // If there is nothing selected, add all candidates and remove the ones that the user 6677 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6678 if (result.size() == 0) { 6679 result.addAll(candidates); 6680 result.removeAll(neverList); 6681 } 6682 } 6683 } 6684 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6685 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6686 result.size()); 6687 for (ResolveInfo info : result) { 6688 Slog.v(TAG, " + " + info.activityInfo); 6689 } 6690 } 6691 return result; 6692 } 6693 6694 // Returns a packed value as a long: 6695 // 6696 // high 'int'-sized word: link status: undefined/ask/never/always. 6697 // low 'int'-sized word: relative priority among 'always' results. 6698 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6699 long result = ps.getDomainVerificationStatusForUser(userId); 6700 // if none available, get the master status 6701 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6702 if (ps.getIntentFilterVerificationInfo() != null) { 6703 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6704 } 6705 } 6706 return result; 6707 } 6708 6709 private ResolveInfo querySkipCurrentProfileIntents( 6710 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6711 int flags, int sourceUserId) { 6712 if (matchingFilters != null) { 6713 int size = matchingFilters.size(); 6714 for (int i = 0; i < size; i ++) { 6715 CrossProfileIntentFilter filter = matchingFilters.get(i); 6716 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6717 // Checking if there are activities in the target user that can handle the 6718 // intent. 6719 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6720 resolvedType, flags, sourceUserId); 6721 if (resolveInfo != null) { 6722 return resolveInfo; 6723 } 6724 } 6725 } 6726 } 6727 return null; 6728 } 6729 6730 // Return matching ResolveInfo in target user if any. 6731 private ResolveInfo queryCrossProfileIntents( 6732 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6733 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6734 if (matchingFilters != null) { 6735 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6736 // match the same intent. For performance reasons, it is better not to 6737 // run queryIntent twice for the same userId 6738 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6739 int size = matchingFilters.size(); 6740 for (int i = 0; i < size; i++) { 6741 CrossProfileIntentFilter filter = matchingFilters.get(i); 6742 int targetUserId = filter.getTargetUserId(); 6743 boolean skipCurrentProfile = 6744 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6745 boolean skipCurrentProfileIfNoMatchFound = 6746 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6747 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6748 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6749 // Checking if there are activities in the target user that can handle the 6750 // intent. 6751 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6752 resolvedType, flags, sourceUserId); 6753 if (resolveInfo != null) return resolveInfo; 6754 alreadyTriedUserIds.put(targetUserId, true); 6755 } 6756 } 6757 } 6758 return null; 6759 } 6760 6761 /** 6762 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6763 * will forward the intent to the filter's target user. 6764 * Otherwise, returns null. 6765 */ 6766 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6767 String resolvedType, int flags, int sourceUserId) { 6768 int targetUserId = filter.getTargetUserId(); 6769 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6770 resolvedType, flags, targetUserId); 6771 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6772 // If all the matches in the target profile are suspended, return null. 6773 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6774 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6775 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6776 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6777 targetUserId); 6778 } 6779 } 6780 } 6781 return null; 6782 } 6783 6784 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6785 int sourceUserId, int targetUserId) { 6786 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6787 long ident = Binder.clearCallingIdentity(); 6788 boolean targetIsProfile; 6789 try { 6790 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6791 } finally { 6792 Binder.restoreCallingIdentity(ident); 6793 } 6794 String className; 6795 if (targetIsProfile) { 6796 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6797 } else { 6798 className = FORWARD_INTENT_TO_PARENT; 6799 } 6800 ComponentName forwardingActivityComponentName = new ComponentName( 6801 mAndroidApplication.packageName, className); 6802 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6803 sourceUserId); 6804 if (!targetIsProfile) { 6805 forwardingActivityInfo.showUserIcon = targetUserId; 6806 forwardingResolveInfo.noResourceId = true; 6807 } 6808 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6809 forwardingResolveInfo.priority = 0; 6810 forwardingResolveInfo.preferredOrder = 0; 6811 forwardingResolveInfo.match = 0; 6812 forwardingResolveInfo.isDefault = true; 6813 forwardingResolveInfo.filter = filter; 6814 forwardingResolveInfo.targetUserId = targetUserId; 6815 return forwardingResolveInfo; 6816 } 6817 6818 @Override 6819 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6820 Intent[] specifics, String[] specificTypes, Intent intent, 6821 String resolvedType, int flags, int userId) { 6822 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6823 specificTypes, intent, resolvedType, flags, userId)); 6824 } 6825 6826 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6827 Intent[] specifics, String[] specificTypes, Intent intent, 6828 String resolvedType, int flags, int userId) { 6829 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6830 final int callingUid = Binder.getCallingUid(); 6831 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6832 false /*includeInstantApps*/); 6833 enforceCrossUserPermission(callingUid, userId, 6834 false /*requireFullPermission*/, false /*checkShell*/, 6835 "query intent activity options"); 6836 final String resultsAction = intent.getAction(); 6837 6838 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6839 | PackageManager.GET_RESOLVED_FILTER, userId); 6840 6841 if (DEBUG_INTENT_MATCHING) { 6842 Log.v(TAG, "Query " + intent + ": " + results); 6843 } 6844 6845 int specificsPos = 0; 6846 int N; 6847 6848 // todo: note that the algorithm used here is O(N^2). This 6849 // isn't a problem in our current environment, but if we start running 6850 // into situations where we have more than 5 or 10 matches then this 6851 // should probably be changed to something smarter... 6852 6853 // First we go through and resolve each of the specific items 6854 // that were supplied, taking care of removing any corresponding 6855 // duplicate items in the generic resolve list. 6856 if (specifics != null) { 6857 for (int i=0; i<specifics.length; i++) { 6858 final Intent sintent = specifics[i]; 6859 if (sintent == null) { 6860 continue; 6861 } 6862 6863 if (DEBUG_INTENT_MATCHING) { 6864 Log.v(TAG, "Specific #" + i + ": " + sintent); 6865 } 6866 6867 String action = sintent.getAction(); 6868 if (resultsAction != null && resultsAction.equals(action)) { 6869 // If this action was explicitly requested, then don't 6870 // remove things that have it. 6871 action = null; 6872 } 6873 6874 ResolveInfo ri = null; 6875 ActivityInfo ai = null; 6876 6877 ComponentName comp = sintent.getComponent(); 6878 if (comp == null) { 6879 ri = resolveIntent( 6880 sintent, 6881 specificTypes != null ? specificTypes[i] : null, 6882 flags, userId); 6883 if (ri == null) { 6884 continue; 6885 } 6886 if (ri == mResolveInfo) { 6887 // ACK! Must do something better with this. 6888 } 6889 ai = ri.activityInfo; 6890 comp = new ComponentName(ai.applicationInfo.packageName, 6891 ai.name); 6892 } else { 6893 ai = getActivityInfo(comp, flags, userId); 6894 if (ai == null) { 6895 continue; 6896 } 6897 } 6898 6899 // Look for any generic query activities that are duplicates 6900 // of this specific one, and remove them from the results. 6901 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6902 N = results.size(); 6903 int j; 6904 for (j=specificsPos; j<N; j++) { 6905 ResolveInfo sri = results.get(j); 6906 if ((sri.activityInfo.name.equals(comp.getClassName()) 6907 && sri.activityInfo.applicationInfo.packageName.equals( 6908 comp.getPackageName())) 6909 || (action != null && sri.filter.matchAction(action))) { 6910 results.remove(j); 6911 if (DEBUG_INTENT_MATCHING) Log.v( 6912 TAG, "Removing duplicate item from " + j 6913 + " due to specific " + specificsPos); 6914 if (ri == null) { 6915 ri = sri; 6916 } 6917 j--; 6918 N--; 6919 } 6920 } 6921 6922 // Add this specific item to its proper place. 6923 if (ri == null) { 6924 ri = new ResolveInfo(); 6925 ri.activityInfo = ai; 6926 } 6927 results.add(specificsPos, ri); 6928 ri.specificIndex = i; 6929 specificsPos++; 6930 } 6931 } 6932 6933 // Now we go through the remaining generic results and remove any 6934 // duplicate actions that are found here. 6935 N = results.size(); 6936 for (int i=specificsPos; i<N-1; i++) { 6937 final ResolveInfo rii = results.get(i); 6938 if (rii.filter == null) { 6939 continue; 6940 } 6941 6942 // Iterate over all of the actions of this result's intent 6943 // filter... typically this should be just one. 6944 final Iterator<String> it = rii.filter.actionsIterator(); 6945 if (it == null) { 6946 continue; 6947 } 6948 while (it.hasNext()) { 6949 final String action = it.next(); 6950 if (resultsAction != null && resultsAction.equals(action)) { 6951 // If this action was explicitly requested, then don't 6952 // remove things that have it. 6953 continue; 6954 } 6955 for (int j=i+1; j<N; j++) { 6956 final ResolveInfo rij = results.get(j); 6957 if (rij.filter != null && rij.filter.hasAction(action)) { 6958 results.remove(j); 6959 if (DEBUG_INTENT_MATCHING) Log.v( 6960 TAG, "Removing duplicate item from " + j 6961 + " due to action " + action + " at " + i); 6962 j--; 6963 N--; 6964 } 6965 } 6966 } 6967 6968 // If the caller didn't request filter information, drop it now 6969 // so we don't have to marshall/unmarshall it. 6970 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6971 rii.filter = null; 6972 } 6973 } 6974 6975 // Filter out the caller activity if so requested. 6976 if (caller != null) { 6977 N = results.size(); 6978 for (int i=0; i<N; i++) { 6979 ActivityInfo ainfo = results.get(i).activityInfo; 6980 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6981 && caller.getClassName().equals(ainfo.name)) { 6982 results.remove(i); 6983 break; 6984 } 6985 } 6986 } 6987 6988 // If the caller didn't request filter information, 6989 // drop them now so we don't have to 6990 // marshall/unmarshall it. 6991 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6992 N = results.size(); 6993 for (int i=0; i<N; i++) { 6994 results.get(i).filter = null; 6995 } 6996 } 6997 6998 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6999 return results; 7000 } 7001 7002 @Override 7003 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7004 String resolvedType, int flags, int userId) { 7005 return new ParceledListSlice<>( 7006 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7007 } 7008 7009 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7010 String resolvedType, int flags, int userId) { 7011 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7012 final int callingUid = Binder.getCallingUid(); 7013 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7014 false /*includeInstantApps*/); 7015 ComponentName comp = intent.getComponent(); 7016 if (comp == null) { 7017 if (intent.getSelector() != null) { 7018 intent = intent.getSelector(); 7019 comp = intent.getComponent(); 7020 } 7021 } 7022 if (comp != null) { 7023 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7024 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7025 if (ai != null) { 7026 ResolveInfo ri = new ResolveInfo(); 7027 ri.activityInfo = ai; 7028 list.add(ri); 7029 } 7030 return list; 7031 } 7032 7033 // reader 7034 synchronized (mPackages) { 7035 String pkgName = intent.getPackage(); 7036 if (pkgName == null) { 7037 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7038 } 7039 final PackageParser.Package pkg = mPackages.get(pkgName); 7040 if (pkg != null) { 7041 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7042 userId); 7043 } 7044 return Collections.emptyList(); 7045 } 7046 } 7047 7048 @Override 7049 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7050 final int callingUid = Binder.getCallingUid(); 7051 return resolveServiceInternal( 7052 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7053 } 7054 7055 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7056 int userId, int callingUid, boolean includeInstantApps) { 7057 if (!sUserManager.exists(userId)) return null; 7058 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7059 List<ResolveInfo> query = queryIntentServicesInternal( 7060 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7061 if (query != null) { 7062 if (query.size() >= 1) { 7063 // If there is more than one service with the same priority, 7064 // just arbitrarily pick the first one. 7065 return query.get(0); 7066 } 7067 } 7068 return null; 7069 } 7070 7071 @Override 7072 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7073 String resolvedType, int flags, int userId) { 7074 final int callingUid = Binder.getCallingUid(); 7075 return new ParceledListSlice<>(queryIntentServicesInternal( 7076 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7077 } 7078 7079 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7080 String resolvedType, int flags, int userId, int callingUid, 7081 boolean includeInstantApps) { 7082 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7083 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7084 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7085 ComponentName comp = intent.getComponent(); 7086 if (comp == null) { 7087 if (intent.getSelector() != null) { 7088 intent = intent.getSelector(); 7089 comp = intent.getComponent(); 7090 } 7091 } 7092 if (comp != null) { 7093 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7094 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7095 if (si != null) { 7096 // When specifying an explicit component, we prevent the service from being 7097 // used when either 1) the service is in an instant application and the 7098 // caller is not the same instant application or 2) the calling package is 7099 // ephemeral and the activity is not visible to ephemeral applications. 7100 final boolean matchVisibleToInstantAppOnly = 7101 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7102 final boolean isCallerInstantApp = 7103 instantAppPkgName != null; 7104 final boolean isTargetSameInstantApp = 7105 comp.getPackageName().equals(instantAppPkgName); 7106 final boolean isTargetHiddenFromInstantApp = 7107 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7108 final boolean blockResolution = 7109 !isTargetSameInstantApp 7110 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7111 && isTargetHiddenFromInstantApp)); 7112 if (!blockResolution) { 7113 final ResolveInfo ri = new ResolveInfo(); 7114 ri.serviceInfo = si; 7115 list.add(ri); 7116 } 7117 } 7118 return list; 7119 } 7120 7121 // reader 7122 synchronized (mPackages) { 7123 String pkgName = intent.getPackage(); 7124 if (pkgName == null) { 7125 return applyPostServiceResolutionFilter( 7126 mServices.queryIntent(intent, resolvedType, flags, userId), 7127 instantAppPkgName); 7128 } 7129 final PackageParser.Package pkg = mPackages.get(pkgName); 7130 if (pkg != null) { 7131 return applyPostServiceResolutionFilter( 7132 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7133 userId), 7134 instantAppPkgName); 7135 } 7136 return Collections.emptyList(); 7137 } 7138 } 7139 7140 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7141 String instantAppPkgName) { 7142 // TODO: When adding on-demand split support for non-instant apps, remove this check 7143 // and always apply post filtering 7144 if (instantAppPkgName == null) { 7145 return resolveInfos; 7146 } 7147 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7148 final ResolveInfo info = resolveInfos.get(i); 7149 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7150 // allow services that are defined in the provided package 7151 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7152 if (info.serviceInfo.splitName != null 7153 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7154 info.serviceInfo.splitName)) { 7155 // requested service is defined in a split that hasn't been installed yet. 7156 // add the installer to the resolve list 7157 if (DEBUG_EPHEMERAL) { 7158 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7159 } 7160 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7161 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7162 info.serviceInfo.packageName, info.serviceInfo.splitName, 7163 info.serviceInfo.applicationInfo.versionCode); 7164 // make sure this resolver is the default 7165 installerInfo.isDefault = true; 7166 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7167 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7168 // add a non-generic filter 7169 installerInfo.filter = new IntentFilter(); 7170 // load resources from the correct package 7171 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7172 resolveInfos.set(i, installerInfo); 7173 } 7174 continue; 7175 } 7176 // allow services that have been explicitly exposed to ephemeral apps 7177 if (!isEphemeralApp 7178 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7179 continue; 7180 } 7181 resolveInfos.remove(i); 7182 } 7183 return resolveInfos; 7184 } 7185 7186 @Override 7187 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7188 String resolvedType, int flags, int userId) { 7189 return new ParceledListSlice<>( 7190 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7191 } 7192 7193 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7194 Intent intent, String resolvedType, int flags, int userId) { 7195 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7196 final int callingUid = Binder.getCallingUid(); 7197 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7198 false /*includeInstantApps*/); 7199 ComponentName comp = intent.getComponent(); 7200 if (comp == null) { 7201 if (intent.getSelector() != null) { 7202 intent = intent.getSelector(); 7203 comp = intent.getComponent(); 7204 } 7205 } 7206 if (comp != null) { 7207 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7208 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7209 if (pi != null) { 7210 final ResolveInfo ri = new ResolveInfo(); 7211 ri.providerInfo = pi; 7212 list.add(ri); 7213 } 7214 return list; 7215 } 7216 7217 // reader 7218 synchronized (mPackages) { 7219 String pkgName = intent.getPackage(); 7220 if (pkgName == null) { 7221 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7222 } 7223 final PackageParser.Package pkg = mPackages.get(pkgName); 7224 if (pkg != null) { 7225 return mProviders.queryIntentForPackage( 7226 intent, resolvedType, flags, pkg.providers, userId); 7227 } 7228 return Collections.emptyList(); 7229 } 7230 } 7231 7232 @Override 7233 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7234 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7235 flags = updateFlagsForPackage(flags, userId, null); 7236 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7237 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7238 true /* requireFullPermission */, false /* checkShell */, 7239 "get installed packages"); 7240 7241 // writer 7242 synchronized (mPackages) { 7243 ArrayList<PackageInfo> list; 7244 if (listUninstalled) { 7245 list = new ArrayList<>(mSettings.mPackages.size()); 7246 for (PackageSetting ps : mSettings.mPackages.values()) { 7247 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7248 continue; 7249 } 7250 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7251 if (pi != null) { 7252 list.add(pi); 7253 } 7254 } 7255 } else { 7256 list = new ArrayList<>(mPackages.size()); 7257 for (PackageParser.Package p : mPackages.values()) { 7258 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7259 Binder.getCallingUid(), userId)) { 7260 continue; 7261 } 7262 final PackageInfo pi = generatePackageInfo((PackageSetting) 7263 p.mExtras, flags, userId); 7264 if (pi != null) { 7265 list.add(pi); 7266 } 7267 } 7268 } 7269 7270 return new ParceledListSlice<>(list); 7271 } 7272 } 7273 7274 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7275 String[] permissions, boolean[] tmp, int flags, int userId) { 7276 int numMatch = 0; 7277 final PermissionsState permissionsState = ps.getPermissionsState(); 7278 for (int i=0; i<permissions.length; i++) { 7279 final String permission = permissions[i]; 7280 if (permissionsState.hasPermission(permission, userId)) { 7281 tmp[i] = true; 7282 numMatch++; 7283 } else { 7284 tmp[i] = false; 7285 } 7286 } 7287 if (numMatch == 0) { 7288 return; 7289 } 7290 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7291 7292 // The above might return null in cases of uninstalled apps or install-state 7293 // skew across users/profiles. 7294 if (pi != null) { 7295 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7296 if (numMatch == permissions.length) { 7297 pi.requestedPermissions = permissions; 7298 } else { 7299 pi.requestedPermissions = new String[numMatch]; 7300 numMatch = 0; 7301 for (int i=0; i<permissions.length; i++) { 7302 if (tmp[i]) { 7303 pi.requestedPermissions[numMatch] = permissions[i]; 7304 numMatch++; 7305 } 7306 } 7307 } 7308 } 7309 list.add(pi); 7310 } 7311 } 7312 7313 @Override 7314 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7315 String[] permissions, int flags, int userId) { 7316 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7317 flags = updateFlagsForPackage(flags, userId, permissions); 7318 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7319 true /* requireFullPermission */, false /* checkShell */, 7320 "get packages holding permissions"); 7321 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7322 7323 // writer 7324 synchronized (mPackages) { 7325 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7326 boolean[] tmpBools = new boolean[permissions.length]; 7327 if (listUninstalled) { 7328 for (PackageSetting ps : mSettings.mPackages.values()) { 7329 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7330 userId); 7331 } 7332 } else { 7333 for (PackageParser.Package pkg : mPackages.values()) { 7334 PackageSetting ps = (PackageSetting)pkg.mExtras; 7335 if (ps != null) { 7336 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7337 userId); 7338 } 7339 } 7340 } 7341 7342 return new ParceledListSlice<PackageInfo>(list); 7343 } 7344 } 7345 7346 @Override 7347 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7348 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7349 flags = updateFlagsForApplication(flags, userId, null); 7350 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7351 7352 // writer 7353 synchronized (mPackages) { 7354 ArrayList<ApplicationInfo> list; 7355 if (listUninstalled) { 7356 list = new ArrayList<>(mSettings.mPackages.size()); 7357 for (PackageSetting ps : mSettings.mPackages.values()) { 7358 ApplicationInfo ai; 7359 int effectiveFlags = flags; 7360 if (ps.isSystem()) { 7361 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7362 } 7363 if (ps.pkg != null) { 7364 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7365 continue; 7366 } 7367 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7368 ps.readUserState(userId), userId); 7369 if (ai != null) { 7370 rebaseEnabledOverlays(ai, userId); 7371 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7372 } 7373 } else { 7374 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7375 // and already converts to externally visible package name 7376 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7377 Binder.getCallingUid(), effectiveFlags, userId); 7378 } 7379 if (ai != null) { 7380 list.add(ai); 7381 } 7382 } 7383 } else { 7384 list = new ArrayList<>(mPackages.size()); 7385 for (PackageParser.Package p : mPackages.values()) { 7386 if (p.mExtras != null) { 7387 PackageSetting ps = (PackageSetting) p.mExtras; 7388 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7389 continue; 7390 } 7391 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7392 ps.readUserState(userId), userId); 7393 if (ai != null) { 7394 rebaseEnabledOverlays(ai, userId); 7395 ai.packageName = resolveExternalPackageNameLPr(p); 7396 list.add(ai); 7397 } 7398 } 7399 } 7400 } 7401 7402 return new ParceledListSlice<>(list); 7403 } 7404 } 7405 7406 @Override 7407 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7408 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7409 return null; 7410 } 7411 7412 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7413 "getEphemeralApplications"); 7414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7415 true /* requireFullPermission */, false /* checkShell */, 7416 "getEphemeralApplications"); 7417 synchronized (mPackages) { 7418 List<InstantAppInfo> instantApps = mInstantAppRegistry 7419 .getInstantAppsLPr(userId); 7420 if (instantApps != null) { 7421 return new ParceledListSlice<>(instantApps); 7422 } 7423 } 7424 return null; 7425 } 7426 7427 @Override 7428 public boolean isInstantApp(String packageName, int userId) { 7429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7430 true /* requireFullPermission */, false /* checkShell */, 7431 "isInstantApp"); 7432 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7433 return false; 7434 } 7435 int uid = Binder.getCallingUid(); 7436 if (Process.isIsolated(uid)) { 7437 uid = mIsolatedOwners.get(uid); 7438 } 7439 7440 synchronized (mPackages) { 7441 final PackageSetting ps = mSettings.mPackages.get(packageName); 7442 PackageParser.Package pkg = mPackages.get(packageName); 7443 final boolean returnAllowed = 7444 ps != null 7445 && (isCallerSameApp(packageName, uid) 7446 || mContext.checkCallingOrSelfPermission( 7447 android.Manifest.permission.ACCESS_INSTANT_APPS) 7448 == PERMISSION_GRANTED 7449 || mInstantAppRegistry.isInstantAccessGranted( 7450 userId, UserHandle.getAppId(uid), ps.appId)); 7451 if (returnAllowed) { 7452 return ps.getInstantApp(userId); 7453 } 7454 } 7455 return false; 7456 } 7457 7458 @Override 7459 public byte[] getInstantAppCookie(String packageName, int userId) { 7460 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7461 return null; 7462 } 7463 7464 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7465 true /* requireFullPermission */, false /* checkShell */, 7466 "getInstantAppCookie"); 7467 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7468 return null; 7469 } 7470 synchronized (mPackages) { 7471 return mInstantAppRegistry.getInstantAppCookieLPw( 7472 packageName, userId); 7473 } 7474 } 7475 7476 @Override 7477 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7478 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7479 return true; 7480 } 7481 7482 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7483 true /* requireFullPermission */, true /* checkShell */, 7484 "setInstantAppCookie"); 7485 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7486 return false; 7487 } 7488 synchronized (mPackages) { 7489 return mInstantAppRegistry.setInstantAppCookieLPw( 7490 packageName, cookie, userId); 7491 } 7492 } 7493 7494 @Override 7495 public Bitmap getInstantAppIcon(String packageName, int userId) { 7496 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7497 return null; 7498 } 7499 7500 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7501 "getInstantAppIcon"); 7502 7503 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7504 true /* requireFullPermission */, false /* checkShell */, 7505 "getInstantAppIcon"); 7506 7507 synchronized (mPackages) { 7508 return mInstantAppRegistry.getInstantAppIconLPw( 7509 packageName, userId); 7510 } 7511 } 7512 7513 private boolean isCallerSameApp(String packageName, int uid) { 7514 PackageParser.Package pkg = mPackages.get(packageName); 7515 return pkg != null 7516 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7517 } 7518 7519 @Override 7520 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7521 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7522 } 7523 7524 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7525 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7526 7527 // reader 7528 synchronized (mPackages) { 7529 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7530 final int userId = UserHandle.getCallingUserId(); 7531 while (i.hasNext()) { 7532 final PackageParser.Package p = i.next(); 7533 if (p.applicationInfo == null) continue; 7534 7535 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7536 && !p.applicationInfo.isDirectBootAware(); 7537 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7538 && p.applicationInfo.isDirectBootAware(); 7539 7540 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7541 && (!mSafeMode || isSystemApp(p)) 7542 && (matchesUnaware || matchesAware)) { 7543 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7544 if (ps != null) { 7545 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7546 ps.readUserState(userId), userId); 7547 if (ai != null) { 7548 rebaseEnabledOverlays(ai, userId); 7549 finalList.add(ai); 7550 } 7551 } 7552 } 7553 } 7554 } 7555 7556 return finalList; 7557 } 7558 7559 @Override 7560 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7561 if (!sUserManager.exists(userId)) return null; 7562 flags = updateFlagsForComponent(flags, userId, name); 7563 // reader 7564 synchronized (mPackages) { 7565 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7566 PackageSetting ps = provider != null 7567 ? mSettings.mPackages.get(provider.owner.packageName) 7568 : null; 7569 return ps != null 7570 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7571 ? PackageParser.generateProviderInfo(provider, flags, 7572 ps.readUserState(userId), userId) 7573 : null; 7574 } 7575 } 7576 7577 /** 7578 * @deprecated 7579 */ 7580 @Deprecated 7581 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7582 // reader 7583 synchronized (mPackages) { 7584 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7585 .entrySet().iterator(); 7586 final int userId = UserHandle.getCallingUserId(); 7587 while (i.hasNext()) { 7588 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7589 PackageParser.Provider p = entry.getValue(); 7590 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7591 7592 if (ps != null && p.syncable 7593 && (!mSafeMode || (p.info.applicationInfo.flags 7594 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7595 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7596 ps.readUserState(userId), userId); 7597 if (info != null) { 7598 outNames.add(entry.getKey()); 7599 outInfo.add(info); 7600 } 7601 } 7602 } 7603 } 7604 } 7605 7606 @Override 7607 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7608 int uid, int flags, String metaDataKey) { 7609 final int userId = processName != null ? UserHandle.getUserId(uid) 7610 : UserHandle.getCallingUserId(); 7611 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7612 flags = updateFlagsForComponent(flags, userId, processName); 7613 7614 ArrayList<ProviderInfo> finalList = null; 7615 // reader 7616 synchronized (mPackages) { 7617 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7618 while (i.hasNext()) { 7619 final PackageParser.Provider p = i.next(); 7620 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7621 if (ps != null && p.info.authority != null 7622 && (processName == null 7623 || (p.info.processName.equals(processName) 7624 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7625 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7626 7627 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7628 // parameter. 7629 if (metaDataKey != null 7630 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7631 continue; 7632 } 7633 7634 if (finalList == null) { 7635 finalList = new ArrayList<ProviderInfo>(3); 7636 } 7637 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7638 ps.readUserState(userId), userId); 7639 if (info != null) { 7640 finalList.add(info); 7641 } 7642 } 7643 } 7644 } 7645 7646 if (finalList != null) { 7647 Collections.sort(finalList, mProviderInitOrderSorter); 7648 return new ParceledListSlice<ProviderInfo>(finalList); 7649 } 7650 7651 return ParceledListSlice.emptyList(); 7652 } 7653 7654 @Override 7655 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7656 // reader 7657 synchronized (mPackages) { 7658 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7659 return PackageParser.generateInstrumentationInfo(i, flags); 7660 } 7661 } 7662 7663 @Override 7664 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7665 String targetPackage, int flags) { 7666 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7667 } 7668 7669 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7670 int flags) { 7671 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7672 7673 // reader 7674 synchronized (mPackages) { 7675 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7676 while (i.hasNext()) { 7677 final PackageParser.Instrumentation p = i.next(); 7678 if (targetPackage == null 7679 || targetPackage.equals(p.info.targetPackage)) { 7680 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7681 flags); 7682 if (ii != null) { 7683 finalList.add(ii); 7684 } 7685 } 7686 } 7687 } 7688 7689 return finalList; 7690 } 7691 7692 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7693 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7694 try { 7695 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7696 } finally { 7697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7698 } 7699 } 7700 7701 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7702 final File[] files = dir.listFiles(); 7703 if (ArrayUtils.isEmpty(files)) { 7704 Log.d(TAG, "No files in app dir " + dir); 7705 return; 7706 } 7707 7708 if (DEBUG_PACKAGE_SCANNING) { 7709 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7710 + " flags=0x" + Integer.toHexString(parseFlags)); 7711 } 7712 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7713 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7714 7715 // Submit files for parsing in parallel 7716 int fileCount = 0; 7717 for (File file : files) { 7718 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7719 && !PackageInstallerService.isStageName(file.getName()); 7720 if (!isPackage) { 7721 // Ignore entries which are not packages 7722 continue; 7723 } 7724 parallelPackageParser.submit(file, parseFlags); 7725 fileCount++; 7726 } 7727 7728 // Process results one by one 7729 for (; fileCount > 0; fileCount--) { 7730 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7731 Throwable throwable = parseResult.throwable; 7732 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7733 7734 if (throwable == null) { 7735 // Static shared libraries have synthetic package names 7736 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7737 renameStaticSharedLibraryPackage(parseResult.pkg); 7738 } 7739 try { 7740 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7741 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7742 currentTime, null); 7743 } 7744 } catch (PackageManagerException e) { 7745 errorCode = e.error; 7746 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7747 } 7748 } else if (throwable instanceof PackageParser.PackageParserException) { 7749 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7750 throwable; 7751 errorCode = e.error; 7752 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7753 } else { 7754 throw new IllegalStateException("Unexpected exception occurred while parsing " 7755 + parseResult.scanFile, throwable); 7756 } 7757 7758 // Delete invalid userdata apps 7759 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7760 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7761 logCriticalInfo(Log.WARN, 7762 "Deleting invalid package at " + parseResult.scanFile); 7763 removeCodePathLI(parseResult.scanFile); 7764 } 7765 } 7766 parallelPackageParser.close(); 7767 } 7768 7769 private static File getSettingsProblemFile() { 7770 File dataDir = Environment.getDataDirectory(); 7771 File systemDir = new File(dataDir, "system"); 7772 File fname = new File(systemDir, "uiderrors.txt"); 7773 return fname; 7774 } 7775 7776 static void reportSettingsProblem(int priority, String msg) { 7777 logCriticalInfo(priority, msg); 7778 } 7779 7780 public static void logCriticalInfo(int priority, String msg) { 7781 Slog.println(priority, TAG, msg); 7782 EventLogTags.writePmCriticalInfo(msg); 7783 try { 7784 File fname = getSettingsProblemFile(); 7785 FileOutputStream out = new FileOutputStream(fname, true); 7786 PrintWriter pw = new FastPrintWriter(out); 7787 SimpleDateFormat formatter = new SimpleDateFormat(); 7788 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7789 pw.println(dateString + ": " + msg); 7790 pw.close(); 7791 FileUtils.setPermissions( 7792 fname.toString(), 7793 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7794 -1, -1); 7795 } catch (java.io.IOException e) { 7796 } 7797 } 7798 7799 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7800 if (srcFile.isDirectory()) { 7801 final File baseFile = new File(pkg.baseCodePath); 7802 long maxModifiedTime = baseFile.lastModified(); 7803 if (pkg.splitCodePaths != null) { 7804 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7805 final File splitFile = new File(pkg.splitCodePaths[i]); 7806 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7807 } 7808 } 7809 return maxModifiedTime; 7810 } 7811 return srcFile.lastModified(); 7812 } 7813 7814 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7815 final int policyFlags) throws PackageManagerException { 7816 // When upgrading from pre-N MR1, verify the package time stamp using the package 7817 // directory and not the APK file. 7818 final long lastModifiedTime = mIsPreNMR1Upgrade 7819 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7820 if (ps != null 7821 && ps.codePath.equals(srcFile) 7822 && ps.timeStamp == lastModifiedTime 7823 && !isCompatSignatureUpdateNeeded(pkg) 7824 && !isRecoverSignatureUpdateNeeded(pkg)) { 7825 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7826 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7827 ArraySet<PublicKey> signingKs; 7828 synchronized (mPackages) { 7829 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7830 } 7831 if (ps.signatures.mSignatures != null 7832 && ps.signatures.mSignatures.length != 0 7833 && signingKs != null) { 7834 // Optimization: reuse the existing cached certificates 7835 // if the package appears to be unchanged. 7836 pkg.mSignatures = ps.signatures.mSignatures; 7837 pkg.mSigningKeys = signingKs; 7838 return; 7839 } 7840 7841 Slog.w(TAG, "PackageSetting for " + ps.name 7842 + " is missing signatures. Collecting certs again to recover them."); 7843 } else { 7844 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7845 } 7846 7847 try { 7848 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7849 PackageParser.collectCertificates(pkg, policyFlags); 7850 } catch (PackageParserException e) { 7851 throw PackageManagerException.from(e); 7852 } finally { 7853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7854 } 7855 } 7856 7857 /** 7858 * Traces a package scan. 7859 * @see #scanPackageLI(File, int, int, long, UserHandle) 7860 */ 7861 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7862 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7863 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7864 try { 7865 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7866 } finally { 7867 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7868 } 7869 } 7870 7871 /** 7872 * Scans a package and returns the newly parsed package. 7873 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7874 */ 7875 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7876 long currentTime, UserHandle user) throws PackageManagerException { 7877 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7878 PackageParser pp = new PackageParser(); 7879 pp.setSeparateProcesses(mSeparateProcesses); 7880 pp.setOnlyCoreApps(mOnlyCore); 7881 pp.setDisplayMetrics(mMetrics); 7882 pp.setCallback(mPackageParserCallback); 7883 7884 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7885 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7886 } 7887 7888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7889 final PackageParser.Package pkg; 7890 try { 7891 pkg = pp.parsePackage(scanFile, parseFlags); 7892 } catch (PackageParserException e) { 7893 throw PackageManagerException.from(e); 7894 } finally { 7895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7896 } 7897 7898 // Static shared libraries have synthetic package names 7899 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7900 renameStaticSharedLibraryPackage(pkg); 7901 } 7902 7903 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7904 } 7905 7906 /** 7907 * Scans a package and returns the newly parsed package. 7908 * @throws PackageManagerException on a parse error. 7909 */ 7910 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7911 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7912 throws PackageManagerException { 7913 // If the package has children and this is the first dive in the function 7914 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7915 // packages (parent and children) would be successfully scanned before the 7916 // actual scan since scanning mutates internal state and we want to atomically 7917 // install the package and its children. 7918 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7919 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7920 scanFlags |= SCAN_CHECK_ONLY; 7921 } 7922 } else { 7923 scanFlags &= ~SCAN_CHECK_ONLY; 7924 } 7925 7926 // Scan the parent 7927 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7928 scanFlags, currentTime, user); 7929 7930 // Scan the children 7931 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7932 for (int i = 0; i < childCount; i++) { 7933 PackageParser.Package childPackage = pkg.childPackages.get(i); 7934 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7935 currentTime, user); 7936 } 7937 7938 7939 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7940 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7941 } 7942 7943 return scannedPkg; 7944 } 7945 7946 /** 7947 * Scans a package and returns the newly parsed package. 7948 * @throws PackageManagerException on a parse error. 7949 */ 7950 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7951 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7952 throws PackageManagerException { 7953 PackageSetting ps = null; 7954 PackageSetting updatedPkg; 7955 // reader 7956 synchronized (mPackages) { 7957 // Look to see if we already know about this package. 7958 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7959 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7960 // This package has been renamed to its original name. Let's 7961 // use that. 7962 ps = mSettings.getPackageLPr(oldName); 7963 } 7964 // If there was no original package, see one for the real package name. 7965 if (ps == null) { 7966 ps = mSettings.getPackageLPr(pkg.packageName); 7967 } 7968 // Check to see if this package could be hiding/updating a system 7969 // package. Must look for it either under the original or real 7970 // package name depending on our state. 7971 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7972 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7973 7974 // If this is a package we don't know about on the system partition, we 7975 // may need to remove disabled child packages on the system partition 7976 // or may need to not add child packages if the parent apk is updated 7977 // on the data partition and no longer defines this child package. 7978 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7979 // If this is a parent package for an updated system app and this system 7980 // app got an OTA update which no longer defines some of the child packages 7981 // we have to prune them from the disabled system packages. 7982 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7983 if (disabledPs != null) { 7984 final int scannedChildCount = (pkg.childPackages != null) 7985 ? pkg.childPackages.size() : 0; 7986 final int disabledChildCount = disabledPs.childPackageNames != null 7987 ? disabledPs.childPackageNames.size() : 0; 7988 for (int i = 0; i < disabledChildCount; i++) { 7989 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7990 boolean disabledPackageAvailable = false; 7991 for (int j = 0; j < scannedChildCount; j++) { 7992 PackageParser.Package childPkg = pkg.childPackages.get(j); 7993 if (childPkg.packageName.equals(disabledChildPackageName)) { 7994 disabledPackageAvailable = true; 7995 break; 7996 } 7997 } 7998 if (!disabledPackageAvailable) { 7999 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8000 } 8001 } 8002 } 8003 } 8004 } 8005 8006 boolean updatedPkgBetter = false; 8007 // First check if this is a system package that may involve an update 8008 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8009 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8010 // it needs to drop FLAG_PRIVILEGED. 8011 if (locationIsPrivileged(scanFile)) { 8012 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8013 } else { 8014 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8015 } 8016 8017 if (ps != null && !ps.codePath.equals(scanFile)) { 8018 // The path has changed from what was last scanned... check the 8019 // version of the new path against what we have stored to determine 8020 // what to do. 8021 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8022 if (pkg.mVersionCode <= ps.versionCode) { 8023 // The system package has been updated and the code path does not match 8024 // Ignore entry. Skip it. 8025 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8026 + " ignored: updated version " + ps.versionCode 8027 + " better than this " + pkg.mVersionCode); 8028 if (!updatedPkg.codePath.equals(scanFile)) { 8029 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8030 + ps.name + " changing from " + updatedPkg.codePathString 8031 + " to " + scanFile); 8032 updatedPkg.codePath = scanFile; 8033 updatedPkg.codePathString = scanFile.toString(); 8034 updatedPkg.resourcePath = scanFile; 8035 updatedPkg.resourcePathString = scanFile.toString(); 8036 } 8037 updatedPkg.pkg = pkg; 8038 updatedPkg.versionCode = pkg.mVersionCode; 8039 8040 // Update the disabled system child packages to point to the package too. 8041 final int childCount = updatedPkg.childPackageNames != null 8042 ? updatedPkg.childPackageNames.size() : 0; 8043 for (int i = 0; i < childCount; i++) { 8044 String childPackageName = updatedPkg.childPackageNames.get(i); 8045 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8046 childPackageName); 8047 if (updatedChildPkg != null) { 8048 updatedChildPkg.pkg = pkg; 8049 updatedChildPkg.versionCode = pkg.mVersionCode; 8050 } 8051 } 8052 8053 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8054 + scanFile + " ignored: updated version " + ps.versionCode 8055 + " better than this " + pkg.mVersionCode); 8056 } else { 8057 // The current app on the system partition is better than 8058 // what we have updated to on the data partition; switch 8059 // back to the system partition version. 8060 // At this point, its safely assumed that package installation for 8061 // apps in system partition will go through. If not there won't be a working 8062 // version of the app 8063 // writer 8064 synchronized (mPackages) { 8065 // Just remove the loaded entries from package lists. 8066 mPackages.remove(ps.name); 8067 } 8068 8069 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8070 + " reverting from " + ps.codePathString 8071 + ": new version " + pkg.mVersionCode 8072 + " better than installed " + ps.versionCode); 8073 8074 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8075 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8076 synchronized (mInstallLock) { 8077 args.cleanUpResourcesLI(); 8078 } 8079 synchronized (mPackages) { 8080 mSettings.enableSystemPackageLPw(ps.name); 8081 } 8082 updatedPkgBetter = true; 8083 } 8084 } 8085 } 8086 8087 if (updatedPkg != null) { 8088 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8089 // initially 8090 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8091 8092 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8093 // flag set initially 8094 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8095 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8096 } 8097 } 8098 8099 // Verify certificates against what was last scanned 8100 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8101 8102 /* 8103 * A new system app appeared, but we already had a non-system one of the 8104 * same name installed earlier. 8105 */ 8106 boolean shouldHideSystemApp = false; 8107 if (updatedPkg == null && ps != null 8108 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8109 /* 8110 * Check to make sure the signatures match first. If they don't, 8111 * wipe the installed application and its data. 8112 */ 8113 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8114 != PackageManager.SIGNATURE_MATCH) { 8115 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8116 + " signatures don't match existing userdata copy; removing"); 8117 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8118 "scanPackageInternalLI")) { 8119 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8120 } 8121 ps = null; 8122 } else { 8123 /* 8124 * If the newly-added system app is an older version than the 8125 * already installed version, hide it. It will be scanned later 8126 * and re-added like an update. 8127 */ 8128 if (pkg.mVersionCode <= ps.versionCode) { 8129 shouldHideSystemApp = true; 8130 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8131 + " but new version " + pkg.mVersionCode + " better than installed " 8132 + ps.versionCode + "; hiding system"); 8133 } else { 8134 /* 8135 * The newly found system app is a newer version that the 8136 * one previously installed. Simply remove the 8137 * already-installed application and replace it with our own 8138 * while keeping the application data. 8139 */ 8140 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8141 + " reverting from " + ps.codePathString + ": new version " 8142 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8143 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8144 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8145 synchronized (mInstallLock) { 8146 args.cleanUpResourcesLI(); 8147 } 8148 } 8149 } 8150 } 8151 8152 // The apk is forward locked (not public) if its code and resources 8153 // are kept in different files. (except for app in either system or 8154 // vendor path). 8155 // TODO grab this value from PackageSettings 8156 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8157 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8158 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8159 } 8160 } 8161 8162 // TODO: extend to support forward-locked splits 8163 String resourcePath = null; 8164 String baseResourcePath = null; 8165 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8166 if (ps != null && ps.resourcePathString != null) { 8167 resourcePath = ps.resourcePathString; 8168 baseResourcePath = ps.resourcePathString; 8169 } else { 8170 // Should not happen at all. Just log an error. 8171 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8172 } 8173 } else { 8174 resourcePath = pkg.codePath; 8175 baseResourcePath = pkg.baseCodePath; 8176 } 8177 8178 // Set application objects path explicitly. 8179 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8180 pkg.setApplicationInfoCodePath(pkg.codePath); 8181 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8182 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8183 pkg.setApplicationInfoResourcePath(resourcePath); 8184 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8185 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8186 8187 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8188 if (ps != null && ps.getInstantApp(userId)) { 8189 scanFlags |= SCAN_AS_INSTANT_APP; 8190 } 8191 8192 // Note that we invoke the following method only if we are about to unpack an application 8193 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8194 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8195 8196 /* 8197 * If the system app should be overridden by a previously installed 8198 * data, hide the system app now and let the /data/app scan pick it up 8199 * again. 8200 */ 8201 if (shouldHideSystemApp) { 8202 synchronized (mPackages) { 8203 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8204 } 8205 } 8206 8207 return scannedPkg; 8208 } 8209 8210 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8211 // Derive the new package synthetic package name 8212 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8213 + pkg.staticSharedLibVersion); 8214 } 8215 8216 private static String fixProcessName(String defProcessName, 8217 String processName) { 8218 if (processName == null) { 8219 return defProcessName; 8220 } 8221 return processName; 8222 } 8223 8224 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8225 throws PackageManagerException { 8226 if (pkgSetting.signatures.mSignatures != null) { 8227 // Already existing package. Make sure signatures match 8228 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8229 == PackageManager.SIGNATURE_MATCH; 8230 if (!match) { 8231 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8232 == PackageManager.SIGNATURE_MATCH; 8233 } 8234 if (!match) { 8235 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8236 == PackageManager.SIGNATURE_MATCH; 8237 } 8238 if (!match) { 8239 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8240 + pkg.packageName + " signatures do not match the " 8241 + "previously installed version; ignoring!"); 8242 } 8243 } 8244 8245 // Check for shared user signatures 8246 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8247 // Already existing package. Make sure signatures match 8248 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8249 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8250 if (!match) { 8251 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8252 == PackageManager.SIGNATURE_MATCH; 8253 } 8254 if (!match) { 8255 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8256 == PackageManager.SIGNATURE_MATCH; 8257 } 8258 if (!match) { 8259 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8260 "Package " + pkg.packageName 8261 + " has no signatures that match those in shared user " 8262 + pkgSetting.sharedUser.name + "; ignoring!"); 8263 } 8264 } 8265 } 8266 8267 /** 8268 * Enforces that only the system UID or root's UID can call a method exposed 8269 * via Binder. 8270 * 8271 * @param message used as message if SecurityException is thrown 8272 * @throws SecurityException if the caller is not system or root 8273 */ 8274 private static final void enforceSystemOrRoot(String message) { 8275 final int uid = Binder.getCallingUid(); 8276 if (uid != Process.SYSTEM_UID && uid != 0) { 8277 throw new SecurityException(message); 8278 } 8279 } 8280 8281 @Override 8282 public void performFstrimIfNeeded() { 8283 enforceSystemOrRoot("Only the system can request fstrim"); 8284 8285 // Before everything else, see whether we need to fstrim. 8286 try { 8287 IStorageManager sm = PackageHelper.getStorageManager(); 8288 if (sm != null) { 8289 boolean doTrim = false; 8290 final long interval = android.provider.Settings.Global.getLong( 8291 mContext.getContentResolver(), 8292 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8293 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8294 if (interval > 0) { 8295 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8296 if (timeSinceLast > interval) { 8297 doTrim = true; 8298 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8299 + "; running immediately"); 8300 } 8301 } 8302 if (doTrim) { 8303 final boolean dexOptDialogShown; 8304 synchronized (mPackages) { 8305 dexOptDialogShown = mDexOptDialogShown; 8306 } 8307 if (!isFirstBoot() && dexOptDialogShown) { 8308 try { 8309 ActivityManager.getService().showBootMessage( 8310 mContext.getResources().getString( 8311 R.string.android_upgrading_fstrim), true); 8312 } catch (RemoteException e) { 8313 } 8314 } 8315 sm.runMaintenance(); 8316 } 8317 } else { 8318 Slog.e(TAG, "storageManager service unavailable!"); 8319 } 8320 } catch (RemoteException e) { 8321 // Can't happen; StorageManagerService is local 8322 } 8323 } 8324 8325 @Override 8326 public void updatePackagesIfNeeded() { 8327 enforceSystemOrRoot("Only the system can request package update"); 8328 8329 // We need to re-extract after an OTA. 8330 boolean causeUpgrade = isUpgrade(); 8331 8332 // First boot or factory reset. 8333 // Note: we also handle devices that are upgrading to N right now as if it is their 8334 // first boot, as they do not have profile data. 8335 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8336 8337 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8338 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8339 8340 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8341 return; 8342 } 8343 8344 List<PackageParser.Package> pkgs; 8345 synchronized (mPackages) { 8346 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8347 } 8348 8349 final long startTime = System.nanoTime(); 8350 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8351 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8352 8353 final int elapsedTimeSeconds = 8354 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8355 8356 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8357 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8358 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8359 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8360 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8361 } 8362 8363 /** 8364 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8365 * containing statistics about the invocation. The array consists of three elements, 8366 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8367 * and {@code numberOfPackagesFailed}. 8368 */ 8369 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8370 String compilerFilter) { 8371 8372 int numberOfPackagesVisited = 0; 8373 int numberOfPackagesOptimized = 0; 8374 int numberOfPackagesSkipped = 0; 8375 int numberOfPackagesFailed = 0; 8376 final int numberOfPackagesToDexopt = pkgs.size(); 8377 8378 for (PackageParser.Package pkg : pkgs) { 8379 numberOfPackagesVisited++; 8380 8381 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8382 if (DEBUG_DEXOPT) { 8383 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8384 } 8385 numberOfPackagesSkipped++; 8386 continue; 8387 } 8388 8389 if (DEBUG_DEXOPT) { 8390 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8391 numberOfPackagesToDexopt + ": " + pkg.packageName); 8392 } 8393 8394 if (showDialog) { 8395 try { 8396 ActivityManager.getService().showBootMessage( 8397 mContext.getResources().getString(R.string.android_upgrading_apk, 8398 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8399 } catch (RemoteException e) { 8400 } 8401 synchronized (mPackages) { 8402 mDexOptDialogShown = true; 8403 } 8404 } 8405 8406 // If the OTA updates a system app which was previously preopted to a non-preopted state 8407 // the app might end up being verified at runtime. That's because by default the apps 8408 // are verify-profile but for preopted apps there's no profile. 8409 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8410 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8411 // filter (by default interpret-only). 8412 // Note that at this stage unused apps are already filtered. 8413 if (isSystemApp(pkg) && 8414 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8415 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8416 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8417 } 8418 8419 // checkProfiles is false to avoid merging profiles during boot which 8420 // might interfere with background compilation (b/28612421). 8421 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8422 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8423 // trade-off worth doing to save boot time work. 8424 int dexOptStatus = performDexOptTraced(pkg.packageName, 8425 false /* checkProfiles */, 8426 compilerFilter, 8427 false /* force */); 8428 switch (dexOptStatus) { 8429 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8430 numberOfPackagesOptimized++; 8431 break; 8432 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8433 numberOfPackagesSkipped++; 8434 break; 8435 case PackageDexOptimizer.DEX_OPT_FAILED: 8436 numberOfPackagesFailed++; 8437 break; 8438 default: 8439 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8440 break; 8441 } 8442 } 8443 8444 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8445 numberOfPackagesFailed }; 8446 } 8447 8448 @Override 8449 public void notifyPackageUse(String packageName, int reason) { 8450 synchronized (mPackages) { 8451 PackageParser.Package p = mPackages.get(packageName); 8452 if (p == null) { 8453 return; 8454 } 8455 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8456 } 8457 } 8458 8459 @Override 8460 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8461 int userId = UserHandle.getCallingUserId(); 8462 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8463 if (ai == null) { 8464 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8465 + loadingPackageName + ", user=" + userId); 8466 return; 8467 } 8468 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8469 } 8470 8471 // TODO: this is not used nor needed. Delete it. 8472 @Override 8473 public boolean performDexOptIfNeeded(String packageName) { 8474 int dexOptStatus = performDexOptTraced(packageName, 8475 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8476 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8477 } 8478 8479 @Override 8480 public boolean performDexOpt(String packageName, 8481 boolean checkProfiles, int compileReason, boolean force) { 8482 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8483 getCompilerFilterForReason(compileReason), force); 8484 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8485 } 8486 8487 @Override 8488 public boolean performDexOptMode(String packageName, 8489 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8490 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8491 targetCompilerFilter, force); 8492 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8493 } 8494 8495 private int performDexOptTraced(String packageName, 8496 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8498 try { 8499 return performDexOptInternal(packageName, checkProfiles, 8500 targetCompilerFilter, force); 8501 } finally { 8502 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8503 } 8504 } 8505 8506 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8507 // if the package can now be considered up to date for the given filter. 8508 private int performDexOptInternal(String packageName, 8509 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8510 PackageParser.Package p; 8511 synchronized (mPackages) { 8512 p = mPackages.get(packageName); 8513 if (p == null) { 8514 // Package could not be found. Report failure. 8515 return PackageDexOptimizer.DEX_OPT_FAILED; 8516 } 8517 mPackageUsage.maybeWriteAsync(mPackages); 8518 mCompilerStats.maybeWriteAsync(); 8519 } 8520 long callingId = Binder.clearCallingIdentity(); 8521 try { 8522 synchronized (mInstallLock) { 8523 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8524 targetCompilerFilter, force); 8525 } 8526 } finally { 8527 Binder.restoreCallingIdentity(callingId); 8528 } 8529 } 8530 8531 public ArraySet<String> getOptimizablePackages() { 8532 ArraySet<String> pkgs = new ArraySet<String>(); 8533 synchronized (mPackages) { 8534 for (PackageParser.Package p : mPackages.values()) { 8535 if (PackageDexOptimizer.canOptimizePackage(p)) { 8536 pkgs.add(p.packageName); 8537 } 8538 } 8539 } 8540 return pkgs; 8541 } 8542 8543 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8544 boolean checkProfiles, String targetCompilerFilter, 8545 boolean force) { 8546 // Select the dex optimizer based on the force parameter. 8547 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8548 // allocate an object here. 8549 PackageDexOptimizer pdo = force 8550 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8551 : mPackageDexOptimizer; 8552 8553 // Dexopt all dependencies first. Note: we ignore the return value and march on 8554 // on errors. 8555 // Note that we are going to call performDexOpt on those libraries as many times as 8556 // they are referenced in packages. When we do a batch of performDexOpt (for example 8557 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8558 // and the first package that uses the library will dexopt it. The 8559 // others will see that the compiled code for the library is up to date. 8560 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8561 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8562 if (!deps.isEmpty()) { 8563 for (PackageParser.Package depPackage : deps) { 8564 // TODO: Analyze and investigate if we (should) profile libraries. 8565 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8566 false /* checkProfiles */, 8567 targetCompilerFilter, 8568 getOrCreateCompilerPackageStats(depPackage), 8569 true /* isUsedByOtherApps */); 8570 } 8571 } 8572 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8573 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8574 mDexManager.isUsedByOtherApps(p.packageName)); 8575 } 8576 8577 // Performs dexopt on the used secondary dex files belonging to the given package. 8578 // Returns true if all dex files were process successfully (which could mean either dexopt or 8579 // skip). Returns false if any of the files caused errors. 8580 @Override 8581 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8582 boolean force) { 8583 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8584 } 8585 8586 public boolean performDexOptSecondary(String packageName, int compileReason, 8587 boolean force) { 8588 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8589 } 8590 8591 /** 8592 * Reconcile the information we have about the secondary dex files belonging to 8593 * {@code packagName} and the actual dex files. For all dex files that were 8594 * deleted, update the internal records and delete the generated oat files. 8595 */ 8596 @Override 8597 public void reconcileSecondaryDexFiles(String packageName) { 8598 mDexManager.reconcileSecondaryDexFiles(packageName); 8599 } 8600 8601 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8602 // a reference there. 8603 /*package*/ DexManager getDexManager() { 8604 return mDexManager; 8605 } 8606 8607 /** 8608 * Execute the background dexopt job immediately. 8609 */ 8610 @Override 8611 public boolean runBackgroundDexoptJob() { 8612 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8613 } 8614 8615 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8616 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8617 || p.usesStaticLibraries != null) { 8618 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8619 Set<String> collectedNames = new HashSet<>(); 8620 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8621 8622 retValue.remove(p); 8623 8624 return retValue; 8625 } else { 8626 return Collections.emptyList(); 8627 } 8628 } 8629 8630 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8631 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8632 if (!collectedNames.contains(p.packageName)) { 8633 collectedNames.add(p.packageName); 8634 collected.add(p); 8635 8636 if (p.usesLibraries != null) { 8637 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8638 null, collected, collectedNames); 8639 } 8640 if (p.usesOptionalLibraries != null) { 8641 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8642 null, collected, collectedNames); 8643 } 8644 if (p.usesStaticLibraries != null) { 8645 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8646 p.usesStaticLibrariesVersions, collected, collectedNames); 8647 } 8648 } 8649 } 8650 8651 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8652 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8653 final int libNameCount = libs.size(); 8654 for (int i = 0; i < libNameCount; i++) { 8655 String libName = libs.get(i); 8656 int version = (versions != null && versions.length == libNameCount) 8657 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8658 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8659 if (libPkg != null) { 8660 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8661 } 8662 } 8663 } 8664 8665 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8666 synchronized (mPackages) { 8667 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8668 if (libEntry != null) { 8669 return mPackages.get(libEntry.apk); 8670 } 8671 return null; 8672 } 8673 } 8674 8675 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8676 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8677 if (versionedLib == null) { 8678 return null; 8679 } 8680 return versionedLib.get(version); 8681 } 8682 8683 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8684 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8685 pkg.staticSharedLibName); 8686 if (versionedLib == null) { 8687 return null; 8688 } 8689 int previousLibVersion = -1; 8690 final int versionCount = versionedLib.size(); 8691 for (int i = 0; i < versionCount; i++) { 8692 final int libVersion = versionedLib.keyAt(i); 8693 if (libVersion < pkg.staticSharedLibVersion) { 8694 previousLibVersion = Math.max(previousLibVersion, libVersion); 8695 } 8696 } 8697 if (previousLibVersion >= 0) { 8698 return versionedLib.get(previousLibVersion); 8699 } 8700 return null; 8701 } 8702 8703 public void shutdown() { 8704 mPackageUsage.writeNow(mPackages); 8705 mCompilerStats.writeNow(); 8706 } 8707 8708 @Override 8709 public void dumpProfiles(String packageName) { 8710 PackageParser.Package pkg; 8711 synchronized (mPackages) { 8712 pkg = mPackages.get(packageName); 8713 if (pkg == null) { 8714 throw new IllegalArgumentException("Unknown package: " + packageName); 8715 } 8716 } 8717 /* Only the shell, root, or the app user should be able to dump profiles. */ 8718 int callingUid = Binder.getCallingUid(); 8719 if (callingUid != Process.SHELL_UID && 8720 callingUid != Process.ROOT_UID && 8721 callingUid != pkg.applicationInfo.uid) { 8722 throw new SecurityException("dumpProfiles"); 8723 } 8724 8725 synchronized (mInstallLock) { 8726 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8727 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8728 try { 8729 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8730 String codePaths = TextUtils.join(";", allCodePaths); 8731 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8732 } catch (InstallerException e) { 8733 Slog.w(TAG, "Failed to dump profiles", e); 8734 } 8735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8736 } 8737 } 8738 8739 @Override 8740 public void forceDexOpt(String packageName) { 8741 enforceSystemOrRoot("forceDexOpt"); 8742 8743 PackageParser.Package pkg; 8744 synchronized (mPackages) { 8745 pkg = mPackages.get(packageName); 8746 if (pkg == null) { 8747 throw new IllegalArgumentException("Unknown package: " + packageName); 8748 } 8749 } 8750 8751 synchronized (mInstallLock) { 8752 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8753 8754 // Whoever is calling forceDexOpt wants a fully compiled package. 8755 // Don't use profiles since that may cause compilation to be skipped. 8756 final int res = performDexOptInternalWithDependenciesLI(pkg, 8757 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8758 true /* force */); 8759 8760 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8761 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8762 throw new IllegalStateException("Failed to dexopt: " + res); 8763 } 8764 } 8765 } 8766 8767 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8768 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8769 Slog.w(TAG, "Unable to update from " + oldPkg.name 8770 + " to " + newPkg.packageName 8771 + ": old package not in system partition"); 8772 return false; 8773 } else if (mPackages.get(oldPkg.name) != null) { 8774 Slog.w(TAG, "Unable to update from " + oldPkg.name 8775 + " to " + newPkg.packageName 8776 + ": old package still exists"); 8777 return false; 8778 } 8779 return true; 8780 } 8781 8782 void removeCodePathLI(File codePath) { 8783 if (codePath.isDirectory()) { 8784 try { 8785 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8786 } catch (InstallerException e) { 8787 Slog.w(TAG, "Failed to remove code path", e); 8788 } 8789 } else { 8790 codePath.delete(); 8791 } 8792 } 8793 8794 private int[] resolveUserIds(int userId) { 8795 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8796 } 8797 8798 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8799 if (pkg == null) { 8800 Slog.wtf(TAG, "Package was null!", new Throwable()); 8801 return; 8802 } 8803 clearAppDataLeafLIF(pkg, userId, flags); 8804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8805 for (int i = 0; i < childCount; i++) { 8806 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8807 } 8808 } 8809 8810 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8811 final PackageSetting ps; 8812 synchronized (mPackages) { 8813 ps = mSettings.mPackages.get(pkg.packageName); 8814 } 8815 for (int realUserId : resolveUserIds(userId)) { 8816 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8817 try { 8818 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8819 ceDataInode); 8820 } catch (InstallerException e) { 8821 Slog.w(TAG, String.valueOf(e)); 8822 } 8823 } 8824 } 8825 8826 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8827 if (pkg == null) { 8828 Slog.wtf(TAG, "Package was null!", new Throwable()); 8829 return; 8830 } 8831 destroyAppDataLeafLIF(pkg, userId, flags); 8832 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8833 for (int i = 0; i < childCount; i++) { 8834 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8835 } 8836 } 8837 8838 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8839 final PackageSetting ps; 8840 synchronized (mPackages) { 8841 ps = mSettings.mPackages.get(pkg.packageName); 8842 } 8843 for (int realUserId : resolveUserIds(userId)) { 8844 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8845 try { 8846 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8847 ceDataInode); 8848 } catch (InstallerException e) { 8849 Slog.w(TAG, String.valueOf(e)); 8850 } 8851 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8852 } 8853 } 8854 8855 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8856 if (pkg == null) { 8857 Slog.wtf(TAG, "Package was null!", new Throwable()); 8858 return; 8859 } 8860 destroyAppProfilesLeafLIF(pkg); 8861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8862 for (int i = 0; i < childCount; i++) { 8863 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8864 } 8865 } 8866 8867 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8868 try { 8869 mInstaller.destroyAppProfiles(pkg.packageName); 8870 } catch (InstallerException e) { 8871 Slog.w(TAG, String.valueOf(e)); 8872 } 8873 } 8874 8875 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8876 if (pkg == null) { 8877 Slog.wtf(TAG, "Package was null!", new Throwable()); 8878 return; 8879 } 8880 clearAppProfilesLeafLIF(pkg); 8881 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8882 for (int i = 0; i < childCount; i++) { 8883 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8884 } 8885 } 8886 8887 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8888 try { 8889 mInstaller.clearAppProfiles(pkg.packageName); 8890 } catch (InstallerException e) { 8891 Slog.w(TAG, String.valueOf(e)); 8892 } 8893 } 8894 8895 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8896 long lastUpdateTime) { 8897 // Set parent install/update time 8898 PackageSetting ps = (PackageSetting) pkg.mExtras; 8899 if (ps != null) { 8900 ps.firstInstallTime = firstInstallTime; 8901 ps.lastUpdateTime = lastUpdateTime; 8902 } 8903 // Set children install/update time 8904 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8905 for (int i = 0; i < childCount; i++) { 8906 PackageParser.Package childPkg = pkg.childPackages.get(i); 8907 ps = (PackageSetting) childPkg.mExtras; 8908 if (ps != null) { 8909 ps.firstInstallTime = firstInstallTime; 8910 ps.lastUpdateTime = lastUpdateTime; 8911 } 8912 } 8913 } 8914 8915 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8916 PackageParser.Package changingLib) { 8917 if (file.path != null) { 8918 usesLibraryFiles.add(file.path); 8919 return; 8920 } 8921 PackageParser.Package p = mPackages.get(file.apk); 8922 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8923 // If we are doing this while in the middle of updating a library apk, 8924 // then we need to make sure to use that new apk for determining the 8925 // dependencies here. (We haven't yet finished committing the new apk 8926 // to the package manager state.) 8927 if (p == null || p.packageName.equals(changingLib.packageName)) { 8928 p = changingLib; 8929 } 8930 } 8931 if (p != null) { 8932 usesLibraryFiles.addAll(p.getAllCodePaths()); 8933 } 8934 } 8935 8936 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8937 PackageParser.Package changingLib) throws PackageManagerException { 8938 if (pkg == null) { 8939 return; 8940 } 8941 ArraySet<String> usesLibraryFiles = null; 8942 if (pkg.usesLibraries != null) { 8943 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8944 null, null, pkg.packageName, changingLib, true, null); 8945 } 8946 if (pkg.usesStaticLibraries != null) { 8947 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8948 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8949 pkg.packageName, changingLib, true, usesLibraryFiles); 8950 } 8951 if (pkg.usesOptionalLibraries != null) { 8952 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8953 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8954 } 8955 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8956 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8957 } else { 8958 pkg.usesLibraryFiles = null; 8959 } 8960 } 8961 8962 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8963 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8964 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8965 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8966 throws PackageManagerException { 8967 final int libCount = requestedLibraries.size(); 8968 for (int i = 0; i < libCount; i++) { 8969 final String libName = requestedLibraries.get(i); 8970 final int libVersion = requiredVersions != null ? requiredVersions[i] 8971 : SharedLibraryInfo.VERSION_UNDEFINED; 8972 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8973 if (libEntry == null) { 8974 if (required) { 8975 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8976 "Package " + packageName + " requires unavailable shared library " 8977 + libName + "; failing!"); 8978 } else { 8979 Slog.w(TAG, "Package " + packageName 8980 + " desires unavailable shared library " 8981 + libName + "; ignoring!"); 8982 } 8983 } else { 8984 if (requiredVersions != null && requiredCertDigests != null) { 8985 if (libEntry.info.getVersion() != requiredVersions[i]) { 8986 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8987 "Package " + packageName + " requires unavailable static shared" 8988 + " library " + libName + " version " 8989 + libEntry.info.getVersion() + "; failing!"); 8990 } 8991 8992 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8993 if (libPkg == null) { 8994 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8995 "Package " + packageName + " requires unavailable static shared" 8996 + " library; failing!"); 8997 } 8998 8999 String expectedCertDigest = requiredCertDigests[i]; 9000 String libCertDigest = PackageUtils.computeCertSha256Digest( 9001 libPkg.mSignatures[0]); 9002 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9003 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9004 "Package " + packageName + " requires differently signed" + 9005 " static shared library; failing!"); 9006 } 9007 } 9008 9009 if (outUsedLibraries == null) { 9010 outUsedLibraries = new ArraySet<>(); 9011 } 9012 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9013 } 9014 } 9015 return outUsedLibraries; 9016 } 9017 9018 private static boolean hasString(List<String> list, List<String> which) { 9019 if (list == null) { 9020 return false; 9021 } 9022 for (int i=list.size()-1; i>=0; i--) { 9023 for (int j=which.size()-1; j>=0; j--) { 9024 if (which.get(j).equals(list.get(i))) { 9025 return true; 9026 } 9027 } 9028 } 9029 return false; 9030 } 9031 9032 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9033 PackageParser.Package changingPkg) { 9034 ArrayList<PackageParser.Package> res = null; 9035 for (PackageParser.Package pkg : mPackages.values()) { 9036 if (changingPkg != null 9037 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9038 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9039 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9040 changingPkg.staticSharedLibName)) { 9041 return null; 9042 } 9043 if (res == null) { 9044 res = new ArrayList<>(); 9045 } 9046 res.add(pkg); 9047 try { 9048 updateSharedLibrariesLPr(pkg, changingPkg); 9049 } catch (PackageManagerException e) { 9050 // If a system app update or an app and a required lib missing we 9051 // delete the package and for updated system apps keep the data as 9052 // it is better for the user to reinstall than to be in an limbo 9053 // state. Also libs disappearing under an app should never happen 9054 // - just in case. 9055 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9056 final int flags = pkg.isUpdatedSystemApp() 9057 ? PackageManager.DELETE_KEEP_DATA : 0; 9058 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9059 flags , null, true, null); 9060 } 9061 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9062 } 9063 } 9064 return res; 9065 } 9066 9067 /** 9068 * Derive the value of the {@code cpuAbiOverride} based on the provided 9069 * value and an optional stored value from the package settings. 9070 */ 9071 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9072 String cpuAbiOverride = null; 9073 9074 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9075 cpuAbiOverride = null; 9076 } else if (abiOverride != null) { 9077 cpuAbiOverride = abiOverride; 9078 } else if (settings != null) { 9079 cpuAbiOverride = settings.cpuAbiOverrideString; 9080 } 9081 9082 return cpuAbiOverride; 9083 } 9084 9085 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9086 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9087 throws PackageManagerException { 9088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9089 // If the package has children and this is the first dive in the function 9090 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9091 // whether all packages (parent and children) would be successfully scanned 9092 // before the actual scan since scanning mutates internal state and we want 9093 // to atomically install the package and its children. 9094 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9095 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9096 scanFlags |= SCAN_CHECK_ONLY; 9097 } 9098 } else { 9099 scanFlags &= ~SCAN_CHECK_ONLY; 9100 } 9101 9102 final PackageParser.Package scannedPkg; 9103 try { 9104 // Scan the parent 9105 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9106 // Scan the children 9107 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9108 for (int i = 0; i < childCount; i++) { 9109 PackageParser.Package childPkg = pkg.childPackages.get(i); 9110 scanPackageLI(childPkg, policyFlags, 9111 scanFlags, currentTime, user); 9112 } 9113 } finally { 9114 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9115 } 9116 9117 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9118 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9119 } 9120 9121 return scannedPkg; 9122 } 9123 9124 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9125 int scanFlags, long currentTime, @Nullable UserHandle user) 9126 throws PackageManagerException { 9127 boolean success = false; 9128 try { 9129 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9130 currentTime, user); 9131 success = true; 9132 return res; 9133 } finally { 9134 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9135 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9136 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9137 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9138 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9139 } 9140 } 9141 } 9142 9143 /** 9144 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9145 */ 9146 private static boolean apkHasCode(String fileName) { 9147 StrictJarFile jarFile = null; 9148 try { 9149 jarFile = new StrictJarFile(fileName, 9150 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9151 return jarFile.findEntry("classes.dex") != null; 9152 } catch (IOException ignore) { 9153 } finally { 9154 try { 9155 if (jarFile != null) { 9156 jarFile.close(); 9157 } 9158 } catch (IOException ignore) {} 9159 } 9160 return false; 9161 } 9162 9163 /** 9164 * Enforces code policy for the package. This ensures that if an APK has 9165 * declared hasCode="true" in its manifest that the APK actually contains 9166 * code. 9167 * 9168 * @throws PackageManagerException If bytecode could not be found when it should exist 9169 */ 9170 private static void assertCodePolicy(PackageParser.Package pkg) 9171 throws PackageManagerException { 9172 final boolean shouldHaveCode = 9173 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9174 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9175 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9176 "Package " + pkg.baseCodePath + " code is missing"); 9177 } 9178 9179 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9180 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9181 final boolean splitShouldHaveCode = 9182 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9183 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9184 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9185 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9186 } 9187 } 9188 } 9189 } 9190 9191 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9192 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9193 throws PackageManagerException { 9194 if (DEBUG_PACKAGE_SCANNING) { 9195 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9196 Log.d(TAG, "Scanning package " + pkg.packageName); 9197 } 9198 9199 applyPolicy(pkg, policyFlags); 9200 9201 assertPackageIsValid(pkg, policyFlags, scanFlags); 9202 9203 // Initialize package source and resource directories 9204 final File scanFile = new File(pkg.codePath); 9205 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9206 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9207 9208 SharedUserSetting suid = null; 9209 PackageSetting pkgSetting = null; 9210 9211 // Getting the package setting may have a side-effect, so if we 9212 // are only checking if scan would succeed, stash a copy of the 9213 // old setting to restore at the end. 9214 PackageSetting nonMutatedPs = null; 9215 9216 // We keep references to the derived CPU Abis from settings in oder to reuse 9217 // them in the case where we're not upgrading or booting for the first time. 9218 String primaryCpuAbiFromSettings = null; 9219 String secondaryCpuAbiFromSettings = null; 9220 9221 // writer 9222 synchronized (mPackages) { 9223 if (pkg.mSharedUserId != null) { 9224 // SIDE EFFECTS; may potentially allocate a new shared user 9225 suid = mSettings.getSharedUserLPw( 9226 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9227 if (DEBUG_PACKAGE_SCANNING) { 9228 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9229 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9230 + "): packages=" + suid.packages); 9231 } 9232 } 9233 9234 // Check if we are renaming from an original package name. 9235 PackageSetting origPackage = null; 9236 String realName = null; 9237 if (pkg.mOriginalPackages != null) { 9238 // This package may need to be renamed to a previously 9239 // installed name. Let's check on that... 9240 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9241 if (pkg.mOriginalPackages.contains(renamed)) { 9242 // This package had originally been installed as the 9243 // original name, and we have already taken care of 9244 // transitioning to the new one. Just update the new 9245 // one to continue using the old name. 9246 realName = pkg.mRealPackage; 9247 if (!pkg.packageName.equals(renamed)) { 9248 // Callers into this function may have already taken 9249 // care of renaming the package; only do it here if 9250 // it is not already done. 9251 pkg.setPackageName(renamed); 9252 } 9253 } else { 9254 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9255 if ((origPackage = mSettings.getPackageLPr( 9256 pkg.mOriginalPackages.get(i))) != null) { 9257 // We do have the package already installed under its 9258 // original name... should we use it? 9259 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9260 // New package is not compatible with original. 9261 origPackage = null; 9262 continue; 9263 } else if (origPackage.sharedUser != null) { 9264 // Make sure uid is compatible between packages. 9265 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9266 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9267 + " to " + pkg.packageName + ": old uid " 9268 + origPackage.sharedUser.name 9269 + " differs from " + pkg.mSharedUserId); 9270 origPackage = null; 9271 continue; 9272 } 9273 // TODO: Add case when shared user id is added [b/28144775] 9274 } else { 9275 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9276 + pkg.packageName + " to old name " + origPackage.name); 9277 } 9278 break; 9279 } 9280 } 9281 } 9282 } 9283 9284 if (mTransferedPackages.contains(pkg.packageName)) { 9285 Slog.w(TAG, "Package " + pkg.packageName 9286 + " was transferred to another, but its .apk remains"); 9287 } 9288 9289 // See comments in nonMutatedPs declaration 9290 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9291 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9292 if (foundPs != null) { 9293 nonMutatedPs = new PackageSetting(foundPs); 9294 } 9295 } 9296 9297 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9298 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9299 if (foundPs != null) { 9300 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9301 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9302 } 9303 } 9304 9305 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9306 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9307 PackageManagerService.reportSettingsProblem(Log.WARN, 9308 "Package " + pkg.packageName + " shared user changed from " 9309 + (pkgSetting.sharedUser != null 9310 ? pkgSetting.sharedUser.name : "<nothing>") 9311 + " to " 9312 + (suid != null ? suid.name : "<nothing>") 9313 + "; replacing with new"); 9314 pkgSetting = null; 9315 } 9316 final PackageSetting oldPkgSetting = 9317 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9318 final PackageSetting disabledPkgSetting = 9319 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9320 9321 String[] usesStaticLibraries = null; 9322 if (pkg.usesStaticLibraries != null) { 9323 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9324 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9325 } 9326 9327 if (pkgSetting == null) { 9328 final String parentPackageName = (pkg.parentPackage != null) 9329 ? pkg.parentPackage.packageName : null; 9330 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9331 // REMOVE SharedUserSetting from method; update in a separate call 9332 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9333 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9334 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9335 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9336 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9337 true /*allowInstall*/, instantApp, parentPackageName, 9338 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9339 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9340 // SIDE EFFECTS; updates system state; move elsewhere 9341 if (origPackage != null) { 9342 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9343 } 9344 mSettings.addUserToSettingLPw(pkgSetting); 9345 } else { 9346 // REMOVE SharedUserSetting from method; update in a separate call. 9347 // 9348 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9349 // secondaryCpuAbi are not known at this point so we always update them 9350 // to null here, only to reset them at a later point. 9351 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9352 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9353 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9354 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9355 UserManagerService.getInstance(), usesStaticLibraries, 9356 pkg.usesStaticLibrariesVersions); 9357 } 9358 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9359 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9360 9361 // SIDE EFFECTS; modifies system state; move elsewhere 9362 if (pkgSetting.origPackage != null) { 9363 // If we are first transitioning from an original package, 9364 // fix up the new package's name now. We need to do this after 9365 // looking up the package under its new name, so getPackageLP 9366 // can take care of fiddling things correctly. 9367 pkg.setPackageName(origPackage.name); 9368 9369 // File a report about this. 9370 String msg = "New package " + pkgSetting.realName 9371 + " renamed to replace old package " + pkgSetting.name; 9372 reportSettingsProblem(Log.WARN, msg); 9373 9374 // Make a note of it. 9375 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9376 mTransferedPackages.add(origPackage.name); 9377 } 9378 9379 // No longer need to retain this. 9380 pkgSetting.origPackage = null; 9381 } 9382 9383 // SIDE EFFECTS; modifies system state; move elsewhere 9384 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9385 // Make a note of it. 9386 mTransferedPackages.add(pkg.packageName); 9387 } 9388 9389 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9390 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9391 } 9392 9393 if ((scanFlags & SCAN_BOOTING) == 0 9394 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9395 // Check all shared libraries and map to their actual file path. 9396 // We only do this here for apps not on a system dir, because those 9397 // are the only ones that can fail an install due to this. We 9398 // will take care of the system apps by updating all of their 9399 // library paths after the scan is done. Also during the initial 9400 // scan don't update any libs as we do this wholesale after all 9401 // apps are scanned to avoid dependency based scanning. 9402 updateSharedLibrariesLPr(pkg, null); 9403 } 9404 9405 if (mFoundPolicyFile) { 9406 SELinuxMMAC.assignSeInfoValue(pkg); 9407 } 9408 pkg.applicationInfo.uid = pkgSetting.appId; 9409 pkg.mExtras = pkgSetting; 9410 9411 9412 // Static shared libs have same package with different versions where 9413 // we internally use a synthetic package name to allow multiple versions 9414 // of the same package, therefore we need to compare signatures against 9415 // the package setting for the latest library version. 9416 PackageSetting signatureCheckPs = pkgSetting; 9417 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9418 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9419 if (libraryEntry != null) { 9420 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9421 } 9422 } 9423 9424 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9425 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9426 // We just determined the app is signed correctly, so bring 9427 // over the latest parsed certs. 9428 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9429 } else { 9430 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9431 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9432 "Package " + pkg.packageName + " upgrade keys do not match the " 9433 + "previously installed version"); 9434 } else { 9435 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9436 String msg = "System package " + pkg.packageName 9437 + " signature changed; retaining data."; 9438 reportSettingsProblem(Log.WARN, msg); 9439 } 9440 } 9441 } else { 9442 try { 9443 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9444 verifySignaturesLP(signatureCheckPs, pkg); 9445 // We just determined the app is signed correctly, so bring 9446 // over the latest parsed certs. 9447 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9448 } catch (PackageManagerException e) { 9449 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9450 throw e; 9451 } 9452 // The signature has changed, but this package is in the system 9453 // image... let's recover! 9454 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9455 // However... if this package is part of a shared user, but it 9456 // doesn't match the signature of the shared user, let's fail. 9457 // What this means is that you can't change the signatures 9458 // associated with an overall shared user, which doesn't seem all 9459 // that unreasonable. 9460 if (signatureCheckPs.sharedUser != null) { 9461 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9462 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9463 throw new PackageManagerException( 9464 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9465 "Signature mismatch for shared user: " 9466 + pkgSetting.sharedUser); 9467 } 9468 } 9469 // File a report about this. 9470 String msg = "System package " + pkg.packageName 9471 + " signature changed; retaining data."; 9472 reportSettingsProblem(Log.WARN, msg); 9473 } 9474 } 9475 9476 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9477 // This package wants to adopt ownership of permissions from 9478 // another package. 9479 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9480 final String origName = pkg.mAdoptPermissions.get(i); 9481 final PackageSetting orig = mSettings.getPackageLPr(origName); 9482 if (orig != null) { 9483 if (verifyPackageUpdateLPr(orig, pkg)) { 9484 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9485 + pkg.packageName); 9486 // SIDE EFFECTS; updates permissions system state; move elsewhere 9487 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9488 } 9489 } 9490 } 9491 } 9492 } 9493 9494 pkg.applicationInfo.processName = fixProcessName( 9495 pkg.applicationInfo.packageName, 9496 pkg.applicationInfo.processName); 9497 9498 if (pkg != mPlatformPackage) { 9499 // Get all of our default paths setup 9500 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9501 } 9502 9503 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9504 9505 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9506 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9508 derivePackageAbi( 9509 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9511 9512 // Some system apps still use directory structure for native libraries 9513 // in which case we might end up not detecting abi solely based on apk 9514 // structure. Try to detect abi based on directory structure. 9515 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9516 pkg.applicationInfo.primaryCpuAbi == null) { 9517 setBundledAppAbisAndRoots(pkg, pkgSetting); 9518 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9519 } 9520 } else { 9521 // This is not a first boot or an upgrade, don't bother deriving the 9522 // ABI during the scan. Instead, trust the value that was stored in the 9523 // package setting. 9524 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9525 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9526 9527 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9528 9529 if (DEBUG_ABI_SELECTION) { 9530 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9531 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9532 pkg.applicationInfo.secondaryCpuAbi); 9533 } 9534 } 9535 } else { 9536 if ((scanFlags & SCAN_MOVE) != 0) { 9537 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9538 // but we already have this packages package info in the PackageSetting. We just 9539 // use that and derive the native library path based on the new codepath. 9540 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9541 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9542 } 9543 9544 // Set native library paths again. For moves, the path will be updated based on the 9545 // ABIs we've determined above. For non-moves, the path will be updated based on the 9546 // ABIs we determined during compilation, but the path will depend on the final 9547 // package path (after the rename away from the stage path). 9548 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9549 } 9550 9551 // This is a special case for the "system" package, where the ABI is 9552 // dictated by the zygote configuration (and init.rc). We should keep track 9553 // of this ABI so that we can deal with "normal" applications that run under 9554 // the same UID correctly. 9555 if (mPlatformPackage == pkg) { 9556 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9557 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9558 } 9559 9560 // If there's a mismatch between the abi-override in the package setting 9561 // and the abiOverride specified for the install. Warn about this because we 9562 // would've already compiled the app without taking the package setting into 9563 // account. 9564 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9565 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9566 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9567 " for package " + pkg.packageName); 9568 } 9569 } 9570 9571 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9572 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9573 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9574 9575 // Copy the derived override back to the parsed package, so that we can 9576 // update the package settings accordingly. 9577 pkg.cpuAbiOverride = cpuAbiOverride; 9578 9579 if (DEBUG_ABI_SELECTION) { 9580 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9581 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9582 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9583 } 9584 9585 // Push the derived path down into PackageSettings so we know what to 9586 // clean up at uninstall time. 9587 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9588 9589 if (DEBUG_ABI_SELECTION) { 9590 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9591 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9592 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9593 } 9594 9595 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9596 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9597 // We don't do this here during boot because we can do it all 9598 // at once after scanning all existing packages. 9599 // 9600 // We also do this *before* we perform dexopt on this package, so that 9601 // we can avoid redundant dexopts, and also to make sure we've got the 9602 // code and package path correct. 9603 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9604 } 9605 9606 if (mFactoryTest && pkg.requestedPermissions.contains( 9607 android.Manifest.permission.FACTORY_TEST)) { 9608 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9609 } 9610 9611 if (isSystemApp(pkg)) { 9612 pkgSetting.isOrphaned = true; 9613 } 9614 9615 // Take care of first install / last update times. 9616 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9617 if (currentTime != 0) { 9618 if (pkgSetting.firstInstallTime == 0) { 9619 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9620 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9621 pkgSetting.lastUpdateTime = currentTime; 9622 } 9623 } else if (pkgSetting.firstInstallTime == 0) { 9624 // We need *something*. Take time time stamp of the file. 9625 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9626 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9627 if (scanFileTime != pkgSetting.timeStamp) { 9628 // A package on the system image has changed; consider this 9629 // to be an update. 9630 pkgSetting.lastUpdateTime = scanFileTime; 9631 } 9632 } 9633 pkgSetting.setTimeStamp(scanFileTime); 9634 9635 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9636 if (nonMutatedPs != null) { 9637 synchronized (mPackages) { 9638 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9639 } 9640 } 9641 } else { 9642 final int userId = user == null ? 0 : user.getIdentifier(); 9643 // Modify state for the given package setting 9644 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9645 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9646 if (pkgSetting.getInstantApp(userId)) { 9647 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9648 } 9649 } 9650 return pkg; 9651 } 9652 9653 /** 9654 * Applies policy to the parsed package based upon the given policy flags. 9655 * Ensures the package is in a good state. 9656 * <p> 9657 * Implementation detail: This method must NOT have any side effect. It would 9658 * ideally be static, but, it requires locks to read system state. 9659 */ 9660 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9661 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9662 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9663 if (pkg.applicationInfo.isDirectBootAware()) { 9664 // we're direct boot aware; set for all components 9665 for (PackageParser.Service s : pkg.services) { 9666 s.info.encryptionAware = s.info.directBootAware = true; 9667 } 9668 for (PackageParser.Provider p : pkg.providers) { 9669 p.info.encryptionAware = p.info.directBootAware = true; 9670 } 9671 for (PackageParser.Activity a : pkg.activities) { 9672 a.info.encryptionAware = a.info.directBootAware = true; 9673 } 9674 for (PackageParser.Activity r : pkg.receivers) { 9675 r.info.encryptionAware = r.info.directBootAware = true; 9676 } 9677 } 9678 } else { 9679 // Only allow system apps to be flagged as core apps. 9680 pkg.coreApp = false; 9681 // clear flags not applicable to regular apps 9682 pkg.applicationInfo.privateFlags &= 9683 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9684 pkg.applicationInfo.privateFlags &= 9685 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9686 } 9687 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9688 9689 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9690 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9691 } 9692 9693 if (!isSystemApp(pkg)) { 9694 // Only system apps can use these features. 9695 pkg.mOriginalPackages = null; 9696 pkg.mRealPackage = null; 9697 pkg.mAdoptPermissions = null; 9698 } 9699 } 9700 9701 /** 9702 * Asserts the parsed package is valid according to the given policy. If the 9703 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9704 * <p> 9705 * Implementation detail: This method must NOT have any side effects. It would 9706 * ideally be static, but, it requires locks to read system state. 9707 * 9708 * @throws PackageManagerException If the package fails any of the validation checks 9709 */ 9710 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9711 throws PackageManagerException { 9712 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9713 assertCodePolicy(pkg); 9714 } 9715 9716 if (pkg.applicationInfo.getCodePath() == null || 9717 pkg.applicationInfo.getResourcePath() == null) { 9718 // Bail out. The resource and code paths haven't been set. 9719 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9720 "Code and resource paths haven't been set correctly"); 9721 } 9722 9723 // Make sure we're not adding any bogus keyset info 9724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9725 ksms.assertScannedPackageValid(pkg); 9726 9727 synchronized (mPackages) { 9728 // The special "android" package can only be defined once 9729 if (pkg.packageName.equals("android")) { 9730 if (mAndroidApplication != null) { 9731 Slog.w(TAG, "*************************************************"); 9732 Slog.w(TAG, "Core android package being redefined. Skipping."); 9733 Slog.w(TAG, " codePath=" + pkg.codePath); 9734 Slog.w(TAG, "*************************************************"); 9735 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9736 "Core android package being redefined. Skipping."); 9737 } 9738 } 9739 9740 // A package name must be unique; don't allow duplicates 9741 if (mPackages.containsKey(pkg.packageName)) { 9742 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9743 "Application package " + pkg.packageName 9744 + " already installed. Skipping duplicate."); 9745 } 9746 9747 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9748 // Static libs have a synthetic package name containing the version 9749 // but we still want the base name to be unique. 9750 if (mPackages.containsKey(pkg.manifestPackageName)) { 9751 throw new PackageManagerException( 9752 "Duplicate static shared lib provider package"); 9753 } 9754 9755 // Static shared libraries should have at least O target SDK 9756 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9757 throw new PackageManagerException( 9758 "Packages declaring static-shared libs must target O SDK or higher"); 9759 } 9760 9761 // Package declaring static a shared lib cannot be instant apps 9762 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9763 throw new PackageManagerException( 9764 "Packages declaring static-shared libs cannot be instant apps"); 9765 } 9766 9767 // Package declaring static a shared lib cannot be renamed since the package 9768 // name is synthetic and apps can't code around package manager internals. 9769 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9770 throw new PackageManagerException( 9771 "Packages declaring static-shared libs cannot be renamed"); 9772 } 9773 9774 // Package declaring static a shared lib cannot declare child packages 9775 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9776 throw new PackageManagerException( 9777 "Packages declaring static-shared libs cannot have child packages"); 9778 } 9779 9780 // Package declaring static a shared lib cannot declare dynamic libs 9781 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9782 throw new PackageManagerException( 9783 "Packages declaring static-shared libs cannot declare dynamic libs"); 9784 } 9785 9786 // Package declaring static a shared lib cannot declare shared users 9787 if (pkg.mSharedUserId != null) { 9788 throw new PackageManagerException( 9789 "Packages declaring static-shared libs cannot declare shared users"); 9790 } 9791 9792 // Static shared libs cannot declare activities 9793 if (!pkg.activities.isEmpty()) { 9794 throw new PackageManagerException( 9795 "Static shared libs cannot declare activities"); 9796 } 9797 9798 // Static shared libs cannot declare services 9799 if (!pkg.services.isEmpty()) { 9800 throw new PackageManagerException( 9801 "Static shared libs cannot declare services"); 9802 } 9803 9804 // Static shared libs cannot declare providers 9805 if (!pkg.providers.isEmpty()) { 9806 throw new PackageManagerException( 9807 "Static shared libs cannot declare content providers"); 9808 } 9809 9810 // Static shared libs cannot declare receivers 9811 if (!pkg.receivers.isEmpty()) { 9812 throw new PackageManagerException( 9813 "Static shared libs cannot declare broadcast receivers"); 9814 } 9815 9816 // Static shared libs cannot declare permission groups 9817 if (!pkg.permissionGroups.isEmpty()) { 9818 throw new PackageManagerException( 9819 "Static shared libs cannot declare permission groups"); 9820 } 9821 9822 // Static shared libs cannot declare permissions 9823 if (!pkg.permissions.isEmpty()) { 9824 throw new PackageManagerException( 9825 "Static shared libs cannot declare permissions"); 9826 } 9827 9828 // Static shared libs cannot declare protected broadcasts 9829 if (pkg.protectedBroadcasts != null) { 9830 throw new PackageManagerException( 9831 "Static shared libs cannot declare protected broadcasts"); 9832 } 9833 9834 // Static shared libs cannot be overlay targets 9835 if (pkg.mOverlayTarget != null) { 9836 throw new PackageManagerException( 9837 "Static shared libs cannot be overlay targets"); 9838 } 9839 9840 // The version codes must be ordered as lib versions 9841 int minVersionCode = Integer.MIN_VALUE; 9842 int maxVersionCode = Integer.MAX_VALUE; 9843 9844 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9845 pkg.staticSharedLibName); 9846 if (versionedLib != null) { 9847 final int versionCount = versionedLib.size(); 9848 for (int i = 0; i < versionCount; i++) { 9849 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9850 // TODO: We will change version code to long, so in the new API it is long 9851 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9852 .getVersionCode(); 9853 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9854 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9855 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9856 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9857 } else { 9858 minVersionCode = maxVersionCode = libVersionCode; 9859 break; 9860 } 9861 } 9862 } 9863 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9864 throw new PackageManagerException("Static shared" 9865 + " lib version codes must be ordered as lib versions"); 9866 } 9867 } 9868 9869 // Only privileged apps and updated privileged apps can add child packages. 9870 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9871 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9872 throw new PackageManagerException("Only privileged apps can add child " 9873 + "packages. Ignoring package " + pkg.packageName); 9874 } 9875 final int childCount = pkg.childPackages.size(); 9876 for (int i = 0; i < childCount; i++) { 9877 PackageParser.Package childPkg = pkg.childPackages.get(i); 9878 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9879 childPkg.packageName)) { 9880 throw new PackageManagerException("Can't override child of " 9881 + "another disabled app. Ignoring package " + pkg.packageName); 9882 } 9883 } 9884 } 9885 9886 // If we're only installing presumed-existing packages, require that the 9887 // scanned APK is both already known and at the path previously established 9888 // for it. Previously unknown packages we pick up normally, but if we have an 9889 // a priori expectation about this package's install presence, enforce it. 9890 // With a singular exception for new system packages. When an OTA contains 9891 // a new system package, we allow the codepath to change from a system location 9892 // to the user-installed location. If we don't allow this change, any newer, 9893 // user-installed version of the application will be ignored. 9894 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9895 if (mExpectingBetter.containsKey(pkg.packageName)) { 9896 logCriticalInfo(Log.WARN, 9897 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9898 } else { 9899 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9900 if (known != null) { 9901 if (DEBUG_PACKAGE_SCANNING) { 9902 Log.d(TAG, "Examining " + pkg.codePath 9903 + " and requiring known paths " + known.codePathString 9904 + " & " + known.resourcePathString); 9905 } 9906 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9907 || !pkg.applicationInfo.getResourcePath().equals( 9908 known.resourcePathString)) { 9909 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9910 "Application package " + pkg.packageName 9911 + " found at " + pkg.applicationInfo.getCodePath() 9912 + " but expected at " + known.codePathString 9913 + "; ignoring."); 9914 } 9915 } 9916 } 9917 } 9918 9919 // Verify that this new package doesn't have any content providers 9920 // that conflict with existing packages. Only do this if the 9921 // package isn't already installed, since we don't want to break 9922 // things that are installed. 9923 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9924 final int N = pkg.providers.size(); 9925 int i; 9926 for (i=0; i<N; i++) { 9927 PackageParser.Provider p = pkg.providers.get(i); 9928 if (p.info.authority != null) { 9929 String names[] = p.info.authority.split(";"); 9930 for (int j = 0; j < names.length; j++) { 9931 if (mProvidersByAuthority.containsKey(names[j])) { 9932 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9933 final String otherPackageName = 9934 ((other != null && other.getComponentName() != null) ? 9935 other.getComponentName().getPackageName() : "?"); 9936 throw new PackageManagerException( 9937 INSTALL_FAILED_CONFLICTING_PROVIDER, 9938 "Can't install because provider name " + names[j] 9939 + " (in package " + pkg.applicationInfo.packageName 9940 + ") is already used by " + otherPackageName); 9941 } 9942 } 9943 } 9944 } 9945 } 9946 } 9947 } 9948 9949 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9950 int type, String declaringPackageName, int declaringVersionCode) { 9951 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9952 if (versionedLib == null) { 9953 versionedLib = new SparseArray<>(); 9954 mSharedLibraries.put(name, versionedLib); 9955 if (type == SharedLibraryInfo.TYPE_STATIC) { 9956 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9957 } 9958 } else if (versionedLib.indexOfKey(version) >= 0) { 9959 return false; 9960 } 9961 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9962 version, type, declaringPackageName, declaringVersionCode); 9963 versionedLib.put(version, libEntry); 9964 return true; 9965 } 9966 9967 private boolean removeSharedLibraryLPw(String name, int version) { 9968 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9969 if (versionedLib == null) { 9970 return false; 9971 } 9972 final int libIdx = versionedLib.indexOfKey(version); 9973 if (libIdx < 0) { 9974 return false; 9975 } 9976 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9977 versionedLib.remove(version); 9978 if (versionedLib.size() <= 0) { 9979 mSharedLibraries.remove(name); 9980 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9981 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9982 .getPackageName()); 9983 } 9984 } 9985 return true; 9986 } 9987 9988 /** 9989 * Adds a scanned package to the system. When this method is finished, the package will 9990 * be available for query, resolution, etc... 9991 */ 9992 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9993 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9994 final String pkgName = pkg.packageName; 9995 if (mCustomResolverComponentName != null && 9996 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9997 setUpCustomResolverActivity(pkg); 9998 } 9999 10000 if (pkg.packageName.equals("android")) { 10001 synchronized (mPackages) { 10002 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10003 // Set up information for our fall-back user intent resolution activity. 10004 mPlatformPackage = pkg; 10005 pkg.mVersionCode = mSdkVersion; 10006 mAndroidApplication = pkg.applicationInfo; 10007 if (!mResolverReplaced) { 10008 mResolveActivity.applicationInfo = mAndroidApplication; 10009 mResolveActivity.name = ResolverActivity.class.getName(); 10010 mResolveActivity.packageName = mAndroidApplication.packageName; 10011 mResolveActivity.processName = "system:ui"; 10012 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10013 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10014 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10015 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10016 mResolveActivity.exported = true; 10017 mResolveActivity.enabled = true; 10018 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10019 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10020 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10021 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10022 | ActivityInfo.CONFIG_ORIENTATION 10023 | ActivityInfo.CONFIG_KEYBOARD 10024 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10025 mResolveInfo.activityInfo = mResolveActivity; 10026 mResolveInfo.priority = 0; 10027 mResolveInfo.preferredOrder = 0; 10028 mResolveInfo.match = 0; 10029 mResolveComponentName = new ComponentName( 10030 mAndroidApplication.packageName, mResolveActivity.name); 10031 } 10032 } 10033 } 10034 } 10035 10036 ArrayList<PackageParser.Package> clientLibPkgs = null; 10037 // writer 10038 synchronized (mPackages) { 10039 boolean hasStaticSharedLibs = false; 10040 10041 // Any app can add new static shared libraries 10042 if (pkg.staticSharedLibName != null) { 10043 // Static shared libs don't allow renaming as they have synthetic package 10044 // names to allow install of multiple versions, so use name from manifest. 10045 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10046 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10047 pkg.manifestPackageName, pkg.mVersionCode)) { 10048 hasStaticSharedLibs = true; 10049 } else { 10050 Slog.w(TAG, "Package " + pkg.packageName + " library " 10051 + pkg.staticSharedLibName + " already exists; skipping"); 10052 } 10053 // Static shared libs cannot be updated once installed since they 10054 // use synthetic package name which includes the version code, so 10055 // not need to update other packages's shared lib dependencies. 10056 } 10057 10058 if (!hasStaticSharedLibs 10059 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10060 // Only system apps can add new dynamic shared libraries. 10061 if (pkg.libraryNames != null) { 10062 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10063 String name = pkg.libraryNames.get(i); 10064 boolean allowed = false; 10065 if (pkg.isUpdatedSystemApp()) { 10066 // New library entries can only be added through the 10067 // system image. This is important to get rid of a lot 10068 // of nasty edge cases: for example if we allowed a non- 10069 // system update of the app to add a library, then uninstalling 10070 // the update would make the library go away, and assumptions 10071 // we made such as through app install filtering would now 10072 // have allowed apps on the device which aren't compatible 10073 // with it. Better to just have the restriction here, be 10074 // conservative, and create many fewer cases that can negatively 10075 // impact the user experience. 10076 final PackageSetting sysPs = mSettings 10077 .getDisabledSystemPkgLPr(pkg.packageName); 10078 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10079 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10080 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10081 allowed = true; 10082 break; 10083 } 10084 } 10085 } 10086 } else { 10087 allowed = true; 10088 } 10089 if (allowed) { 10090 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10091 SharedLibraryInfo.VERSION_UNDEFINED, 10092 SharedLibraryInfo.TYPE_DYNAMIC, 10093 pkg.packageName, pkg.mVersionCode)) { 10094 Slog.w(TAG, "Package " + pkg.packageName + " library " 10095 + name + " already exists; skipping"); 10096 } 10097 } else { 10098 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10099 + name + " that is not declared on system image; skipping"); 10100 } 10101 } 10102 10103 if ((scanFlags & SCAN_BOOTING) == 0) { 10104 // If we are not booting, we need to update any applications 10105 // that are clients of our shared library. If we are booting, 10106 // this will all be done once the scan is complete. 10107 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10108 } 10109 } 10110 } 10111 } 10112 10113 if ((scanFlags & SCAN_BOOTING) != 0) { 10114 // No apps can run during boot scan, so they don't need to be frozen 10115 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10116 // Caller asked to not kill app, so it's probably not frozen 10117 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10118 // Caller asked us to ignore frozen check for some reason; they 10119 // probably didn't know the package name 10120 } else { 10121 // We're doing major surgery on this package, so it better be frozen 10122 // right now to keep it from launching 10123 checkPackageFrozen(pkgName); 10124 } 10125 10126 // Also need to kill any apps that are dependent on the library. 10127 if (clientLibPkgs != null) { 10128 for (int i=0; i<clientLibPkgs.size(); i++) { 10129 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10130 killApplication(clientPkg.applicationInfo.packageName, 10131 clientPkg.applicationInfo.uid, "update lib"); 10132 } 10133 } 10134 10135 // writer 10136 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10137 10138 synchronized (mPackages) { 10139 // We don't expect installation to fail beyond this point 10140 10141 // Add the new setting to mSettings 10142 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10143 // Add the new setting to mPackages 10144 mPackages.put(pkg.applicationInfo.packageName, pkg); 10145 // Make sure we don't accidentally delete its data. 10146 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10147 while (iter.hasNext()) { 10148 PackageCleanItem item = iter.next(); 10149 if (pkgName.equals(item.packageName)) { 10150 iter.remove(); 10151 } 10152 } 10153 10154 // Add the package's KeySets to the global KeySetManagerService 10155 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10156 ksms.addScannedPackageLPw(pkg); 10157 10158 int N = pkg.providers.size(); 10159 StringBuilder r = null; 10160 int i; 10161 for (i=0; i<N; i++) { 10162 PackageParser.Provider p = pkg.providers.get(i); 10163 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10164 p.info.processName); 10165 mProviders.addProvider(p); 10166 p.syncable = p.info.isSyncable; 10167 if (p.info.authority != null) { 10168 String names[] = p.info.authority.split(";"); 10169 p.info.authority = null; 10170 for (int j = 0; j < names.length; j++) { 10171 if (j == 1 && p.syncable) { 10172 // We only want the first authority for a provider to possibly be 10173 // syncable, so if we already added this provider using a different 10174 // authority clear the syncable flag. We copy the provider before 10175 // changing it because the mProviders object contains a reference 10176 // to a provider that we don't want to change. 10177 // Only do this for the second authority since the resulting provider 10178 // object can be the same for all future authorities for this provider. 10179 p = new PackageParser.Provider(p); 10180 p.syncable = false; 10181 } 10182 if (!mProvidersByAuthority.containsKey(names[j])) { 10183 mProvidersByAuthority.put(names[j], p); 10184 if (p.info.authority == null) { 10185 p.info.authority = names[j]; 10186 } else { 10187 p.info.authority = p.info.authority + ";" + names[j]; 10188 } 10189 if (DEBUG_PACKAGE_SCANNING) { 10190 if (chatty) 10191 Log.d(TAG, "Registered content provider: " + names[j] 10192 + ", className = " + p.info.name + ", isSyncable = " 10193 + p.info.isSyncable); 10194 } 10195 } else { 10196 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10197 Slog.w(TAG, "Skipping provider name " + names[j] + 10198 " (in package " + pkg.applicationInfo.packageName + 10199 "): name already used by " 10200 + ((other != null && other.getComponentName() != null) 10201 ? other.getComponentName().getPackageName() : "?")); 10202 } 10203 } 10204 } 10205 if (chatty) { 10206 if (r == null) { 10207 r = new StringBuilder(256); 10208 } else { 10209 r.append(' '); 10210 } 10211 r.append(p.info.name); 10212 } 10213 } 10214 if (r != null) { 10215 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10216 } 10217 10218 N = pkg.services.size(); 10219 r = null; 10220 for (i=0; i<N; i++) { 10221 PackageParser.Service s = pkg.services.get(i); 10222 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10223 s.info.processName); 10224 mServices.addService(s); 10225 if (chatty) { 10226 if (r == null) { 10227 r = new StringBuilder(256); 10228 } else { 10229 r.append(' '); 10230 } 10231 r.append(s.info.name); 10232 } 10233 } 10234 if (r != null) { 10235 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10236 } 10237 10238 N = pkg.receivers.size(); 10239 r = null; 10240 for (i=0; i<N; i++) { 10241 PackageParser.Activity a = pkg.receivers.get(i); 10242 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10243 a.info.processName); 10244 mReceivers.addActivity(a, "receiver"); 10245 if (chatty) { 10246 if (r == null) { 10247 r = new StringBuilder(256); 10248 } else { 10249 r.append(' '); 10250 } 10251 r.append(a.info.name); 10252 } 10253 } 10254 if (r != null) { 10255 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10256 } 10257 10258 N = pkg.activities.size(); 10259 r = null; 10260 for (i=0; i<N; i++) { 10261 PackageParser.Activity a = pkg.activities.get(i); 10262 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10263 a.info.processName); 10264 mActivities.addActivity(a, "activity"); 10265 if (chatty) { 10266 if (r == null) { 10267 r = new StringBuilder(256); 10268 } else { 10269 r.append(' '); 10270 } 10271 r.append(a.info.name); 10272 } 10273 } 10274 if (r != null) { 10275 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10276 } 10277 10278 N = pkg.permissionGroups.size(); 10279 r = null; 10280 for (i=0; i<N; i++) { 10281 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10282 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10283 final String curPackageName = cur == null ? null : cur.info.packageName; 10284 // Dont allow ephemeral apps to define new permission groups. 10285 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10286 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10287 + pg.info.packageName 10288 + " ignored: instant apps cannot define new permission groups."); 10289 continue; 10290 } 10291 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10292 if (cur == null || isPackageUpdate) { 10293 mPermissionGroups.put(pg.info.name, pg); 10294 if (chatty) { 10295 if (r == null) { 10296 r = new StringBuilder(256); 10297 } else { 10298 r.append(' '); 10299 } 10300 if (isPackageUpdate) { 10301 r.append("UPD:"); 10302 } 10303 r.append(pg.info.name); 10304 } 10305 } else { 10306 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10307 + pg.info.packageName + " ignored: original from " 10308 + cur.info.packageName); 10309 if (chatty) { 10310 if (r == null) { 10311 r = new StringBuilder(256); 10312 } else { 10313 r.append(' '); 10314 } 10315 r.append("DUP:"); 10316 r.append(pg.info.name); 10317 } 10318 } 10319 } 10320 if (r != null) { 10321 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10322 } 10323 10324 N = pkg.permissions.size(); 10325 r = null; 10326 for (i=0; i<N; i++) { 10327 PackageParser.Permission p = pkg.permissions.get(i); 10328 10329 // Dont allow ephemeral apps to define new permissions. 10330 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10331 Slog.w(TAG, "Permission " + p.info.name + " from package " 10332 + p.info.packageName 10333 + " ignored: instant apps cannot define new permissions."); 10334 continue; 10335 } 10336 10337 // Assume by default that we did not install this permission into the system. 10338 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10339 10340 // Now that permission groups have a special meaning, we ignore permission 10341 // groups for legacy apps to prevent unexpected behavior. In particular, 10342 // permissions for one app being granted to someone just becase they happen 10343 // to be in a group defined by another app (before this had no implications). 10344 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10345 p.group = mPermissionGroups.get(p.info.group); 10346 // Warn for a permission in an unknown group. 10347 if (p.info.group != null && p.group == null) { 10348 Slog.w(TAG, "Permission " + p.info.name + " from package " 10349 + p.info.packageName + " in an unknown group " + p.info.group); 10350 } 10351 } 10352 10353 ArrayMap<String, BasePermission> permissionMap = 10354 p.tree ? mSettings.mPermissionTrees 10355 : mSettings.mPermissions; 10356 BasePermission bp = permissionMap.get(p.info.name); 10357 10358 // Allow system apps to redefine non-system permissions 10359 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10360 final boolean currentOwnerIsSystem = (bp.perm != null 10361 && isSystemApp(bp.perm.owner)); 10362 if (isSystemApp(p.owner)) { 10363 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10364 // It's a built-in permission and no owner, take ownership now 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 } else if (!currentOwnerIsSystem) { 10371 String msg = "New decl " + p.owner + " of permission " 10372 + p.info.name + " is system; overriding " + bp.sourcePackage; 10373 reportSettingsProblem(Log.WARN, msg); 10374 bp = null; 10375 } 10376 } 10377 } 10378 10379 if (bp == null) { 10380 bp = new BasePermission(p.info.name, p.info.packageName, 10381 BasePermission.TYPE_NORMAL); 10382 permissionMap.put(p.info.name, bp); 10383 } 10384 10385 if (bp.perm == null) { 10386 if (bp.sourcePackage == null 10387 || bp.sourcePackage.equals(p.info.packageName)) { 10388 BasePermission tree = findPermissionTreeLP(p.info.name); 10389 if (tree == null 10390 || tree.sourcePackage.equals(p.info.packageName)) { 10391 bp.packageSetting = pkgSetting; 10392 bp.perm = p; 10393 bp.uid = pkg.applicationInfo.uid; 10394 bp.sourcePackage = p.info.packageName; 10395 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10396 if (chatty) { 10397 if (r == null) { 10398 r = new StringBuilder(256); 10399 } else { 10400 r.append(' '); 10401 } 10402 r.append(p.info.name); 10403 } 10404 } else { 10405 Slog.w(TAG, "Permission " + p.info.name + " from package " 10406 + p.info.packageName + " ignored: base tree " 10407 + tree.name + " is from package " 10408 + tree.sourcePackage); 10409 } 10410 } else { 10411 Slog.w(TAG, "Permission " + p.info.name + " from package " 10412 + p.info.packageName + " ignored: original from " 10413 + bp.sourcePackage); 10414 } 10415 } else if (chatty) { 10416 if (r == null) { 10417 r = new StringBuilder(256); 10418 } else { 10419 r.append(' '); 10420 } 10421 r.append("DUP:"); 10422 r.append(p.info.name); 10423 } 10424 if (bp.perm == p) { 10425 bp.protectionLevel = p.info.protectionLevel; 10426 } 10427 } 10428 10429 if (r != null) { 10430 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10431 } 10432 10433 N = pkg.instrumentation.size(); 10434 r = null; 10435 for (i=0; i<N; i++) { 10436 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10437 a.info.packageName = pkg.applicationInfo.packageName; 10438 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10439 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10440 a.info.splitNames = pkg.splitNames; 10441 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10442 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10443 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10444 a.info.dataDir = pkg.applicationInfo.dataDir; 10445 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10446 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10447 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10448 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10449 mInstrumentation.put(a.getComponentName(), a); 10450 if (chatty) { 10451 if (r == null) { 10452 r = new StringBuilder(256); 10453 } else { 10454 r.append(' '); 10455 } 10456 r.append(a.info.name); 10457 } 10458 } 10459 if (r != null) { 10460 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10461 } 10462 10463 if (pkg.protectedBroadcasts != null) { 10464 N = pkg.protectedBroadcasts.size(); 10465 for (i=0; i<N; i++) { 10466 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10467 } 10468 } 10469 } 10470 10471 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10472 } 10473 10474 /** 10475 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10476 * is derived purely on the basis of the contents of {@code scanFile} and 10477 * {@code cpuAbiOverride}. 10478 * 10479 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10480 */ 10481 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10482 String cpuAbiOverride, boolean extractLibs, 10483 File appLib32InstallDir) 10484 throws PackageManagerException { 10485 // Give ourselves some initial paths; we'll come back for another 10486 // pass once we've determined ABI below. 10487 setNativeLibraryPaths(pkg, appLib32InstallDir); 10488 10489 // We would never need to extract libs for forward-locked and external packages, 10490 // since the container service will do it for us. We shouldn't attempt to 10491 // extract libs from system app when it was not updated. 10492 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10493 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10494 extractLibs = false; 10495 } 10496 10497 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10498 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10499 10500 NativeLibraryHelper.Handle handle = null; 10501 try { 10502 handle = NativeLibraryHelper.Handle.create(pkg); 10503 // TODO(multiArch): This can be null for apps that didn't go through the 10504 // usual installation process. We can calculate it again, like we 10505 // do during install time. 10506 // 10507 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10508 // unnecessary. 10509 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10510 10511 // Null out the abis so that they can be recalculated. 10512 pkg.applicationInfo.primaryCpuAbi = null; 10513 pkg.applicationInfo.secondaryCpuAbi = null; 10514 if (isMultiArch(pkg.applicationInfo)) { 10515 // Warn if we've set an abiOverride for multi-lib packages.. 10516 // By definition, we need to copy both 32 and 64 bit libraries for 10517 // such packages. 10518 if (pkg.cpuAbiOverride != null 10519 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10520 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10521 } 10522 10523 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10524 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10525 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10526 if (extractLibs) { 10527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10528 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10529 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10530 useIsaSpecificSubdirs); 10531 } else { 10532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10533 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10534 } 10535 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10536 } 10537 10538 maybeThrowExceptionForMultiArchCopy( 10539 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10540 10541 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10542 if (extractLibs) { 10543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10544 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10545 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10546 useIsaSpecificSubdirs); 10547 } else { 10548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10549 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10550 } 10551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10552 } 10553 10554 maybeThrowExceptionForMultiArchCopy( 10555 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10556 10557 if (abi64 >= 0) { 10558 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10559 } 10560 10561 if (abi32 >= 0) { 10562 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10563 if (abi64 >= 0) { 10564 if (pkg.use32bitAbi) { 10565 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10566 pkg.applicationInfo.primaryCpuAbi = abi; 10567 } else { 10568 pkg.applicationInfo.secondaryCpuAbi = abi; 10569 } 10570 } else { 10571 pkg.applicationInfo.primaryCpuAbi = abi; 10572 } 10573 } 10574 10575 } else { 10576 String[] abiList = (cpuAbiOverride != null) ? 10577 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10578 10579 // Enable gross and lame hacks for apps that are built with old 10580 // SDK tools. We must scan their APKs for renderscript bitcode and 10581 // not launch them if it's present. Don't bother checking on devices 10582 // that don't have 64 bit support. 10583 boolean needsRenderScriptOverride = false; 10584 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10585 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10586 abiList = Build.SUPPORTED_32_BIT_ABIS; 10587 needsRenderScriptOverride = true; 10588 } 10589 10590 final int copyRet; 10591 if (extractLibs) { 10592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10593 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10594 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10595 } else { 10596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10597 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10598 } 10599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10600 10601 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10602 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10603 "Error unpackaging native libs for app, errorCode=" + copyRet); 10604 } 10605 10606 if (copyRet >= 0) { 10607 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10608 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10609 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10610 } else if (needsRenderScriptOverride) { 10611 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10612 } 10613 } 10614 } catch (IOException ioe) { 10615 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10616 } finally { 10617 IoUtils.closeQuietly(handle); 10618 } 10619 10620 // Now that we've calculated the ABIs and determined if it's an internal app, 10621 // we will go ahead and populate the nativeLibraryPath. 10622 setNativeLibraryPaths(pkg, appLib32InstallDir); 10623 } 10624 10625 /** 10626 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10627 * i.e, so that all packages can be run inside a single process if required. 10628 * 10629 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10630 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10631 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10632 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10633 * updating a package that belongs to a shared user. 10634 * 10635 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10636 * adds unnecessary complexity. 10637 */ 10638 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10639 PackageParser.Package scannedPackage) { 10640 String requiredInstructionSet = null; 10641 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10642 requiredInstructionSet = VMRuntime.getInstructionSet( 10643 scannedPackage.applicationInfo.primaryCpuAbi); 10644 } 10645 10646 PackageSetting requirer = null; 10647 for (PackageSetting ps : packagesForUser) { 10648 // If packagesForUser contains scannedPackage, we skip it. This will happen 10649 // when scannedPackage is an update of an existing package. Without this check, 10650 // we will never be able to change the ABI of any package belonging to a shared 10651 // user, even if it's compatible with other packages. 10652 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10653 if (ps.primaryCpuAbiString == null) { 10654 continue; 10655 } 10656 10657 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10658 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10659 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10660 // this but there's not much we can do. 10661 String errorMessage = "Instruction set mismatch, " 10662 + ((requirer == null) ? "[caller]" : requirer) 10663 + " requires " + requiredInstructionSet + " whereas " + ps 10664 + " requires " + instructionSet; 10665 Slog.w(TAG, errorMessage); 10666 } 10667 10668 if (requiredInstructionSet == null) { 10669 requiredInstructionSet = instructionSet; 10670 requirer = ps; 10671 } 10672 } 10673 } 10674 10675 if (requiredInstructionSet != null) { 10676 String adjustedAbi; 10677 if (requirer != null) { 10678 // requirer != null implies that either scannedPackage was null or that scannedPackage 10679 // did not require an ABI, in which case we have to adjust scannedPackage to match 10680 // the ABI of the set (which is the same as requirer's ABI) 10681 adjustedAbi = requirer.primaryCpuAbiString; 10682 if (scannedPackage != null) { 10683 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10684 } 10685 } else { 10686 // requirer == null implies that we're updating all ABIs in the set to 10687 // match scannedPackage. 10688 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10689 } 10690 10691 for (PackageSetting ps : packagesForUser) { 10692 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10693 if (ps.primaryCpuAbiString != null) { 10694 continue; 10695 } 10696 10697 ps.primaryCpuAbiString = adjustedAbi; 10698 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10699 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10700 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10701 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10702 + " (requirer=" 10703 + (requirer != null ? requirer.pkg : "null") 10704 + ", scannedPackage=" 10705 + (scannedPackage != null ? scannedPackage : "null") 10706 + ")"); 10707 try { 10708 mInstaller.rmdex(ps.codePathString, 10709 getDexCodeInstructionSet(getPreferredInstructionSet())); 10710 } catch (InstallerException ignored) { 10711 } 10712 } 10713 } 10714 } 10715 } 10716 } 10717 10718 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10719 synchronized (mPackages) { 10720 mResolverReplaced = true; 10721 // Set up information for custom user intent resolution activity. 10722 mResolveActivity.applicationInfo = pkg.applicationInfo; 10723 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10724 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10725 mResolveActivity.processName = pkg.applicationInfo.packageName; 10726 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10727 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10728 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10729 mResolveActivity.theme = 0; 10730 mResolveActivity.exported = true; 10731 mResolveActivity.enabled = true; 10732 mResolveInfo.activityInfo = mResolveActivity; 10733 mResolveInfo.priority = 0; 10734 mResolveInfo.preferredOrder = 0; 10735 mResolveInfo.match = 0; 10736 mResolveComponentName = mCustomResolverComponentName; 10737 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10738 mResolveComponentName); 10739 } 10740 } 10741 10742 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10743 if (installerActivity == null) { 10744 if (DEBUG_EPHEMERAL) { 10745 Slog.d(TAG, "Clear ephemeral installer activity"); 10746 } 10747 mInstantAppInstallerActivity = null; 10748 return; 10749 } 10750 10751 if (DEBUG_EPHEMERAL) { 10752 Slog.d(TAG, "Set ephemeral installer activity: " 10753 + installerActivity.getComponentName()); 10754 } 10755 // Set up information for ephemeral installer activity 10756 mInstantAppInstallerActivity = installerActivity; 10757 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10758 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10759 mInstantAppInstallerActivity.exported = true; 10760 mInstantAppInstallerActivity.enabled = true; 10761 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10762 mInstantAppInstallerInfo.priority = 0; 10763 mInstantAppInstallerInfo.preferredOrder = 1; 10764 mInstantAppInstallerInfo.isDefault = true; 10765 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10766 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10767 } 10768 10769 private static String calculateBundledApkRoot(final String codePathString) { 10770 final File codePath = new File(codePathString); 10771 final File codeRoot; 10772 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10773 codeRoot = Environment.getRootDirectory(); 10774 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10775 codeRoot = Environment.getOemDirectory(); 10776 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10777 codeRoot = Environment.getVendorDirectory(); 10778 } else { 10779 // Unrecognized code path; take its top real segment as the apk root: 10780 // e.g. /something/app/blah.apk => /something 10781 try { 10782 File f = codePath.getCanonicalFile(); 10783 File parent = f.getParentFile(); // non-null because codePath is a file 10784 File tmp; 10785 while ((tmp = parent.getParentFile()) != null) { 10786 f = parent; 10787 parent = tmp; 10788 } 10789 codeRoot = f; 10790 Slog.w(TAG, "Unrecognized code path " 10791 + codePath + " - using " + codeRoot); 10792 } catch (IOException e) { 10793 // Can't canonicalize the code path -- shenanigans? 10794 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10795 return Environment.getRootDirectory().getPath(); 10796 } 10797 } 10798 return codeRoot.getPath(); 10799 } 10800 10801 /** 10802 * Derive and set the location of native libraries for the given package, 10803 * which varies depending on where and how the package was installed. 10804 */ 10805 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10806 final ApplicationInfo info = pkg.applicationInfo; 10807 final String codePath = pkg.codePath; 10808 final File codeFile = new File(codePath); 10809 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10810 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10811 10812 info.nativeLibraryRootDir = null; 10813 info.nativeLibraryRootRequiresIsa = false; 10814 info.nativeLibraryDir = null; 10815 info.secondaryNativeLibraryDir = null; 10816 10817 if (isApkFile(codeFile)) { 10818 // Monolithic install 10819 if (bundledApp) { 10820 // If "/system/lib64/apkname" exists, assume that is the per-package 10821 // native library directory to use; otherwise use "/system/lib/apkname". 10822 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10823 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10824 getPrimaryInstructionSet(info)); 10825 10826 // This is a bundled system app so choose the path based on the ABI. 10827 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10828 // is just the default path. 10829 final String apkName = deriveCodePathName(codePath); 10830 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10831 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10832 apkName).getAbsolutePath(); 10833 10834 if (info.secondaryCpuAbi != null) { 10835 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10836 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10837 secondaryLibDir, apkName).getAbsolutePath(); 10838 } 10839 } else if (asecApp) { 10840 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10841 .getAbsolutePath(); 10842 } else { 10843 final String apkName = deriveCodePathName(codePath); 10844 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10845 .getAbsolutePath(); 10846 } 10847 10848 info.nativeLibraryRootRequiresIsa = false; 10849 info.nativeLibraryDir = info.nativeLibraryRootDir; 10850 } else { 10851 // Cluster install 10852 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10853 info.nativeLibraryRootRequiresIsa = true; 10854 10855 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10856 getPrimaryInstructionSet(info)).getAbsolutePath(); 10857 10858 if (info.secondaryCpuAbi != null) { 10859 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10860 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10861 } 10862 } 10863 } 10864 10865 /** 10866 * Calculate the abis and roots for a bundled app. These can uniquely 10867 * be determined from the contents of the system partition, i.e whether 10868 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10869 * of this information, and instead assume that the system was built 10870 * sensibly. 10871 */ 10872 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10873 PackageSetting pkgSetting) { 10874 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10875 10876 // If "/system/lib64/apkname" exists, assume that is the per-package 10877 // native library directory to use; otherwise use "/system/lib/apkname". 10878 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10879 setBundledAppAbi(pkg, apkRoot, apkName); 10880 // pkgSetting might be null during rescan following uninstall of updates 10881 // to a bundled app, so accommodate that possibility. The settings in 10882 // that case will be established later from the parsed package. 10883 // 10884 // If the settings aren't null, sync them up with what we've just derived. 10885 // note that apkRoot isn't stored in the package settings. 10886 if (pkgSetting != null) { 10887 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10888 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10889 } 10890 } 10891 10892 /** 10893 * Deduces the ABI of a bundled app and sets the relevant fields on the 10894 * parsed pkg object. 10895 * 10896 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10897 * under which system libraries are installed. 10898 * @param apkName the name of the installed package. 10899 */ 10900 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10901 final File codeFile = new File(pkg.codePath); 10902 10903 final boolean has64BitLibs; 10904 final boolean has32BitLibs; 10905 if (isApkFile(codeFile)) { 10906 // Monolithic install 10907 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10908 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10909 } else { 10910 // Cluster install 10911 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10912 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10913 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10914 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10915 has64BitLibs = (new File(rootDir, isa)).exists(); 10916 } else { 10917 has64BitLibs = false; 10918 } 10919 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10920 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10921 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10922 has32BitLibs = (new File(rootDir, isa)).exists(); 10923 } else { 10924 has32BitLibs = false; 10925 } 10926 } 10927 10928 if (has64BitLibs && !has32BitLibs) { 10929 // The package has 64 bit libs, but not 32 bit libs. Its primary 10930 // ABI should be 64 bit. We can safely assume here that the bundled 10931 // native libraries correspond to the most preferred ABI in the list. 10932 10933 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10934 pkg.applicationInfo.secondaryCpuAbi = null; 10935 } else if (has32BitLibs && !has64BitLibs) { 10936 // The package has 32 bit libs but not 64 bit libs. Its primary 10937 // ABI should be 32 bit. 10938 10939 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10940 pkg.applicationInfo.secondaryCpuAbi = null; 10941 } else if (has32BitLibs && has64BitLibs) { 10942 // The application has both 64 and 32 bit bundled libraries. We check 10943 // here that the app declares multiArch support, and warn if it doesn't. 10944 // 10945 // We will be lenient here and record both ABIs. The primary will be the 10946 // ABI that's higher on the list, i.e, a device that's configured to prefer 10947 // 64 bit apps will see a 64 bit primary ABI, 10948 10949 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10950 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10951 } 10952 10953 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10954 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10955 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10956 } else { 10957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10958 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10959 } 10960 } else { 10961 pkg.applicationInfo.primaryCpuAbi = null; 10962 pkg.applicationInfo.secondaryCpuAbi = null; 10963 } 10964 } 10965 10966 private void killApplication(String pkgName, int appId, String reason) { 10967 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10968 } 10969 10970 private void killApplication(String pkgName, int appId, int userId, String reason) { 10971 // Request the ActivityManager to kill the process(only for existing packages) 10972 // so that we do not end up in a confused state while the user is still using the older 10973 // version of the application while the new one gets installed. 10974 final long token = Binder.clearCallingIdentity(); 10975 try { 10976 IActivityManager am = ActivityManager.getService(); 10977 if (am != null) { 10978 try { 10979 am.killApplication(pkgName, appId, userId, reason); 10980 } catch (RemoteException e) { 10981 } 10982 } 10983 } finally { 10984 Binder.restoreCallingIdentity(token); 10985 } 10986 } 10987 10988 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10989 // Remove the parent package setting 10990 PackageSetting ps = (PackageSetting) pkg.mExtras; 10991 if (ps != null) { 10992 removePackageLI(ps, chatty); 10993 } 10994 // Remove the child package setting 10995 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10996 for (int i = 0; i < childCount; i++) { 10997 PackageParser.Package childPkg = pkg.childPackages.get(i); 10998 ps = (PackageSetting) childPkg.mExtras; 10999 if (ps != null) { 11000 removePackageLI(ps, chatty); 11001 } 11002 } 11003 } 11004 11005 void removePackageLI(PackageSetting ps, boolean chatty) { 11006 if (DEBUG_INSTALL) { 11007 if (chatty) 11008 Log.d(TAG, "Removing package " + ps.name); 11009 } 11010 11011 // writer 11012 synchronized (mPackages) { 11013 mPackages.remove(ps.name); 11014 final PackageParser.Package pkg = ps.pkg; 11015 if (pkg != null) { 11016 cleanPackageDataStructuresLILPw(pkg, chatty); 11017 } 11018 } 11019 } 11020 11021 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11022 if (DEBUG_INSTALL) { 11023 if (chatty) 11024 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11025 } 11026 11027 // writer 11028 synchronized (mPackages) { 11029 // Remove the parent package 11030 mPackages.remove(pkg.applicationInfo.packageName); 11031 cleanPackageDataStructuresLILPw(pkg, chatty); 11032 11033 // Remove the child packages 11034 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11035 for (int i = 0; i < childCount; i++) { 11036 PackageParser.Package childPkg = pkg.childPackages.get(i); 11037 mPackages.remove(childPkg.applicationInfo.packageName); 11038 cleanPackageDataStructuresLILPw(childPkg, chatty); 11039 } 11040 } 11041 } 11042 11043 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11044 int N = pkg.providers.size(); 11045 StringBuilder r = null; 11046 int i; 11047 for (i=0; i<N; i++) { 11048 PackageParser.Provider p = pkg.providers.get(i); 11049 mProviders.removeProvider(p); 11050 if (p.info.authority == null) { 11051 11052 /* There was another ContentProvider with this authority when 11053 * this app was installed so this authority is null, 11054 * Ignore it as we don't have to unregister the provider. 11055 */ 11056 continue; 11057 } 11058 String names[] = p.info.authority.split(";"); 11059 for (int j = 0; j < names.length; j++) { 11060 if (mProvidersByAuthority.get(names[j]) == p) { 11061 mProvidersByAuthority.remove(names[j]); 11062 if (DEBUG_REMOVE) { 11063 if (chatty) 11064 Log.d(TAG, "Unregistered content provider: " + names[j] 11065 + ", className = " + p.info.name + ", isSyncable = " 11066 + p.info.isSyncable); 11067 } 11068 } 11069 } 11070 if (DEBUG_REMOVE && chatty) { 11071 if (r == null) { 11072 r = new StringBuilder(256); 11073 } else { 11074 r.append(' '); 11075 } 11076 r.append(p.info.name); 11077 } 11078 } 11079 if (r != null) { 11080 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11081 } 11082 11083 N = pkg.services.size(); 11084 r = null; 11085 for (i=0; i<N; i++) { 11086 PackageParser.Service s = pkg.services.get(i); 11087 mServices.removeService(s); 11088 if (chatty) { 11089 if (r == null) { 11090 r = new StringBuilder(256); 11091 } else { 11092 r.append(' '); 11093 } 11094 r.append(s.info.name); 11095 } 11096 } 11097 if (r != null) { 11098 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11099 } 11100 11101 N = pkg.receivers.size(); 11102 r = null; 11103 for (i=0; i<N; i++) { 11104 PackageParser.Activity a = pkg.receivers.get(i); 11105 mReceivers.removeActivity(a, "receiver"); 11106 if (DEBUG_REMOVE && chatty) { 11107 if (r == null) { 11108 r = new StringBuilder(256); 11109 } else { 11110 r.append(' '); 11111 } 11112 r.append(a.info.name); 11113 } 11114 } 11115 if (r != null) { 11116 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11117 } 11118 11119 N = pkg.activities.size(); 11120 r = null; 11121 for (i=0; i<N; i++) { 11122 PackageParser.Activity a = pkg.activities.get(i); 11123 mActivities.removeActivity(a, "activity"); 11124 if (DEBUG_REMOVE && chatty) { 11125 if (r == null) { 11126 r = new StringBuilder(256); 11127 } else { 11128 r.append(' '); 11129 } 11130 r.append(a.info.name); 11131 } 11132 } 11133 if (r != null) { 11134 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11135 } 11136 11137 N = pkg.permissions.size(); 11138 r = null; 11139 for (i=0; i<N; i++) { 11140 PackageParser.Permission p = pkg.permissions.get(i); 11141 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11142 if (bp == null) { 11143 bp = mSettings.mPermissionTrees.get(p.info.name); 11144 } 11145 if (bp != null && bp.perm == p) { 11146 bp.perm = null; 11147 if (DEBUG_REMOVE && chatty) { 11148 if (r == null) { 11149 r = new StringBuilder(256); 11150 } else { 11151 r.append(' '); 11152 } 11153 r.append(p.info.name); 11154 } 11155 } 11156 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11157 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11158 if (appOpPkgs != null) { 11159 appOpPkgs.remove(pkg.packageName); 11160 } 11161 } 11162 } 11163 if (r != null) { 11164 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11165 } 11166 11167 N = pkg.requestedPermissions.size(); 11168 r = null; 11169 for (i=0; i<N; i++) { 11170 String perm = pkg.requestedPermissions.get(i); 11171 BasePermission bp = mSettings.mPermissions.get(perm); 11172 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11173 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11174 if (appOpPkgs != null) { 11175 appOpPkgs.remove(pkg.packageName); 11176 if (appOpPkgs.isEmpty()) { 11177 mAppOpPermissionPackages.remove(perm); 11178 } 11179 } 11180 } 11181 } 11182 if (r != null) { 11183 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11184 } 11185 11186 N = pkg.instrumentation.size(); 11187 r = null; 11188 for (i=0; i<N; i++) { 11189 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11190 mInstrumentation.remove(a.getComponentName()); 11191 if (DEBUG_REMOVE && chatty) { 11192 if (r == null) { 11193 r = new StringBuilder(256); 11194 } else { 11195 r.append(' '); 11196 } 11197 r.append(a.info.name); 11198 } 11199 } 11200 if (r != null) { 11201 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11202 } 11203 11204 r = null; 11205 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11206 // Only system apps can hold shared libraries. 11207 if (pkg.libraryNames != null) { 11208 for (i = 0; i < pkg.libraryNames.size(); i++) { 11209 String name = pkg.libraryNames.get(i); 11210 if (removeSharedLibraryLPw(name, 0)) { 11211 if (DEBUG_REMOVE && chatty) { 11212 if (r == null) { 11213 r = new StringBuilder(256); 11214 } else { 11215 r.append(' '); 11216 } 11217 r.append(name); 11218 } 11219 } 11220 } 11221 } 11222 } 11223 11224 r = null; 11225 11226 // Any package can hold static shared libraries. 11227 if (pkg.staticSharedLibName != null) { 11228 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11229 if (DEBUG_REMOVE && chatty) { 11230 if (r == null) { 11231 r = new StringBuilder(256); 11232 } else { 11233 r.append(' '); 11234 } 11235 r.append(pkg.staticSharedLibName); 11236 } 11237 } 11238 } 11239 11240 if (r != null) { 11241 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11242 } 11243 } 11244 11245 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11246 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11247 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11248 return true; 11249 } 11250 } 11251 return false; 11252 } 11253 11254 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11255 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11256 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11257 11258 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11259 // Update the parent permissions 11260 updatePermissionsLPw(pkg.packageName, pkg, flags); 11261 // Update the child permissions 11262 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11263 for (int i = 0; i < childCount; i++) { 11264 PackageParser.Package childPkg = pkg.childPackages.get(i); 11265 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11266 } 11267 } 11268 11269 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11270 int flags) { 11271 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11272 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11273 } 11274 11275 private void updatePermissionsLPw(String changingPkg, 11276 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11277 // Make sure there are no dangling permission trees. 11278 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11279 while (it.hasNext()) { 11280 final BasePermission bp = it.next(); 11281 if (bp.packageSetting == null) { 11282 // We may not yet have parsed the package, so just see if 11283 // we still know about its settings. 11284 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11285 } 11286 if (bp.packageSetting == null) { 11287 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11288 + " from package " + bp.sourcePackage); 11289 it.remove(); 11290 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11291 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11292 Slog.i(TAG, "Removing old permission tree: " + bp.name 11293 + " from package " + bp.sourcePackage); 11294 flags |= UPDATE_PERMISSIONS_ALL; 11295 it.remove(); 11296 } 11297 } 11298 } 11299 11300 // Make sure all dynamic permissions have been assigned to a package, 11301 // and make sure there are no dangling permissions. 11302 it = mSettings.mPermissions.values().iterator(); 11303 while (it.hasNext()) { 11304 final BasePermission bp = it.next(); 11305 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11306 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11307 + bp.name + " pkg=" + bp.sourcePackage 11308 + " info=" + bp.pendingInfo); 11309 if (bp.packageSetting == null && bp.pendingInfo != null) { 11310 final BasePermission tree = findPermissionTreeLP(bp.name); 11311 if (tree != null && tree.perm != null) { 11312 bp.packageSetting = tree.packageSetting; 11313 bp.perm = new PackageParser.Permission(tree.perm.owner, 11314 new PermissionInfo(bp.pendingInfo)); 11315 bp.perm.info.packageName = tree.perm.info.packageName; 11316 bp.perm.info.name = bp.name; 11317 bp.uid = tree.uid; 11318 } 11319 } 11320 } 11321 if (bp.packageSetting == null) { 11322 // We may not yet have parsed the package, so just see if 11323 // we still know about its settings. 11324 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11325 } 11326 if (bp.packageSetting == null) { 11327 Slog.w(TAG, "Removing dangling permission: " + bp.name 11328 + " from package " + bp.sourcePackage); 11329 it.remove(); 11330 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11331 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11332 Slog.i(TAG, "Removing old permission: " + bp.name 11333 + " from package " + bp.sourcePackage); 11334 flags |= UPDATE_PERMISSIONS_ALL; 11335 it.remove(); 11336 } 11337 } 11338 } 11339 11340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11341 // Now update the permissions for all packages, in particular 11342 // replace the granted permissions of the system packages. 11343 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11344 for (PackageParser.Package pkg : mPackages.values()) { 11345 if (pkg != pkgInfo) { 11346 // Only replace for packages on requested volume 11347 final String volumeUuid = getVolumeUuidForPackage(pkg); 11348 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11349 && Objects.equals(replaceVolumeUuid, volumeUuid); 11350 grantPermissionsLPw(pkg, replace, changingPkg); 11351 } 11352 } 11353 } 11354 11355 if (pkgInfo != null) { 11356 // Only replace for packages on requested volume 11357 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11358 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11359 && Objects.equals(replaceVolumeUuid, volumeUuid); 11360 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11361 } 11362 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11363 } 11364 11365 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11366 String packageOfInterest) { 11367 // IMPORTANT: There are two types of permissions: install and runtime. 11368 // Install time permissions are granted when the app is installed to 11369 // all device users and users added in the future. Runtime permissions 11370 // are granted at runtime explicitly to specific users. Normal and signature 11371 // protected permissions are install time permissions. Dangerous permissions 11372 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11373 // otherwise they are runtime permissions. This function does not manage 11374 // runtime permissions except for the case an app targeting Lollipop MR1 11375 // being upgraded to target a newer SDK, in which case dangerous permissions 11376 // are transformed from install time to runtime ones. 11377 11378 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11379 if (ps == null) { 11380 return; 11381 } 11382 11383 PermissionsState permissionsState = ps.getPermissionsState(); 11384 PermissionsState origPermissions = permissionsState; 11385 11386 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11387 11388 boolean runtimePermissionsRevoked = false; 11389 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11390 11391 boolean changedInstallPermission = false; 11392 11393 if (replace) { 11394 ps.installPermissionsFixed = false; 11395 if (!ps.isSharedUser()) { 11396 origPermissions = new PermissionsState(permissionsState); 11397 permissionsState.reset(); 11398 } else { 11399 // We need to know only about runtime permission changes since the 11400 // calling code always writes the install permissions state but 11401 // the runtime ones are written only if changed. The only cases of 11402 // changed runtime permissions here are promotion of an install to 11403 // runtime and revocation of a runtime from a shared user. 11404 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11405 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11406 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11407 runtimePermissionsRevoked = true; 11408 } 11409 } 11410 } 11411 11412 permissionsState.setGlobalGids(mGlobalGids); 11413 11414 final int N = pkg.requestedPermissions.size(); 11415 for (int i=0; i<N; i++) { 11416 final String name = pkg.requestedPermissions.get(i); 11417 final BasePermission bp = mSettings.mPermissions.get(name); 11418 11419 if (DEBUG_INSTALL) { 11420 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11421 } 11422 11423 if (bp == null || bp.packageSetting == null) { 11424 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11425 Slog.w(TAG, "Unknown permission " + name 11426 + " in package " + pkg.packageName); 11427 } 11428 continue; 11429 } 11430 11431 11432 // Limit ephemeral apps to ephemeral allowed permissions. 11433 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11434 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11435 + pkg.packageName); 11436 continue; 11437 } 11438 11439 final String perm = bp.name; 11440 boolean allowedSig = false; 11441 int grant = GRANT_DENIED; 11442 11443 // Keep track of app op permissions. 11444 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11445 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11446 if (pkgs == null) { 11447 pkgs = new ArraySet<>(); 11448 mAppOpPermissionPackages.put(bp.name, pkgs); 11449 } 11450 pkgs.add(pkg.packageName); 11451 } 11452 11453 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11454 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11455 >= Build.VERSION_CODES.M; 11456 switch (level) { 11457 case PermissionInfo.PROTECTION_NORMAL: { 11458 // For all apps normal permissions are install time ones. 11459 grant = GRANT_INSTALL; 11460 } break; 11461 11462 case PermissionInfo.PROTECTION_DANGEROUS: { 11463 // If a permission review is required for legacy apps we represent 11464 // their permissions as always granted runtime ones since we need 11465 // to keep the review required permission flag per user while an 11466 // install permission's state is shared across all users. 11467 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11468 // For legacy apps dangerous permissions are install time ones. 11469 grant = GRANT_INSTALL; 11470 } else if (origPermissions.hasInstallPermission(bp.name)) { 11471 // For legacy apps that became modern, install becomes runtime. 11472 grant = GRANT_UPGRADE; 11473 } else if (mPromoteSystemApps 11474 && isSystemApp(ps) 11475 && mExistingSystemPackages.contains(ps.name)) { 11476 // For legacy system apps, install becomes runtime. 11477 // We cannot check hasInstallPermission() for system apps since those 11478 // permissions were granted implicitly and not persisted pre-M. 11479 grant = GRANT_UPGRADE; 11480 } else { 11481 // For modern apps keep runtime permissions unchanged. 11482 grant = GRANT_RUNTIME; 11483 } 11484 } break; 11485 11486 case PermissionInfo.PROTECTION_SIGNATURE: { 11487 // For all apps signature permissions are install time ones. 11488 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11489 if (allowedSig) { 11490 grant = GRANT_INSTALL; 11491 } 11492 } break; 11493 } 11494 11495 if (DEBUG_INSTALL) { 11496 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11497 } 11498 11499 if (grant != GRANT_DENIED) { 11500 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11501 // If this is an existing, non-system package, then 11502 // we can't add any new permissions to it. 11503 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11504 // Except... if this is a permission that was added 11505 // to the platform (note: need to only do this when 11506 // updating the platform). 11507 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11508 grant = GRANT_DENIED; 11509 } 11510 } 11511 } 11512 11513 switch (grant) { 11514 case GRANT_INSTALL: { 11515 // Revoke this as runtime permission to handle the case of 11516 // a runtime permission being downgraded to an install one. 11517 // Also in permission review mode we keep dangerous permissions 11518 // for legacy apps 11519 for (int userId : UserManagerService.getInstance().getUserIds()) { 11520 if (origPermissions.getRuntimePermissionState( 11521 bp.name, userId) != null) { 11522 // Revoke the runtime permission and clear the flags. 11523 origPermissions.revokeRuntimePermission(bp, userId); 11524 origPermissions.updatePermissionFlags(bp, userId, 11525 PackageManager.MASK_PERMISSION_FLAGS, 0); 11526 // If we revoked a permission permission, we have to write. 11527 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11528 changedRuntimePermissionUserIds, userId); 11529 } 11530 } 11531 // Grant an install permission. 11532 if (permissionsState.grantInstallPermission(bp) != 11533 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11534 changedInstallPermission = true; 11535 } 11536 } break; 11537 11538 case GRANT_RUNTIME: { 11539 // Grant previously granted runtime permissions. 11540 for (int userId : UserManagerService.getInstance().getUserIds()) { 11541 PermissionState permissionState = origPermissions 11542 .getRuntimePermissionState(bp.name, userId); 11543 int flags = permissionState != null 11544 ? permissionState.getFlags() : 0; 11545 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11546 // Don't propagate the permission in a permission review mode if 11547 // the former was revoked, i.e. marked to not propagate on upgrade. 11548 // Note that in a permission review mode install permissions are 11549 // represented as constantly granted runtime ones since we need to 11550 // keep a per user state associated with the permission. Also the 11551 // revoke on upgrade flag is no longer applicable and is reset. 11552 final boolean revokeOnUpgrade = (flags & PackageManager 11553 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11554 if (revokeOnUpgrade) { 11555 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11556 // Since we changed the flags, we have to write. 11557 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11558 changedRuntimePermissionUserIds, userId); 11559 } 11560 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11561 if (permissionsState.grantRuntimePermission(bp, userId) == 11562 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11563 // If we cannot put the permission as it was, 11564 // we have to write. 11565 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11566 changedRuntimePermissionUserIds, userId); 11567 } 11568 } 11569 11570 // If the app supports runtime permissions no need for a review. 11571 if (mPermissionReviewRequired 11572 && appSupportsRuntimePermissions 11573 && (flags & PackageManager 11574 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11575 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11576 // Since we changed the flags, we have to write. 11577 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11578 changedRuntimePermissionUserIds, userId); 11579 } 11580 } else if (mPermissionReviewRequired 11581 && !appSupportsRuntimePermissions) { 11582 // For legacy apps that need a permission review, every new 11583 // runtime permission is granted but it is pending a review. 11584 // We also need to review only platform defined runtime 11585 // permissions as these are the only ones the platform knows 11586 // how to disable the API to simulate revocation as legacy 11587 // apps don't expect to run with revoked permissions. 11588 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11589 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11590 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11591 // We changed the flags, hence have to write. 11592 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11593 changedRuntimePermissionUserIds, userId); 11594 } 11595 } 11596 if (permissionsState.grantRuntimePermission(bp, userId) 11597 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11598 // We changed the permission, hence have to write. 11599 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11600 changedRuntimePermissionUserIds, userId); 11601 } 11602 } 11603 // Propagate the permission flags. 11604 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11605 } 11606 } break; 11607 11608 case GRANT_UPGRADE: { 11609 // Grant runtime permissions for a previously held install permission. 11610 PermissionState permissionState = origPermissions 11611 .getInstallPermissionState(bp.name); 11612 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11613 11614 if (origPermissions.revokeInstallPermission(bp) 11615 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11616 // We will be transferring the permission flags, so clear them. 11617 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11618 PackageManager.MASK_PERMISSION_FLAGS, 0); 11619 changedInstallPermission = true; 11620 } 11621 11622 // If the permission is not to be promoted to runtime we ignore it and 11623 // also its other flags as they are not applicable to install permissions. 11624 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11625 for (int userId : currentUserIds) { 11626 if (permissionsState.grantRuntimePermission(bp, userId) != 11627 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11628 // Transfer the permission flags. 11629 permissionsState.updatePermissionFlags(bp, userId, 11630 flags, flags); 11631 // If we granted the permission, we have to write. 11632 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11633 changedRuntimePermissionUserIds, userId); 11634 } 11635 } 11636 } 11637 } break; 11638 11639 default: { 11640 if (packageOfInterest == null 11641 || packageOfInterest.equals(pkg.packageName)) { 11642 Slog.w(TAG, "Not granting permission " + perm 11643 + " to package " + pkg.packageName 11644 + " because it was previously installed without"); 11645 } 11646 } break; 11647 } 11648 } else { 11649 if (permissionsState.revokeInstallPermission(bp) != 11650 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11651 // Also drop the permission flags. 11652 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11653 PackageManager.MASK_PERMISSION_FLAGS, 0); 11654 changedInstallPermission = true; 11655 Slog.i(TAG, "Un-granting permission " + perm 11656 + " from package " + pkg.packageName 11657 + " (protectionLevel=" + bp.protectionLevel 11658 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11659 + ")"); 11660 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11661 // Don't print warning for app op permissions, since it is fine for them 11662 // not to be granted, there is a UI for the user to decide. 11663 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11664 Slog.w(TAG, "Not granting permission " + perm 11665 + " to package " + pkg.packageName 11666 + " (protectionLevel=" + bp.protectionLevel 11667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11668 + ")"); 11669 } 11670 } 11671 } 11672 } 11673 11674 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11675 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11676 // This is the first that we have heard about this package, so the 11677 // permissions we have now selected are fixed until explicitly 11678 // changed. 11679 ps.installPermissionsFixed = true; 11680 } 11681 11682 // Persist the runtime permissions state for users with changes. If permissions 11683 // were revoked because no app in the shared user declares them we have to 11684 // write synchronously to avoid losing runtime permissions state. 11685 for (int userId : changedRuntimePermissionUserIds) { 11686 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11687 } 11688 } 11689 11690 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11691 boolean allowed = false; 11692 final int NP = PackageParser.NEW_PERMISSIONS.length; 11693 for (int ip=0; ip<NP; ip++) { 11694 final PackageParser.NewPermissionInfo npi 11695 = PackageParser.NEW_PERMISSIONS[ip]; 11696 if (npi.name.equals(perm) 11697 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11698 allowed = true; 11699 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11700 + pkg.packageName); 11701 break; 11702 } 11703 } 11704 return allowed; 11705 } 11706 11707 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11708 BasePermission bp, PermissionsState origPermissions) { 11709 boolean privilegedPermission = (bp.protectionLevel 11710 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11711 boolean privappPermissionsDisable = 11712 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11713 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11714 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11715 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11716 && !platformPackage && platformPermission) { 11717 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11718 .getPrivAppPermissions(pkg.packageName); 11719 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11720 if (!whitelisted) { 11721 Slog.w(TAG, "Privileged permission " + perm + " for package " 11722 + pkg.packageName + " - not in privapp-permissions whitelist"); 11723 // Only report violations for apps on system image 11724 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11725 if (mPrivappPermissionsViolations == null) { 11726 mPrivappPermissionsViolations = new ArraySet<>(); 11727 } 11728 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11729 } 11730 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11731 return false; 11732 } 11733 } 11734 } 11735 boolean allowed = (compareSignatures( 11736 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11737 == PackageManager.SIGNATURE_MATCH) 11738 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11739 == PackageManager.SIGNATURE_MATCH); 11740 if (!allowed && privilegedPermission) { 11741 if (isSystemApp(pkg)) { 11742 // For updated system applications, a system permission 11743 // is granted only if it had been defined by the original application. 11744 if (pkg.isUpdatedSystemApp()) { 11745 final PackageSetting sysPs = mSettings 11746 .getDisabledSystemPkgLPr(pkg.packageName); 11747 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11748 // If the original was granted this permission, we take 11749 // that grant decision as read and propagate it to the 11750 // update. 11751 if (sysPs.isPrivileged()) { 11752 allowed = true; 11753 } 11754 } else { 11755 // The system apk may have been updated with an older 11756 // version of the one on the data partition, but which 11757 // granted a new system permission that it didn't have 11758 // before. In this case we do want to allow the app to 11759 // now get the new permission if the ancestral apk is 11760 // privileged to get it. 11761 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11762 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11763 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11764 allowed = true; 11765 break; 11766 } 11767 } 11768 } 11769 // Also if a privileged parent package on the system image or any of 11770 // its children requested a privileged permission, the updated child 11771 // packages can also get the permission. 11772 if (pkg.parentPackage != null) { 11773 final PackageSetting disabledSysParentPs = mSettings 11774 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11775 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11776 && disabledSysParentPs.isPrivileged()) { 11777 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11778 allowed = true; 11779 } else if (disabledSysParentPs.pkg.childPackages != null) { 11780 final int count = disabledSysParentPs.pkg.childPackages.size(); 11781 for (int i = 0; i < count; i++) { 11782 PackageParser.Package disabledSysChildPkg = 11783 disabledSysParentPs.pkg.childPackages.get(i); 11784 if (isPackageRequestingPermission(disabledSysChildPkg, 11785 perm)) { 11786 allowed = true; 11787 break; 11788 } 11789 } 11790 } 11791 } 11792 } 11793 } 11794 } else { 11795 allowed = isPrivilegedApp(pkg); 11796 } 11797 } 11798 } 11799 if (!allowed) { 11800 if (!allowed && (bp.protectionLevel 11801 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11802 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11803 // If this was a previously normal/dangerous permission that got moved 11804 // to a system permission as part of the runtime permission redesign, then 11805 // we still want to blindly grant it to old apps. 11806 allowed = true; 11807 } 11808 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11809 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11810 // If this permission is to be granted to the system installer and 11811 // this app is an installer, then it gets the permission. 11812 allowed = true; 11813 } 11814 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11815 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11816 // If this permission is to be granted to the system verifier and 11817 // this app is a verifier, then it gets the permission. 11818 allowed = true; 11819 } 11820 if (!allowed && (bp.protectionLevel 11821 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11822 && isSystemApp(pkg)) { 11823 // Any pre-installed system app is allowed to get this permission. 11824 allowed = true; 11825 } 11826 if (!allowed && (bp.protectionLevel 11827 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11828 // For development permissions, a development permission 11829 // is granted only if it was already granted. 11830 allowed = origPermissions.hasInstallPermission(perm); 11831 } 11832 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11833 && pkg.packageName.equals(mSetupWizardPackage)) { 11834 // If this permission is to be granted to the system setup wizard and 11835 // this app is a setup wizard, then it gets the permission. 11836 allowed = true; 11837 } 11838 } 11839 return allowed; 11840 } 11841 11842 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11843 final int permCount = pkg.requestedPermissions.size(); 11844 for (int j = 0; j < permCount; j++) { 11845 String requestedPermission = pkg.requestedPermissions.get(j); 11846 if (permission.equals(requestedPermission)) { 11847 return true; 11848 } 11849 } 11850 return false; 11851 } 11852 11853 final class ActivityIntentResolver 11854 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11855 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11856 boolean defaultOnly, int userId) { 11857 if (!sUserManager.exists(userId)) return null; 11858 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11859 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11860 } 11861 11862 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11863 int userId) { 11864 if (!sUserManager.exists(userId)) return null; 11865 mFlags = flags; 11866 return super.queryIntent(intent, resolvedType, 11867 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11868 userId); 11869 } 11870 11871 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11872 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11873 if (!sUserManager.exists(userId)) return null; 11874 if (packageActivities == null) { 11875 return null; 11876 } 11877 mFlags = flags; 11878 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11879 final int N = packageActivities.size(); 11880 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11881 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11882 11883 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11884 for (int i = 0; i < N; ++i) { 11885 intentFilters = packageActivities.get(i).intents; 11886 if (intentFilters != null && intentFilters.size() > 0) { 11887 PackageParser.ActivityIntentInfo[] array = 11888 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11889 intentFilters.toArray(array); 11890 listCut.add(array); 11891 } 11892 } 11893 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11894 } 11895 11896 /** 11897 * Finds a privileged activity that matches the specified activity names. 11898 */ 11899 private PackageParser.Activity findMatchingActivity( 11900 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11901 for (PackageParser.Activity sysActivity : activityList) { 11902 if (sysActivity.info.name.equals(activityInfo.name)) { 11903 return sysActivity; 11904 } 11905 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11906 return sysActivity; 11907 } 11908 if (sysActivity.info.targetActivity != null) { 11909 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11910 return sysActivity; 11911 } 11912 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11913 return sysActivity; 11914 } 11915 } 11916 } 11917 return null; 11918 } 11919 11920 public class IterGenerator<E> { 11921 public Iterator<E> generate(ActivityIntentInfo info) { 11922 return null; 11923 } 11924 } 11925 11926 public class ActionIterGenerator extends IterGenerator<String> { 11927 @Override 11928 public Iterator<String> generate(ActivityIntentInfo info) { 11929 return info.actionsIterator(); 11930 } 11931 } 11932 11933 public class CategoriesIterGenerator extends IterGenerator<String> { 11934 @Override 11935 public Iterator<String> generate(ActivityIntentInfo info) { 11936 return info.categoriesIterator(); 11937 } 11938 } 11939 11940 public class SchemesIterGenerator extends IterGenerator<String> { 11941 @Override 11942 public Iterator<String> generate(ActivityIntentInfo info) { 11943 return info.schemesIterator(); 11944 } 11945 } 11946 11947 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11948 @Override 11949 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11950 return info.authoritiesIterator(); 11951 } 11952 } 11953 11954 /** 11955 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11956 * MODIFIED. Do not pass in a list that should not be changed. 11957 */ 11958 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11959 IterGenerator<T> generator, Iterator<T> searchIterator) { 11960 // loop through the set of actions; every one must be found in the intent filter 11961 while (searchIterator.hasNext()) { 11962 // we must have at least one filter in the list to consider a match 11963 if (intentList.size() == 0) { 11964 break; 11965 } 11966 11967 final T searchAction = searchIterator.next(); 11968 11969 // loop through the set of intent filters 11970 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11971 while (intentIter.hasNext()) { 11972 final ActivityIntentInfo intentInfo = intentIter.next(); 11973 boolean selectionFound = false; 11974 11975 // loop through the intent filter's selection criteria; at least one 11976 // of them must match the searched criteria 11977 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11978 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11979 final T intentSelection = intentSelectionIter.next(); 11980 if (intentSelection != null && intentSelection.equals(searchAction)) { 11981 selectionFound = true; 11982 break; 11983 } 11984 } 11985 11986 // the selection criteria wasn't found in this filter's set; this filter 11987 // is not a potential match 11988 if (!selectionFound) { 11989 intentIter.remove(); 11990 } 11991 } 11992 } 11993 } 11994 11995 private boolean isProtectedAction(ActivityIntentInfo filter) { 11996 final Iterator<String> actionsIter = filter.actionsIterator(); 11997 while (actionsIter != null && actionsIter.hasNext()) { 11998 final String filterAction = actionsIter.next(); 11999 if (PROTECTED_ACTIONS.contains(filterAction)) { 12000 return true; 12001 } 12002 } 12003 return false; 12004 } 12005 12006 /** 12007 * Adjusts the priority of the given intent filter according to policy. 12008 * <p> 12009 * <ul> 12010 * <li>The priority for non privileged applications is capped to '0'</li> 12011 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12012 * <li>The priority for unbundled updates to privileged applications is capped to the 12013 * priority defined on the system partition</li> 12014 * </ul> 12015 * <p> 12016 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12017 * allowed to obtain any priority on any action. 12018 */ 12019 private void adjustPriority( 12020 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12021 // nothing to do; priority is fine as-is 12022 if (intent.getPriority() <= 0) { 12023 return; 12024 } 12025 12026 final ActivityInfo activityInfo = intent.activity.info; 12027 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12028 12029 final boolean privilegedApp = 12030 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12031 if (!privilegedApp) { 12032 // non-privileged applications can never define a priority >0 12033 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12034 + " package: " + applicationInfo.packageName 12035 + " activity: " + intent.activity.className 12036 + " origPrio: " + intent.getPriority()); 12037 intent.setPriority(0); 12038 return; 12039 } 12040 12041 if (systemActivities == null) { 12042 // the system package is not disabled; we're parsing the system partition 12043 if (isProtectedAction(intent)) { 12044 if (mDeferProtectedFilters) { 12045 // We can't deal with these just yet. No component should ever obtain a 12046 // >0 priority for a protected actions, with ONE exception -- the setup 12047 // wizard. The setup wizard, however, cannot be known until we're able to 12048 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12049 // until all intent filters have been processed. Chicken, meet egg. 12050 // Let the filter temporarily have a high priority and rectify the 12051 // priorities after all system packages have been scanned. 12052 mProtectedFilters.add(intent); 12053 if (DEBUG_FILTERS) { 12054 Slog.i(TAG, "Protected action; save for later;" 12055 + " package: " + applicationInfo.packageName 12056 + " activity: " + intent.activity.className 12057 + " origPrio: " + intent.getPriority()); 12058 } 12059 return; 12060 } else { 12061 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12062 Slog.i(TAG, "No setup wizard;" 12063 + " All protected intents capped to priority 0"); 12064 } 12065 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12066 if (DEBUG_FILTERS) { 12067 Slog.i(TAG, "Found setup wizard;" 12068 + " allow priority " + intent.getPriority() + ";" 12069 + " package: " + intent.activity.info.packageName 12070 + " activity: " + intent.activity.className 12071 + " priority: " + intent.getPriority()); 12072 } 12073 // setup wizard gets whatever it wants 12074 return; 12075 } 12076 Slog.w(TAG, "Protected action; cap priority to 0;" 12077 + " package: " + intent.activity.info.packageName 12078 + " activity: " + intent.activity.className 12079 + " origPrio: " + intent.getPriority()); 12080 intent.setPriority(0); 12081 return; 12082 } 12083 } 12084 // privileged apps on the system image get whatever priority they request 12085 return; 12086 } 12087 12088 // privileged app unbundled update ... try to find the same activity 12089 final PackageParser.Activity foundActivity = 12090 findMatchingActivity(systemActivities, activityInfo); 12091 if (foundActivity == null) { 12092 // this is a new activity; it cannot obtain >0 priority 12093 if (DEBUG_FILTERS) { 12094 Slog.i(TAG, "New activity; cap priority to 0;" 12095 + " package: " + applicationInfo.packageName 12096 + " activity: " + intent.activity.className 12097 + " origPrio: " + intent.getPriority()); 12098 } 12099 intent.setPriority(0); 12100 return; 12101 } 12102 12103 // found activity, now check for filter equivalence 12104 12105 // a shallow copy is enough; we modify the list, not its contents 12106 final List<ActivityIntentInfo> intentListCopy = 12107 new ArrayList<>(foundActivity.intents); 12108 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12109 12110 // find matching action subsets 12111 final Iterator<String> actionsIterator = intent.actionsIterator(); 12112 if (actionsIterator != null) { 12113 getIntentListSubset( 12114 intentListCopy, new ActionIterGenerator(), actionsIterator); 12115 if (intentListCopy.size() == 0) { 12116 // no more intents to match; we're not equivalent 12117 if (DEBUG_FILTERS) { 12118 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12119 + " package: " + applicationInfo.packageName 12120 + " activity: " + intent.activity.className 12121 + " origPrio: " + intent.getPriority()); 12122 } 12123 intent.setPriority(0); 12124 return; 12125 } 12126 } 12127 12128 // find matching category subsets 12129 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12130 if (categoriesIterator != null) { 12131 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12132 categoriesIterator); 12133 if (intentListCopy.size() == 0) { 12134 // no more intents to match; we're not equivalent 12135 if (DEBUG_FILTERS) { 12136 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12137 + " package: " + applicationInfo.packageName 12138 + " activity: " + intent.activity.className 12139 + " origPrio: " + intent.getPriority()); 12140 } 12141 intent.setPriority(0); 12142 return; 12143 } 12144 } 12145 12146 // find matching schemes subsets 12147 final Iterator<String> schemesIterator = intent.schemesIterator(); 12148 if (schemesIterator != null) { 12149 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12150 schemesIterator); 12151 if (intentListCopy.size() == 0) { 12152 // no more intents to match; we're not equivalent 12153 if (DEBUG_FILTERS) { 12154 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12155 + " package: " + applicationInfo.packageName 12156 + " activity: " + intent.activity.className 12157 + " origPrio: " + intent.getPriority()); 12158 } 12159 intent.setPriority(0); 12160 return; 12161 } 12162 } 12163 12164 // find matching authorities subsets 12165 final Iterator<IntentFilter.AuthorityEntry> 12166 authoritiesIterator = intent.authoritiesIterator(); 12167 if (authoritiesIterator != null) { 12168 getIntentListSubset(intentListCopy, 12169 new AuthoritiesIterGenerator(), 12170 authoritiesIterator); 12171 if (intentListCopy.size() == 0) { 12172 // no more intents to match; we're not equivalent 12173 if (DEBUG_FILTERS) { 12174 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12175 + " package: " + applicationInfo.packageName 12176 + " activity: " + intent.activity.className 12177 + " origPrio: " + intent.getPriority()); 12178 } 12179 intent.setPriority(0); 12180 return; 12181 } 12182 } 12183 12184 // we found matching filter(s); app gets the max priority of all intents 12185 int cappedPriority = 0; 12186 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12187 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12188 } 12189 if (intent.getPriority() > cappedPriority) { 12190 if (DEBUG_FILTERS) { 12191 Slog.i(TAG, "Found matching filter(s);" 12192 + " cap priority to " + cappedPriority + ";" 12193 + " package: " + applicationInfo.packageName 12194 + " activity: " + intent.activity.className 12195 + " origPrio: " + intent.getPriority()); 12196 } 12197 intent.setPriority(cappedPriority); 12198 return; 12199 } 12200 // all this for nothing; the requested priority was <= what was on the system 12201 } 12202 12203 public final void addActivity(PackageParser.Activity a, String type) { 12204 mActivities.put(a.getComponentName(), a); 12205 if (DEBUG_SHOW_INFO) 12206 Log.v( 12207 TAG, " " + type + " " + 12208 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12209 if (DEBUG_SHOW_INFO) 12210 Log.v(TAG, " Class=" + a.info.name); 12211 final int NI = a.intents.size(); 12212 for (int j=0; j<NI; j++) { 12213 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12214 if ("activity".equals(type)) { 12215 final PackageSetting ps = 12216 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12217 final List<PackageParser.Activity> systemActivities = 12218 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12219 adjustPriority(systemActivities, intent); 12220 } 12221 if (DEBUG_SHOW_INFO) { 12222 Log.v(TAG, " IntentFilter:"); 12223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12224 } 12225 if (!intent.debugCheck()) { 12226 Log.w(TAG, "==> For Activity " + a.info.name); 12227 } 12228 addFilter(intent); 12229 } 12230 } 12231 12232 public final void removeActivity(PackageParser.Activity a, String type) { 12233 mActivities.remove(a.getComponentName()); 12234 if (DEBUG_SHOW_INFO) { 12235 Log.v(TAG, " " + type + " " 12236 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12237 : a.info.name) + ":"); 12238 Log.v(TAG, " Class=" + a.info.name); 12239 } 12240 final int NI = a.intents.size(); 12241 for (int j=0; j<NI; j++) { 12242 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12243 if (DEBUG_SHOW_INFO) { 12244 Log.v(TAG, " IntentFilter:"); 12245 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12246 } 12247 removeFilter(intent); 12248 } 12249 } 12250 12251 @Override 12252 protected boolean allowFilterResult( 12253 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12254 ActivityInfo filterAi = filter.activity.info; 12255 for (int i=dest.size()-1; i>=0; i--) { 12256 ActivityInfo destAi = dest.get(i).activityInfo; 12257 if (destAi.name == filterAi.name 12258 && destAi.packageName == filterAi.packageName) { 12259 return false; 12260 } 12261 } 12262 return true; 12263 } 12264 12265 @Override 12266 protected ActivityIntentInfo[] newArray(int size) { 12267 return new ActivityIntentInfo[size]; 12268 } 12269 12270 @Override 12271 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12272 if (!sUserManager.exists(userId)) return true; 12273 PackageParser.Package p = filter.activity.owner; 12274 if (p != null) { 12275 PackageSetting ps = (PackageSetting)p.mExtras; 12276 if (ps != null) { 12277 // System apps are never considered stopped for purposes of 12278 // filtering, because there may be no way for the user to 12279 // actually re-launch them. 12280 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12281 && ps.getStopped(userId); 12282 } 12283 } 12284 return false; 12285 } 12286 12287 @Override 12288 protected boolean isPackageForFilter(String packageName, 12289 PackageParser.ActivityIntentInfo info) { 12290 return packageName.equals(info.activity.owner.packageName); 12291 } 12292 12293 @Override 12294 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12295 int match, int userId) { 12296 if (!sUserManager.exists(userId)) return null; 12297 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12298 return null; 12299 } 12300 final PackageParser.Activity activity = info.activity; 12301 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12302 if (ps == null) { 12303 return null; 12304 } 12305 final PackageUserState userState = ps.readUserState(userId); 12306 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12307 userState, userId); 12308 if (ai == null) { 12309 return null; 12310 } 12311 final boolean matchVisibleToInstantApp = 12312 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12313 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12314 // throw out filters that aren't visible to ephemeral apps 12315 if (matchVisibleToInstantApp 12316 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12317 return null; 12318 } 12319 // throw out ephemeral filters if we're not explicitly requesting them 12320 if (!isInstantApp && userState.instantApp) { 12321 return null; 12322 } 12323 // throw out instant app filters if updates are available; will trigger 12324 // instant app resolution 12325 if (userState.instantApp && ps.isUpdateAvailable()) { 12326 return null; 12327 } 12328 final ResolveInfo res = new ResolveInfo(); 12329 res.activityInfo = ai; 12330 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12331 res.filter = info; 12332 } 12333 if (info != null) { 12334 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12335 } 12336 res.priority = info.getPriority(); 12337 res.preferredOrder = activity.owner.mPreferredOrder; 12338 //System.out.println("Result: " + res.activityInfo.className + 12339 // " = " + res.priority); 12340 res.match = match; 12341 res.isDefault = info.hasDefault; 12342 res.labelRes = info.labelRes; 12343 res.nonLocalizedLabel = info.nonLocalizedLabel; 12344 if (userNeedsBadging(userId)) { 12345 res.noResourceId = true; 12346 } else { 12347 res.icon = info.icon; 12348 } 12349 res.iconResourceId = info.icon; 12350 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12351 res.instantAppAvailable = userState.instantApp; 12352 return res; 12353 } 12354 12355 @Override 12356 protected void sortResults(List<ResolveInfo> results) { 12357 Collections.sort(results, mResolvePrioritySorter); 12358 } 12359 12360 @Override 12361 protected void dumpFilter(PrintWriter out, String prefix, 12362 PackageParser.ActivityIntentInfo filter) { 12363 out.print(prefix); out.print( 12364 Integer.toHexString(System.identityHashCode(filter.activity))); 12365 out.print(' '); 12366 filter.activity.printComponentShortName(out); 12367 out.print(" filter "); 12368 out.println(Integer.toHexString(System.identityHashCode(filter))); 12369 } 12370 12371 @Override 12372 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12373 return filter.activity; 12374 } 12375 12376 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12377 PackageParser.Activity activity = (PackageParser.Activity)label; 12378 out.print(prefix); out.print( 12379 Integer.toHexString(System.identityHashCode(activity))); 12380 out.print(' '); 12381 activity.printComponentShortName(out); 12382 if (count > 1) { 12383 out.print(" ("); out.print(count); out.print(" filters)"); 12384 } 12385 out.println(); 12386 } 12387 12388 // Keys are String (activity class name), values are Activity. 12389 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12390 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12391 private int mFlags; 12392 } 12393 12394 private final class ServiceIntentResolver 12395 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12396 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12397 boolean defaultOnly, int userId) { 12398 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12399 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12400 } 12401 12402 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12403 int userId) { 12404 if (!sUserManager.exists(userId)) return null; 12405 mFlags = flags; 12406 return super.queryIntent(intent, resolvedType, 12407 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12408 userId); 12409 } 12410 12411 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12412 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12413 if (!sUserManager.exists(userId)) return null; 12414 if (packageServices == null) { 12415 return null; 12416 } 12417 mFlags = flags; 12418 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12419 final int N = packageServices.size(); 12420 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12421 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12422 12423 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12424 for (int i = 0; i < N; ++i) { 12425 intentFilters = packageServices.get(i).intents; 12426 if (intentFilters != null && intentFilters.size() > 0) { 12427 PackageParser.ServiceIntentInfo[] array = 12428 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12429 intentFilters.toArray(array); 12430 listCut.add(array); 12431 } 12432 } 12433 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12434 } 12435 12436 public final void addService(PackageParser.Service s) { 12437 mServices.put(s.getComponentName(), s); 12438 if (DEBUG_SHOW_INFO) { 12439 Log.v(TAG, " " 12440 + (s.info.nonLocalizedLabel != null 12441 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12442 Log.v(TAG, " Class=" + s.info.name); 12443 } 12444 final int NI = s.intents.size(); 12445 int j; 12446 for (j=0; j<NI; j++) { 12447 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12448 if (DEBUG_SHOW_INFO) { 12449 Log.v(TAG, " IntentFilter:"); 12450 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12451 } 12452 if (!intent.debugCheck()) { 12453 Log.w(TAG, "==> For Service " + s.info.name); 12454 } 12455 addFilter(intent); 12456 } 12457 } 12458 12459 public final void removeService(PackageParser.Service s) { 12460 mServices.remove(s.getComponentName()); 12461 if (DEBUG_SHOW_INFO) { 12462 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12463 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12464 Log.v(TAG, " Class=" + s.info.name); 12465 } 12466 final int NI = s.intents.size(); 12467 int j; 12468 for (j=0; j<NI; j++) { 12469 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12470 if (DEBUG_SHOW_INFO) { 12471 Log.v(TAG, " IntentFilter:"); 12472 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12473 } 12474 removeFilter(intent); 12475 } 12476 } 12477 12478 @Override 12479 protected boolean allowFilterResult( 12480 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12481 ServiceInfo filterSi = filter.service.info; 12482 for (int i=dest.size()-1; i>=0; i--) { 12483 ServiceInfo destAi = dest.get(i).serviceInfo; 12484 if (destAi.name == filterSi.name 12485 && destAi.packageName == filterSi.packageName) { 12486 return false; 12487 } 12488 } 12489 return true; 12490 } 12491 12492 @Override 12493 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12494 return new PackageParser.ServiceIntentInfo[size]; 12495 } 12496 12497 @Override 12498 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12499 if (!sUserManager.exists(userId)) return true; 12500 PackageParser.Package p = filter.service.owner; 12501 if (p != null) { 12502 PackageSetting ps = (PackageSetting)p.mExtras; 12503 if (ps != null) { 12504 // System apps are never considered stopped for purposes of 12505 // filtering, because there may be no way for the user to 12506 // actually re-launch them. 12507 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12508 && ps.getStopped(userId); 12509 } 12510 } 12511 return false; 12512 } 12513 12514 @Override 12515 protected boolean isPackageForFilter(String packageName, 12516 PackageParser.ServiceIntentInfo info) { 12517 return packageName.equals(info.service.owner.packageName); 12518 } 12519 12520 @Override 12521 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12522 int match, int userId) { 12523 if (!sUserManager.exists(userId)) return null; 12524 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12525 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12526 return null; 12527 } 12528 final PackageParser.Service service = info.service; 12529 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12530 if (ps == null) { 12531 return null; 12532 } 12533 final PackageUserState userState = ps.readUserState(userId); 12534 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12535 userState, userId); 12536 if (si == null) { 12537 return null; 12538 } 12539 final boolean matchVisibleToInstantApp = 12540 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12541 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12542 // throw out filters that aren't visible to ephemeral apps 12543 if (matchVisibleToInstantApp 12544 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12545 return null; 12546 } 12547 // throw out ephemeral filters if we're not explicitly requesting them 12548 if (!isInstantApp && userState.instantApp) { 12549 return null; 12550 } 12551 // throw out instant app filters if updates are available; will trigger 12552 // instant app resolution 12553 if (userState.instantApp && ps.isUpdateAvailable()) { 12554 return null; 12555 } 12556 final ResolveInfo res = new ResolveInfo(); 12557 res.serviceInfo = si; 12558 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12559 res.filter = filter; 12560 } 12561 res.priority = info.getPriority(); 12562 res.preferredOrder = service.owner.mPreferredOrder; 12563 res.match = match; 12564 res.isDefault = info.hasDefault; 12565 res.labelRes = info.labelRes; 12566 res.nonLocalizedLabel = info.nonLocalizedLabel; 12567 res.icon = info.icon; 12568 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12569 return res; 12570 } 12571 12572 @Override 12573 protected void sortResults(List<ResolveInfo> results) { 12574 Collections.sort(results, mResolvePrioritySorter); 12575 } 12576 12577 @Override 12578 protected void dumpFilter(PrintWriter out, String prefix, 12579 PackageParser.ServiceIntentInfo filter) { 12580 out.print(prefix); out.print( 12581 Integer.toHexString(System.identityHashCode(filter.service))); 12582 out.print(' '); 12583 filter.service.printComponentShortName(out); 12584 out.print(" filter "); 12585 out.println(Integer.toHexString(System.identityHashCode(filter))); 12586 } 12587 12588 @Override 12589 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12590 return filter.service; 12591 } 12592 12593 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12594 PackageParser.Service service = (PackageParser.Service)label; 12595 out.print(prefix); out.print( 12596 Integer.toHexString(System.identityHashCode(service))); 12597 out.print(' '); 12598 service.printComponentShortName(out); 12599 if (count > 1) { 12600 out.print(" ("); out.print(count); out.print(" filters)"); 12601 } 12602 out.println(); 12603 } 12604 12605// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12606// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12607// final List<ResolveInfo> retList = Lists.newArrayList(); 12608// while (i.hasNext()) { 12609// final ResolveInfo resolveInfo = (ResolveInfo) i; 12610// if (isEnabledLP(resolveInfo.serviceInfo)) { 12611// retList.add(resolveInfo); 12612// } 12613// } 12614// return retList; 12615// } 12616 12617 // Keys are String (activity class name), values are Activity. 12618 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12619 = new ArrayMap<ComponentName, PackageParser.Service>(); 12620 private int mFlags; 12621 } 12622 12623 private final class ProviderIntentResolver 12624 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12625 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12626 boolean defaultOnly, int userId) { 12627 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12628 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12629 } 12630 12631 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12632 int userId) { 12633 if (!sUserManager.exists(userId)) 12634 return null; 12635 mFlags = flags; 12636 return super.queryIntent(intent, resolvedType, 12637 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12638 userId); 12639 } 12640 12641 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12642 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12643 if (!sUserManager.exists(userId)) 12644 return null; 12645 if (packageProviders == null) { 12646 return null; 12647 } 12648 mFlags = flags; 12649 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12650 final int N = packageProviders.size(); 12651 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12652 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12653 12654 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12655 for (int i = 0; i < N; ++i) { 12656 intentFilters = packageProviders.get(i).intents; 12657 if (intentFilters != null && intentFilters.size() > 0) { 12658 PackageParser.ProviderIntentInfo[] array = 12659 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12660 intentFilters.toArray(array); 12661 listCut.add(array); 12662 } 12663 } 12664 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12665 } 12666 12667 public final void addProvider(PackageParser.Provider p) { 12668 if (mProviders.containsKey(p.getComponentName())) { 12669 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12670 return; 12671 } 12672 12673 mProviders.put(p.getComponentName(), p); 12674 if (DEBUG_SHOW_INFO) { 12675 Log.v(TAG, " " 12676 + (p.info.nonLocalizedLabel != null 12677 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12678 Log.v(TAG, " Class=" + p.info.name); 12679 } 12680 final int NI = p.intents.size(); 12681 int j; 12682 for (j = 0; j < NI; j++) { 12683 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12684 if (DEBUG_SHOW_INFO) { 12685 Log.v(TAG, " IntentFilter:"); 12686 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12687 } 12688 if (!intent.debugCheck()) { 12689 Log.w(TAG, "==> For Provider " + p.info.name); 12690 } 12691 addFilter(intent); 12692 } 12693 } 12694 12695 public final void removeProvider(PackageParser.Provider p) { 12696 mProviders.remove(p.getComponentName()); 12697 if (DEBUG_SHOW_INFO) { 12698 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12699 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12700 Log.v(TAG, " Class=" + p.info.name); 12701 } 12702 final int NI = p.intents.size(); 12703 int j; 12704 for (j = 0; j < NI; j++) { 12705 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12706 if (DEBUG_SHOW_INFO) { 12707 Log.v(TAG, " IntentFilter:"); 12708 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12709 } 12710 removeFilter(intent); 12711 } 12712 } 12713 12714 @Override 12715 protected boolean allowFilterResult( 12716 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12717 ProviderInfo filterPi = filter.provider.info; 12718 for (int i = dest.size() - 1; i >= 0; i--) { 12719 ProviderInfo destPi = dest.get(i).providerInfo; 12720 if (destPi.name == filterPi.name 12721 && destPi.packageName == filterPi.packageName) { 12722 return false; 12723 } 12724 } 12725 return true; 12726 } 12727 12728 @Override 12729 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12730 return new PackageParser.ProviderIntentInfo[size]; 12731 } 12732 12733 @Override 12734 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12735 if (!sUserManager.exists(userId)) 12736 return true; 12737 PackageParser.Package p = filter.provider.owner; 12738 if (p != null) { 12739 PackageSetting ps = (PackageSetting) p.mExtras; 12740 if (ps != null) { 12741 // System apps are never considered stopped for purposes of 12742 // filtering, because there may be no way for the user to 12743 // actually re-launch them. 12744 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12745 && ps.getStopped(userId); 12746 } 12747 } 12748 return false; 12749 } 12750 12751 @Override 12752 protected boolean isPackageForFilter(String packageName, 12753 PackageParser.ProviderIntentInfo info) { 12754 return packageName.equals(info.provider.owner.packageName); 12755 } 12756 12757 @Override 12758 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12759 int match, int userId) { 12760 if (!sUserManager.exists(userId)) 12761 return null; 12762 final PackageParser.ProviderIntentInfo info = filter; 12763 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12764 return null; 12765 } 12766 final PackageParser.Provider provider = info.provider; 12767 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12768 if (ps == null) { 12769 return null; 12770 } 12771 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12772 ps.readUserState(userId), userId); 12773 if (pi == null) { 12774 return null; 12775 } 12776 final ResolveInfo res = new ResolveInfo(); 12777 res.providerInfo = pi; 12778 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12779 res.filter = filter; 12780 } 12781 res.priority = info.getPriority(); 12782 res.preferredOrder = provider.owner.mPreferredOrder; 12783 res.match = match; 12784 res.isDefault = info.hasDefault; 12785 res.labelRes = info.labelRes; 12786 res.nonLocalizedLabel = info.nonLocalizedLabel; 12787 res.icon = info.icon; 12788 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12789 return res; 12790 } 12791 12792 @Override 12793 protected void sortResults(List<ResolveInfo> results) { 12794 Collections.sort(results, mResolvePrioritySorter); 12795 } 12796 12797 @Override 12798 protected void dumpFilter(PrintWriter out, String prefix, 12799 PackageParser.ProviderIntentInfo filter) { 12800 out.print(prefix); 12801 out.print( 12802 Integer.toHexString(System.identityHashCode(filter.provider))); 12803 out.print(' '); 12804 filter.provider.printComponentShortName(out); 12805 out.print(" filter "); 12806 out.println(Integer.toHexString(System.identityHashCode(filter))); 12807 } 12808 12809 @Override 12810 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12811 return filter.provider; 12812 } 12813 12814 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12815 PackageParser.Provider provider = (PackageParser.Provider)label; 12816 out.print(prefix); out.print( 12817 Integer.toHexString(System.identityHashCode(provider))); 12818 out.print(' '); 12819 provider.printComponentShortName(out); 12820 if (count > 1) { 12821 out.print(" ("); out.print(count); out.print(" filters)"); 12822 } 12823 out.println(); 12824 } 12825 12826 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12827 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12828 private int mFlags; 12829 } 12830 12831 static final class EphemeralIntentResolver 12832 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12833 /** 12834 * The result that has the highest defined order. Ordering applies on a 12835 * per-package basis. Mapping is from package name to Pair of order and 12836 * EphemeralResolveInfo. 12837 * <p> 12838 * NOTE: This is implemented as a field variable for convenience and efficiency. 12839 * By having a field variable, we're able to track filter ordering as soon as 12840 * a non-zero order is defined. Otherwise, multiple loops across the result set 12841 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12842 * this needs to be contained entirely within {@link #filterResults}. 12843 */ 12844 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12845 12846 @Override 12847 protected AuxiliaryResolveInfo[] newArray(int size) { 12848 return new AuxiliaryResolveInfo[size]; 12849 } 12850 12851 @Override 12852 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12853 return true; 12854 } 12855 12856 @Override 12857 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12858 int userId) { 12859 if (!sUserManager.exists(userId)) { 12860 return null; 12861 } 12862 final String packageName = responseObj.resolveInfo.getPackageName(); 12863 final Integer order = responseObj.getOrder(); 12864 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12865 mOrderResult.get(packageName); 12866 // ordering is enabled and this item's order isn't high enough 12867 if (lastOrderResult != null && lastOrderResult.first >= order) { 12868 return null; 12869 } 12870 final InstantAppResolveInfo res = responseObj.resolveInfo; 12871 if (order > 0) { 12872 // non-zero order, enable ordering 12873 mOrderResult.put(packageName, new Pair<>(order, res)); 12874 } 12875 return responseObj; 12876 } 12877 12878 @Override 12879 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12880 // only do work if ordering is enabled [most of the time it won't be] 12881 if (mOrderResult.size() == 0) { 12882 return; 12883 } 12884 int resultSize = results.size(); 12885 for (int i = 0; i < resultSize; i++) { 12886 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12887 final String packageName = info.getPackageName(); 12888 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12889 if (savedInfo == null) { 12890 // package doesn't having ordering 12891 continue; 12892 } 12893 if (savedInfo.second == info) { 12894 // circled back to the highest ordered item; remove from order list 12895 mOrderResult.remove(savedInfo); 12896 if (mOrderResult.size() == 0) { 12897 // no more ordered items 12898 break; 12899 } 12900 continue; 12901 } 12902 // item has a worse order, remove it from the result list 12903 results.remove(i); 12904 resultSize--; 12905 i--; 12906 } 12907 } 12908 } 12909 12910 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12911 new Comparator<ResolveInfo>() { 12912 public int compare(ResolveInfo r1, ResolveInfo r2) { 12913 int v1 = r1.priority; 12914 int v2 = r2.priority; 12915 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12916 if (v1 != v2) { 12917 return (v1 > v2) ? -1 : 1; 12918 } 12919 v1 = r1.preferredOrder; 12920 v2 = r2.preferredOrder; 12921 if (v1 != v2) { 12922 return (v1 > v2) ? -1 : 1; 12923 } 12924 if (r1.isDefault != r2.isDefault) { 12925 return r1.isDefault ? -1 : 1; 12926 } 12927 v1 = r1.match; 12928 v2 = r2.match; 12929 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12930 if (v1 != v2) { 12931 return (v1 > v2) ? -1 : 1; 12932 } 12933 if (r1.system != r2.system) { 12934 return r1.system ? -1 : 1; 12935 } 12936 if (r1.activityInfo != null) { 12937 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12938 } 12939 if (r1.serviceInfo != null) { 12940 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12941 } 12942 if (r1.providerInfo != null) { 12943 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12944 } 12945 return 0; 12946 } 12947 }; 12948 12949 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12950 new Comparator<ProviderInfo>() { 12951 public int compare(ProviderInfo p1, ProviderInfo p2) { 12952 final int v1 = p1.initOrder; 12953 final int v2 = p2.initOrder; 12954 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12955 } 12956 }; 12957 12958 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12959 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12960 final int[] userIds) { 12961 mHandler.post(new Runnable() { 12962 @Override 12963 public void run() { 12964 try { 12965 final IActivityManager am = ActivityManager.getService(); 12966 if (am == null) return; 12967 final int[] resolvedUserIds; 12968 if (userIds == null) { 12969 resolvedUserIds = am.getRunningUserIds(); 12970 } else { 12971 resolvedUserIds = userIds; 12972 } 12973 for (int id : resolvedUserIds) { 12974 final Intent intent = new Intent(action, 12975 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12976 if (extras != null) { 12977 intent.putExtras(extras); 12978 } 12979 if (targetPkg != null) { 12980 intent.setPackage(targetPkg); 12981 } 12982 // Modify the UID when posting to other users 12983 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12984 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12985 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12986 intent.putExtra(Intent.EXTRA_UID, uid); 12987 } 12988 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12989 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12990 if (DEBUG_BROADCASTS) { 12991 RuntimeException here = new RuntimeException("here"); 12992 here.fillInStackTrace(); 12993 Slog.d(TAG, "Sending to user " + id + ": " 12994 + intent.toShortString(false, true, false, false) 12995 + " " + intent.getExtras(), here); 12996 } 12997 am.broadcastIntent(null, intent, null, finishedReceiver, 12998 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12999 null, finishedReceiver != null, false, id); 13000 } 13001 } catch (RemoteException ex) { 13002 } 13003 } 13004 }); 13005 } 13006 13007 /** 13008 * Check if the external storage media is available. This is true if there 13009 * is a mounted external storage medium or if the external storage is 13010 * emulated. 13011 */ 13012 private boolean isExternalMediaAvailable() { 13013 return mMediaMounted || Environment.isExternalStorageEmulated(); 13014 } 13015 13016 @Override 13017 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13018 // writer 13019 synchronized (mPackages) { 13020 if (!isExternalMediaAvailable()) { 13021 // If the external storage is no longer mounted at this point, 13022 // the caller may not have been able to delete all of this 13023 // packages files and can not delete any more. Bail. 13024 return null; 13025 } 13026 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13027 if (lastPackage != null) { 13028 pkgs.remove(lastPackage); 13029 } 13030 if (pkgs.size() > 0) { 13031 return pkgs.get(0); 13032 } 13033 } 13034 return null; 13035 } 13036 13037 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13038 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13039 userId, andCode ? 1 : 0, packageName); 13040 if (mSystemReady) { 13041 msg.sendToTarget(); 13042 } else { 13043 if (mPostSystemReadyMessages == null) { 13044 mPostSystemReadyMessages = new ArrayList<>(); 13045 } 13046 mPostSystemReadyMessages.add(msg); 13047 } 13048 } 13049 13050 void startCleaningPackages() { 13051 // reader 13052 if (!isExternalMediaAvailable()) { 13053 return; 13054 } 13055 synchronized (mPackages) { 13056 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13057 return; 13058 } 13059 } 13060 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13061 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13062 IActivityManager am = ActivityManager.getService(); 13063 if (am != null) { 13064 int dcsUid = -1; 13065 synchronized (mPackages) { 13066 if (!mDefaultContainerWhitelisted) { 13067 mDefaultContainerWhitelisted = true; 13068 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13069 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13070 } 13071 } 13072 try { 13073 if (dcsUid > 0) { 13074 am.backgroundWhitelistUid(dcsUid); 13075 } 13076 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13077 UserHandle.USER_SYSTEM); 13078 } catch (RemoteException e) { 13079 } 13080 } 13081 } 13082 13083 @Override 13084 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13085 int installFlags, String installerPackageName, int userId) { 13086 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13087 13088 final int callingUid = Binder.getCallingUid(); 13089 enforceCrossUserPermission(callingUid, userId, 13090 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13091 13092 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13093 try { 13094 if (observer != null) { 13095 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13096 } 13097 } catch (RemoteException re) { 13098 } 13099 return; 13100 } 13101 13102 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13103 installFlags |= PackageManager.INSTALL_FROM_ADB; 13104 13105 } else { 13106 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13107 // about installerPackageName. 13108 13109 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13110 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13111 } 13112 13113 UserHandle user; 13114 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13115 user = UserHandle.ALL; 13116 } else { 13117 user = new UserHandle(userId); 13118 } 13119 13120 // Only system components can circumvent runtime permissions when installing. 13121 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13122 && mContext.checkCallingOrSelfPermission(Manifest.permission 13123 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13124 throw new SecurityException("You need the " 13125 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13126 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13127 } 13128 13129 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13130 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13131 throw new IllegalArgumentException( 13132 "New installs into ASEC containers no longer supported"); 13133 } 13134 13135 final File originFile = new File(originPath); 13136 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13137 13138 final Message msg = mHandler.obtainMessage(INIT_COPY); 13139 final VerificationInfo verificationInfo = new VerificationInfo( 13140 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13141 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13142 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13143 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13144 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13145 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13146 msg.obj = params; 13147 13148 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13149 System.identityHashCode(msg.obj)); 13150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13151 System.identityHashCode(msg.obj)); 13152 13153 mHandler.sendMessage(msg); 13154 } 13155 13156 13157 /** 13158 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13159 * it is acting on behalf on an enterprise or the user). 13160 * 13161 * Note that the ordering of the conditionals in this method is important. The checks we perform 13162 * are as follows, in this order: 13163 * 13164 * 1) If the install is being performed by a system app, we can trust the app to have set the 13165 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13166 * what it is. 13167 * 2) If the install is being performed by a device or profile owner app, the install reason 13168 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13169 * set the install reason correctly. If the app targets an older SDK version where install 13170 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13171 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13172 * 3) In all other cases, the install is being performed by a regular app that is neither part 13173 * of the system nor a device or profile owner. We have no reason to believe that this app is 13174 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13175 * set to enterprise policy and if so, change it to unknown instead. 13176 */ 13177 private int fixUpInstallReason(String installerPackageName, int installerUid, 13178 int installReason) { 13179 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13180 == PERMISSION_GRANTED) { 13181 // If the install is being performed by a system app, we trust that app to have set the 13182 // install reason correctly. 13183 return installReason; 13184 } 13185 13186 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13187 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13188 if (dpm != null) { 13189 ComponentName owner = null; 13190 try { 13191 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13192 if (owner == null) { 13193 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13194 } 13195 } catch (RemoteException e) { 13196 } 13197 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13198 // If the install is being performed by a device or profile owner, the install 13199 // reason should be enterprise policy. 13200 return PackageManager.INSTALL_REASON_POLICY; 13201 } 13202 } 13203 13204 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13205 // If the install is being performed by a regular app (i.e. neither system app nor 13206 // device or profile owner), we have no reason to believe that the app is acting on 13207 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13208 // change it to unknown instead. 13209 return PackageManager.INSTALL_REASON_UNKNOWN; 13210 } 13211 13212 // If the install is being performed by a regular app and the install reason was set to any 13213 // value but enterprise policy, leave the install reason unchanged. 13214 return installReason; 13215 } 13216 13217 void installStage(String packageName, File stagedDir, String stagedCid, 13218 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13219 String installerPackageName, int installerUid, UserHandle user, 13220 Certificate[][] certificates) { 13221 if (DEBUG_EPHEMERAL) { 13222 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13223 Slog.d(TAG, "Ephemeral install of " + packageName); 13224 } 13225 } 13226 final VerificationInfo verificationInfo = new VerificationInfo( 13227 sessionParams.originatingUri, sessionParams.referrerUri, 13228 sessionParams.originatingUid, installerUid); 13229 13230 final OriginInfo origin; 13231 if (stagedDir != null) { 13232 origin = OriginInfo.fromStagedFile(stagedDir); 13233 } else { 13234 origin = OriginInfo.fromStagedContainer(stagedCid); 13235 } 13236 13237 final Message msg = mHandler.obtainMessage(INIT_COPY); 13238 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13239 sessionParams.installReason); 13240 final InstallParams params = new InstallParams(origin, null, observer, 13241 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13242 verificationInfo, user, sessionParams.abiOverride, 13243 sessionParams.grantedRuntimePermissions, certificates, installReason); 13244 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13245 msg.obj = params; 13246 13247 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13248 System.identityHashCode(msg.obj)); 13249 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13250 System.identityHashCode(msg.obj)); 13251 13252 mHandler.sendMessage(msg); 13253 } 13254 13255 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13256 int userId) { 13257 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13258 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13259 } 13260 13261 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13262 int appId, int... userIds) { 13263 if (ArrayUtils.isEmpty(userIds)) { 13264 return; 13265 } 13266 Bundle extras = new Bundle(1); 13267 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13268 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13269 13270 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13271 packageName, extras, 0, null, null, userIds); 13272 if (isSystem) { 13273 mHandler.post(() -> { 13274 for (int userId : userIds) { 13275 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13276 } 13277 } 13278 ); 13279 } 13280 } 13281 13282 /** 13283 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13284 * automatically without needing an explicit launch. 13285 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13286 */ 13287 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13288 // If user is not running, the app didn't miss any broadcast 13289 if (!mUserManagerInternal.isUserRunning(userId)) { 13290 return; 13291 } 13292 final IActivityManager am = ActivityManager.getService(); 13293 try { 13294 // Deliver LOCKED_BOOT_COMPLETED first 13295 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13296 .setPackage(packageName); 13297 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13298 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13299 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13300 13301 // Deliver BOOT_COMPLETED only if user is unlocked 13302 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13303 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13304 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13305 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13306 } 13307 } catch (RemoteException e) { 13308 throw e.rethrowFromSystemServer(); 13309 } 13310 } 13311 13312 @Override 13313 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13314 int userId) { 13315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13316 PackageSetting pkgSetting; 13317 final int uid = Binder.getCallingUid(); 13318 enforceCrossUserPermission(uid, userId, 13319 true /* requireFullPermission */, true /* checkShell */, 13320 "setApplicationHiddenSetting for user " + userId); 13321 13322 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13323 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13324 return false; 13325 } 13326 13327 long callingId = Binder.clearCallingIdentity(); 13328 try { 13329 boolean sendAdded = false; 13330 boolean sendRemoved = false; 13331 // writer 13332 synchronized (mPackages) { 13333 pkgSetting = mSettings.mPackages.get(packageName); 13334 if (pkgSetting == null) { 13335 return false; 13336 } 13337 // Do not allow "android" is being disabled 13338 if ("android".equals(packageName)) { 13339 Slog.w(TAG, "Cannot hide package: android"); 13340 return false; 13341 } 13342 // Cannot hide static shared libs as they are considered 13343 // a part of the using app (emulating static linking). Also 13344 // static libs are installed always on internal storage. 13345 PackageParser.Package pkg = mPackages.get(packageName); 13346 if (pkg != null && pkg.staticSharedLibName != null) { 13347 Slog.w(TAG, "Cannot hide package: " + packageName 13348 + " providing static shared library: " 13349 + pkg.staticSharedLibName); 13350 return false; 13351 } 13352 // Only allow protected packages to hide themselves. 13353 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13354 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13355 Slog.w(TAG, "Not hiding protected package: " + packageName); 13356 return false; 13357 } 13358 13359 if (pkgSetting.getHidden(userId) != hidden) { 13360 pkgSetting.setHidden(hidden, userId); 13361 mSettings.writePackageRestrictionsLPr(userId); 13362 if (hidden) { 13363 sendRemoved = true; 13364 } else { 13365 sendAdded = true; 13366 } 13367 } 13368 } 13369 if (sendAdded) { 13370 sendPackageAddedForUser(packageName, pkgSetting, userId); 13371 return true; 13372 } 13373 if (sendRemoved) { 13374 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13375 "hiding pkg"); 13376 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13377 return true; 13378 } 13379 } finally { 13380 Binder.restoreCallingIdentity(callingId); 13381 } 13382 return false; 13383 } 13384 13385 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13386 int userId) { 13387 final PackageRemovedInfo info = new PackageRemovedInfo(); 13388 info.removedPackage = packageName; 13389 info.removedUsers = new int[] {userId}; 13390 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13391 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13392 } 13393 13394 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13395 if (pkgList.length > 0) { 13396 Bundle extras = new Bundle(1); 13397 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13398 13399 sendPackageBroadcast( 13400 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13401 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13402 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13403 new int[] {userId}); 13404 } 13405 } 13406 13407 /** 13408 * Returns true if application is not found or there was an error. Otherwise it returns 13409 * the hidden state of the package for the given user. 13410 */ 13411 @Override 13412 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13413 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13415 true /* requireFullPermission */, false /* checkShell */, 13416 "getApplicationHidden for user " + userId); 13417 PackageSetting pkgSetting; 13418 long callingId = Binder.clearCallingIdentity(); 13419 try { 13420 // writer 13421 synchronized (mPackages) { 13422 pkgSetting = mSettings.mPackages.get(packageName); 13423 if (pkgSetting == null) { 13424 return true; 13425 } 13426 return pkgSetting.getHidden(userId); 13427 } 13428 } finally { 13429 Binder.restoreCallingIdentity(callingId); 13430 } 13431 } 13432 13433 /** 13434 * @hide 13435 */ 13436 @Override 13437 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13438 int installReason) { 13439 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13440 null); 13441 PackageSetting pkgSetting; 13442 final int uid = Binder.getCallingUid(); 13443 enforceCrossUserPermission(uid, userId, 13444 true /* requireFullPermission */, true /* checkShell */, 13445 "installExistingPackage for user " + userId); 13446 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13447 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13448 } 13449 13450 long callingId = Binder.clearCallingIdentity(); 13451 try { 13452 boolean installed = false; 13453 final boolean instantApp = 13454 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13455 final boolean fullApp = 13456 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13457 13458 // writer 13459 synchronized (mPackages) { 13460 pkgSetting = mSettings.mPackages.get(packageName); 13461 if (pkgSetting == null) { 13462 return PackageManager.INSTALL_FAILED_INVALID_URI; 13463 } 13464 if (!pkgSetting.getInstalled(userId)) { 13465 pkgSetting.setInstalled(true, userId); 13466 pkgSetting.setHidden(false, userId); 13467 pkgSetting.setInstallReason(installReason, userId); 13468 mSettings.writePackageRestrictionsLPr(userId); 13469 mSettings.writeKernelMappingLPr(pkgSetting); 13470 installed = true; 13471 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13472 // upgrade app from instant to full; we don't allow app downgrade 13473 installed = true; 13474 } 13475 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13476 } 13477 13478 if (installed) { 13479 if (pkgSetting.pkg != null) { 13480 synchronized (mInstallLock) { 13481 // We don't need to freeze for a brand new install 13482 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13483 } 13484 } 13485 sendPackageAddedForUser(packageName, pkgSetting, userId); 13486 synchronized (mPackages) { 13487 updateSequenceNumberLP(packageName, new int[]{ userId }); 13488 } 13489 } 13490 } finally { 13491 Binder.restoreCallingIdentity(callingId); 13492 } 13493 13494 return PackageManager.INSTALL_SUCCEEDED; 13495 } 13496 13497 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13498 boolean instantApp, boolean fullApp) { 13499 // no state specified; do nothing 13500 if (!instantApp && !fullApp) { 13501 return; 13502 } 13503 if (userId != UserHandle.USER_ALL) { 13504 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13505 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13506 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13507 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13508 } 13509 } else { 13510 for (int currentUserId : sUserManager.getUserIds()) { 13511 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13512 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13513 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13514 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13515 } 13516 } 13517 } 13518 } 13519 13520 boolean isUserRestricted(int userId, String restrictionKey) { 13521 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13522 if (restrictions.getBoolean(restrictionKey, false)) { 13523 Log.w(TAG, "User is restricted: " + restrictionKey); 13524 return true; 13525 } 13526 return false; 13527 } 13528 13529 @Override 13530 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13531 int userId) { 13532 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13533 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13534 true /* requireFullPermission */, true /* checkShell */, 13535 "setPackagesSuspended for user " + userId); 13536 13537 if (ArrayUtils.isEmpty(packageNames)) { 13538 return packageNames; 13539 } 13540 13541 // List of package names for whom the suspended state has changed. 13542 List<String> changedPackages = new ArrayList<>(packageNames.length); 13543 // List of package names for whom the suspended state is not set as requested in this 13544 // method. 13545 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13546 long callingId = Binder.clearCallingIdentity(); 13547 try { 13548 for (int i = 0; i < packageNames.length; i++) { 13549 String packageName = packageNames[i]; 13550 boolean changed = false; 13551 final int appId; 13552 synchronized (mPackages) { 13553 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13554 if (pkgSetting == null) { 13555 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13556 + "\". Skipping suspending/un-suspending."); 13557 unactionedPackages.add(packageName); 13558 continue; 13559 } 13560 appId = pkgSetting.appId; 13561 if (pkgSetting.getSuspended(userId) != suspended) { 13562 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13563 unactionedPackages.add(packageName); 13564 continue; 13565 } 13566 pkgSetting.setSuspended(suspended, userId); 13567 mSettings.writePackageRestrictionsLPr(userId); 13568 changed = true; 13569 changedPackages.add(packageName); 13570 } 13571 } 13572 13573 if (changed && suspended) { 13574 killApplication(packageName, UserHandle.getUid(userId, appId), 13575 "suspending package"); 13576 } 13577 } 13578 } finally { 13579 Binder.restoreCallingIdentity(callingId); 13580 } 13581 13582 if (!changedPackages.isEmpty()) { 13583 sendPackagesSuspendedForUser(changedPackages.toArray( 13584 new String[changedPackages.size()]), userId, suspended); 13585 } 13586 13587 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13588 } 13589 13590 @Override 13591 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13592 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13593 true /* requireFullPermission */, false /* checkShell */, 13594 "isPackageSuspendedForUser for user " + userId); 13595 synchronized (mPackages) { 13596 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13597 if (pkgSetting == null) { 13598 throw new IllegalArgumentException("Unknown target package: " + packageName); 13599 } 13600 return pkgSetting.getSuspended(userId); 13601 } 13602 } 13603 13604 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13605 if (isPackageDeviceAdmin(packageName, userId)) { 13606 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13607 + "\": has an active device admin"); 13608 return false; 13609 } 13610 13611 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13612 if (packageName.equals(activeLauncherPackageName)) { 13613 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13614 + "\": contains the active launcher"); 13615 return false; 13616 } 13617 13618 if (packageName.equals(mRequiredInstallerPackage)) { 13619 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13620 + "\": required for package installation"); 13621 return false; 13622 } 13623 13624 if (packageName.equals(mRequiredUninstallerPackage)) { 13625 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13626 + "\": required for package uninstallation"); 13627 return false; 13628 } 13629 13630 if (packageName.equals(mRequiredVerifierPackage)) { 13631 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13632 + "\": required for package verification"); 13633 return false; 13634 } 13635 13636 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13637 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13638 + "\": is the default dialer"); 13639 return false; 13640 } 13641 13642 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13643 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13644 + "\": protected package"); 13645 return false; 13646 } 13647 13648 // Cannot suspend static shared libs as they are considered 13649 // a part of the using app (emulating static linking). Also 13650 // static libs are installed always on internal storage. 13651 PackageParser.Package pkg = mPackages.get(packageName); 13652 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13653 Slog.w(TAG, "Cannot suspend package: " + packageName 13654 + " providing static shared library: " 13655 + pkg.staticSharedLibName); 13656 return false; 13657 } 13658 13659 return true; 13660 } 13661 13662 private String getActiveLauncherPackageName(int userId) { 13663 Intent intent = new Intent(Intent.ACTION_MAIN); 13664 intent.addCategory(Intent.CATEGORY_HOME); 13665 ResolveInfo resolveInfo = resolveIntent( 13666 intent, 13667 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13668 PackageManager.MATCH_DEFAULT_ONLY, 13669 userId); 13670 13671 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13672 } 13673 13674 private String getDefaultDialerPackageName(int userId) { 13675 synchronized (mPackages) { 13676 return mSettings.getDefaultDialerPackageNameLPw(userId); 13677 } 13678 } 13679 13680 @Override 13681 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13682 mContext.enforceCallingOrSelfPermission( 13683 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13684 "Only package verification agents can verify applications"); 13685 13686 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13687 final PackageVerificationResponse response = new PackageVerificationResponse( 13688 verificationCode, Binder.getCallingUid()); 13689 msg.arg1 = id; 13690 msg.obj = response; 13691 mHandler.sendMessage(msg); 13692 } 13693 13694 @Override 13695 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13696 long millisecondsToDelay) { 13697 mContext.enforceCallingOrSelfPermission( 13698 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13699 "Only package verification agents can extend verification timeouts"); 13700 13701 final PackageVerificationState state = mPendingVerification.get(id); 13702 final PackageVerificationResponse response = new PackageVerificationResponse( 13703 verificationCodeAtTimeout, Binder.getCallingUid()); 13704 13705 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13706 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13707 } 13708 if (millisecondsToDelay < 0) { 13709 millisecondsToDelay = 0; 13710 } 13711 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13712 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13713 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13714 } 13715 13716 if ((state != null) && !state.timeoutExtended()) { 13717 state.extendTimeout(); 13718 13719 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13720 msg.arg1 = id; 13721 msg.obj = response; 13722 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13723 } 13724 } 13725 13726 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13727 int verificationCode, UserHandle user) { 13728 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13729 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13730 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13731 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13732 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13733 13734 mContext.sendBroadcastAsUser(intent, user, 13735 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13736 } 13737 13738 private ComponentName matchComponentForVerifier(String packageName, 13739 List<ResolveInfo> receivers) { 13740 ActivityInfo targetReceiver = null; 13741 13742 final int NR = receivers.size(); 13743 for (int i = 0; i < NR; i++) { 13744 final ResolveInfo info = receivers.get(i); 13745 if (info.activityInfo == null) { 13746 continue; 13747 } 13748 13749 if (packageName.equals(info.activityInfo.packageName)) { 13750 targetReceiver = info.activityInfo; 13751 break; 13752 } 13753 } 13754 13755 if (targetReceiver == null) { 13756 return null; 13757 } 13758 13759 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13760 } 13761 13762 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13763 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13764 if (pkgInfo.verifiers.length == 0) { 13765 return null; 13766 } 13767 13768 final int N = pkgInfo.verifiers.length; 13769 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13770 for (int i = 0; i < N; i++) { 13771 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13772 13773 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13774 receivers); 13775 if (comp == null) { 13776 continue; 13777 } 13778 13779 final int verifierUid = getUidForVerifier(verifierInfo); 13780 if (verifierUid == -1) { 13781 continue; 13782 } 13783 13784 if (DEBUG_VERIFY) { 13785 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13786 + " with the correct signature"); 13787 } 13788 sufficientVerifiers.add(comp); 13789 verificationState.addSufficientVerifier(verifierUid); 13790 } 13791 13792 return sufficientVerifiers; 13793 } 13794 13795 private int getUidForVerifier(VerifierInfo verifierInfo) { 13796 synchronized (mPackages) { 13797 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13798 if (pkg == null) { 13799 return -1; 13800 } else if (pkg.mSignatures.length != 1) { 13801 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13802 + " has more than one signature; ignoring"); 13803 return -1; 13804 } 13805 13806 /* 13807 * If the public key of the package's signature does not match 13808 * our expected public key, then this is a different package and 13809 * we should skip. 13810 */ 13811 13812 final byte[] expectedPublicKey; 13813 try { 13814 final Signature verifierSig = pkg.mSignatures[0]; 13815 final PublicKey publicKey = verifierSig.getPublicKey(); 13816 expectedPublicKey = publicKey.getEncoded(); 13817 } catch (CertificateException e) { 13818 return -1; 13819 } 13820 13821 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13822 13823 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13824 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13825 + " does not have the expected public key; ignoring"); 13826 return -1; 13827 } 13828 13829 return pkg.applicationInfo.uid; 13830 } 13831 } 13832 13833 @Override 13834 public void finishPackageInstall(int token, boolean didLaunch) { 13835 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13836 13837 if (DEBUG_INSTALL) { 13838 Slog.v(TAG, "BM finishing package install for " + token); 13839 } 13840 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13841 13842 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13843 mHandler.sendMessage(msg); 13844 } 13845 13846 /** 13847 * Get the verification agent timeout. 13848 * 13849 * @return verification timeout in milliseconds 13850 */ 13851 private long getVerificationTimeout() { 13852 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13853 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13854 DEFAULT_VERIFICATION_TIMEOUT); 13855 } 13856 13857 /** 13858 * Get the default verification agent response code. 13859 * 13860 * @return default verification response code 13861 */ 13862 private int getDefaultVerificationResponse() { 13863 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13864 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13865 DEFAULT_VERIFICATION_RESPONSE); 13866 } 13867 13868 /** 13869 * Check whether or not package verification has been enabled. 13870 * 13871 * @return true if verification should be performed 13872 */ 13873 private boolean isVerificationEnabled(int userId, int installFlags) { 13874 if (!DEFAULT_VERIFY_ENABLE) { 13875 return false; 13876 } 13877 13878 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13879 13880 // Check if installing from ADB 13881 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13882 // Do not run verification in a test harness environment 13883 if (ActivityManager.isRunningInTestHarness()) { 13884 return false; 13885 } 13886 if (ensureVerifyAppsEnabled) { 13887 return true; 13888 } 13889 // Check if the developer does not want package verification for ADB installs 13890 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13891 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13892 return false; 13893 } 13894 } 13895 13896 if (ensureVerifyAppsEnabled) { 13897 return true; 13898 } 13899 13900 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13901 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13902 } 13903 13904 @Override 13905 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13906 throws RemoteException { 13907 mContext.enforceCallingOrSelfPermission( 13908 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13909 "Only intentfilter verification agents can verify applications"); 13910 13911 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13912 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13913 Binder.getCallingUid(), verificationCode, failedDomains); 13914 msg.arg1 = id; 13915 msg.obj = response; 13916 mHandler.sendMessage(msg); 13917 } 13918 13919 @Override 13920 public int getIntentVerificationStatus(String packageName, int userId) { 13921 synchronized (mPackages) { 13922 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13923 } 13924 } 13925 13926 @Override 13927 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13928 mContext.enforceCallingOrSelfPermission( 13929 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13930 13931 boolean result = false; 13932 synchronized (mPackages) { 13933 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13934 } 13935 if (result) { 13936 scheduleWritePackageRestrictionsLocked(userId); 13937 } 13938 return result; 13939 } 13940 13941 @Override 13942 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13943 String packageName) { 13944 synchronized (mPackages) { 13945 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13946 } 13947 } 13948 13949 @Override 13950 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13951 if (TextUtils.isEmpty(packageName)) { 13952 return ParceledListSlice.emptyList(); 13953 } 13954 synchronized (mPackages) { 13955 PackageParser.Package pkg = mPackages.get(packageName); 13956 if (pkg == null || pkg.activities == null) { 13957 return ParceledListSlice.emptyList(); 13958 } 13959 final int count = pkg.activities.size(); 13960 ArrayList<IntentFilter> result = new ArrayList<>(); 13961 for (int n=0; n<count; n++) { 13962 PackageParser.Activity activity = pkg.activities.get(n); 13963 if (activity.intents != null && activity.intents.size() > 0) { 13964 result.addAll(activity.intents); 13965 } 13966 } 13967 return new ParceledListSlice<>(result); 13968 } 13969 } 13970 13971 @Override 13972 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13973 mContext.enforceCallingOrSelfPermission( 13974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13975 13976 synchronized (mPackages) { 13977 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13978 if (packageName != null) { 13979 result |= updateIntentVerificationStatus(packageName, 13980 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13981 userId); 13982 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13983 packageName, userId); 13984 } 13985 return result; 13986 } 13987 } 13988 13989 @Override 13990 public String getDefaultBrowserPackageName(int userId) { 13991 synchronized (mPackages) { 13992 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13993 } 13994 } 13995 13996 /** 13997 * Get the "allow unknown sources" setting. 13998 * 13999 * @return the current "allow unknown sources" setting 14000 */ 14001 private int getUnknownSourcesSettings() { 14002 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14003 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14004 -1); 14005 } 14006 14007 @Override 14008 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14009 final int uid = Binder.getCallingUid(); 14010 // writer 14011 synchronized (mPackages) { 14012 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14013 if (targetPackageSetting == null) { 14014 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14015 } 14016 14017 PackageSetting installerPackageSetting; 14018 if (installerPackageName != null) { 14019 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14020 if (installerPackageSetting == null) { 14021 throw new IllegalArgumentException("Unknown installer package: " 14022 + installerPackageName); 14023 } 14024 } else { 14025 installerPackageSetting = null; 14026 } 14027 14028 Signature[] callerSignature; 14029 Object obj = mSettings.getUserIdLPr(uid); 14030 if (obj != null) { 14031 if (obj instanceof SharedUserSetting) { 14032 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14033 } else if (obj instanceof PackageSetting) { 14034 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14035 } else { 14036 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14037 } 14038 } else { 14039 throw new SecurityException("Unknown calling UID: " + uid); 14040 } 14041 14042 // Verify: can't set installerPackageName to a package that is 14043 // not signed with the same cert as the caller. 14044 if (installerPackageSetting != null) { 14045 if (compareSignatures(callerSignature, 14046 installerPackageSetting.signatures.mSignatures) 14047 != PackageManager.SIGNATURE_MATCH) { 14048 throw new SecurityException( 14049 "Caller does not have same cert as new installer package " 14050 + installerPackageName); 14051 } 14052 } 14053 14054 // Verify: if target already has an installer package, it must 14055 // be signed with the same cert as the caller. 14056 if (targetPackageSetting.installerPackageName != null) { 14057 PackageSetting setting = mSettings.mPackages.get( 14058 targetPackageSetting.installerPackageName); 14059 // If the currently set package isn't valid, then it's always 14060 // okay to change it. 14061 if (setting != null) { 14062 if (compareSignatures(callerSignature, 14063 setting.signatures.mSignatures) 14064 != PackageManager.SIGNATURE_MATCH) { 14065 throw new SecurityException( 14066 "Caller does not have same cert as old installer package " 14067 + targetPackageSetting.installerPackageName); 14068 } 14069 } 14070 } 14071 14072 // Okay! 14073 targetPackageSetting.installerPackageName = installerPackageName; 14074 if (installerPackageName != null) { 14075 mSettings.mInstallerPackages.add(installerPackageName); 14076 } 14077 scheduleWriteSettingsLocked(); 14078 } 14079 } 14080 14081 @Override 14082 public void setApplicationCategoryHint(String packageName, int categoryHint, 14083 String callerPackageName) { 14084 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14085 callerPackageName); 14086 synchronized (mPackages) { 14087 PackageSetting ps = mSettings.mPackages.get(packageName); 14088 if (ps == null) { 14089 throw new IllegalArgumentException("Unknown target package " + packageName); 14090 } 14091 14092 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14093 throw new IllegalArgumentException("Calling package " + callerPackageName 14094 + " is not installer for " + packageName); 14095 } 14096 14097 if (ps.categoryHint != categoryHint) { 14098 ps.categoryHint = categoryHint; 14099 scheduleWriteSettingsLocked(); 14100 } 14101 } 14102 } 14103 14104 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14105 // Queue up an async operation since the package installation may take a little while. 14106 mHandler.post(new Runnable() { 14107 public void run() { 14108 mHandler.removeCallbacks(this); 14109 // Result object to be returned 14110 PackageInstalledInfo res = new PackageInstalledInfo(); 14111 res.setReturnCode(currentStatus); 14112 res.uid = -1; 14113 res.pkg = null; 14114 res.removedInfo = null; 14115 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14116 args.doPreInstall(res.returnCode); 14117 synchronized (mInstallLock) { 14118 installPackageTracedLI(args, res); 14119 } 14120 args.doPostInstall(res.returnCode, res.uid); 14121 } 14122 14123 // A restore should be performed at this point if (a) the install 14124 // succeeded, (b) the operation is not an update, and (c) the new 14125 // package has not opted out of backup participation. 14126 final boolean update = res.removedInfo != null 14127 && res.removedInfo.removedPackage != null; 14128 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14129 boolean doRestore = !update 14130 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14131 14132 // Set up the post-install work request bookkeeping. This will be used 14133 // and cleaned up by the post-install event handling regardless of whether 14134 // there's a restore pass performed. Token values are >= 1. 14135 int token; 14136 if (mNextInstallToken < 0) mNextInstallToken = 1; 14137 token = mNextInstallToken++; 14138 14139 PostInstallData data = new PostInstallData(args, res); 14140 mRunningInstalls.put(token, data); 14141 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14142 14143 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14144 // Pass responsibility to the Backup Manager. It will perform a 14145 // restore if appropriate, then pass responsibility back to the 14146 // Package Manager to run the post-install observer callbacks 14147 // and broadcasts. 14148 IBackupManager bm = IBackupManager.Stub.asInterface( 14149 ServiceManager.getService(Context.BACKUP_SERVICE)); 14150 if (bm != null) { 14151 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14152 + " to BM for possible restore"); 14153 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14154 try { 14155 // TODO: http://b/22388012 14156 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14157 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14158 } else { 14159 doRestore = false; 14160 } 14161 } catch (RemoteException e) { 14162 // can't happen; the backup manager is local 14163 } catch (Exception e) { 14164 Slog.e(TAG, "Exception trying to enqueue restore", e); 14165 doRestore = false; 14166 } 14167 } else { 14168 Slog.e(TAG, "Backup Manager not found!"); 14169 doRestore = false; 14170 } 14171 } 14172 14173 if (!doRestore) { 14174 // No restore possible, or the Backup Manager was mysteriously not 14175 // available -- just fire the post-install work request directly. 14176 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14177 14178 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14179 14180 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14181 mHandler.sendMessage(msg); 14182 } 14183 } 14184 }); 14185 } 14186 14187 /** 14188 * Callback from PackageSettings whenever an app is first transitioned out of the 14189 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14190 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14191 * here whether the app is the target of an ongoing install, and only send the 14192 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14193 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14194 * handling. 14195 */ 14196 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14197 // Serialize this with the rest of the install-process message chain. In the 14198 // restore-at-install case, this Runnable will necessarily run before the 14199 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14200 // are coherent. In the non-restore case, the app has already completed install 14201 // and been launched through some other means, so it is not in a problematic 14202 // state for observers to see the FIRST_LAUNCH signal. 14203 mHandler.post(new Runnable() { 14204 @Override 14205 public void run() { 14206 for (int i = 0; i < mRunningInstalls.size(); i++) { 14207 final PostInstallData data = mRunningInstalls.valueAt(i); 14208 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14209 continue; 14210 } 14211 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14212 // right package; but is it for the right user? 14213 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14214 if (userId == data.res.newUsers[uIndex]) { 14215 if (DEBUG_BACKUP) { 14216 Slog.i(TAG, "Package " + pkgName 14217 + " being restored so deferring FIRST_LAUNCH"); 14218 } 14219 return; 14220 } 14221 } 14222 } 14223 } 14224 // didn't find it, so not being restored 14225 if (DEBUG_BACKUP) { 14226 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14227 } 14228 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14229 } 14230 }); 14231 } 14232 14233 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14234 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14235 installerPkg, null, userIds); 14236 } 14237 14238 private abstract class HandlerParams { 14239 private static final int MAX_RETRIES = 4; 14240 14241 /** 14242 * Number of times startCopy() has been attempted and had a non-fatal 14243 * error. 14244 */ 14245 private int mRetries = 0; 14246 14247 /** User handle for the user requesting the information or installation. */ 14248 private final UserHandle mUser; 14249 String traceMethod; 14250 int traceCookie; 14251 14252 HandlerParams(UserHandle user) { 14253 mUser = user; 14254 } 14255 14256 UserHandle getUser() { 14257 return mUser; 14258 } 14259 14260 HandlerParams setTraceMethod(String traceMethod) { 14261 this.traceMethod = traceMethod; 14262 return this; 14263 } 14264 14265 HandlerParams setTraceCookie(int traceCookie) { 14266 this.traceCookie = traceCookie; 14267 return this; 14268 } 14269 14270 final boolean startCopy() { 14271 boolean res; 14272 try { 14273 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14274 14275 if (++mRetries > MAX_RETRIES) { 14276 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14277 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14278 handleServiceError(); 14279 return false; 14280 } else { 14281 handleStartCopy(); 14282 res = true; 14283 } 14284 } catch (RemoteException e) { 14285 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14286 mHandler.sendEmptyMessage(MCS_RECONNECT); 14287 res = false; 14288 } 14289 handleReturnCode(); 14290 return res; 14291 } 14292 14293 final void serviceError() { 14294 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14295 handleServiceError(); 14296 handleReturnCode(); 14297 } 14298 14299 abstract void handleStartCopy() throws RemoteException; 14300 abstract void handleServiceError(); 14301 abstract void handleReturnCode(); 14302 } 14303 14304 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14305 for (File path : paths) { 14306 try { 14307 mcs.clearDirectory(path.getAbsolutePath()); 14308 } catch (RemoteException e) { 14309 } 14310 } 14311 } 14312 14313 static class OriginInfo { 14314 /** 14315 * Location where install is coming from, before it has been 14316 * copied/renamed into place. This could be a single monolithic APK 14317 * file, or a cluster directory. This location may be untrusted. 14318 */ 14319 final File file; 14320 final String cid; 14321 14322 /** 14323 * Flag indicating that {@link #file} or {@link #cid} has already been 14324 * staged, meaning downstream users don't need to defensively copy the 14325 * contents. 14326 */ 14327 final boolean staged; 14328 14329 /** 14330 * Flag indicating that {@link #file} or {@link #cid} is an already 14331 * installed app that is being moved. 14332 */ 14333 final boolean existing; 14334 14335 final String resolvedPath; 14336 final File resolvedFile; 14337 14338 static OriginInfo fromNothing() { 14339 return new OriginInfo(null, null, false, false); 14340 } 14341 14342 static OriginInfo fromUntrustedFile(File file) { 14343 return new OriginInfo(file, null, false, false); 14344 } 14345 14346 static OriginInfo fromExistingFile(File file) { 14347 return new OriginInfo(file, null, false, true); 14348 } 14349 14350 static OriginInfo fromStagedFile(File file) { 14351 return new OriginInfo(file, null, true, false); 14352 } 14353 14354 static OriginInfo fromStagedContainer(String cid) { 14355 return new OriginInfo(null, cid, true, false); 14356 } 14357 14358 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14359 this.file = file; 14360 this.cid = cid; 14361 this.staged = staged; 14362 this.existing = existing; 14363 14364 if (cid != null) { 14365 resolvedPath = PackageHelper.getSdDir(cid); 14366 resolvedFile = new File(resolvedPath); 14367 } else if (file != null) { 14368 resolvedPath = file.getAbsolutePath(); 14369 resolvedFile = file; 14370 } else { 14371 resolvedPath = null; 14372 resolvedFile = null; 14373 } 14374 } 14375 } 14376 14377 static class MoveInfo { 14378 final int moveId; 14379 final String fromUuid; 14380 final String toUuid; 14381 final String packageName; 14382 final String dataAppName; 14383 final int appId; 14384 final String seinfo; 14385 final int targetSdkVersion; 14386 14387 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14388 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14389 this.moveId = moveId; 14390 this.fromUuid = fromUuid; 14391 this.toUuid = toUuid; 14392 this.packageName = packageName; 14393 this.dataAppName = dataAppName; 14394 this.appId = appId; 14395 this.seinfo = seinfo; 14396 this.targetSdkVersion = targetSdkVersion; 14397 } 14398 } 14399 14400 static class VerificationInfo { 14401 /** A constant used to indicate that a uid value is not present. */ 14402 public static final int NO_UID = -1; 14403 14404 /** URI referencing where the package was downloaded from. */ 14405 final Uri originatingUri; 14406 14407 /** HTTP referrer URI associated with the originatingURI. */ 14408 final Uri referrer; 14409 14410 /** UID of the application that the install request originated from. */ 14411 final int originatingUid; 14412 14413 /** UID of application requesting the install */ 14414 final int installerUid; 14415 14416 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14417 this.originatingUri = originatingUri; 14418 this.referrer = referrer; 14419 this.originatingUid = originatingUid; 14420 this.installerUid = installerUid; 14421 } 14422 } 14423 14424 class InstallParams extends HandlerParams { 14425 final OriginInfo origin; 14426 final MoveInfo move; 14427 final IPackageInstallObserver2 observer; 14428 int installFlags; 14429 final String installerPackageName; 14430 final String volumeUuid; 14431 private InstallArgs mArgs; 14432 private int mRet; 14433 final String packageAbiOverride; 14434 final String[] grantedRuntimePermissions; 14435 final VerificationInfo verificationInfo; 14436 final Certificate[][] certificates; 14437 final int installReason; 14438 14439 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14440 int installFlags, String installerPackageName, String volumeUuid, 14441 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14442 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14443 super(user); 14444 this.origin = origin; 14445 this.move = move; 14446 this.observer = observer; 14447 this.installFlags = installFlags; 14448 this.installerPackageName = installerPackageName; 14449 this.volumeUuid = volumeUuid; 14450 this.verificationInfo = verificationInfo; 14451 this.packageAbiOverride = packageAbiOverride; 14452 this.grantedRuntimePermissions = grantedPermissions; 14453 this.certificates = certificates; 14454 this.installReason = installReason; 14455 } 14456 14457 @Override 14458 public String toString() { 14459 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14460 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14461 } 14462 14463 private int installLocationPolicy(PackageInfoLite pkgLite) { 14464 String packageName = pkgLite.packageName; 14465 int installLocation = pkgLite.installLocation; 14466 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14467 // reader 14468 synchronized (mPackages) { 14469 // Currently installed package which the new package is attempting to replace or 14470 // null if no such package is installed. 14471 PackageParser.Package installedPkg = mPackages.get(packageName); 14472 // Package which currently owns the data which the new package will own if installed. 14473 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14474 // will be null whereas dataOwnerPkg will contain information about the package 14475 // which was uninstalled while keeping its data. 14476 PackageParser.Package dataOwnerPkg = installedPkg; 14477 if (dataOwnerPkg == null) { 14478 PackageSetting ps = mSettings.mPackages.get(packageName); 14479 if (ps != null) { 14480 dataOwnerPkg = ps.pkg; 14481 } 14482 } 14483 14484 if (dataOwnerPkg != null) { 14485 // If installed, the package will get access to data left on the device by its 14486 // predecessor. As a security measure, this is permited only if this is not a 14487 // version downgrade or if the predecessor package is marked as debuggable and 14488 // a downgrade is explicitly requested. 14489 // 14490 // On debuggable platform builds, downgrades are permitted even for 14491 // non-debuggable packages to make testing easier. Debuggable platform builds do 14492 // not offer security guarantees and thus it's OK to disable some security 14493 // mechanisms to make debugging/testing easier on those builds. However, even on 14494 // debuggable builds downgrades of packages are permitted only if requested via 14495 // installFlags. This is because we aim to keep the behavior of debuggable 14496 // platform builds as close as possible to the behavior of non-debuggable 14497 // platform builds. 14498 final boolean downgradeRequested = 14499 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14500 final boolean packageDebuggable = 14501 (dataOwnerPkg.applicationInfo.flags 14502 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14503 final boolean downgradePermitted = 14504 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14505 if (!downgradePermitted) { 14506 try { 14507 checkDowngrade(dataOwnerPkg, pkgLite); 14508 } catch (PackageManagerException e) { 14509 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14510 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14511 } 14512 } 14513 } 14514 14515 if (installedPkg != null) { 14516 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14517 // Check for updated system application. 14518 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14519 if (onSd) { 14520 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14521 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14522 } 14523 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14524 } else { 14525 if (onSd) { 14526 // Install flag overrides everything. 14527 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14528 } 14529 // If current upgrade specifies particular preference 14530 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14531 // Application explicitly specified internal. 14532 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14533 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14534 // App explictly prefers external. Let policy decide 14535 } else { 14536 // Prefer previous location 14537 if (isExternal(installedPkg)) { 14538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14539 } 14540 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14541 } 14542 } 14543 } else { 14544 // Invalid install. Return error code 14545 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14546 } 14547 } 14548 } 14549 // All the special cases have been taken care of. 14550 // Return result based on recommended install location. 14551 if (onSd) { 14552 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14553 } 14554 return pkgLite.recommendedInstallLocation; 14555 } 14556 14557 /* 14558 * Invoke remote method to get package information and install 14559 * location values. Override install location based on default 14560 * policy if needed and then create install arguments based 14561 * on the install location. 14562 */ 14563 public void handleStartCopy() throws RemoteException { 14564 int ret = PackageManager.INSTALL_SUCCEEDED; 14565 14566 // If we're already staged, we've firmly committed to an install location 14567 if (origin.staged) { 14568 if (origin.file != null) { 14569 installFlags |= PackageManager.INSTALL_INTERNAL; 14570 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14571 } else if (origin.cid != null) { 14572 installFlags |= PackageManager.INSTALL_EXTERNAL; 14573 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14574 } else { 14575 throw new IllegalStateException("Invalid stage location"); 14576 } 14577 } 14578 14579 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14580 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14581 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14582 PackageInfoLite pkgLite = null; 14583 14584 if (onInt && onSd) { 14585 // Check if both bits are set. 14586 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14587 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14588 } else if (onSd && ephemeral) { 14589 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14590 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14591 } else { 14592 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14593 packageAbiOverride); 14594 14595 if (DEBUG_EPHEMERAL && ephemeral) { 14596 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14597 } 14598 14599 /* 14600 * If we have too little free space, try to free cache 14601 * before giving up. 14602 */ 14603 if (!origin.staged && pkgLite.recommendedInstallLocation 14604 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14605 // TODO: focus freeing disk space on the target device 14606 final StorageManager storage = StorageManager.from(mContext); 14607 final long lowThreshold = storage.getStorageLowBytes( 14608 Environment.getDataDirectory()); 14609 14610 final long sizeBytes = mContainerService.calculateInstalledSize( 14611 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14612 14613 try { 14614 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14615 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14616 installFlags, packageAbiOverride); 14617 } catch (InstallerException e) { 14618 Slog.w(TAG, "Failed to free cache", e); 14619 } 14620 14621 /* 14622 * The cache free must have deleted the file we 14623 * downloaded to install. 14624 * 14625 * TODO: fix the "freeCache" call to not delete 14626 * the file we care about. 14627 */ 14628 if (pkgLite.recommendedInstallLocation 14629 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14630 pkgLite.recommendedInstallLocation 14631 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14632 } 14633 } 14634 } 14635 14636 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14637 int loc = pkgLite.recommendedInstallLocation; 14638 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14639 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14640 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14641 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14642 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14643 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14644 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14645 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14646 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14647 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14648 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14649 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14650 } else { 14651 // Override with defaults if needed. 14652 loc = installLocationPolicy(pkgLite); 14653 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14654 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14655 } else if (!onSd && !onInt) { 14656 // Override install location with flags 14657 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14658 // Set the flag to install on external media. 14659 installFlags |= PackageManager.INSTALL_EXTERNAL; 14660 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14661 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14662 if (DEBUG_EPHEMERAL) { 14663 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14664 } 14665 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14666 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14667 |PackageManager.INSTALL_INTERNAL); 14668 } else { 14669 // Make sure the flag for installing on external 14670 // media is unset 14671 installFlags |= PackageManager.INSTALL_INTERNAL; 14672 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14673 } 14674 } 14675 } 14676 } 14677 14678 final InstallArgs args = createInstallArgs(this); 14679 mArgs = args; 14680 14681 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14682 // TODO: http://b/22976637 14683 // Apps installed for "all" users use the device owner to verify the app 14684 UserHandle verifierUser = getUser(); 14685 if (verifierUser == UserHandle.ALL) { 14686 verifierUser = UserHandle.SYSTEM; 14687 } 14688 14689 /* 14690 * Determine if we have any installed package verifiers. If we 14691 * do, then we'll defer to them to verify the packages. 14692 */ 14693 final int requiredUid = mRequiredVerifierPackage == null ? -1 14694 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14695 verifierUser.getIdentifier()); 14696 if (!origin.existing && requiredUid != -1 14697 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14698 final Intent verification = new Intent( 14699 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14700 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14701 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14702 PACKAGE_MIME_TYPE); 14703 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14704 14705 // Query all live verifiers based on current user state 14706 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14707 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14708 14709 if (DEBUG_VERIFY) { 14710 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14711 + verification.toString() + " with " + pkgLite.verifiers.length 14712 + " optional verifiers"); 14713 } 14714 14715 final int verificationId = mPendingVerificationToken++; 14716 14717 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14718 14719 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14720 installerPackageName); 14721 14722 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14723 installFlags); 14724 14725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14726 pkgLite.packageName); 14727 14728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14729 pkgLite.versionCode); 14730 14731 if (verificationInfo != null) { 14732 if (verificationInfo.originatingUri != null) { 14733 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14734 verificationInfo.originatingUri); 14735 } 14736 if (verificationInfo.referrer != null) { 14737 verification.putExtra(Intent.EXTRA_REFERRER, 14738 verificationInfo.referrer); 14739 } 14740 if (verificationInfo.originatingUid >= 0) { 14741 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14742 verificationInfo.originatingUid); 14743 } 14744 if (verificationInfo.installerUid >= 0) { 14745 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14746 verificationInfo.installerUid); 14747 } 14748 } 14749 14750 final PackageVerificationState verificationState = new PackageVerificationState( 14751 requiredUid, args); 14752 14753 mPendingVerification.append(verificationId, verificationState); 14754 14755 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14756 receivers, verificationState); 14757 14758 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14759 final long idleDuration = getVerificationTimeout(); 14760 14761 /* 14762 * If any sufficient verifiers were listed in the package 14763 * manifest, attempt to ask them. 14764 */ 14765 if (sufficientVerifiers != null) { 14766 final int N = sufficientVerifiers.size(); 14767 if (N == 0) { 14768 Slog.i(TAG, "Additional verifiers required, but none installed."); 14769 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14770 } else { 14771 for (int i = 0; i < N; i++) { 14772 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14773 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14774 verifierComponent.getPackageName(), idleDuration, 14775 verifierUser.getIdentifier(), false, "package verifier"); 14776 14777 final Intent sufficientIntent = new Intent(verification); 14778 sufficientIntent.setComponent(verifierComponent); 14779 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14780 } 14781 } 14782 } 14783 14784 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14785 mRequiredVerifierPackage, receivers); 14786 if (ret == PackageManager.INSTALL_SUCCEEDED 14787 && mRequiredVerifierPackage != null) { 14788 Trace.asyncTraceBegin( 14789 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14790 /* 14791 * Send the intent to the required verification agent, 14792 * but only start the verification timeout after the 14793 * target BroadcastReceivers have run. 14794 */ 14795 verification.setComponent(requiredVerifierComponent); 14796 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14797 mRequiredVerifierPackage, idleDuration, 14798 verifierUser.getIdentifier(), false, "package verifier"); 14799 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14800 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14801 new BroadcastReceiver() { 14802 @Override 14803 public void onReceive(Context context, Intent intent) { 14804 final Message msg = mHandler 14805 .obtainMessage(CHECK_PENDING_VERIFICATION); 14806 msg.arg1 = verificationId; 14807 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14808 } 14809 }, null, 0, null, null); 14810 14811 /* 14812 * We don't want the copy to proceed until verification 14813 * succeeds, so null out this field. 14814 */ 14815 mArgs = null; 14816 } 14817 } else { 14818 /* 14819 * No package verification is enabled, so immediately start 14820 * the remote call to initiate copy using temporary file. 14821 */ 14822 ret = args.copyApk(mContainerService, true); 14823 } 14824 } 14825 14826 mRet = ret; 14827 } 14828 14829 @Override 14830 void handleReturnCode() { 14831 // If mArgs is null, then MCS couldn't be reached. When it 14832 // reconnects, it will try again to install. At that point, this 14833 // will succeed. 14834 if (mArgs != null) { 14835 processPendingInstall(mArgs, mRet); 14836 } 14837 } 14838 14839 @Override 14840 void handleServiceError() { 14841 mArgs = createInstallArgs(this); 14842 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14843 } 14844 14845 public boolean isForwardLocked() { 14846 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14847 } 14848 } 14849 14850 /** 14851 * Used during creation of InstallArgs 14852 * 14853 * @param installFlags package installation flags 14854 * @return true if should be installed on external storage 14855 */ 14856 private static boolean installOnExternalAsec(int installFlags) { 14857 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14858 return false; 14859 } 14860 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14861 return true; 14862 } 14863 return false; 14864 } 14865 14866 /** 14867 * Used during creation of InstallArgs 14868 * 14869 * @param installFlags package installation flags 14870 * @return true if should be installed as forward locked 14871 */ 14872 private static boolean installForwardLocked(int installFlags) { 14873 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14874 } 14875 14876 private InstallArgs createInstallArgs(InstallParams params) { 14877 if (params.move != null) { 14878 return new MoveInstallArgs(params); 14879 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14880 return new AsecInstallArgs(params); 14881 } else { 14882 return new FileInstallArgs(params); 14883 } 14884 } 14885 14886 /** 14887 * Create args that describe an existing installed package. Typically used 14888 * when cleaning up old installs, or used as a move source. 14889 */ 14890 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14891 String resourcePath, String[] instructionSets) { 14892 final boolean isInAsec; 14893 if (installOnExternalAsec(installFlags)) { 14894 /* Apps on SD card are always in ASEC containers. */ 14895 isInAsec = true; 14896 } else if (installForwardLocked(installFlags) 14897 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14898 /* 14899 * Forward-locked apps are only in ASEC containers if they're the 14900 * new style 14901 */ 14902 isInAsec = true; 14903 } else { 14904 isInAsec = false; 14905 } 14906 14907 if (isInAsec) { 14908 return new AsecInstallArgs(codePath, instructionSets, 14909 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14910 } else { 14911 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14912 } 14913 } 14914 14915 static abstract class InstallArgs { 14916 /** @see InstallParams#origin */ 14917 final OriginInfo origin; 14918 /** @see InstallParams#move */ 14919 final MoveInfo move; 14920 14921 final IPackageInstallObserver2 observer; 14922 // Always refers to PackageManager flags only 14923 final int installFlags; 14924 final String installerPackageName; 14925 final String volumeUuid; 14926 final UserHandle user; 14927 final String abiOverride; 14928 final String[] installGrantPermissions; 14929 /** If non-null, drop an async trace when the install completes */ 14930 final String traceMethod; 14931 final int traceCookie; 14932 final Certificate[][] certificates; 14933 final int installReason; 14934 14935 // The list of instruction sets supported by this app. This is currently 14936 // only used during the rmdex() phase to clean up resources. We can get rid of this 14937 // if we move dex files under the common app path. 14938 /* nullable */ String[] instructionSets; 14939 14940 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14941 int installFlags, String installerPackageName, String volumeUuid, 14942 UserHandle user, String[] instructionSets, 14943 String abiOverride, String[] installGrantPermissions, 14944 String traceMethod, int traceCookie, Certificate[][] certificates, 14945 int installReason) { 14946 this.origin = origin; 14947 this.move = move; 14948 this.installFlags = installFlags; 14949 this.observer = observer; 14950 this.installerPackageName = installerPackageName; 14951 this.volumeUuid = volumeUuid; 14952 this.user = user; 14953 this.instructionSets = instructionSets; 14954 this.abiOverride = abiOverride; 14955 this.installGrantPermissions = installGrantPermissions; 14956 this.traceMethod = traceMethod; 14957 this.traceCookie = traceCookie; 14958 this.certificates = certificates; 14959 this.installReason = installReason; 14960 } 14961 14962 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14963 abstract int doPreInstall(int status); 14964 14965 /** 14966 * Rename package into final resting place. All paths on the given 14967 * scanned package should be updated to reflect the rename. 14968 */ 14969 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14970 abstract int doPostInstall(int status, int uid); 14971 14972 /** @see PackageSettingBase#codePathString */ 14973 abstract String getCodePath(); 14974 /** @see PackageSettingBase#resourcePathString */ 14975 abstract String getResourcePath(); 14976 14977 // Need installer lock especially for dex file removal. 14978 abstract void cleanUpResourcesLI(); 14979 abstract boolean doPostDeleteLI(boolean delete); 14980 14981 /** 14982 * Called before the source arguments are copied. This is used mostly 14983 * for MoveParams when it needs to read the source file to put it in the 14984 * destination. 14985 */ 14986 int doPreCopy() { 14987 return PackageManager.INSTALL_SUCCEEDED; 14988 } 14989 14990 /** 14991 * Called after the source arguments are copied. This is used mostly for 14992 * MoveParams when it needs to read the source file to put it in the 14993 * destination. 14994 */ 14995 int doPostCopy(int uid) { 14996 return PackageManager.INSTALL_SUCCEEDED; 14997 } 14998 14999 protected boolean isFwdLocked() { 15000 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15001 } 15002 15003 protected boolean isExternalAsec() { 15004 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15005 } 15006 15007 protected boolean isEphemeral() { 15008 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15009 } 15010 15011 UserHandle getUser() { 15012 return user; 15013 } 15014 } 15015 15016 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15017 if (!allCodePaths.isEmpty()) { 15018 if (instructionSets == null) { 15019 throw new IllegalStateException("instructionSet == null"); 15020 } 15021 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15022 for (String codePath : allCodePaths) { 15023 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15024 try { 15025 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15026 } catch (InstallerException ignored) { 15027 } 15028 } 15029 } 15030 } 15031 } 15032 15033 /** 15034 * Logic to handle installation of non-ASEC applications, including copying 15035 * and renaming logic. 15036 */ 15037 class FileInstallArgs extends InstallArgs { 15038 private File codeFile; 15039 private File resourceFile; 15040 15041 // Example topology: 15042 // /data/app/com.example/base.apk 15043 // /data/app/com.example/split_foo.apk 15044 // /data/app/com.example/lib/arm/libfoo.so 15045 // /data/app/com.example/lib/arm64/libfoo.so 15046 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15047 15048 /** New install */ 15049 FileInstallArgs(InstallParams params) { 15050 super(params.origin, params.move, params.observer, params.installFlags, 15051 params.installerPackageName, params.volumeUuid, 15052 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15053 params.grantedRuntimePermissions, 15054 params.traceMethod, params.traceCookie, params.certificates, 15055 params.installReason); 15056 if (isFwdLocked()) { 15057 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15058 } 15059 } 15060 15061 /** Existing install */ 15062 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15063 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15064 null, null, null, 0, null /*certificates*/, 15065 PackageManager.INSTALL_REASON_UNKNOWN); 15066 this.codeFile = (codePath != null) ? new File(codePath) : null; 15067 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15068 } 15069 15070 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15071 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15072 try { 15073 return doCopyApk(imcs, temp); 15074 } finally { 15075 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15076 } 15077 } 15078 15079 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15080 if (origin.staged) { 15081 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15082 codeFile = origin.file; 15083 resourceFile = origin.file; 15084 return PackageManager.INSTALL_SUCCEEDED; 15085 } 15086 15087 try { 15088 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15089 final File tempDir = 15090 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15091 codeFile = tempDir; 15092 resourceFile = tempDir; 15093 } catch (IOException e) { 15094 Slog.w(TAG, "Failed to create copy file: " + e); 15095 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15096 } 15097 15098 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15099 @Override 15100 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15101 if (!FileUtils.isValidExtFilename(name)) { 15102 throw new IllegalArgumentException("Invalid filename: " + name); 15103 } 15104 try { 15105 final File file = new File(codeFile, name); 15106 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15107 O_RDWR | O_CREAT, 0644); 15108 Os.chmod(file.getAbsolutePath(), 0644); 15109 return new ParcelFileDescriptor(fd); 15110 } catch (ErrnoException e) { 15111 throw new RemoteException("Failed to open: " + e.getMessage()); 15112 } 15113 } 15114 }; 15115 15116 int ret = PackageManager.INSTALL_SUCCEEDED; 15117 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15118 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15119 Slog.e(TAG, "Failed to copy package"); 15120 return ret; 15121 } 15122 15123 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15124 NativeLibraryHelper.Handle handle = null; 15125 try { 15126 handle = NativeLibraryHelper.Handle.create(codeFile); 15127 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15128 abiOverride); 15129 } catch (IOException e) { 15130 Slog.e(TAG, "Copying native libraries failed", e); 15131 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15132 } finally { 15133 IoUtils.closeQuietly(handle); 15134 } 15135 15136 return ret; 15137 } 15138 15139 int doPreInstall(int status) { 15140 if (status != PackageManager.INSTALL_SUCCEEDED) { 15141 cleanUp(); 15142 } 15143 return status; 15144 } 15145 15146 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15147 if (status != PackageManager.INSTALL_SUCCEEDED) { 15148 cleanUp(); 15149 return false; 15150 } 15151 15152 final File targetDir = codeFile.getParentFile(); 15153 final File beforeCodeFile = codeFile; 15154 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15155 15156 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15157 try { 15158 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15159 } catch (ErrnoException e) { 15160 Slog.w(TAG, "Failed to rename", e); 15161 return false; 15162 } 15163 15164 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15165 Slog.w(TAG, "Failed to restorecon"); 15166 return false; 15167 } 15168 15169 // Reflect the rename internally 15170 codeFile = afterCodeFile; 15171 resourceFile = afterCodeFile; 15172 15173 // Reflect the rename in scanned details 15174 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15175 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15176 afterCodeFile, pkg.baseCodePath)); 15177 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15178 afterCodeFile, pkg.splitCodePaths)); 15179 15180 // Reflect the rename in app info 15181 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15182 pkg.setApplicationInfoCodePath(pkg.codePath); 15183 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15184 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15185 pkg.setApplicationInfoResourcePath(pkg.codePath); 15186 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15187 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15188 15189 return true; 15190 } 15191 15192 int doPostInstall(int status, int uid) { 15193 if (status != PackageManager.INSTALL_SUCCEEDED) { 15194 cleanUp(); 15195 } 15196 return status; 15197 } 15198 15199 @Override 15200 String getCodePath() { 15201 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15202 } 15203 15204 @Override 15205 String getResourcePath() { 15206 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15207 } 15208 15209 private boolean cleanUp() { 15210 if (codeFile == null || !codeFile.exists()) { 15211 return false; 15212 } 15213 15214 removeCodePathLI(codeFile); 15215 15216 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15217 resourceFile.delete(); 15218 } 15219 15220 return true; 15221 } 15222 15223 void cleanUpResourcesLI() { 15224 // Try enumerating all code paths before deleting 15225 List<String> allCodePaths = Collections.EMPTY_LIST; 15226 if (codeFile != null && codeFile.exists()) { 15227 try { 15228 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15229 allCodePaths = pkg.getAllCodePaths(); 15230 } catch (PackageParserException e) { 15231 // Ignored; we tried our best 15232 } 15233 } 15234 15235 cleanUp(); 15236 removeDexFiles(allCodePaths, instructionSets); 15237 } 15238 15239 boolean doPostDeleteLI(boolean delete) { 15240 // XXX err, shouldn't we respect the delete flag? 15241 cleanUpResourcesLI(); 15242 return true; 15243 } 15244 } 15245 15246 private boolean isAsecExternal(String cid) { 15247 final String asecPath = PackageHelper.getSdFilesystem(cid); 15248 return !asecPath.startsWith(mAsecInternalPath); 15249 } 15250 15251 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15252 PackageManagerException { 15253 if (copyRet < 0) { 15254 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15255 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15256 throw new PackageManagerException(copyRet, message); 15257 } 15258 } 15259 } 15260 15261 /** 15262 * Extract the StorageManagerService "container ID" from the full code path of an 15263 * .apk. 15264 */ 15265 static String cidFromCodePath(String fullCodePath) { 15266 int eidx = fullCodePath.lastIndexOf("/"); 15267 String subStr1 = fullCodePath.substring(0, eidx); 15268 int sidx = subStr1.lastIndexOf("/"); 15269 return subStr1.substring(sidx+1, eidx); 15270 } 15271 15272 /** 15273 * Logic to handle installation of ASEC applications, including copying and 15274 * renaming logic. 15275 */ 15276 class AsecInstallArgs extends InstallArgs { 15277 static final String RES_FILE_NAME = "pkg.apk"; 15278 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15279 15280 String cid; 15281 String packagePath; 15282 String resourcePath; 15283 15284 /** New install */ 15285 AsecInstallArgs(InstallParams params) { 15286 super(params.origin, params.move, params.observer, params.installFlags, 15287 params.installerPackageName, params.volumeUuid, 15288 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15289 params.grantedRuntimePermissions, 15290 params.traceMethod, params.traceCookie, params.certificates, 15291 params.installReason); 15292 } 15293 15294 /** Existing install */ 15295 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15296 boolean isExternal, boolean isForwardLocked) { 15297 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15298 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15299 instructionSets, null, null, null, 0, null /*certificates*/, 15300 PackageManager.INSTALL_REASON_UNKNOWN); 15301 // Hackily pretend we're still looking at a full code path 15302 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15303 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15304 } 15305 15306 // Extract cid from fullCodePath 15307 int eidx = fullCodePath.lastIndexOf("/"); 15308 String subStr1 = fullCodePath.substring(0, eidx); 15309 int sidx = subStr1.lastIndexOf("/"); 15310 cid = subStr1.substring(sidx+1, eidx); 15311 setMountPath(subStr1); 15312 } 15313 15314 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15315 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15316 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15317 instructionSets, null, null, null, 0, null /*certificates*/, 15318 PackageManager.INSTALL_REASON_UNKNOWN); 15319 this.cid = cid; 15320 setMountPath(PackageHelper.getSdDir(cid)); 15321 } 15322 15323 void createCopyFile() { 15324 cid = mInstallerService.allocateExternalStageCidLegacy(); 15325 } 15326 15327 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15328 if (origin.staged && origin.cid != null) { 15329 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15330 cid = origin.cid; 15331 setMountPath(PackageHelper.getSdDir(cid)); 15332 return PackageManager.INSTALL_SUCCEEDED; 15333 } 15334 15335 if (temp) { 15336 createCopyFile(); 15337 } else { 15338 /* 15339 * Pre-emptively destroy the container since it's destroyed if 15340 * copying fails due to it existing anyway. 15341 */ 15342 PackageHelper.destroySdDir(cid); 15343 } 15344 15345 final String newMountPath = imcs.copyPackageToContainer( 15346 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15347 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15348 15349 if (newMountPath != null) { 15350 setMountPath(newMountPath); 15351 return PackageManager.INSTALL_SUCCEEDED; 15352 } else { 15353 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15354 } 15355 } 15356 15357 @Override 15358 String getCodePath() { 15359 return packagePath; 15360 } 15361 15362 @Override 15363 String getResourcePath() { 15364 return resourcePath; 15365 } 15366 15367 int doPreInstall(int status) { 15368 if (status != PackageManager.INSTALL_SUCCEEDED) { 15369 // Destroy container 15370 PackageHelper.destroySdDir(cid); 15371 } else { 15372 boolean mounted = PackageHelper.isContainerMounted(cid); 15373 if (!mounted) { 15374 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15375 Process.SYSTEM_UID); 15376 if (newMountPath != null) { 15377 setMountPath(newMountPath); 15378 } else { 15379 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15380 } 15381 } 15382 } 15383 return status; 15384 } 15385 15386 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15387 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15388 String newMountPath = null; 15389 if (PackageHelper.isContainerMounted(cid)) { 15390 // Unmount the container 15391 if (!PackageHelper.unMountSdDir(cid)) { 15392 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15393 return false; 15394 } 15395 } 15396 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15397 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15398 " which might be stale. Will try to clean up."); 15399 // Clean up the stale container and proceed to recreate. 15400 if (!PackageHelper.destroySdDir(newCacheId)) { 15401 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15402 return false; 15403 } 15404 // Successfully cleaned up stale container. Try to rename again. 15405 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15406 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15407 + " inspite of cleaning it up."); 15408 return false; 15409 } 15410 } 15411 if (!PackageHelper.isContainerMounted(newCacheId)) { 15412 Slog.w(TAG, "Mounting container " + newCacheId); 15413 newMountPath = PackageHelper.mountSdDir(newCacheId, 15414 getEncryptKey(), Process.SYSTEM_UID); 15415 } else { 15416 newMountPath = PackageHelper.getSdDir(newCacheId); 15417 } 15418 if (newMountPath == null) { 15419 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15420 return false; 15421 } 15422 Log.i(TAG, "Succesfully renamed " + cid + 15423 " to " + newCacheId + 15424 " at new path: " + newMountPath); 15425 cid = newCacheId; 15426 15427 final File beforeCodeFile = new File(packagePath); 15428 setMountPath(newMountPath); 15429 final File afterCodeFile = new File(packagePath); 15430 15431 // Reflect the rename in scanned details 15432 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15433 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15434 afterCodeFile, pkg.baseCodePath)); 15435 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15436 afterCodeFile, pkg.splitCodePaths)); 15437 15438 // Reflect the rename in app info 15439 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15440 pkg.setApplicationInfoCodePath(pkg.codePath); 15441 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15442 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15443 pkg.setApplicationInfoResourcePath(pkg.codePath); 15444 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15445 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15446 15447 return true; 15448 } 15449 15450 private void setMountPath(String mountPath) { 15451 final File mountFile = new File(mountPath); 15452 15453 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15454 if (monolithicFile.exists()) { 15455 packagePath = monolithicFile.getAbsolutePath(); 15456 if (isFwdLocked()) { 15457 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15458 } else { 15459 resourcePath = packagePath; 15460 } 15461 } else { 15462 packagePath = mountFile.getAbsolutePath(); 15463 resourcePath = packagePath; 15464 } 15465 } 15466 15467 int doPostInstall(int status, int uid) { 15468 if (status != PackageManager.INSTALL_SUCCEEDED) { 15469 cleanUp(); 15470 } else { 15471 final int groupOwner; 15472 final String protectedFile; 15473 if (isFwdLocked()) { 15474 groupOwner = UserHandle.getSharedAppGid(uid); 15475 protectedFile = RES_FILE_NAME; 15476 } else { 15477 groupOwner = -1; 15478 protectedFile = null; 15479 } 15480 15481 if (uid < Process.FIRST_APPLICATION_UID 15482 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15483 Slog.e(TAG, "Failed to finalize " + cid); 15484 PackageHelper.destroySdDir(cid); 15485 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15486 } 15487 15488 boolean mounted = PackageHelper.isContainerMounted(cid); 15489 if (!mounted) { 15490 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15491 } 15492 } 15493 return status; 15494 } 15495 15496 private void cleanUp() { 15497 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15498 15499 // Destroy secure container 15500 PackageHelper.destroySdDir(cid); 15501 } 15502 15503 private List<String> getAllCodePaths() { 15504 final File codeFile = new File(getCodePath()); 15505 if (codeFile != null && codeFile.exists()) { 15506 try { 15507 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15508 return pkg.getAllCodePaths(); 15509 } catch (PackageParserException e) { 15510 // Ignored; we tried our best 15511 } 15512 } 15513 return Collections.EMPTY_LIST; 15514 } 15515 15516 void cleanUpResourcesLI() { 15517 // Enumerate all code paths before deleting 15518 cleanUpResourcesLI(getAllCodePaths()); 15519 } 15520 15521 private void cleanUpResourcesLI(List<String> allCodePaths) { 15522 cleanUp(); 15523 removeDexFiles(allCodePaths, instructionSets); 15524 } 15525 15526 String getPackageName() { 15527 return getAsecPackageName(cid); 15528 } 15529 15530 boolean doPostDeleteLI(boolean delete) { 15531 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15532 final List<String> allCodePaths = getAllCodePaths(); 15533 boolean mounted = PackageHelper.isContainerMounted(cid); 15534 if (mounted) { 15535 // Unmount first 15536 if (PackageHelper.unMountSdDir(cid)) { 15537 mounted = false; 15538 } 15539 } 15540 if (!mounted && delete) { 15541 cleanUpResourcesLI(allCodePaths); 15542 } 15543 return !mounted; 15544 } 15545 15546 @Override 15547 int doPreCopy() { 15548 if (isFwdLocked()) { 15549 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15550 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15551 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15552 } 15553 } 15554 15555 return PackageManager.INSTALL_SUCCEEDED; 15556 } 15557 15558 @Override 15559 int doPostCopy(int uid) { 15560 if (isFwdLocked()) { 15561 if (uid < Process.FIRST_APPLICATION_UID 15562 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15563 RES_FILE_NAME)) { 15564 Slog.e(TAG, "Failed to finalize " + cid); 15565 PackageHelper.destroySdDir(cid); 15566 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15567 } 15568 } 15569 15570 return PackageManager.INSTALL_SUCCEEDED; 15571 } 15572 } 15573 15574 /** 15575 * Logic to handle movement of existing installed applications. 15576 */ 15577 class MoveInstallArgs extends InstallArgs { 15578 private File codeFile; 15579 private File resourceFile; 15580 15581 /** New install */ 15582 MoveInstallArgs(InstallParams params) { 15583 super(params.origin, params.move, params.observer, params.installFlags, 15584 params.installerPackageName, params.volumeUuid, 15585 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15586 params.grantedRuntimePermissions, 15587 params.traceMethod, params.traceCookie, params.certificates, 15588 params.installReason); 15589 } 15590 15591 int copyApk(IMediaContainerService imcs, boolean temp) { 15592 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15593 + move.fromUuid + " to " + move.toUuid); 15594 synchronized (mInstaller) { 15595 try { 15596 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15597 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15598 } catch (InstallerException e) { 15599 Slog.w(TAG, "Failed to move app", e); 15600 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15601 } 15602 } 15603 15604 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15605 resourceFile = codeFile; 15606 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15607 15608 return PackageManager.INSTALL_SUCCEEDED; 15609 } 15610 15611 int doPreInstall(int status) { 15612 if (status != PackageManager.INSTALL_SUCCEEDED) { 15613 cleanUp(move.toUuid); 15614 } 15615 return status; 15616 } 15617 15618 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15619 if (status != PackageManager.INSTALL_SUCCEEDED) { 15620 cleanUp(move.toUuid); 15621 return false; 15622 } 15623 15624 // Reflect the move in app info 15625 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15626 pkg.setApplicationInfoCodePath(pkg.codePath); 15627 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15628 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15629 pkg.setApplicationInfoResourcePath(pkg.codePath); 15630 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15631 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15632 15633 return true; 15634 } 15635 15636 int doPostInstall(int status, int uid) { 15637 if (status == PackageManager.INSTALL_SUCCEEDED) { 15638 cleanUp(move.fromUuid); 15639 } else { 15640 cleanUp(move.toUuid); 15641 } 15642 return status; 15643 } 15644 15645 @Override 15646 String getCodePath() { 15647 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15648 } 15649 15650 @Override 15651 String getResourcePath() { 15652 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15653 } 15654 15655 private boolean cleanUp(String volumeUuid) { 15656 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15657 move.dataAppName); 15658 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15659 final int[] userIds = sUserManager.getUserIds(); 15660 synchronized (mInstallLock) { 15661 // Clean up both app data and code 15662 // All package moves are frozen until finished 15663 for (int userId : userIds) { 15664 try { 15665 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15666 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15667 } catch (InstallerException e) { 15668 Slog.w(TAG, String.valueOf(e)); 15669 } 15670 } 15671 removeCodePathLI(codeFile); 15672 } 15673 return true; 15674 } 15675 15676 void cleanUpResourcesLI() { 15677 throw new UnsupportedOperationException(); 15678 } 15679 15680 boolean doPostDeleteLI(boolean delete) { 15681 throw new UnsupportedOperationException(); 15682 } 15683 } 15684 15685 static String getAsecPackageName(String packageCid) { 15686 int idx = packageCid.lastIndexOf("-"); 15687 if (idx == -1) { 15688 return packageCid; 15689 } 15690 return packageCid.substring(0, idx); 15691 } 15692 15693 // Utility method used to create code paths based on package name and available index. 15694 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15695 String idxStr = ""; 15696 int idx = 1; 15697 // Fall back to default value of idx=1 if prefix is not 15698 // part of oldCodePath 15699 if (oldCodePath != null) { 15700 String subStr = oldCodePath; 15701 // Drop the suffix right away 15702 if (suffix != null && subStr.endsWith(suffix)) { 15703 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15704 } 15705 // If oldCodePath already contains prefix find out the 15706 // ending index to either increment or decrement. 15707 int sidx = subStr.lastIndexOf(prefix); 15708 if (sidx != -1) { 15709 subStr = subStr.substring(sidx + prefix.length()); 15710 if (subStr != null) { 15711 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15712 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15713 } 15714 try { 15715 idx = Integer.parseInt(subStr); 15716 if (idx <= 1) { 15717 idx++; 15718 } else { 15719 idx--; 15720 } 15721 } catch(NumberFormatException e) { 15722 } 15723 } 15724 } 15725 } 15726 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15727 return prefix + idxStr; 15728 } 15729 15730 private File getNextCodePath(File targetDir, String packageName) { 15731 File result; 15732 SecureRandom random = new SecureRandom(); 15733 byte[] bytes = new byte[16]; 15734 do { 15735 random.nextBytes(bytes); 15736 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15737 result = new File(targetDir, packageName + "-" + suffix); 15738 } while (result.exists()); 15739 return result; 15740 } 15741 15742 // Utility method that returns the relative package path with respect 15743 // to the installation directory. Like say for /data/data/com.test-1.apk 15744 // string com.test-1 is returned. 15745 static String deriveCodePathName(String codePath) { 15746 if (codePath == null) { 15747 return null; 15748 } 15749 final File codeFile = new File(codePath); 15750 final String name = codeFile.getName(); 15751 if (codeFile.isDirectory()) { 15752 return name; 15753 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15754 final int lastDot = name.lastIndexOf('.'); 15755 return name.substring(0, lastDot); 15756 } else { 15757 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15758 return null; 15759 } 15760 } 15761 15762 static class PackageInstalledInfo { 15763 String name; 15764 int uid; 15765 // The set of users that originally had this package installed. 15766 int[] origUsers; 15767 // The set of users that now have this package installed. 15768 int[] newUsers; 15769 PackageParser.Package pkg; 15770 int returnCode; 15771 String returnMsg; 15772 PackageRemovedInfo removedInfo; 15773 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15774 15775 public void setError(int code, String msg) { 15776 setReturnCode(code); 15777 setReturnMessage(msg); 15778 Slog.w(TAG, msg); 15779 } 15780 15781 public void setError(String msg, PackageParserException e) { 15782 setReturnCode(e.error); 15783 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15784 Slog.w(TAG, msg, e); 15785 } 15786 15787 public void setError(String msg, PackageManagerException e) { 15788 returnCode = e.error; 15789 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15790 Slog.w(TAG, msg, e); 15791 } 15792 15793 public void setReturnCode(int returnCode) { 15794 this.returnCode = returnCode; 15795 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15796 for (int i = 0; i < childCount; i++) { 15797 addedChildPackages.valueAt(i).returnCode = returnCode; 15798 } 15799 } 15800 15801 private void setReturnMessage(String returnMsg) { 15802 this.returnMsg = returnMsg; 15803 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15804 for (int i = 0; i < childCount; i++) { 15805 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15806 } 15807 } 15808 15809 // In some error cases we want to convey more info back to the observer 15810 String origPackage; 15811 String origPermission; 15812 } 15813 15814 /* 15815 * Install a non-existing package. 15816 */ 15817 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15818 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15819 PackageInstalledInfo res, int installReason) { 15820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15821 15822 // Remember this for later, in case we need to rollback this install 15823 String pkgName = pkg.packageName; 15824 15825 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15826 15827 synchronized(mPackages) { 15828 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15829 if (renamedPackage != null) { 15830 // A package with the same name is already installed, though 15831 // it has been renamed to an older name. The package we 15832 // are trying to install should be installed as an update to 15833 // the existing one, but that has not been requested, so bail. 15834 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15835 + " without first uninstalling package running as " 15836 + renamedPackage); 15837 return; 15838 } 15839 if (mPackages.containsKey(pkgName)) { 15840 // Don't allow installation over an existing package with the same name. 15841 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15842 + " without first uninstalling."); 15843 return; 15844 } 15845 } 15846 15847 try { 15848 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15849 System.currentTimeMillis(), user); 15850 15851 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15852 15853 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15854 prepareAppDataAfterInstallLIF(newPackage); 15855 15856 } else { 15857 // Remove package from internal structures, but keep around any 15858 // data that might have already existed 15859 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15860 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15861 } 15862 } catch (PackageManagerException e) { 15863 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15864 } 15865 15866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15867 } 15868 15869 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15870 // Can't rotate keys during boot or if sharedUser. 15871 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15872 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15873 return false; 15874 } 15875 // app is using upgradeKeySets; make sure all are valid 15876 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15877 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15878 for (int i = 0; i < upgradeKeySets.length; i++) { 15879 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15880 Slog.wtf(TAG, "Package " 15881 + (oldPs.name != null ? oldPs.name : "<null>") 15882 + " contains upgrade-key-set reference to unknown key-set: " 15883 + upgradeKeySets[i] 15884 + " reverting to signatures check."); 15885 return false; 15886 } 15887 } 15888 return true; 15889 } 15890 15891 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15892 // Upgrade keysets are being used. Determine if new package has a superset of the 15893 // required keys. 15894 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15895 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15896 for (int i = 0; i < upgradeKeySets.length; i++) { 15897 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15898 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15899 return true; 15900 } 15901 } 15902 return false; 15903 } 15904 15905 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15906 try (DigestInputStream digestStream = 15907 new DigestInputStream(new FileInputStream(file), digest)) { 15908 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15909 } 15910 } 15911 15912 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15913 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15914 int installReason) { 15915 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15916 15917 final PackageParser.Package oldPackage; 15918 final String pkgName = pkg.packageName; 15919 final int[] allUsers; 15920 final int[] installedUsers; 15921 15922 synchronized(mPackages) { 15923 oldPackage = mPackages.get(pkgName); 15924 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15925 15926 // don't allow upgrade to target a release SDK from a pre-release SDK 15927 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15928 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15929 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15930 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15931 if (oldTargetsPreRelease 15932 && !newTargetsPreRelease 15933 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15934 Slog.w(TAG, "Can't install package targeting released sdk"); 15935 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15936 return; 15937 } 15938 15939 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15940 15941 // verify signatures are valid 15942 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15943 if (!checkUpgradeKeySetLP(ps, pkg)) { 15944 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15945 "New package not signed by keys specified by upgrade-keysets: " 15946 + pkgName); 15947 return; 15948 } 15949 } else { 15950 // default to original signature matching 15951 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15952 != PackageManager.SIGNATURE_MATCH) { 15953 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15954 "New package has a different signature: " + pkgName); 15955 return; 15956 } 15957 } 15958 15959 // don't allow a system upgrade unless the upgrade hash matches 15960 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15961 byte[] digestBytes = null; 15962 try { 15963 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15964 updateDigest(digest, new File(pkg.baseCodePath)); 15965 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15966 for (String path : pkg.splitCodePaths) { 15967 updateDigest(digest, new File(path)); 15968 } 15969 } 15970 digestBytes = digest.digest(); 15971 } catch (NoSuchAlgorithmException | IOException e) { 15972 res.setError(INSTALL_FAILED_INVALID_APK, 15973 "Could not compute hash: " + pkgName); 15974 return; 15975 } 15976 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15977 res.setError(INSTALL_FAILED_INVALID_APK, 15978 "New package fails restrict-update check: " + pkgName); 15979 return; 15980 } 15981 // retain upgrade restriction 15982 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15983 } 15984 15985 // Check for shared user id changes 15986 String invalidPackageName = 15987 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15988 if (invalidPackageName != null) { 15989 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15990 "Package " + invalidPackageName + " tried to change user " 15991 + oldPackage.mSharedUserId); 15992 return; 15993 } 15994 15995 // In case of rollback, remember per-user/profile install state 15996 allUsers = sUserManager.getUserIds(); 15997 installedUsers = ps.queryInstalledUsers(allUsers, true); 15998 15999 // don't allow an upgrade from full to ephemeral 16000 if (isInstantApp) { 16001 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16002 for (int currentUser : allUsers) { 16003 if (!ps.getInstantApp(currentUser)) { 16004 // can't downgrade from full to instant 16005 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16006 + " for user: " + currentUser); 16007 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16008 return; 16009 } 16010 } 16011 } else if (!ps.getInstantApp(user.getIdentifier())) { 16012 // can't downgrade from full to instant 16013 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16014 + " for user: " + user.getIdentifier()); 16015 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16016 return; 16017 } 16018 } 16019 } 16020 16021 // Update what is removed 16022 res.removedInfo = new PackageRemovedInfo(); 16023 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16024 res.removedInfo.removedPackage = oldPackage.packageName; 16025 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16026 res.removedInfo.isUpdate = true; 16027 res.removedInfo.origUsers = installedUsers; 16028 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16029 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16030 for (int i = 0; i < installedUsers.length; i++) { 16031 final int userId = installedUsers[i]; 16032 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16033 } 16034 16035 final int childCount = (oldPackage.childPackages != null) 16036 ? oldPackage.childPackages.size() : 0; 16037 for (int i = 0; i < childCount; i++) { 16038 boolean childPackageUpdated = false; 16039 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16040 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16041 if (res.addedChildPackages != null) { 16042 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16043 if (childRes != null) { 16044 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16045 childRes.removedInfo.removedPackage = childPkg.packageName; 16046 childRes.removedInfo.isUpdate = true; 16047 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16048 childPackageUpdated = true; 16049 } 16050 } 16051 if (!childPackageUpdated) { 16052 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16053 childRemovedRes.removedPackage = childPkg.packageName; 16054 childRemovedRes.isUpdate = false; 16055 childRemovedRes.dataRemoved = true; 16056 synchronized (mPackages) { 16057 if (childPs != null) { 16058 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16059 } 16060 } 16061 if (res.removedInfo.removedChildPackages == null) { 16062 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16063 } 16064 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16065 } 16066 } 16067 16068 boolean sysPkg = (isSystemApp(oldPackage)); 16069 if (sysPkg) { 16070 // Set the system/privileged flags as needed 16071 final boolean privileged = 16072 (oldPackage.applicationInfo.privateFlags 16073 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16074 final int systemPolicyFlags = policyFlags 16075 | PackageParser.PARSE_IS_SYSTEM 16076 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16077 16078 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16079 user, allUsers, installerPackageName, res, installReason); 16080 } else { 16081 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16082 user, allUsers, installerPackageName, res, installReason); 16083 } 16084 } 16085 16086 public List<String> getPreviousCodePaths(String packageName) { 16087 final PackageSetting ps = mSettings.mPackages.get(packageName); 16088 final List<String> result = new ArrayList<String>(); 16089 if (ps != null && ps.oldCodePaths != null) { 16090 result.addAll(ps.oldCodePaths); 16091 } 16092 return result; 16093 } 16094 16095 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16096 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16097 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16098 int installReason) { 16099 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16100 + deletedPackage); 16101 16102 String pkgName = deletedPackage.packageName; 16103 boolean deletedPkg = true; 16104 boolean addedPkg = false; 16105 boolean updatedSettings = false; 16106 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16107 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16108 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16109 16110 final long origUpdateTime = (pkg.mExtras != null) 16111 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16112 16113 // First delete the existing package while retaining the data directory 16114 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16115 res.removedInfo, true, pkg)) { 16116 // If the existing package wasn't successfully deleted 16117 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16118 deletedPkg = false; 16119 } else { 16120 // Successfully deleted the old package; proceed with replace. 16121 16122 // If deleted package lived in a container, give users a chance to 16123 // relinquish resources before killing. 16124 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16125 if (DEBUG_INSTALL) { 16126 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16127 } 16128 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16129 final ArrayList<String> pkgList = new ArrayList<String>(1); 16130 pkgList.add(deletedPackage.applicationInfo.packageName); 16131 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16132 } 16133 16134 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16135 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16136 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16137 16138 try { 16139 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16140 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16141 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16142 installReason); 16143 16144 // Update the in-memory copy of the previous code paths. 16145 PackageSetting ps = mSettings.mPackages.get(pkgName); 16146 if (!killApp) { 16147 if (ps.oldCodePaths == null) { 16148 ps.oldCodePaths = new ArraySet<>(); 16149 } 16150 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16151 if (deletedPackage.splitCodePaths != null) { 16152 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16153 } 16154 } else { 16155 ps.oldCodePaths = null; 16156 } 16157 if (ps.childPackageNames != null) { 16158 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16159 final String childPkgName = ps.childPackageNames.get(i); 16160 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16161 childPs.oldCodePaths = ps.oldCodePaths; 16162 } 16163 } 16164 // set instant app status, but, only if it's explicitly specified 16165 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16166 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16167 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16168 prepareAppDataAfterInstallLIF(newPackage); 16169 addedPkg = true; 16170 mDexManager.notifyPackageUpdated(newPackage.packageName, 16171 newPackage.baseCodePath, newPackage.splitCodePaths); 16172 } catch (PackageManagerException e) { 16173 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16174 } 16175 } 16176 16177 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16178 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16179 16180 // Revert all internal state mutations and added folders for the failed install 16181 if (addedPkg) { 16182 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16183 res.removedInfo, true, null); 16184 } 16185 16186 // Restore the old package 16187 if (deletedPkg) { 16188 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16189 File restoreFile = new File(deletedPackage.codePath); 16190 // Parse old package 16191 boolean oldExternal = isExternal(deletedPackage); 16192 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16193 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16194 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16195 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16196 try { 16197 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16198 null); 16199 } catch (PackageManagerException e) { 16200 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16201 + e.getMessage()); 16202 return; 16203 } 16204 16205 synchronized (mPackages) { 16206 // Ensure the installer package name up to date 16207 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16208 16209 // Update permissions for restored package 16210 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16211 16212 mSettings.writeLPr(); 16213 } 16214 16215 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16216 } 16217 } else { 16218 synchronized (mPackages) { 16219 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16220 if (ps != null) { 16221 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16222 if (res.removedInfo.removedChildPackages != null) { 16223 final int childCount = res.removedInfo.removedChildPackages.size(); 16224 // Iterate in reverse as we may modify the collection 16225 for (int i = childCount - 1; i >= 0; i--) { 16226 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16227 if (res.addedChildPackages.containsKey(childPackageName)) { 16228 res.removedInfo.removedChildPackages.removeAt(i); 16229 } else { 16230 PackageRemovedInfo childInfo = res.removedInfo 16231 .removedChildPackages.valueAt(i); 16232 childInfo.removedForAllUsers = mPackages.get( 16233 childInfo.removedPackage) == null; 16234 } 16235 } 16236 } 16237 } 16238 } 16239 } 16240 } 16241 16242 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16243 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16244 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16245 int installReason) { 16246 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16247 + ", old=" + deletedPackage); 16248 16249 final boolean disabledSystem; 16250 16251 // Remove existing system package 16252 removePackageLI(deletedPackage, true); 16253 16254 synchronized (mPackages) { 16255 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16256 } 16257 if (!disabledSystem) { 16258 // We didn't need to disable the .apk as a current system package, 16259 // which means we are replacing another update that is already 16260 // installed. We need to make sure to delete the older one's .apk. 16261 res.removedInfo.args = createInstallArgsForExisting(0, 16262 deletedPackage.applicationInfo.getCodePath(), 16263 deletedPackage.applicationInfo.getResourcePath(), 16264 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16265 } else { 16266 res.removedInfo.args = null; 16267 } 16268 16269 // Successfully disabled the old package. Now proceed with re-installation 16270 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16271 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16272 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16273 16274 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16275 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16276 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16277 16278 PackageParser.Package newPackage = null; 16279 try { 16280 // Add the package to the internal data structures 16281 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16282 16283 // Set the update and install times 16284 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16285 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16286 System.currentTimeMillis()); 16287 16288 // Update the package dynamic state if succeeded 16289 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16290 // Now that the install succeeded make sure we remove data 16291 // directories for any child package the update removed. 16292 final int deletedChildCount = (deletedPackage.childPackages != null) 16293 ? deletedPackage.childPackages.size() : 0; 16294 final int newChildCount = (newPackage.childPackages != null) 16295 ? newPackage.childPackages.size() : 0; 16296 for (int i = 0; i < deletedChildCount; i++) { 16297 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16298 boolean childPackageDeleted = true; 16299 for (int j = 0; j < newChildCount; j++) { 16300 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16301 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16302 childPackageDeleted = false; 16303 break; 16304 } 16305 } 16306 if (childPackageDeleted) { 16307 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16308 deletedChildPkg.packageName); 16309 if (ps != null && res.removedInfo.removedChildPackages != null) { 16310 PackageRemovedInfo removedChildRes = res.removedInfo 16311 .removedChildPackages.get(deletedChildPkg.packageName); 16312 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16313 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16314 } 16315 } 16316 } 16317 16318 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16319 installReason); 16320 prepareAppDataAfterInstallLIF(newPackage); 16321 16322 mDexManager.notifyPackageUpdated(newPackage.packageName, 16323 newPackage.baseCodePath, newPackage.splitCodePaths); 16324 } 16325 } catch (PackageManagerException e) { 16326 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16327 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16328 } 16329 16330 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16331 // Re installation failed. Restore old information 16332 // Remove new pkg information 16333 if (newPackage != null) { 16334 removeInstalledPackageLI(newPackage, true); 16335 } 16336 // Add back the old system package 16337 try { 16338 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16339 } catch (PackageManagerException e) { 16340 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16341 } 16342 16343 synchronized (mPackages) { 16344 if (disabledSystem) { 16345 enableSystemPackageLPw(deletedPackage); 16346 } 16347 16348 // Ensure the installer package name up to date 16349 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16350 16351 // Update permissions for restored package 16352 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16353 16354 mSettings.writeLPr(); 16355 } 16356 16357 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16358 + " after failed upgrade"); 16359 } 16360 } 16361 16362 /** 16363 * Checks whether the parent or any of the child packages have a change shared 16364 * user. For a package to be a valid update the shred users of the parent and 16365 * the children should match. We may later support changing child shared users. 16366 * @param oldPkg The updated package. 16367 * @param newPkg The update package. 16368 * @return The shared user that change between the versions. 16369 */ 16370 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16371 PackageParser.Package newPkg) { 16372 // Check parent shared user 16373 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16374 return newPkg.packageName; 16375 } 16376 // Check child shared users 16377 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16378 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16379 for (int i = 0; i < newChildCount; i++) { 16380 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16381 // If this child was present, did it have the same shared user? 16382 for (int j = 0; j < oldChildCount; j++) { 16383 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16384 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16385 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16386 return newChildPkg.packageName; 16387 } 16388 } 16389 } 16390 return null; 16391 } 16392 16393 private void removeNativeBinariesLI(PackageSetting ps) { 16394 // Remove the lib path for the parent package 16395 if (ps != null) { 16396 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16397 // Remove the lib path for the child packages 16398 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16399 for (int i = 0; i < childCount; i++) { 16400 PackageSetting childPs = null; 16401 synchronized (mPackages) { 16402 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16403 } 16404 if (childPs != null) { 16405 NativeLibraryHelper.removeNativeBinariesLI(childPs 16406 .legacyNativeLibraryPathString); 16407 } 16408 } 16409 } 16410 } 16411 16412 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16413 // Enable the parent package 16414 mSettings.enableSystemPackageLPw(pkg.packageName); 16415 // Enable the child packages 16416 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16417 for (int i = 0; i < childCount; i++) { 16418 PackageParser.Package childPkg = pkg.childPackages.get(i); 16419 mSettings.enableSystemPackageLPw(childPkg.packageName); 16420 } 16421 } 16422 16423 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16424 PackageParser.Package newPkg) { 16425 // Disable the parent package (parent always replaced) 16426 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16427 // Disable the child packages 16428 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16429 for (int i = 0; i < childCount; i++) { 16430 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16431 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16432 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16433 } 16434 return disabled; 16435 } 16436 16437 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16438 String installerPackageName) { 16439 // Enable the parent package 16440 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16441 // Enable the child packages 16442 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16443 for (int i = 0; i < childCount; i++) { 16444 PackageParser.Package childPkg = pkg.childPackages.get(i); 16445 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16446 } 16447 } 16448 16449 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16450 // Collect all used permissions in the UID 16451 ArraySet<String> usedPermissions = new ArraySet<>(); 16452 final int packageCount = su.packages.size(); 16453 for (int i = 0; i < packageCount; i++) { 16454 PackageSetting ps = su.packages.valueAt(i); 16455 if (ps.pkg == null) { 16456 continue; 16457 } 16458 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16459 for (int j = 0; j < requestedPermCount; j++) { 16460 String permission = ps.pkg.requestedPermissions.get(j); 16461 BasePermission bp = mSettings.mPermissions.get(permission); 16462 if (bp != null) { 16463 usedPermissions.add(permission); 16464 } 16465 } 16466 } 16467 16468 PermissionsState permissionsState = su.getPermissionsState(); 16469 // Prune install permissions 16470 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16471 final int installPermCount = installPermStates.size(); 16472 for (int i = installPermCount - 1; i >= 0; i--) { 16473 PermissionState permissionState = installPermStates.get(i); 16474 if (!usedPermissions.contains(permissionState.getName())) { 16475 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16476 if (bp != null) { 16477 permissionsState.revokeInstallPermission(bp); 16478 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16479 PackageManager.MASK_PERMISSION_FLAGS, 0); 16480 } 16481 } 16482 } 16483 16484 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16485 16486 // Prune runtime permissions 16487 for (int userId : allUserIds) { 16488 List<PermissionState> runtimePermStates = permissionsState 16489 .getRuntimePermissionStates(userId); 16490 final int runtimePermCount = runtimePermStates.size(); 16491 for (int i = runtimePermCount - 1; i >= 0; i--) { 16492 PermissionState permissionState = runtimePermStates.get(i); 16493 if (!usedPermissions.contains(permissionState.getName())) { 16494 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16495 if (bp != null) { 16496 permissionsState.revokeRuntimePermission(bp, userId); 16497 permissionsState.updatePermissionFlags(bp, userId, 16498 PackageManager.MASK_PERMISSION_FLAGS, 0); 16499 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16500 runtimePermissionChangedUserIds, userId); 16501 } 16502 } 16503 } 16504 } 16505 16506 return runtimePermissionChangedUserIds; 16507 } 16508 16509 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16510 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16511 // Update the parent package setting 16512 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16513 res, user, installReason); 16514 // Update the child packages setting 16515 final int childCount = (newPackage.childPackages != null) 16516 ? newPackage.childPackages.size() : 0; 16517 for (int i = 0; i < childCount; i++) { 16518 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16519 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16520 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16521 childRes.origUsers, childRes, user, installReason); 16522 } 16523 } 16524 16525 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16526 String installerPackageName, int[] allUsers, int[] installedForUsers, 16527 PackageInstalledInfo res, UserHandle user, int installReason) { 16528 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16529 16530 String pkgName = newPackage.packageName; 16531 synchronized (mPackages) { 16532 //write settings. the installStatus will be incomplete at this stage. 16533 //note that the new package setting would have already been 16534 //added to mPackages. It hasn't been persisted yet. 16535 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16536 // TODO: Remove this write? It's also written at the end of this method 16537 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16538 mSettings.writeLPr(); 16539 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16540 } 16541 16542 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16543 synchronized (mPackages) { 16544 updatePermissionsLPw(newPackage.packageName, newPackage, 16545 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16546 ? UPDATE_PERMISSIONS_ALL : 0)); 16547 // For system-bundled packages, we assume that installing an upgraded version 16548 // of the package implies that the user actually wants to run that new code, 16549 // so we enable the package. 16550 PackageSetting ps = mSettings.mPackages.get(pkgName); 16551 final int userId = user.getIdentifier(); 16552 if (ps != null) { 16553 if (isSystemApp(newPackage)) { 16554 if (DEBUG_INSTALL) { 16555 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16556 } 16557 // Enable system package for requested users 16558 if (res.origUsers != null) { 16559 for (int origUserId : res.origUsers) { 16560 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16561 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16562 origUserId, installerPackageName); 16563 } 16564 } 16565 } 16566 // Also convey the prior install/uninstall state 16567 if (allUsers != null && installedForUsers != null) { 16568 for (int currentUserId : allUsers) { 16569 final boolean installed = ArrayUtils.contains( 16570 installedForUsers, currentUserId); 16571 if (DEBUG_INSTALL) { 16572 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16573 } 16574 ps.setInstalled(installed, currentUserId); 16575 } 16576 // these install state changes will be persisted in the 16577 // upcoming call to mSettings.writeLPr(). 16578 } 16579 } 16580 // It's implied that when a user requests installation, they want the app to be 16581 // installed and enabled. 16582 if (userId != UserHandle.USER_ALL) { 16583 ps.setInstalled(true, userId); 16584 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16585 } 16586 16587 // When replacing an existing package, preserve the original install reason for all 16588 // users that had the package installed before. 16589 final Set<Integer> previousUserIds = new ArraySet<>(); 16590 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16591 final int installReasonCount = res.removedInfo.installReasons.size(); 16592 for (int i = 0; i < installReasonCount; i++) { 16593 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16594 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16595 ps.setInstallReason(previousInstallReason, previousUserId); 16596 previousUserIds.add(previousUserId); 16597 } 16598 } 16599 16600 // Set install reason for users that are having the package newly installed. 16601 if (userId == UserHandle.USER_ALL) { 16602 for (int currentUserId : sUserManager.getUserIds()) { 16603 if (!previousUserIds.contains(currentUserId)) { 16604 ps.setInstallReason(installReason, currentUserId); 16605 } 16606 } 16607 } else if (!previousUserIds.contains(userId)) { 16608 ps.setInstallReason(installReason, userId); 16609 } 16610 mSettings.writeKernelMappingLPr(ps); 16611 } 16612 res.name = pkgName; 16613 res.uid = newPackage.applicationInfo.uid; 16614 res.pkg = newPackage; 16615 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16616 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16617 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16618 //to update install status 16619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16620 mSettings.writeLPr(); 16621 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16622 } 16623 16624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16625 } 16626 16627 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16628 try { 16629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16630 installPackageLI(args, res); 16631 } finally { 16632 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16633 } 16634 } 16635 16636 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16637 final int installFlags = args.installFlags; 16638 final String installerPackageName = args.installerPackageName; 16639 final String volumeUuid = args.volumeUuid; 16640 final File tmpPackageFile = new File(args.getCodePath()); 16641 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16642 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16643 || (args.volumeUuid != null)); 16644 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16645 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16646 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16647 boolean replace = false; 16648 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16649 if (args.move != null) { 16650 // moving a complete application; perform an initial scan on the new install location 16651 scanFlags |= SCAN_INITIAL; 16652 } 16653 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16654 scanFlags |= SCAN_DONT_KILL_APP; 16655 } 16656 if (instantApp) { 16657 scanFlags |= SCAN_AS_INSTANT_APP; 16658 } 16659 if (fullApp) { 16660 scanFlags |= SCAN_AS_FULL_APP; 16661 } 16662 16663 // Result object to be returned 16664 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16665 16666 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16667 16668 // Sanity check 16669 if (instantApp && (forwardLocked || onExternal)) { 16670 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16671 + " external=" + onExternal); 16672 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16673 return; 16674 } 16675 16676 // Retrieve PackageSettings and parse package 16677 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16678 | PackageParser.PARSE_ENFORCE_CODE 16679 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16680 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16681 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16682 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16683 PackageParser pp = new PackageParser(); 16684 pp.setSeparateProcesses(mSeparateProcesses); 16685 pp.setDisplayMetrics(mMetrics); 16686 pp.setCallback(mPackageParserCallback); 16687 16688 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16689 final PackageParser.Package pkg; 16690 try { 16691 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16692 } catch (PackageParserException e) { 16693 res.setError("Failed parse during installPackageLI", e); 16694 return; 16695 } finally { 16696 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16697 } 16698 16699 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16700 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16701 Slog.w(TAG, "Instant app package " + pkg.packageName 16702 + " does not target O, this will be a fatal error."); 16703 // STOPSHIP: Make this a fatal error 16704 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16705 } 16706 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16707 Slog.w(TAG, "Instant app package " + pkg.packageName 16708 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16709 // STOPSHIP: Make this a fatal error 16710 pkg.applicationInfo.targetSandboxVersion = 2; 16711 } 16712 16713 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16714 // Static shared libraries have synthetic package names 16715 renameStaticSharedLibraryPackage(pkg); 16716 16717 // No static shared libs on external storage 16718 if (onExternal) { 16719 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16720 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16721 "Packages declaring static-shared libs cannot be updated"); 16722 return; 16723 } 16724 } 16725 16726 // If we are installing a clustered package add results for the children 16727 if (pkg.childPackages != null) { 16728 synchronized (mPackages) { 16729 final int childCount = pkg.childPackages.size(); 16730 for (int i = 0; i < childCount; i++) { 16731 PackageParser.Package childPkg = pkg.childPackages.get(i); 16732 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16733 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16734 childRes.pkg = childPkg; 16735 childRes.name = childPkg.packageName; 16736 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16737 if (childPs != null) { 16738 childRes.origUsers = childPs.queryInstalledUsers( 16739 sUserManager.getUserIds(), true); 16740 } 16741 if ((mPackages.containsKey(childPkg.packageName))) { 16742 childRes.removedInfo = new PackageRemovedInfo(); 16743 childRes.removedInfo.removedPackage = childPkg.packageName; 16744 } 16745 if (res.addedChildPackages == null) { 16746 res.addedChildPackages = new ArrayMap<>(); 16747 } 16748 res.addedChildPackages.put(childPkg.packageName, childRes); 16749 } 16750 } 16751 } 16752 16753 // If package doesn't declare API override, mark that we have an install 16754 // time CPU ABI override. 16755 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16756 pkg.cpuAbiOverride = args.abiOverride; 16757 } 16758 16759 String pkgName = res.name = pkg.packageName; 16760 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16761 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16762 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16763 return; 16764 } 16765 } 16766 16767 try { 16768 // either use what we've been given or parse directly from the APK 16769 if (args.certificates != null) { 16770 try { 16771 PackageParser.populateCertificates(pkg, args.certificates); 16772 } catch (PackageParserException e) { 16773 // there was something wrong with the certificates we were given; 16774 // try to pull them from the APK 16775 PackageParser.collectCertificates(pkg, parseFlags); 16776 } 16777 } else { 16778 PackageParser.collectCertificates(pkg, parseFlags); 16779 } 16780 } catch (PackageParserException e) { 16781 res.setError("Failed collect during installPackageLI", e); 16782 return; 16783 } 16784 16785 // Get rid of all references to package scan path via parser. 16786 pp = null; 16787 String oldCodePath = null; 16788 boolean systemApp = false; 16789 synchronized (mPackages) { 16790 // Check if installing already existing package 16791 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16792 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16793 if (pkg.mOriginalPackages != null 16794 && pkg.mOriginalPackages.contains(oldName) 16795 && mPackages.containsKey(oldName)) { 16796 // This package is derived from an original package, 16797 // and this device has been updating from that original 16798 // name. We must continue using the original name, so 16799 // rename the new package here. 16800 pkg.setPackageName(oldName); 16801 pkgName = pkg.packageName; 16802 replace = true; 16803 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16804 + oldName + " pkgName=" + pkgName); 16805 } else if (mPackages.containsKey(pkgName)) { 16806 // This package, under its official name, already exists 16807 // on the device; we should replace it. 16808 replace = true; 16809 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16810 } 16811 16812 // Child packages are installed through the parent package 16813 if (pkg.parentPackage != null) { 16814 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16815 "Package " + pkg.packageName + " is child of package " 16816 + pkg.parentPackage.parentPackage + ". Child packages " 16817 + "can be updated only through the parent package."); 16818 return; 16819 } 16820 16821 if (replace) { 16822 // Prevent apps opting out from runtime permissions 16823 PackageParser.Package oldPackage = mPackages.get(pkgName); 16824 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16825 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16826 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16827 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16828 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16829 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16830 + " doesn't support runtime permissions but the old" 16831 + " target SDK " + oldTargetSdk + " does."); 16832 return; 16833 } 16834 // Prevent apps from downgrading their targetSandbox. 16835 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16836 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16837 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16838 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16839 "Package " + pkg.packageName + " new target sandbox " 16840 + newTargetSandbox + " is incompatible with the previous value of" 16841 + oldTargetSandbox + "."); 16842 return; 16843 } 16844 16845 // Prevent installing of child packages 16846 if (oldPackage.parentPackage != null) { 16847 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16848 "Package " + pkg.packageName + " is child of package " 16849 + oldPackage.parentPackage + ". Child packages " 16850 + "can be updated only through the parent package."); 16851 return; 16852 } 16853 } 16854 } 16855 16856 PackageSetting ps = mSettings.mPackages.get(pkgName); 16857 if (ps != null) { 16858 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16859 16860 // Static shared libs have same package with different versions where 16861 // we internally use a synthetic package name to allow multiple versions 16862 // of the same package, therefore we need to compare signatures against 16863 // the package setting for the latest library version. 16864 PackageSetting signatureCheckPs = ps; 16865 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16866 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16867 if (libraryEntry != null) { 16868 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16869 } 16870 } 16871 16872 // Quick sanity check that we're signed correctly if updating; 16873 // we'll check this again later when scanning, but we want to 16874 // bail early here before tripping over redefined permissions. 16875 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16876 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16877 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16878 + pkg.packageName + " upgrade keys do not match the " 16879 + "previously installed version"); 16880 return; 16881 } 16882 } else { 16883 try { 16884 verifySignaturesLP(signatureCheckPs, pkg); 16885 } catch (PackageManagerException e) { 16886 res.setError(e.error, e.getMessage()); 16887 return; 16888 } 16889 } 16890 16891 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16892 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16893 systemApp = (ps.pkg.applicationInfo.flags & 16894 ApplicationInfo.FLAG_SYSTEM) != 0; 16895 } 16896 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16897 } 16898 16899 int N = pkg.permissions.size(); 16900 for (int i = N-1; i >= 0; i--) { 16901 PackageParser.Permission perm = pkg.permissions.get(i); 16902 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16903 16904 // Don't allow anyone but the platform to define ephemeral permissions. 16905 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16906 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16907 Slog.w(TAG, "Package " + pkg.packageName 16908 + " attempting to delcare ephemeral permission " 16909 + perm.info.name + "; Removing ephemeral."); 16910 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16911 } 16912 // Check whether the newly-scanned package wants to define an already-defined perm 16913 if (bp != null) { 16914 // If the defining package is signed with our cert, it's okay. This 16915 // also includes the "updating the same package" case, of course. 16916 // "updating same package" could also involve key-rotation. 16917 final boolean sigsOk; 16918 if (bp.sourcePackage.equals(pkg.packageName) 16919 && (bp.packageSetting instanceof PackageSetting) 16920 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16921 scanFlags))) { 16922 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16923 } else { 16924 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16925 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16926 } 16927 if (!sigsOk) { 16928 // If the owning package is the system itself, we log but allow 16929 // install to proceed; we fail the install on all other permission 16930 // redefinitions. 16931 if (!bp.sourcePackage.equals("android")) { 16932 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16933 + pkg.packageName + " attempting to redeclare permission " 16934 + perm.info.name + " already owned by " + bp.sourcePackage); 16935 res.origPermission = perm.info.name; 16936 res.origPackage = bp.sourcePackage; 16937 return; 16938 } else { 16939 Slog.w(TAG, "Package " + pkg.packageName 16940 + " attempting to redeclare system permission " 16941 + perm.info.name + "; ignoring new declaration"); 16942 pkg.permissions.remove(i); 16943 } 16944 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16945 // Prevent apps to change protection level to dangerous from any other 16946 // type as this would allow a privilege escalation where an app adds a 16947 // normal/signature permission in other app's group and later redefines 16948 // it as dangerous leading to the group auto-grant. 16949 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16950 == PermissionInfo.PROTECTION_DANGEROUS) { 16951 if (bp != null && !bp.isRuntime()) { 16952 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16953 + "non-runtime permission " + perm.info.name 16954 + " to runtime; keeping old protection level"); 16955 perm.info.protectionLevel = bp.protectionLevel; 16956 } 16957 } 16958 } 16959 } 16960 } 16961 } 16962 16963 if (systemApp) { 16964 if (onExternal) { 16965 // Abort update; system app can't be replaced with app on sdcard 16966 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16967 "Cannot install updates to system apps on sdcard"); 16968 return; 16969 } else if (instantApp) { 16970 // Abort update; system app can't be replaced with an instant app 16971 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16972 "Cannot update a system app with an instant app"); 16973 return; 16974 } 16975 } 16976 16977 if (args.move != null) { 16978 // We did an in-place move, so dex is ready to roll 16979 scanFlags |= SCAN_NO_DEX; 16980 scanFlags |= SCAN_MOVE; 16981 16982 synchronized (mPackages) { 16983 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16984 if (ps == null) { 16985 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16986 "Missing settings for moved package " + pkgName); 16987 } 16988 16989 // We moved the entire application as-is, so bring over the 16990 // previously derived ABI information. 16991 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16992 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16993 } 16994 16995 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16996 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16997 scanFlags |= SCAN_NO_DEX; 16998 16999 try { 17000 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17001 args.abiOverride : pkg.cpuAbiOverride); 17002 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17003 true /*extractLibs*/, mAppLib32InstallDir); 17004 } catch (PackageManagerException pme) { 17005 Slog.e(TAG, "Error deriving application ABI", pme); 17006 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17007 return; 17008 } 17009 17010 // Shared libraries for the package need to be updated. 17011 synchronized (mPackages) { 17012 try { 17013 updateSharedLibrariesLPr(pkg, null); 17014 } catch (PackageManagerException e) { 17015 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17016 } 17017 } 17018 17019 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17020 // Do not run PackageDexOptimizer through the local performDexOpt 17021 // method because `pkg` may not be in `mPackages` yet. 17022 // 17023 // Also, don't fail application installs if the dexopt step fails. 17024 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17025 null /* instructionSets */, false /* checkProfiles */, 17026 getCompilerFilterForReason(REASON_INSTALL), 17027 getOrCreateCompilerPackageStats(pkg), 17028 mDexManager.isUsedByOtherApps(pkg.packageName)); 17029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17030 17031 // Notify BackgroundDexOptService that the package has been changed. 17032 // If this is an update of a package which used to fail to compile, 17033 // BDOS will remove it from its blacklist. 17034 // TODO: Layering violation 17035 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17036 } 17037 17038 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17039 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17040 return; 17041 } 17042 17043 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17044 17045 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17046 "installPackageLI")) { 17047 if (replace) { 17048 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17049 // Static libs have a synthetic package name containing the version 17050 // and cannot be updated as an update would get a new package name, 17051 // unless this is the exact same version code which is useful for 17052 // development. 17053 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17054 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17055 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17056 + "static-shared libs cannot be updated"); 17057 return; 17058 } 17059 } 17060 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17061 installerPackageName, res, args.installReason); 17062 } else { 17063 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17064 args.user, installerPackageName, volumeUuid, res, args.installReason); 17065 } 17066 } 17067 17068 synchronized (mPackages) { 17069 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17070 if (ps != null) { 17071 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17072 ps.setUpdateAvailable(false /*updateAvailable*/); 17073 } 17074 17075 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17076 for (int i = 0; i < childCount; i++) { 17077 PackageParser.Package childPkg = pkg.childPackages.get(i); 17078 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17079 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17080 if (childPs != null) { 17081 childRes.newUsers = childPs.queryInstalledUsers( 17082 sUserManager.getUserIds(), true); 17083 } 17084 } 17085 17086 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17087 updateSequenceNumberLP(pkgName, res.newUsers); 17088 updateInstantAppInstallerLocked(); 17089 } 17090 } 17091 } 17092 17093 private void startIntentFilterVerifications(int userId, boolean replacing, 17094 PackageParser.Package pkg) { 17095 if (mIntentFilterVerifierComponent == null) { 17096 Slog.w(TAG, "No IntentFilter verification will not be done as " 17097 + "there is no IntentFilterVerifier available!"); 17098 return; 17099 } 17100 17101 final int verifierUid = getPackageUid( 17102 mIntentFilterVerifierComponent.getPackageName(), 17103 MATCH_DEBUG_TRIAGED_MISSING, 17104 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17105 17106 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17107 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17108 mHandler.sendMessage(msg); 17109 17110 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17111 for (int i = 0; i < childCount; i++) { 17112 PackageParser.Package childPkg = pkg.childPackages.get(i); 17113 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17114 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17115 mHandler.sendMessage(msg); 17116 } 17117 } 17118 17119 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17120 PackageParser.Package pkg) { 17121 int size = pkg.activities.size(); 17122 if (size == 0) { 17123 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17124 "No activity, so no need to verify any IntentFilter!"); 17125 return; 17126 } 17127 17128 final boolean hasDomainURLs = hasDomainURLs(pkg); 17129 if (!hasDomainURLs) { 17130 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17131 "No domain URLs, so no need to verify any IntentFilter!"); 17132 return; 17133 } 17134 17135 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17136 + " if any IntentFilter from the " + size 17137 + " Activities needs verification ..."); 17138 17139 int count = 0; 17140 final String packageName = pkg.packageName; 17141 17142 synchronized (mPackages) { 17143 // If this is a new install and we see that we've already run verification for this 17144 // package, we have nothing to do: it means the state was restored from backup. 17145 if (!replacing) { 17146 IntentFilterVerificationInfo ivi = 17147 mSettings.getIntentFilterVerificationLPr(packageName); 17148 if (ivi != null) { 17149 if (DEBUG_DOMAIN_VERIFICATION) { 17150 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17151 + ivi.getStatusString()); 17152 } 17153 return; 17154 } 17155 } 17156 17157 // If any filters need to be verified, then all need to be. 17158 boolean needToVerify = false; 17159 for (PackageParser.Activity a : pkg.activities) { 17160 for (ActivityIntentInfo filter : a.intents) { 17161 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17162 if (DEBUG_DOMAIN_VERIFICATION) { 17163 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17164 } 17165 needToVerify = true; 17166 break; 17167 } 17168 } 17169 } 17170 17171 if (needToVerify) { 17172 final int verificationId = mIntentFilterVerificationToken++; 17173 for (PackageParser.Activity a : pkg.activities) { 17174 for (ActivityIntentInfo filter : a.intents) { 17175 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17176 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17177 "Verification needed for IntentFilter:" + filter.toString()); 17178 mIntentFilterVerifier.addOneIntentFilterVerification( 17179 verifierUid, userId, verificationId, filter, packageName); 17180 count++; 17181 } 17182 } 17183 } 17184 } 17185 } 17186 17187 if (count > 0) { 17188 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17189 + " IntentFilter verification" + (count > 1 ? "s" : "") 17190 + " for userId:" + userId); 17191 mIntentFilterVerifier.startVerifications(userId); 17192 } else { 17193 if (DEBUG_DOMAIN_VERIFICATION) { 17194 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17195 } 17196 } 17197 } 17198 17199 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17200 final ComponentName cn = filter.activity.getComponentName(); 17201 final String packageName = cn.getPackageName(); 17202 17203 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17204 packageName); 17205 if (ivi == null) { 17206 return true; 17207 } 17208 int status = ivi.getStatus(); 17209 switch (status) { 17210 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17211 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17212 return true; 17213 17214 default: 17215 // Nothing to do 17216 return false; 17217 } 17218 } 17219 17220 private static boolean isMultiArch(ApplicationInfo info) { 17221 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17222 } 17223 17224 private static boolean isExternal(PackageParser.Package pkg) { 17225 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17226 } 17227 17228 private static boolean isExternal(PackageSetting ps) { 17229 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17230 } 17231 17232 private static boolean isSystemApp(PackageParser.Package pkg) { 17233 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17234 } 17235 17236 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17237 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17238 } 17239 17240 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17241 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17242 } 17243 17244 private static boolean isSystemApp(PackageSetting ps) { 17245 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17246 } 17247 17248 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17249 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17250 } 17251 17252 private int packageFlagsToInstallFlags(PackageSetting ps) { 17253 int installFlags = 0; 17254 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17255 // This existing package was an external ASEC install when we have 17256 // the external flag without a UUID 17257 installFlags |= PackageManager.INSTALL_EXTERNAL; 17258 } 17259 if (ps.isForwardLocked()) { 17260 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17261 } 17262 return installFlags; 17263 } 17264 17265 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17266 if (isExternal(pkg)) { 17267 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17268 return StorageManager.UUID_PRIMARY_PHYSICAL; 17269 } else { 17270 return pkg.volumeUuid; 17271 } 17272 } else { 17273 return StorageManager.UUID_PRIVATE_INTERNAL; 17274 } 17275 } 17276 17277 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17278 if (isExternal(pkg)) { 17279 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17280 return mSettings.getExternalVersion(); 17281 } else { 17282 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17283 } 17284 } else { 17285 return mSettings.getInternalVersion(); 17286 } 17287 } 17288 17289 private void deleteTempPackageFiles() { 17290 final FilenameFilter filter = new FilenameFilter() { 17291 public boolean accept(File dir, String name) { 17292 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17293 } 17294 }; 17295 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17296 file.delete(); 17297 } 17298 } 17299 17300 @Override 17301 public void deletePackageAsUser(String packageName, int versionCode, 17302 IPackageDeleteObserver observer, int userId, int flags) { 17303 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17304 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17305 } 17306 17307 @Override 17308 public void deletePackageVersioned(VersionedPackage versionedPackage, 17309 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17310 mContext.enforceCallingOrSelfPermission( 17311 android.Manifest.permission.DELETE_PACKAGES, null); 17312 Preconditions.checkNotNull(versionedPackage); 17313 Preconditions.checkNotNull(observer); 17314 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17315 PackageManager.VERSION_CODE_HIGHEST, 17316 Integer.MAX_VALUE, "versionCode must be >= -1"); 17317 17318 final String packageName = versionedPackage.getPackageName(); 17319 // TODO: We will change version code to long, so in the new API it is long 17320 final int versionCode = (int) versionedPackage.getVersionCode(); 17321 final String internalPackageName; 17322 synchronized (mPackages) { 17323 // Normalize package name to handle renamed packages and static libs 17324 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17325 // TODO: We will change version code to long, so in the new API it is long 17326 (int) versionedPackage.getVersionCode()); 17327 } 17328 17329 final int uid = Binder.getCallingUid(); 17330 if (!isOrphaned(internalPackageName) 17331 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17332 try { 17333 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17334 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17335 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17336 observer.onUserActionRequired(intent); 17337 } catch (RemoteException re) { 17338 } 17339 return; 17340 } 17341 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17342 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17343 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17344 mContext.enforceCallingOrSelfPermission( 17345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17346 "deletePackage for user " + userId); 17347 } 17348 17349 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17350 try { 17351 observer.onPackageDeleted(packageName, 17352 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17353 } catch (RemoteException re) { 17354 } 17355 return; 17356 } 17357 17358 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17359 try { 17360 observer.onPackageDeleted(packageName, 17361 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17362 } catch (RemoteException re) { 17363 } 17364 return; 17365 } 17366 17367 if (DEBUG_REMOVE) { 17368 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17369 + " deleteAllUsers: " + deleteAllUsers + " version=" 17370 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17371 ? "VERSION_CODE_HIGHEST" : versionCode)); 17372 } 17373 // Queue up an async operation since the package deletion may take a little while. 17374 mHandler.post(new Runnable() { 17375 public void run() { 17376 mHandler.removeCallbacks(this); 17377 int returnCode; 17378 if (!deleteAllUsers) { 17379 returnCode = deletePackageX(internalPackageName, versionCode, 17380 userId, deleteFlags); 17381 } else { 17382 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17383 internalPackageName, users); 17384 // If nobody is blocking uninstall, proceed with delete for all users 17385 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17386 returnCode = deletePackageX(internalPackageName, versionCode, 17387 userId, deleteFlags); 17388 } else { 17389 // Otherwise uninstall individually for users with blockUninstalls=false 17390 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17391 for (int userId : users) { 17392 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17393 returnCode = deletePackageX(internalPackageName, versionCode, 17394 userId, userFlags); 17395 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17396 Slog.w(TAG, "Package delete failed for user " + userId 17397 + ", returnCode " + returnCode); 17398 } 17399 } 17400 } 17401 // The app has only been marked uninstalled for certain users. 17402 // We still need to report that delete was blocked 17403 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17404 } 17405 } 17406 try { 17407 observer.onPackageDeleted(packageName, returnCode, null); 17408 } catch (RemoteException e) { 17409 Log.i(TAG, "Observer no longer exists."); 17410 } //end catch 17411 } //end run 17412 }); 17413 } 17414 17415 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17416 if (pkg.staticSharedLibName != null) { 17417 return pkg.manifestPackageName; 17418 } 17419 return pkg.packageName; 17420 } 17421 17422 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17423 // Handle renamed packages 17424 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17425 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17426 17427 // Is this a static library? 17428 SparseArray<SharedLibraryEntry> versionedLib = 17429 mStaticLibsByDeclaringPackage.get(packageName); 17430 if (versionedLib == null || versionedLib.size() <= 0) { 17431 return packageName; 17432 } 17433 17434 // Figure out which lib versions the caller can see 17435 SparseIntArray versionsCallerCanSee = null; 17436 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17437 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17438 && callingAppId != Process.ROOT_UID) { 17439 versionsCallerCanSee = new SparseIntArray(); 17440 String libName = versionedLib.valueAt(0).info.getName(); 17441 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17442 if (uidPackages != null) { 17443 for (String uidPackage : uidPackages) { 17444 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17445 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17446 if (libIdx >= 0) { 17447 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17448 versionsCallerCanSee.append(libVersion, libVersion); 17449 } 17450 } 17451 } 17452 } 17453 17454 // Caller can see nothing - done 17455 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17456 return packageName; 17457 } 17458 17459 // Find the version the caller can see and the app version code 17460 SharedLibraryEntry highestVersion = null; 17461 final int versionCount = versionedLib.size(); 17462 for (int i = 0; i < versionCount; i++) { 17463 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17464 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17465 libEntry.info.getVersion()) < 0) { 17466 continue; 17467 } 17468 // TODO: We will change version code to long, so in the new API it is long 17469 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17470 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17471 if (libVersionCode == versionCode) { 17472 return libEntry.apk; 17473 } 17474 } else if (highestVersion == null) { 17475 highestVersion = libEntry; 17476 } else if (libVersionCode > highestVersion.info 17477 .getDeclaringPackage().getVersionCode()) { 17478 highestVersion = libEntry; 17479 } 17480 } 17481 17482 if (highestVersion != null) { 17483 return highestVersion.apk; 17484 } 17485 17486 return packageName; 17487 } 17488 17489 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17490 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17491 || callingUid == Process.SYSTEM_UID) { 17492 return true; 17493 } 17494 final int callingUserId = UserHandle.getUserId(callingUid); 17495 // If the caller installed the pkgName, then allow it to silently uninstall. 17496 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17497 return true; 17498 } 17499 17500 // Allow package verifier to silently uninstall. 17501 if (mRequiredVerifierPackage != null && 17502 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17503 return true; 17504 } 17505 17506 // Allow package uninstaller to silently uninstall. 17507 if (mRequiredUninstallerPackage != null && 17508 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17509 return true; 17510 } 17511 17512 // Allow storage manager to silently uninstall. 17513 if (mStorageManagerPackage != null && 17514 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17515 return true; 17516 } 17517 return false; 17518 } 17519 17520 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17521 int[] result = EMPTY_INT_ARRAY; 17522 for (int userId : userIds) { 17523 if (getBlockUninstallForUser(packageName, userId)) { 17524 result = ArrayUtils.appendInt(result, userId); 17525 } 17526 } 17527 return result; 17528 } 17529 17530 @Override 17531 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17532 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17533 } 17534 17535 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17536 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17537 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17538 try { 17539 if (dpm != null) { 17540 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17541 /* callingUserOnly =*/ false); 17542 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17543 : deviceOwnerComponentName.getPackageName(); 17544 // Does the package contains the device owner? 17545 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17546 // this check is probably not needed, since DO should be registered as a device 17547 // admin on some user too. (Original bug for this: b/17657954) 17548 if (packageName.equals(deviceOwnerPackageName)) { 17549 return true; 17550 } 17551 // Does it contain a device admin for any user? 17552 int[] users; 17553 if (userId == UserHandle.USER_ALL) { 17554 users = sUserManager.getUserIds(); 17555 } else { 17556 users = new int[]{userId}; 17557 } 17558 for (int i = 0; i < users.length; ++i) { 17559 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17560 return true; 17561 } 17562 } 17563 } 17564 } catch (RemoteException e) { 17565 } 17566 return false; 17567 } 17568 17569 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17570 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17571 } 17572 17573 /** 17574 * This method is an internal method that could be get invoked either 17575 * to delete an installed package or to clean up a failed installation. 17576 * After deleting an installed package, a broadcast is sent to notify any 17577 * listeners that the package has been removed. For cleaning up a failed 17578 * installation, the broadcast is not necessary since the package's 17579 * installation wouldn't have sent the initial broadcast either 17580 * The key steps in deleting a package are 17581 * deleting the package information in internal structures like mPackages, 17582 * deleting the packages base directories through installd 17583 * updating mSettings to reflect current status 17584 * persisting settings for later use 17585 * sending a broadcast if necessary 17586 */ 17587 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17588 final PackageRemovedInfo info = new PackageRemovedInfo(); 17589 final boolean res; 17590 17591 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17592 ? UserHandle.USER_ALL : userId; 17593 17594 if (isPackageDeviceAdmin(packageName, removeUser)) { 17595 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17596 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17597 } 17598 17599 PackageSetting uninstalledPs = null; 17600 PackageParser.Package pkg = null; 17601 17602 // for the uninstall-updates case and restricted profiles, remember the per- 17603 // user handle installed state 17604 int[] allUsers; 17605 synchronized (mPackages) { 17606 uninstalledPs = mSettings.mPackages.get(packageName); 17607 if (uninstalledPs == null) { 17608 Slog.w(TAG, "Not removing non-existent package " + packageName); 17609 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17610 } 17611 17612 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17613 && uninstalledPs.versionCode != versionCode) { 17614 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17615 + uninstalledPs.versionCode + " != " + versionCode); 17616 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17617 } 17618 17619 // Static shared libs can be declared by any package, so let us not 17620 // allow removing a package if it provides a lib others depend on. 17621 pkg = mPackages.get(packageName); 17622 if (pkg != null && pkg.staticSharedLibName != null) { 17623 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17624 pkg.staticSharedLibVersion); 17625 if (libEntry != null) { 17626 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17627 libEntry.info, 0, userId); 17628 if (!ArrayUtils.isEmpty(libClientPackages)) { 17629 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17630 + " hosting lib " + libEntry.info.getName() + " version " 17631 + libEntry.info.getVersion() + " used by " + libClientPackages); 17632 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17633 } 17634 } 17635 } 17636 17637 allUsers = sUserManager.getUserIds(); 17638 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17639 } 17640 17641 final int freezeUser; 17642 if (isUpdatedSystemApp(uninstalledPs) 17643 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17644 // We're downgrading a system app, which will apply to all users, so 17645 // freeze them all during the downgrade 17646 freezeUser = UserHandle.USER_ALL; 17647 } else { 17648 freezeUser = removeUser; 17649 } 17650 17651 synchronized (mInstallLock) { 17652 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17653 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17654 deleteFlags, "deletePackageX")) { 17655 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17656 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17657 } 17658 synchronized (mPackages) { 17659 if (res) { 17660 if (pkg != null) { 17661 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17662 } 17663 updateSequenceNumberLP(packageName, info.removedUsers); 17664 updateInstantAppInstallerLocked(); 17665 } 17666 } 17667 } 17668 17669 if (res) { 17670 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17671 info.sendPackageRemovedBroadcasts(killApp); 17672 info.sendSystemPackageUpdatedBroadcasts(); 17673 info.sendSystemPackageAppearedBroadcasts(); 17674 } 17675 // Force a gc here. 17676 Runtime.getRuntime().gc(); 17677 // Delete the resources here after sending the broadcast to let 17678 // other processes clean up before deleting resources. 17679 if (info.args != null) { 17680 synchronized (mInstallLock) { 17681 info.args.doPostDeleteLI(true); 17682 } 17683 } 17684 17685 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17686 } 17687 17688 class PackageRemovedInfo { 17689 String removedPackage; 17690 int uid = -1; 17691 int removedAppId = -1; 17692 int[] origUsers; 17693 int[] removedUsers = null; 17694 int[] broadcastUsers = null; 17695 SparseArray<Integer> installReasons; 17696 boolean isRemovedPackageSystemUpdate = false; 17697 boolean isUpdate; 17698 boolean dataRemoved; 17699 boolean removedForAllUsers; 17700 boolean isStaticSharedLib; 17701 // Clean up resources deleted packages. 17702 InstallArgs args = null; 17703 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17704 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17705 17706 void sendPackageRemovedBroadcasts(boolean killApp) { 17707 sendPackageRemovedBroadcastInternal(killApp); 17708 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17709 for (int i = 0; i < childCount; i++) { 17710 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17711 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17712 } 17713 } 17714 17715 void sendSystemPackageUpdatedBroadcasts() { 17716 if (isRemovedPackageSystemUpdate) { 17717 sendSystemPackageUpdatedBroadcastsInternal(); 17718 final int childCount = (removedChildPackages != null) 17719 ? removedChildPackages.size() : 0; 17720 for (int i = 0; i < childCount; i++) { 17721 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17722 if (childInfo.isRemovedPackageSystemUpdate) { 17723 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17724 } 17725 } 17726 } 17727 } 17728 17729 void sendSystemPackageAppearedBroadcasts() { 17730 final int packageCount = (appearedChildPackages != null) 17731 ? appearedChildPackages.size() : 0; 17732 for (int i = 0; i < packageCount; i++) { 17733 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17734 sendPackageAddedForNewUsers(installedInfo.name, true, 17735 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17736 } 17737 } 17738 17739 private void sendSystemPackageUpdatedBroadcastsInternal() { 17740 Bundle extras = new Bundle(2); 17741 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17742 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17743 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17744 extras, 0, null, null, null); 17745 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17746 extras, 0, null, null, null); 17747 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17748 null, 0, removedPackage, null, null); 17749 } 17750 17751 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17752 // Don't send static shared library removal broadcasts as these 17753 // libs are visible only the the apps that depend on them an one 17754 // cannot remove the library if it has a dependency. 17755 if (isStaticSharedLib) { 17756 return; 17757 } 17758 Bundle extras = new Bundle(2); 17759 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17760 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17761 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17762 if (isUpdate || isRemovedPackageSystemUpdate) { 17763 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17764 } 17765 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17766 if (removedPackage != null) { 17767 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17768 extras, 0, null, null, broadcastUsers); 17769 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17770 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17771 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17772 null, null, broadcastUsers); 17773 } 17774 } 17775 if (removedAppId >= 0) { 17776 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17777 broadcastUsers); 17778 } 17779 } 17780 } 17781 17782 /* 17783 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17784 * flag is not set, the data directory is removed as well. 17785 * make sure this flag is set for partially installed apps. If not its meaningless to 17786 * delete a partially installed application. 17787 */ 17788 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17789 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17790 String packageName = ps.name; 17791 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17792 // Retrieve object to delete permissions for shared user later on 17793 final PackageParser.Package deletedPkg; 17794 final PackageSetting deletedPs; 17795 // reader 17796 synchronized (mPackages) { 17797 deletedPkg = mPackages.get(packageName); 17798 deletedPs = mSettings.mPackages.get(packageName); 17799 if (outInfo != null) { 17800 outInfo.removedPackage = packageName; 17801 outInfo.isStaticSharedLib = deletedPkg != null 17802 && deletedPkg.staticSharedLibName != null; 17803 outInfo.removedUsers = deletedPs != null 17804 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17805 : null; 17806 if (outInfo.removedUsers == null) { 17807 outInfo.broadcastUsers = null; 17808 } else { 17809 outInfo.broadcastUsers = EMPTY_INT_ARRAY; 17810 int[] allUsers = outInfo.removedUsers; 17811 for (int i = allUsers.length - 1; i >= 0; --i) { 17812 final int userId = allUsers[i]; 17813 if (deletedPs.getInstantApp(userId)) { 17814 continue; 17815 } 17816 outInfo.broadcastUsers = 17817 ArrayUtils.appendInt(outInfo.broadcastUsers, userId); 17818 } 17819 } 17820 } 17821 } 17822 17823 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17824 17825 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17826 final PackageParser.Package resolvedPkg; 17827 if (deletedPkg != null) { 17828 resolvedPkg = deletedPkg; 17829 } else { 17830 // We don't have a parsed package when it lives on an ejected 17831 // adopted storage device, so fake something together 17832 resolvedPkg = new PackageParser.Package(ps.name); 17833 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17834 } 17835 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17836 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17837 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17838 if (outInfo != null) { 17839 outInfo.dataRemoved = true; 17840 } 17841 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17842 } 17843 17844 int removedAppId = -1; 17845 17846 // writer 17847 synchronized (mPackages) { 17848 boolean installedStateChanged = false; 17849 if (deletedPs != null) { 17850 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17851 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17852 clearDefaultBrowserIfNeeded(packageName); 17853 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17854 removedAppId = mSettings.removePackageLPw(packageName); 17855 if (outInfo != null) { 17856 outInfo.removedAppId = removedAppId; 17857 } 17858 updatePermissionsLPw(deletedPs.name, null, 0); 17859 if (deletedPs.sharedUser != null) { 17860 // Remove permissions associated with package. Since runtime 17861 // permissions are per user we have to kill the removed package 17862 // or packages running under the shared user of the removed 17863 // package if revoking the permissions requested only by the removed 17864 // package is successful and this causes a change in gids. 17865 for (int userId : UserManagerService.getInstance().getUserIds()) { 17866 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17867 userId); 17868 if (userIdToKill == UserHandle.USER_ALL 17869 || userIdToKill >= UserHandle.USER_SYSTEM) { 17870 // If gids changed for this user, kill all affected packages. 17871 mHandler.post(new Runnable() { 17872 @Override 17873 public void run() { 17874 // This has to happen with no lock held. 17875 killApplication(deletedPs.name, deletedPs.appId, 17876 KILL_APP_REASON_GIDS_CHANGED); 17877 } 17878 }); 17879 break; 17880 } 17881 } 17882 } 17883 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17884 } 17885 // make sure to preserve per-user disabled state if this removal was just 17886 // a downgrade of a system app to the factory package 17887 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17888 if (DEBUG_REMOVE) { 17889 Slog.d(TAG, "Propagating install state across downgrade"); 17890 } 17891 for (int userId : allUserHandles) { 17892 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17893 if (DEBUG_REMOVE) { 17894 Slog.d(TAG, " user " + userId + " => " + installed); 17895 } 17896 if (installed != ps.getInstalled(userId)) { 17897 installedStateChanged = true; 17898 } 17899 ps.setInstalled(installed, userId); 17900 } 17901 } 17902 } 17903 // can downgrade to reader 17904 if (writeSettings) { 17905 // Save settings now 17906 mSettings.writeLPr(); 17907 } 17908 if (installedStateChanged) { 17909 mSettings.writeKernelMappingLPr(ps); 17910 } 17911 } 17912 if (removedAppId != -1) { 17913 // A user ID was deleted here. Go through all users and remove it 17914 // from KeyStore. 17915 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17916 } 17917 } 17918 17919 static boolean locationIsPrivileged(File path) { 17920 try { 17921 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17922 .getCanonicalPath(); 17923 return path.getCanonicalPath().startsWith(privilegedAppDir); 17924 } catch (IOException e) { 17925 Slog.e(TAG, "Unable to access code path " + path); 17926 } 17927 return false; 17928 } 17929 17930 /* 17931 * Tries to delete system package. 17932 */ 17933 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17934 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17935 boolean writeSettings) { 17936 if (deletedPs.parentPackageName != null) { 17937 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17938 return false; 17939 } 17940 17941 final boolean applyUserRestrictions 17942 = (allUserHandles != null) && (outInfo.origUsers != null); 17943 final PackageSetting disabledPs; 17944 // Confirm if the system package has been updated 17945 // An updated system app can be deleted. This will also have to restore 17946 // the system pkg from system partition 17947 // reader 17948 synchronized (mPackages) { 17949 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17950 } 17951 17952 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17953 + " disabledPs=" + disabledPs); 17954 17955 if (disabledPs == null) { 17956 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17957 return false; 17958 } else if (DEBUG_REMOVE) { 17959 Slog.d(TAG, "Deleting system pkg from data partition"); 17960 } 17961 17962 if (DEBUG_REMOVE) { 17963 if (applyUserRestrictions) { 17964 Slog.d(TAG, "Remembering install states:"); 17965 for (int userId : allUserHandles) { 17966 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17967 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17968 } 17969 } 17970 } 17971 17972 // Delete the updated package 17973 outInfo.isRemovedPackageSystemUpdate = true; 17974 if (outInfo.removedChildPackages != null) { 17975 final int childCount = (deletedPs.childPackageNames != null) 17976 ? deletedPs.childPackageNames.size() : 0; 17977 for (int i = 0; i < childCount; i++) { 17978 String childPackageName = deletedPs.childPackageNames.get(i); 17979 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17980 .contains(childPackageName)) { 17981 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17982 childPackageName); 17983 if (childInfo != null) { 17984 childInfo.isRemovedPackageSystemUpdate = true; 17985 } 17986 } 17987 } 17988 } 17989 17990 if (disabledPs.versionCode < deletedPs.versionCode) { 17991 // Delete data for downgrades 17992 flags &= ~PackageManager.DELETE_KEEP_DATA; 17993 } else { 17994 // Preserve data by setting flag 17995 flags |= PackageManager.DELETE_KEEP_DATA; 17996 } 17997 17998 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17999 outInfo, writeSettings, disabledPs.pkg); 18000 if (!ret) { 18001 return false; 18002 } 18003 18004 // writer 18005 synchronized (mPackages) { 18006 // Reinstate the old system package 18007 enableSystemPackageLPw(disabledPs.pkg); 18008 // Remove any native libraries from the upgraded package. 18009 removeNativeBinariesLI(deletedPs); 18010 } 18011 18012 // Install the system package 18013 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18014 int parseFlags = mDefParseFlags 18015 | PackageParser.PARSE_MUST_BE_APK 18016 | PackageParser.PARSE_IS_SYSTEM 18017 | PackageParser.PARSE_IS_SYSTEM_DIR; 18018 if (locationIsPrivileged(disabledPs.codePath)) { 18019 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18020 } 18021 18022 final PackageParser.Package newPkg; 18023 try { 18024 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18025 0 /* currentTime */, null); 18026 } catch (PackageManagerException e) { 18027 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18028 + e.getMessage()); 18029 return false; 18030 } 18031 18032 try { 18033 // update shared libraries for the newly re-installed system package 18034 updateSharedLibrariesLPr(newPkg, null); 18035 } catch (PackageManagerException e) { 18036 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18037 } 18038 18039 prepareAppDataAfterInstallLIF(newPkg); 18040 18041 // writer 18042 synchronized (mPackages) { 18043 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18044 18045 // Propagate the permissions state as we do not want to drop on the floor 18046 // runtime permissions. The update permissions method below will take 18047 // care of removing obsolete permissions and grant install permissions. 18048 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18049 updatePermissionsLPw(newPkg.packageName, newPkg, 18050 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18051 18052 if (applyUserRestrictions) { 18053 boolean installedStateChanged = false; 18054 if (DEBUG_REMOVE) { 18055 Slog.d(TAG, "Propagating install state across reinstall"); 18056 } 18057 for (int userId : allUserHandles) { 18058 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18059 if (DEBUG_REMOVE) { 18060 Slog.d(TAG, " user " + userId + " => " + installed); 18061 } 18062 if (installed != ps.getInstalled(userId)) { 18063 installedStateChanged = true; 18064 } 18065 ps.setInstalled(installed, userId); 18066 18067 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18068 } 18069 // Regardless of writeSettings we need to ensure that this restriction 18070 // state propagation is persisted 18071 mSettings.writeAllUsersPackageRestrictionsLPr(); 18072 if (installedStateChanged) { 18073 mSettings.writeKernelMappingLPr(ps); 18074 } 18075 } 18076 // can downgrade to reader here 18077 if (writeSettings) { 18078 mSettings.writeLPr(); 18079 } 18080 } 18081 return true; 18082 } 18083 18084 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18085 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18086 PackageRemovedInfo outInfo, boolean writeSettings, 18087 PackageParser.Package replacingPackage) { 18088 synchronized (mPackages) { 18089 if (outInfo != null) { 18090 outInfo.uid = ps.appId; 18091 } 18092 18093 if (outInfo != null && outInfo.removedChildPackages != null) { 18094 final int childCount = (ps.childPackageNames != null) 18095 ? ps.childPackageNames.size() : 0; 18096 for (int i = 0; i < childCount; i++) { 18097 String childPackageName = ps.childPackageNames.get(i); 18098 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18099 if (childPs == null) { 18100 return false; 18101 } 18102 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18103 childPackageName); 18104 if (childInfo != null) { 18105 childInfo.uid = childPs.appId; 18106 } 18107 } 18108 } 18109 } 18110 18111 // Delete package data from internal structures and also remove data if flag is set 18112 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18113 18114 // Delete the child packages data 18115 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18116 for (int i = 0; i < childCount; i++) { 18117 PackageSetting childPs; 18118 synchronized (mPackages) { 18119 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18120 } 18121 if (childPs != null) { 18122 PackageRemovedInfo childOutInfo = (outInfo != null 18123 && outInfo.removedChildPackages != null) 18124 ? outInfo.removedChildPackages.get(childPs.name) : null; 18125 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18126 && (replacingPackage != null 18127 && !replacingPackage.hasChildPackage(childPs.name)) 18128 ? flags & ~DELETE_KEEP_DATA : flags; 18129 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18130 deleteFlags, writeSettings); 18131 } 18132 } 18133 18134 // Delete application code and resources only for parent packages 18135 if (ps.parentPackageName == null) { 18136 if (deleteCodeAndResources && (outInfo != null)) { 18137 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18138 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18139 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18140 } 18141 } 18142 18143 return true; 18144 } 18145 18146 @Override 18147 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18148 int userId) { 18149 mContext.enforceCallingOrSelfPermission( 18150 android.Manifest.permission.DELETE_PACKAGES, null); 18151 synchronized (mPackages) { 18152 PackageSetting ps = mSettings.mPackages.get(packageName); 18153 if (ps == null) { 18154 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18155 return false; 18156 } 18157 // Cannot block uninstall of static shared libs as they are 18158 // considered a part of the using app (emulating static linking). 18159 // Also static libs are installed always on internal storage. 18160 PackageParser.Package pkg = mPackages.get(packageName); 18161 if (pkg != null && pkg.staticSharedLibName != null) { 18162 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18163 + " providing static shared library: " + pkg.staticSharedLibName); 18164 return false; 18165 } 18166 if (!ps.getInstalled(userId)) { 18167 // Can't block uninstall for an app that is not installed or enabled. 18168 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18169 return false; 18170 } 18171 ps.setBlockUninstall(blockUninstall, userId); 18172 mSettings.writePackageRestrictionsLPr(userId); 18173 } 18174 return true; 18175 } 18176 18177 @Override 18178 public boolean getBlockUninstallForUser(String packageName, int userId) { 18179 synchronized (mPackages) { 18180 PackageSetting ps = mSettings.mPackages.get(packageName); 18181 if (ps == null) { 18182 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18183 return false; 18184 } 18185 return ps.getBlockUninstall(userId); 18186 } 18187 } 18188 18189 @Override 18190 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18191 int callingUid = Binder.getCallingUid(); 18192 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18193 throw new SecurityException( 18194 "setRequiredForSystemUser can only be run by the system or root"); 18195 } 18196 synchronized (mPackages) { 18197 PackageSetting ps = mSettings.mPackages.get(packageName); 18198 if (ps == null) { 18199 Log.w(TAG, "Package doesn't exist: " + packageName); 18200 return false; 18201 } 18202 if (systemUserApp) { 18203 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18204 } else { 18205 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18206 } 18207 mSettings.writeLPr(); 18208 } 18209 return true; 18210 } 18211 18212 /* 18213 * This method handles package deletion in general 18214 */ 18215 private boolean deletePackageLIF(String packageName, UserHandle user, 18216 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18217 PackageRemovedInfo outInfo, boolean writeSettings, 18218 PackageParser.Package replacingPackage) { 18219 if (packageName == null) { 18220 Slog.w(TAG, "Attempt to delete null packageName."); 18221 return false; 18222 } 18223 18224 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18225 18226 PackageSetting ps; 18227 synchronized (mPackages) { 18228 ps = mSettings.mPackages.get(packageName); 18229 if (ps == null) { 18230 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18231 return false; 18232 } 18233 18234 if (ps.parentPackageName != null && (!isSystemApp(ps) 18235 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18236 if (DEBUG_REMOVE) { 18237 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18238 + ((user == null) ? UserHandle.USER_ALL : user)); 18239 } 18240 final int removedUserId = (user != null) ? user.getIdentifier() 18241 : UserHandle.USER_ALL; 18242 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18243 return false; 18244 } 18245 markPackageUninstalledForUserLPw(ps, user); 18246 scheduleWritePackageRestrictionsLocked(user); 18247 return true; 18248 } 18249 } 18250 18251 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18252 && user.getIdentifier() != UserHandle.USER_ALL)) { 18253 // The caller is asking that the package only be deleted for a single 18254 // user. To do this, we just mark its uninstalled state and delete 18255 // its data. If this is a system app, we only allow this to happen if 18256 // they have set the special DELETE_SYSTEM_APP which requests different 18257 // semantics than normal for uninstalling system apps. 18258 markPackageUninstalledForUserLPw(ps, user); 18259 18260 if (!isSystemApp(ps)) { 18261 // Do not uninstall the APK if an app should be cached 18262 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18263 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18264 // Other user still have this package installed, so all 18265 // we need to do is clear this user's data and save that 18266 // it is uninstalled. 18267 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18268 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18269 return false; 18270 } 18271 scheduleWritePackageRestrictionsLocked(user); 18272 return true; 18273 } else { 18274 // We need to set it back to 'installed' so the uninstall 18275 // broadcasts will be sent correctly. 18276 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18277 ps.setInstalled(true, user.getIdentifier()); 18278 mSettings.writeKernelMappingLPr(ps); 18279 } 18280 } else { 18281 // This is a system app, so we assume that the 18282 // other users still have this package installed, so all 18283 // we need to do is clear this user's data and save that 18284 // it is uninstalled. 18285 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18286 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18287 return false; 18288 } 18289 scheduleWritePackageRestrictionsLocked(user); 18290 return true; 18291 } 18292 } 18293 18294 // If we are deleting a composite package for all users, keep track 18295 // of result for each child. 18296 if (ps.childPackageNames != null && outInfo != null) { 18297 synchronized (mPackages) { 18298 final int childCount = ps.childPackageNames.size(); 18299 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18300 for (int i = 0; i < childCount; i++) { 18301 String childPackageName = ps.childPackageNames.get(i); 18302 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18303 childInfo.removedPackage = childPackageName; 18304 outInfo.removedChildPackages.put(childPackageName, childInfo); 18305 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18306 if (childPs != null) { 18307 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18308 } 18309 } 18310 } 18311 } 18312 18313 boolean ret = false; 18314 if (isSystemApp(ps)) { 18315 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18316 // When an updated system application is deleted we delete the existing resources 18317 // as well and fall back to existing code in system partition 18318 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18319 } else { 18320 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18321 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18322 outInfo, writeSettings, replacingPackage); 18323 } 18324 18325 // Take a note whether we deleted the package for all users 18326 if (outInfo != null) { 18327 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18328 if (outInfo.removedChildPackages != null) { 18329 synchronized (mPackages) { 18330 final int childCount = outInfo.removedChildPackages.size(); 18331 for (int i = 0; i < childCount; i++) { 18332 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18333 if (childInfo != null) { 18334 childInfo.removedForAllUsers = mPackages.get( 18335 childInfo.removedPackage) == null; 18336 } 18337 } 18338 } 18339 } 18340 // If we uninstalled an update to a system app there may be some 18341 // child packages that appeared as they are declared in the system 18342 // app but were not declared in the update. 18343 if (isSystemApp(ps)) { 18344 synchronized (mPackages) { 18345 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18346 final int childCount = (updatedPs.childPackageNames != null) 18347 ? updatedPs.childPackageNames.size() : 0; 18348 for (int i = 0; i < childCount; i++) { 18349 String childPackageName = updatedPs.childPackageNames.get(i); 18350 if (outInfo.removedChildPackages == null 18351 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18352 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18353 if (childPs == null) { 18354 continue; 18355 } 18356 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18357 installRes.name = childPackageName; 18358 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18359 installRes.pkg = mPackages.get(childPackageName); 18360 installRes.uid = childPs.pkg.applicationInfo.uid; 18361 if (outInfo.appearedChildPackages == null) { 18362 outInfo.appearedChildPackages = new ArrayMap<>(); 18363 } 18364 outInfo.appearedChildPackages.put(childPackageName, installRes); 18365 } 18366 } 18367 } 18368 } 18369 } 18370 18371 return ret; 18372 } 18373 18374 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18375 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18376 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18377 for (int nextUserId : userIds) { 18378 if (DEBUG_REMOVE) { 18379 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18380 } 18381 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18382 false /*installed*/, 18383 true /*stopped*/, 18384 true /*notLaunched*/, 18385 false /*hidden*/, 18386 false /*suspended*/, 18387 false /*instantApp*/, 18388 null /*lastDisableAppCaller*/, 18389 null /*enabledComponents*/, 18390 null /*disabledComponents*/, 18391 false /*blockUninstall*/, 18392 ps.readUserState(nextUserId).domainVerificationStatus, 18393 0, PackageManager.INSTALL_REASON_UNKNOWN); 18394 } 18395 mSettings.writeKernelMappingLPr(ps); 18396 } 18397 18398 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18399 PackageRemovedInfo outInfo) { 18400 final PackageParser.Package pkg; 18401 synchronized (mPackages) { 18402 pkg = mPackages.get(ps.name); 18403 } 18404 18405 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18406 : new int[] {userId}; 18407 for (int nextUserId : userIds) { 18408 if (DEBUG_REMOVE) { 18409 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18410 + nextUserId); 18411 } 18412 18413 destroyAppDataLIF(pkg, userId, 18414 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18415 destroyAppProfilesLIF(pkg, userId); 18416 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18417 schedulePackageCleaning(ps.name, nextUserId, false); 18418 synchronized (mPackages) { 18419 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18420 scheduleWritePackageRestrictionsLocked(nextUserId); 18421 } 18422 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18423 } 18424 } 18425 18426 if (outInfo != null) { 18427 outInfo.removedPackage = ps.name; 18428 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18429 outInfo.removedAppId = ps.appId; 18430 outInfo.removedUsers = userIds; 18431 } 18432 18433 return true; 18434 } 18435 18436 private final class ClearStorageConnection implements ServiceConnection { 18437 IMediaContainerService mContainerService; 18438 18439 @Override 18440 public void onServiceConnected(ComponentName name, IBinder service) { 18441 synchronized (this) { 18442 mContainerService = IMediaContainerService.Stub 18443 .asInterface(Binder.allowBlocking(service)); 18444 notifyAll(); 18445 } 18446 } 18447 18448 @Override 18449 public void onServiceDisconnected(ComponentName name) { 18450 } 18451 } 18452 18453 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18454 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18455 18456 final boolean mounted; 18457 if (Environment.isExternalStorageEmulated()) { 18458 mounted = true; 18459 } else { 18460 final String status = Environment.getExternalStorageState(); 18461 18462 mounted = status.equals(Environment.MEDIA_MOUNTED) 18463 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18464 } 18465 18466 if (!mounted) { 18467 return; 18468 } 18469 18470 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18471 int[] users; 18472 if (userId == UserHandle.USER_ALL) { 18473 users = sUserManager.getUserIds(); 18474 } else { 18475 users = new int[] { userId }; 18476 } 18477 final ClearStorageConnection conn = new ClearStorageConnection(); 18478 if (mContext.bindServiceAsUser( 18479 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18480 try { 18481 for (int curUser : users) { 18482 long timeout = SystemClock.uptimeMillis() + 5000; 18483 synchronized (conn) { 18484 long now; 18485 while (conn.mContainerService == null && 18486 (now = SystemClock.uptimeMillis()) < timeout) { 18487 try { 18488 conn.wait(timeout - now); 18489 } catch (InterruptedException e) { 18490 } 18491 } 18492 } 18493 if (conn.mContainerService == null) { 18494 return; 18495 } 18496 18497 final UserEnvironment userEnv = new UserEnvironment(curUser); 18498 clearDirectory(conn.mContainerService, 18499 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18500 if (allData) { 18501 clearDirectory(conn.mContainerService, 18502 userEnv.buildExternalStorageAppDataDirs(packageName)); 18503 clearDirectory(conn.mContainerService, 18504 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18505 } 18506 } 18507 } finally { 18508 mContext.unbindService(conn); 18509 } 18510 } 18511 } 18512 18513 @Override 18514 public void clearApplicationProfileData(String packageName) { 18515 enforceSystemOrRoot("Only the system can clear all profile data"); 18516 18517 final PackageParser.Package pkg; 18518 synchronized (mPackages) { 18519 pkg = mPackages.get(packageName); 18520 } 18521 18522 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18523 synchronized (mInstallLock) { 18524 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18525 } 18526 } 18527 } 18528 18529 @Override 18530 public void clearApplicationUserData(final String packageName, 18531 final IPackageDataObserver observer, final int userId) { 18532 mContext.enforceCallingOrSelfPermission( 18533 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18534 18535 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18536 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18537 18538 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18539 throw new SecurityException("Cannot clear data for a protected package: " 18540 + packageName); 18541 } 18542 // Queue up an async operation since the package deletion may take a little while. 18543 mHandler.post(new Runnable() { 18544 public void run() { 18545 mHandler.removeCallbacks(this); 18546 final boolean succeeded; 18547 try (PackageFreezer freezer = freezePackage(packageName, 18548 "clearApplicationUserData")) { 18549 synchronized (mInstallLock) { 18550 succeeded = clearApplicationUserDataLIF(packageName, userId); 18551 } 18552 clearExternalStorageDataSync(packageName, userId, true); 18553 synchronized (mPackages) { 18554 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18555 packageName, userId); 18556 } 18557 } 18558 if (succeeded) { 18559 // invoke DeviceStorageMonitor's update method to clear any notifications 18560 DeviceStorageMonitorInternal dsm = LocalServices 18561 .getService(DeviceStorageMonitorInternal.class); 18562 if (dsm != null) { 18563 dsm.checkMemory(); 18564 } 18565 } 18566 if(observer != null) { 18567 try { 18568 observer.onRemoveCompleted(packageName, succeeded); 18569 } catch (RemoteException e) { 18570 Log.i(TAG, "Observer no longer exists."); 18571 } 18572 } //end if observer 18573 } //end run 18574 }); 18575 } 18576 18577 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18578 if (packageName == null) { 18579 Slog.w(TAG, "Attempt to delete null packageName."); 18580 return false; 18581 } 18582 18583 // Try finding details about the requested package 18584 PackageParser.Package pkg; 18585 synchronized (mPackages) { 18586 pkg = mPackages.get(packageName); 18587 if (pkg == null) { 18588 final PackageSetting ps = mSettings.mPackages.get(packageName); 18589 if (ps != null) { 18590 pkg = ps.pkg; 18591 } 18592 } 18593 18594 if (pkg == null) { 18595 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18596 return false; 18597 } 18598 18599 PackageSetting ps = (PackageSetting) pkg.mExtras; 18600 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18601 } 18602 18603 clearAppDataLIF(pkg, userId, 18604 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18605 18606 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18607 removeKeystoreDataIfNeeded(userId, appId); 18608 18609 UserManagerInternal umInternal = getUserManagerInternal(); 18610 final int flags; 18611 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18612 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18613 } else if (umInternal.isUserRunning(userId)) { 18614 flags = StorageManager.FLAG_STORAGE_DE; 18615 } else { 18616 flags = 0; 18617 } 18618 prepareAppDataContentsLIF(pkg, userId, flags); 18619 18620 return true; 18621 } 18622 18623 /** 18624 * Reverts user permission state changes (permissions and flags) in 18625 * all packages for a given user. 18626 * 18627 * @param userId The device user for which to do a reset. 18628 */ 18629 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18630 final int packageCount = mPackages.size(); 18631 for (int i = 0; i < packageCount; i++) { 18632 PackageParser.Package pkg = mPackages.valueAt(i); 18633 PackageSetting ps = (PackageSetting) pkg.mExtras; 18634 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18635 } 18636 } 18637 18638 private void resetNetworkPolicies(int userId) { 18639 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18640 } 18641 18642 /** 18643 * Reverts user permission state changes (permissions and flags). 18644 * 18645 * @param ps The package for which to reset. 18646 * @param userId The device user for which to do a reset. 18647 */ 18648 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18649 final PackageSetting ps, final int userId) { 18650 if (ps.pkg == null) { 18651 return; 18652 } 18653 18654 // These are flags that can change base on user actions. 18655 final int userSettableMask = FLAG_PERMISSION_USER_SET 18656 | FLAG_PERMISSION_USER_FIXED 18657 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18658 | FLAG_PERMISSION_REVIEW_REQUIRED; 18659 18660 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18661 | FLAG_PERMISSION_POLICY_FIXED; 18662 18663 boolean writeInstallPermissions = false; 18664 boolean writeRuntimePermissions = false; 18665 18666 final int permissionCount = ps.pkg.requestedPermissions.size(); 18667 for (int i = 0; i < permissionCount; i++) { 18668 String permission = ps.pkg.requestedPermissions.get(i); 18669 18670 BasePermission bp = mSettings.mPermissions.get(permission); 18671 if (bp == null) { 18672 continue; 18673 } 18674 18675 // If shared user we just reset the state to which only this app contributed. 18676 if (ps.sharedUser != null) { 18677 boolean used = false; 18678 final int packageCount = ps.sharedUser.packages.size(); 18679 for (int j = 0; j < packageCount; j++) { 18680 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18681 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18682 && pkg.pkg.requestedPermissions.contains(permission)) { 18683 used = true; 18684 break; 18685 } 18686 } 18687 if (used) { 18688 continue; 18689 } 18690 } 18691 18692 PermissionsState permissionsState = ps.getPermissionsState(); 18693 18694 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18695 18696 // Always clear the user settable flags. 18697 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18698 bp.name) != null; 18699 // If permission review is enabled and this is a legacy app, mark the 18700 // permission as requiring a review as this is the initial state. 18701 int flags = 0; 18702 if (mPermissionReviewRequired 18703 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18704 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18705 } 18706 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18707 if (hasInstallState) { 18708 writeInstallPermissions = true; 18709 } else { 18710 writeRuntimePermissions = true; 18711 } 18712 } 18713 18714 // Below is only runtime permission handling. 18715 if (!bp.isRuntime()) { 18716 continue; 18717 } 18718 18719 // Never clobber system or policy. 18720 if ((oldFlags & policyOrSystemFlags) != 0) { 18721 continue; 18722 } 18723 18724 // If this permission was granted by default, make sure it is. 18725 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18726 if (permissionsState.grantRuntimePermission(bp, userId) 18727 != PERMISSION_OPERATION_FAILURE) { 18728 writeRuntimePermissions = true; 18729 } 18730 // If permission review is enabled the permissions for a legacy apps 18731 // are represented as constantly granted runtime ones, so don't revoke. 18732 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18733 // Otherwise, reset the permission. 18734 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18735 switch (revokeResult) { 18736 case PERMISSION_OPERATION_SUCCESS: 18737 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18738 writeRuntimePermissions = true; 18739 final int appId = ps.appId; 18740 mHandler.post(new Runnable() { 18741 @Override 18742 public void run() { 18743 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18744 } 18745 }); 18746 } break; 18747 } 18748 } 18749 } 18750 18751 // Synchronously write as we are taking permissions away. 18752 if (writeRuntimePermissions) { 18753 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18754 } 18755 18756 // Synchronously write as we are taking permissions away. 18757 if (writeInstallPermissions) { 18758 mSettings.writeLPr(); 18759 } 18760 } 18761 18762 /** 18763 * Remove entries from the keystore daemon. Will only remove it if the 18764 * {@code appId} is valid. 18765 */ 18766 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18767 if (appId < 0) { 18768 return; 18769 } 18770 18771 final KeyStore keyStore = KeyStore.getInstance(); 18772 if (keyStore != null) { 18773 if (userId == UserHandle.USER_ALL) { 18774 for (final int individual : sUserManager.getUserIds()) { 18775 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18776 } 18777 } else { 18778 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18779 } 18780 } else { 18781 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18782 } 18783 } 18784 18785 @Override 18786 public void deleteApplicationCacheFiles(final String packageName, 18787 final IPackageDataObserver observer) { 18788 final int userId = UserHandle.getCallingUserId(); 18789 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18790 } 18791 18792 @Override 18793 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18794 final IPackageDataObserver observer) { 18795 mContext.enforceCallingOrSelfPermission( 18796 android.Manifest.permission.DELETE_CACHE_FILES, null); 18797 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18798 /* requireFullPermission= */ true, /* checkShell= */ false, 18799 "delete application cache files"); 18800 18801 final PackageParser.Package pkg; 18802 synchronized (mPackages) { 18803 pkg = mPackages.get(packageName); 18804 } 18805 18806 // Queue up an async operation since the package deletion may take a little while. 18807 mHandler.post(new Runnable() { 18808 public void run() { 18809 synchronized (mInstallLock) { 18810 final int flags = StorageManager.FLAG_STORAGE_DE 18811 | StorageManager.FLAG_STORAGE_CE; 18812 // We're only clearing cache files, so we don't care if the 18813 // app is unfrozen and still able to run 18814 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18815 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18816 } 18817 clearExternalStorageDataSync(packageName, userId, false); 18818 if (observer != null) { 18819 try { 18820 observer.onRemoveCompleted(packageName, true); 18821 } catch (RemoteException e) { 18822 Log.i(TAG, "Observer no longer exists."); 18823 } 18824 } 18825 } 18826 }); 18827 } 18828 18829 @Override 18830 public void getPackageSizeInfo(final String packageName, int userHandle, 18831 final IPackageStatsObserver observer) { 18832 throw new UnsupportedOperationException( 18833 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18834 } 18835 18836 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18837 final PackageSetting ps; 18838 synchronized (mPackages) { 18839 ps = mSettings.mPackages.get(packageName); 18840 if (ps == null) { 18841 Slog.w(TAG, "Failed to find settings for " + packageName); 18842 return false; 18843 } 18844 } 18845 18846 final String[] packageNames = { packageName }; 18847 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18848 final String[] codePaths = { ps.codePathString }; 18849 18850 try { 18851 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18852 ps.appId, ceDataInodes, codePaths, stats); 18853 18854 // For now, ignore code size of packages on system partition 18855 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18856 stats.codeSize = 0; 18857 } 18858 18859 // External clients expect these to be tracked separately 18860 stats.dataSize -= stats.cacheSize; 18861 18862 } catch (InstallerException e) { 18863 Slog.w(TAG, String.valueOf(e)); 18864 return false; 18865 } 18866 18867 return true; 18868 } 18869 18870 private int getUidTargetSdkVersionLockedLPr(int uid) { 18871 Object obj = mSettings.getUserIdLPr(uid); 18872 if (obj instanceof SharedUserSetting) { 18873 final SharedUserSetting sus = (SharedUserSetting) obj; 18874 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18875 final Iterator<PackageSetting> it = sus.packages.iterator(); 18876 while (it.hasNext()) { 18877 final PackageSetting ps = it.next(); 18878 if (ps.pkg != null) { 18879 int v = ps.pkg.applicationInfo.targetSdkVersion; 18880 if (v < vers) vers = v; 18881 } 18882 } 18883 return vers; 18884 } else if (obj instanceof PackageSetting) { 18885 final PackageSetting ps = (PackageSetting) obj; 18886 if (ps.pkg != null) { 18887 return ps.pkg.applicationInfo.targetSdkVersion; 18888 } 18889 } 18890 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18891 } 18892 18893 @Override 18894 public void addPreferredActivity(IntentFilter filter, int match, 18895 ComponentName[] set, ComponentName activity, int userId) { 18896 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18897 "Adding preferred"); 18898 } 18899 18900 private void addPreferredActivityInternal(IntentFilter filter, int match, 18901 ComponentName[] set, ComponentName activity, boolean always, int userId, 18902 String opname) { 18903 // writer 18904 int callingUid = Binder.getCallingUid(); 18905 enforceCrossUserPermission(callingUid, userId, 18906 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18907 if (filter.countActions() == 0) { 18908 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18909 return; 18910 } 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 addPreferredActivity() from uid " 18918 + callingUid); 18919 return; 18920 } 18921 mContext.enforceCallingOrSelfPermission( 18922 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18923 } 18924 18925 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18926 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18927 + userId + ":"); 18928 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18929 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18930 scheduleWritePackageRestrictionsLocked(userId); 18931 postPreferredActivityChangedBroadcast(userId); 18932 } 18933 } 18934 18935 private void postPreferredActivityChangedBroadcast(int userId) { 18936 mHandler.post(() -> { 18937 final IActivityManager am = ActivityManager.getService(); 18938 if (am == null) { 18939 return; 18940 } 18941 18942 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18943 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18944 try { 18945 am.broadcastIntent(null, intent, null, null, 18946 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18947 null, false, false, userId); 18948 } catch (RemoteException e) { 18949 } 18950 }); 18951 } 18952 18953 @Override 18954 public void replacePreferredActivity(IntentFilter filter, int match, 18955 ComponentName[] set, ComponentName activity, int userId) { 18956 if (filter.countActions() != 1) { 18957 throw new IllegalArgumentException( 18958 "replacePreferredActivity expects filter to have only 1 action."); 18959 } 18960 if (filter.countDataAuthorities() != 0 18961 || filter.countDataPaths() != 0 18962 || filter.countDataSchemes() > 1 18963 || filter.countDataTypes() != 0) { 18964 throw new IllegalArgumentException( 18965 "replacePreferredActivity expects filter to have no data authorities, " + 18966 "paths, or types; and at most one scheme."); 18967 } 18968 18969 final int callingUid = Binder.getCallingUid(); 18970 enforceCrossUserPermission(callingUid, userId, 18971 true /* requireFullPermission */, false /* checkShell */, 18972 "replace preferred activity"); 18973 synchronized (mPackages) { 18974 if (mContext.checkCallingOrSelfPermission( 18975 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18976 != PackageManager.PERMISSION_GRANTED) { 18977 if (getUidTargetSdkVersionLockedLPr(callingUid) 18978 < Build.VERSION_CODES.FROYO) { 18979 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18980 + Binder.getCallingUid()); 18981 return; 18982 } 18983 mContext.enforceCallingOrSelfPermission( 18984 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18985 } 18986 18987 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18988 if (pir != null) { 18989 // Get all of the existing entries that exactly match this filter. 18990 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18991 if (existing != null && existing.size() == 1) { 18992 PreferredActivity cur = existing.get(0); 18993 if (DEBUG_PREFERRED) { 18994 Slog.i(TAG, "Checking replace of preferred:"); 18995 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18996 if (!cur.mPref.mAlways) { 18997 Slog.i(TAG, " -- CUR; not mAlways!"); 18998 } else { 18999 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19000 Slog.i(TAG, " -- CUR: mSet=" 19001 + Arrays.toString(cur.mPref.mSetComponents)); 19002 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19003 Slog.i(TAG, " -- NEW: mMatch=" 19004 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19005 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19006 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19007 } 19008 } 19009 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19010 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19011 && cur.mPref.sameSet(set)) { 19012 // Setting the preferred activity to what it happens to be already 19013 if (DEBUG_PREFERRED) { 19014 Slog.i(TAG, "Replacing with same preferred activity " 19015 + cur.mPref.mShortComponent + " for user " 19016 + userId + ":"); 19017 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19018 } 19019 return; 19020 } 19021 } 19022 19023 if (existing != null) { 19024 if (DEBUG_PREFERRED) { 19025 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19026 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19027 } 19028 for (int i = 0; i < existing.size(); i++) { 19029 PreferredActivity pa = existing.get(i); 19030 if (DEBUG_PREFERRED) { 19031 Slog.i(TAG, "Removing existing preferred activity " 19032 + pa.mPref.mComponent + ":"); 19033 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19034 } 19035 pir.removeFilter(pa); 19036 } 19037 } 19038 } 19039 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19040 "Replacing preferred"); 19041 } 19042 } 19043 19044 @Override 19045 public void clearPackagePreferredActivities(String packageName) { 19046 final int uid = Binder.getCallingUid(); 19047 // writer 19048 synchronized (mPackages) { 19049 PackageParser.Package pkg = mPackages.get(packageName); 19050 if (pkg == null || pkg.applicationInfo.uid != uid) { 19051 if (mContext.checkCallingOrSelfPermission( 19052 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19053 != PackageManager.PERMISSION_GRANTED) { 19054 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19055 < Build.VERSION_CODES.FROYO) { 19056 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19057 + Binder.getCallingUid()); 19058 return; 19059 } 19060 mContext.enforceCallingOrSelfPermission( 19061 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19062 } 19063 } 19064 19065 int user = UserHandle.getCallingUserId(); 19066 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19067 scheduleWritePackageRestrictionsLocked(user); 19068 } 19069 } 19070 } 19071 19072 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19073 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19074 ArrayList<PreferredActivity> removed = null; 19075 boolean changed = false; 19076 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19077 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19078 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19079 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19080 continue; 19081 } 19082 Iterator<PreferredActivity> it = pir.filterIterator(); 19083 while (it.hasNext()) { 19084 PreferredActivity pa = it.next(); 19085 // Mark entry for removal only if it matches the package name 19086 // and the entry is of type "always". 19087 if (packageName == null || 19088 (pa.mPref.mComponent.getPackageName().equals(packageName) 19089 && pa.mPref.mAlways)) { 19090 if (removed == null) { 19091 removed = new ArrayList<PreferredActivity>(); 19092 } 19093 removed.add(pa); 19094 } 19095 } 19096 if (removed != null) { 19097 for (int j=0; j<removed.size(); j++) { 19098 PreferredActivity pa = removed.get(j); 19099 pir.removeFilter(pa); 19100 } 19101 changed = true; 19102 } 19103 } 19104 if (changed) { 19105 postPreferredActivityChangedBroadcast(userId); 19106 } 19107 return changed; 19108 } 19109 19110 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19111 private void clearIntentFilterVerificationsLPw(int userId) { 19112 final int packageCount = mPackages.size(); 19113 for (int i = 0; i < packageCount; i++) { 19114 PackageParser.Package pkg = mPackages.valueAt(i); 19115 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19116 } 19117 } 19118 19119 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19120 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19121 if (userId == UserHandle.USER_ALL) { 19122 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19123 sUserManager.getUserIds())) { 19124 for (int oneUserId : sUserManager.getUserIds()) { 19125 scheduleWritePackageRestrictionsLocked(oneUserId); 19126 } 19127 } 19128 } else { 19129 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19130 scheduleWritePackageRestrictionsLocked(userId); 19131 } 19132 } 19133 } 19134 19135 void clearDefaultBrowserIfNeeded(String packageName) { 19136 for (int oneUserId : sUserManager.getUserIds()) { 19137 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19138 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19139 if (packageName.equals(defaultBrowserPackageName)) { 19140 setDefaultBrowserPackageName(null, oneUserId); 19141 } 19142 } 19143 } 19144 19145 @Override 19146 public void resetApplicationPreferences(int userId) { 19147 mContext.enforceCallingOrSelfPermission( 19148 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19149 final long identity = Binder.clearCallingIdentity(); 19150 // writer 19151 try { 19152 synchronized (mPackages) { 19153 clearPackagePreferredActivitiesLPw(null, userId); 19154 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19155 // TODO: We have to reset the default SMS and Phone. This requires 19156 // significant refactoring to keep all default apps in the package 19157 // manager (cleaner but more work) or have the services provide 19158 // callbacks to the package manager to request a default app reset. 19159 applyFactoryDefaultBrowserLPw(userId); 19160 clearIntentFilterVerificationsLPw(userId); 19161 primeDomainVerificationsLPw(userId); 19162 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19163 scheduleWritePackageRestrictionsLocked(userId); 19164 } 19165 resetNetworkPolicies(userId); 19166 } finally { 19167 Binder.restoreCallingIdentity(identity); 19168 } 19169 } 19170 19171 @Override 19172 public int getPreferredActivities(List<IntentFilter> outFilters, 19173 List<ComponentName> outActivities, String packageName) { 19174 19175 int num = 0; 19176 final int userId = UserHandle.getCallingUserId(); 19177 // reader 19178 synchronized (mPackages) { 19179 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19180 if (pir != null) { 19181 final Iterator<PreferredActivity> it = pir.filterIterator(); 19182 while (it.hasNext()) { 19183 final PreferredActivity pa = it.next(); 19184 if (packageName == null 19185 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19186 && pa.mPref.mAlways)) { 19187 if (outFilters != null) { 19188 outFilters.add(new IntentFilter(pa)); 19189 } 19190 if (outActivities != null) { 19191 outActivities.add(pa.mPref.mComponent); 19192 } 19193 } 19194 } 19195 } 19196 } 19197 19198 return num; 19199 } 19200 19201 @Override 19202 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19203 int userId) { 19204 int callingUid = Binder.getCallingUid(); 19205 if (callingUid != Process.SYSTEM_UID) { 19206 throw new SecurityException( 19207 "addPersistentPreferredActivity can only be run by the system"); 19208 } 19209 if (filter.countActions() == 0) { 19210 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19211 return; 19212 } 19213 synchronized (mPackages) { 19214 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19215 ":"); 19216 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19217 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19218 new PersistentPreferredActivity(filter, activity)); 19219 scheduleWritePackageRestrictionsLocked(userId); 19220 postPreferredActivityChangedBroadcast(userId); 19221 } 19222 } 19223 19224 @Override 19225 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19226 int callingUid = Binder.getCallingUid(); 19227 if (callingUid != Process.SYSTEM_UID) { 19228 throw new SecurityException( 19229 "clearPackagePersistentPreferredActivities can only be run by the system"); 19230 } 19231 ArrayList<PersistentPreferredActivity> removed = null; 19232 boolean changed = false; 19233 synchronized (mPackages) { 19234 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19235 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19236 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19237 .valueAt(i); 19238 if (userId != thisUserId) { 19239 continue; 19240 } 19241 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19242 while (it.hasNext()) { 19243 PersistentPreferredActivity ppa = it.next(); 19244 // Mark entry for removal only if it matches the package name. 19245 if (ppa.mComponent.getPackageName().equals(packageName)) { 19246 if (removed == null) { 19247 removed = new ArrayList<PersistentPreferredActivity>(); 19248 } 19249 removed.add(ppa); 19250 } 19251 } 19252 if (removed != null) { 19253 for (int j=0; j<removed.size(); j++) { 19254 PersistentPreferredActivity ppa = removed.get(j); 19255 ppir.removeFilter(ppa); 19256 } 19257 changed = true; 19258 } 19259 } 19260 19261 if (changed) { 19262 scheduleWritePackageRestrictionsLocked(userId); 19263 postPreferredActivityChangedBroadcast(userId); 19264 } 19265 } 19266 } 19267 19268 /** 19269 * Common machinery for picking apart a restored XML blob and passing 19270 * it to a caller-supplied functor to be applied to the running system. 19271 */ 19272 private void restoreFromXml(XmlPullParser parser, int userId, 19273 String expectedStartTag, BlobXmlRestorer functor) 19274 throws IOException, XmlPullParserException { 19275 int type; 19276 while ((type = parser.next()) != XmlPullParser.START_TAG 19277 && type != XmlPullParser.END_DOCUMENT) { 19278 } 19279 if (type != XmlPullParser.START_TAG) { 19280 // oops didn't find a start tag?! 19281 if (DEBUG_BACKUP) { 19282 Slog.e(TAG, "Didn't find start tag during restore"); 19283 } 19284 return; 19285 } 19286Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19287 // this is supposed to be TAG_PREFERRED_BACKUP 19288 if (!expectedStartTag.equals(parser.getName())) { 19289 if (DEBUG_BACKUP) { 19290 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19291 } 19292 return; 19293 } 19294 19295 // skip interfering stuff, then we're aligned with the backing implementation 19296 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19297Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19298 functor.apply(parser, userId); 19299 } 19300 19301 private interface BlobXmlRestorer { 19302 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19303 } 19304 19305 /** 19306 * Non-Binder method, support for the backup/restore mechanism: write the 19307 * full set of preferred activities in its canonical XML format. Returns the 19308 * XML output as a byte array, or null if there is none. 19309 */ 19310 @Override 19311 public byte[] getPreferredActivityBackup(int userId) { 19312 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19313 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19314 } 19315 19316 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19317 try { 19318 final XmlSerializer serializer = new FastXmlSerializer(); 19319 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19320 serializer.startDocument(null, true); 19321 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19322 19323 synchronized (mPackages) { 19324 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19325 } 19326 19327 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19328 serializer.endDocument(); 19329 serializer.flush(); 19330 } catch (Exception e) { 19331 if (DEBUG_BACKUP) { 19332 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19333 } 19334 return null; 19335 } 19336 19337 return dataStream.toByteArray(); 19338 } 19339 19340 @Override 19341 public void restorePreferredActivities(byte[] backup, int userId) { 19342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19343 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19344 } 19345 19346 try { 19347 final XmlPullParser parser = Xml.newPullParser(); 19348 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19349 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19350 new BlobXmlRestorer() { 19351 @Override 19352 public void apply(XmlPullParser parser, int userId) 19353 throws XmlPullParserException, IOException { 19354 synchronized (mPackages) { 19355 mSettings.readPreferredActivitiesLPw(parser, userId); 19356 } 19357 } 19358 } ); 19359 } catch (Exception e) { 19360 if (DEBUG_BACKUP) { 19361 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19362 } 19363 } 19364 } 19365 19366 /** 19367 * Non-Binder method, support for the backup/restore mechanism: write the 19368 * default browser (etc) settings in its canonical XML format. Returns the default 19369 * browser XML representation as a byte array, or null if there is none. 19370 */ 19371 @Override 19372 public byte[] getDefaultAppsBackup(int userId) { 19373 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19374 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19375 } 19376 19377 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19378 try { 19379 final XmlSerializer serializer = new FastXmlSerializer(); 19380 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19381 serializer.startDocument(null, true); 19382 serializer.startTag(null, TAG_DEFAULT_APPS); 19383 19384 synchronized (mPackages) { 19385 mSettings.writeDefaultAppsLPr(serializer, userId); 19386 } 19387 19388 serializer.endTag(null, TAG_DEFAULT_APPS); 19389 serializer.endDocument(); 19390 serializer.flush(); 19391 } catch (Exception e) { 19392 if (DEBUG_BACKUP) { 19393 Slog.e(TAG, "Unable to write default apps for backup", e); 19394 } 19395 return null; 19396 } 19397 19398 return dataStream.toByteArray(); 19399 } 19400 19401 @Override 19402 public void restoreDefaultApps(byte[] backup, int userId) { 19403 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19404 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19405 } 19406 19407 try { 19408 final XmlPullParser parser = Xml.newPullParser(); 19409 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19410 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19411 new BlobXmlRestorer() { 19412 @Override 19413 public void apply(XmlPullParser parser, int userId) 19414 throws XmlPullParserException, IOException { 19415 synchronized (mPackages) { 19416 mSettings.readDefaultAppsLPw(parser, userId); 19417 } 19418 } 19419 } ); 19420 } catch (Exception e) { 19421 if (DEBUG_BACKUP) { 19422 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19423 } 19424 } 19425 } 19426 19427 @Override 19428 public byte[] getIntentFilterVerificationBackup(int userId) { 19429 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19430 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19431 } 19432 19433 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19434 try { 19435 final XmlSerializer serializer = new FastXmlSerializer(); 19436 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19437 serializer.startDocument(null, true); 19438 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19439 19440 synchronized (mPackages) { 19441 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19442 } 19443 19444 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19445 serializer.endDocument(); 19446 serializer.flush(); 19447 } catch (Exception e) { 19448 if (DEBUG_BACKUP) { 19449 Slog.e(TAG, "Unable to write default apps for backup", e); 19450 } 19451 return null; 19452 } 19453 19454 return dataStream.toByteArray(); 19455 } 19456 19457 @Override 19458 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19459 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19460 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19461 } 19462 19463 try { 19464 final XmlPullParser parser = Xml.newPullParser(); 19465 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19466 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19467 new BlobXmlRestorer() { 19468 @Override 19469 public void apply(XmlPullParser parser, int userId) 19470 throws XmlPullParserException, IOException { 19471 synchronized (mPackages) { 19472 mSettings.readAllDomainVerificationsLPr(parser, userId); 19473 mSettings.writeLPr(); 19474 } 19475 } 19476 } ); 19477 } catch (Exception e) { 19478 if (DEBUG_BACKUP) { 19479 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19480 } 19481 } 19482 } 19483 19484 @Override 19485 public byte[] getPermissionGrantBackup(int userId) { 19486 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19487 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19488 } 19489 19490 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19491 try { 19492 final XmlSerializer serializer = new FastXmlSerializer(); 19493 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19494 serializer.startDocument(null, true); 19495 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19496 19497 synchronized (mPackages) { 19498 serializeRuntimePermissionGrantsLPr(serializer, userId); 19499 } 19500 19501 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19502 serializer.endDocument(); 19503 serializer.flush(); 19504 } catch (Exception e) { 19505 if (DEBUG_BACKUP) { 19506 Slog.e(TAG, "Unable to write default apps for backup", e); 19507 } 19508 return null; 19509 } 19510 19511 return dataStream.toByteArray(); 19512 } 19513 19514 @Override 19515 public void restorePermissionGrants(byte[] backup, int userId) { 19516 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19517 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19518 } 19519 19520 try { 19521 final XmlPullParser parser = Xml.newPullParser(); 19522 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19523 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19524 new BlobXmlRestorer() { 19525 @Override 19526 public void apply(XmlPullParser parser, int userId) 19527 throws XmlPullParserException, IOException { 19528 synchronized (mPackages) { 19529 processRestoredPermissionGrantsLPr(parser, userId); 19530 } 19531 } 19532 } ); 19533 } catch (Exception e) { 19534 if (DEBUG_BACKUP) { 19535 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19536 } 19537 } 19538 } 19539 19540 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19541 throws IOException { 19542 serializer.startTag(null, TAG_ALL_GRANTS); 19543 19544 final int N = mSettings.mPackages.size(); 19545 for (int i = 0; i < N; i++) { 19546 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19547 boolean pkgGrantsKnown = false; 19548 19549 PermissionsState packagePerms = ps.getPermissionsState(); 19550 19551 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19552 final int grantFlags = state.getFlags(); 19553 // only look at grants that are not system/policy fixed 19554 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19555 final boolean isGranted = state.isGranted(); 19556 // And only back up the user-twiddled state bits 19557 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19558 final String packageName = mSettings.mPackages.keyAt(i); 19559 if (!pkgGrantsKnown) { 19560 serializer.startTag(null, TAG_GRANT); 19561 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19562 pkgGrantsKnown = true; 19563 } 19564 19565 final boolean userSet = 19566 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19567 final boolean userFixed = 19568 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19569 final boolean revoke = 19570 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19571 19572 serializer.startTag(null, TAG_PERMISSION); 19573 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19574 if (isGranted) { 19575 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19576 } 19577 if (userSet) { 19578 serializer.attribute(null, ATTR_USER_SET, "true"); 19579 } 19580 if (userFixed) { 19581 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19582 } 19583 if (revoke) { 19584 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19585 } 19586 serializer.endTag(null, TAG_PERMISSION); 19587 } 19588 } 19589 } 19590 19591 if (pkgGrantsKnown) { 19592 serializer.endTag(null, TAG_GRANT); 19593 } 19594 } 19595 19596 serializer.endTag(null, TAG_ALL_GRANTS); 19597 } 19598 19599 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19600 throws XmlPullParserException, IOException { 19601 String pkgName = null; 19602 int outerDepth = parser.getDepth(); 19603 int type; 19604 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19605 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19606 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19607 continue; 19608 } 19609 19610 final String tagName = parser.getName(); 19611 if (tagName.equals(TAG_GRANT)) { 19612 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19613 if (DEBUG_BACKUP) { 19614 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19615 } 19616 } else if (tagName.equals(TAG_PERMISSION)) { 19617 19618 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19619 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19620 19621 int newFlagSet = 0; 19622 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19623 newFlagSet |= FLAG_PERMISSION_USER_SET; 19624 } 19625 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19626 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19627 } 19628 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19629 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19630 } 19631 if (DEBUG_BACKUP) { 19632 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19633 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19634 } 19635 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19636 if (ps != null) { 19637 // Already installed so we apply the grant immediately 19638 if (DEBUG_BACKUP) { 19639 Slog.v(TAG, " + already installed; applying"); 19640 } 19641 PermissionsState perms = ps.getPermissionsState(); 19642 BasePermission bp = mSettings.mPermissions.get(permName); 19643 if (bp != null) { 19644 if (isGranted) { 19645 perms.grantRuntimePermission(bp, userId); 19646 } 19647 if (newFlagSet != 0) { 19648 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19649 } 19650 } 19651 } else { 19652 // Need to wait for post-restore install to apply the grant 19653 if (DEBUG_BACKUP) { 19654 Slog.v(TAG, " - not yet installed; saving for later"); 19655 } 19656 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19657 isGranted, newFlagSet, userId); 19658 } 19659 } else { 19660 PackageManagerService.reportSettingsProblem(Log.WARN, 19661 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19662 XmlUtils.skipCurrentTag(parser); 19663 } 19664 } 19665 19666 scheduleWriteSettingsLocked(); 19667 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19668 } 19669 19670 @Override 19671 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19672 int sourceUserId, int targetUserId, int flags) { 19673 mContext.enforceCallingOrSelfPermission( 19674 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19675 int callingUid = Binder.getCallingUid(); 19676 enforceOwnerRights(ownerPackage, callingUid); 19677 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19678 if (intentFilter.countActions() == 0) { 19679 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19680 return; 19681 } 19682 synchronized (mPackages) { 19683 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19684 ownerPackage, targetUserId, flags); 19685 CrossProfileIntentResolver resolver = 19686 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19687 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19688 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19689 if (existing != null) { 19690 int size = existing.size(); 19691 for (int i = 0; i < size; i++) { 19692 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19693 return; 19694 } 19695 } 19696 } 19697 resolver.addFilter(newFilter); 19698 scheduleWritePackageRestrictionsLocked(sourceUserId); 19699 } 19700 } 19701 19702 @Override 19703 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19704 mContext.enforceCallingOrSelfPermission( 19705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19706 int callingUid = Binder.getCallingUid(); 19707 enforceOwnerRights(ownerPackage, callingUid); 19708 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19709 synchronized (mPackages) { 19710 CrossProfileIntentResolver resolver = 19711 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19712 ArraySet<CrossProfileIntentFilter> set = 19713 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19714 for (CrossProfileIntentFilter filter : set) { 19715 if (filter.getOwnerPackage().equals(ownerPackage)) { 19716 resolver.removeFilter(filter); 19717 } 19718 } 19719 scheduleWritePackageRestrictionsLocked(sourceUserId); 19720 } 19721 } 19722 19723 // Enforcing that callingUid is owning pkg on userId 19724 private void enforceOwnerRights(String pkg, int callingUid) { 19725 // The system owns everything. 19726 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19727 return; 19728 } 19729 int callingUserId = UserHandle.getUserId(callingUid); 19730 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19731 if (pi == null) { 19732 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19733 + callingUserId); 19734 } 19735 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19736 throw new SecurityException("Calling uid " + callingUid 19737 + " does not own package " + pkg); 19738 } 19739 } 19740 19741 @Override 19742 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19743 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19744 } 19745 19746 /** 19747 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19748 * then reports the most likely home activity or null if there are more than one. 19749 */ 19750 public ComponentName getDefaultHomeActivity(int userId) { 19751 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19752 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19753 if (cn != null) { 19754 return cn; 19755 } 19756 19757 // Find the launcher with the highest priority and return that component if there are no 19758 // other home activity with the same priority. 19759 int lastPriority = Integer.MIN_VALUE; 19760 ComponentName lastComponent = null; 19761 final int size = allHomeCandidates.size(); 19762 for (int i = 0; i < size; i++) { 19763 final ResolveInfo ri = allHomeCandidates.get(i); 19764 if (ri.priority > lastPriority) { 19765 lastComponent = ri.activityInfo.getComponentName(); 19766 lastPriority = ri.priority; 19767 } else if (ri.priority == lastPriority) { 19768 // Two components found with same priority. 19769 lastComponent = null; 19770 } 19771 } 19772 return lastComponent; 19773 } 19774 19775 private Intent getHomeIntent() { 19776 Intent intent = new Intent(Intent.ACTION_MAIN); 19777 intent.addCategory(Intent.CATEGORY_HOME); 19778 intent.addCategory(Intent.CATEGORY_DEFAULT); 19779 return intent; 19780 } 19781 19782 private IntentFilter getHomeFilter() { 19783 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19784 filter.addCategory(Intent.CATEGORY_HOME); 19785 filter.addCategory(Intent.CATEGORY_DEFAULT); 19786 return filter; 19787 } 19788 19789 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19790 int userId) { 19791 Intent intent = getHomeIntent(); 19792 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19793 PackageManager.GET_META_DATA, userId); 19794 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19795 true, false, false, userId); 19796 19797 allHomeCandidates.clear(); 19798 if (list != null) { 19799 for (ResolveInfo ri : list) { 19800 allHomeCandidates.add(ri); 19801 } 19802 } 19803 return (preferred == null || preferred.activityInfo == null) 19804 ? null 19805 : new ComponentName(preferred.activityInfo.packageName, 19806 preferred.activityInfo.name); 19807 } 19808 19809 @Override 19810 public void setHomeActivity(ComponentName comp, int userId) { 19811 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19812 getHomeActivitiesAsUser(homeActivities, userId); 19813 19814 boolean found = false; 19815 19816 final int size = homeActivities.size(); 19817 final ComponentName[] set = new ComponentName[size]; 19818 for (int i = 0; i < size; i++) { 19819 final ResolveInfo candidate = homeActivities.get(i); 19820 final ActivityInfo info = candidate.activityInfo; 19821 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19822 set[i] = activityName; 19823 if (!found && activityName.equals(comp)) { 19824 found = true; 19825 } 19826 } 19827 if (!found) { 19828 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19829 + userId); 19830 } 19831 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19832 set, comp, userId); 19833 } 19834 19835 private @Nullable String getSetupWizardPackageName() { 19836 final Intent intent = new Intent(Intent.ACTION_MAIN); 19837 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19838 19839 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19840 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19841 | MATCH_DISABLED_COMPONENTS, 19842 UserHandle.myUserId()); 19843 if (matches.size() == 1) { 19844 return matches.get(0).getComponentInfo().packageName; 19845 } else { 19846 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19847 + ": matches=" + matches); 19848 return null; 19849 } 19850 } 19851 19852 private @Nullable String getStorageManagerPackageName() { 19853 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19854 19855 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19856 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19857 | MATCH_DISABLED_COMPONENTS, 19858 UserHandle.myUserId()); 19859 if (matches.size() == 1) { 19860 return matches.get(0).getComponentInfo().packageName; 19861 } else { 19862 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19863 + matches.size() + ": matches=" + matches); 19864 return null; 19865 } 19866 } 19867 19868 @Override 19869 public void setApplicationEnabledSetting(String appPackageName, 19870 int newState, int flags, int userId, String callingPackage) { 19871 if (!sUserManager.exists(userId)) return; 19872 if (callingPackage == null) { 19873 callingPackage = Integer.toString(Binder.getCallingUid()); 19874 } 19875 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19876 } 19877 19878 @Override 19879 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19880 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19881 synchronized (mPackages) { 19882 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19883 if (pkgSetting != null) { 19884 pkgSetting.setUpdateAvailable(updateAvailable); 19885 } 19886 } 19887 } 19888 19889 @Override 19890 public void setComponentEnabledSetting(ComponentName componentName, 19891 int newState, int flags, int userId) { 19892 if (!sUserManager.exists(userId)) return; 19893 setEnabledSetting(componentName.getPackageName(), 19894 componentName.getClassName(), newState, flags, userId, null); 19895 } 19896 19897 private void setEnabledSetting(final String packageName, String className, int newState, 19898 final int flags, int userId, String callingPackage) { 19899 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19900 || newState == COMPONENT_ENABLED_STATE_ENABLED 19901 || newState == COMPONENT_ENABLED_STATE_DISABLED 19902 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19903 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19904 throw new IllegalArgumentException("Invalid new component state: " 19905 + newState); 19906 } 19907 PackageSetting pkgSetting; 19908 final int uid = Binder.getCallingUid(); 19909 final int permission; 19910 if (uid == Process.SYSTEM_UID) { 19911 permission = PackageManager.PERMISSION_GRANTED; 19912 } else { 19913 permission = mContext.checkCallingOrSelfPermission( 19914 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19915 } 19916 enforceCrossUserPermission(uid, userId, 19917 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19918 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19919 boolean sendNow = false; 19920 boolean isApp = (className == null); 19921 String componentName = isApp ? packageName : className; 19922 int packageUid = -1; 19923 ArrayList<String> components; 19924 19925 // writer 19926 synchronized (mPackages) { 19927 pkgSetting = mSettings.mPackages.get(packageName); 19928 if (pkgSetting == null) { 19929 if (className == null) { 19930 throw new IllegalArgumentException("Unknown package: " + packageName); 19931 } 19932 throw new IllegalArgumentException( 19933 "Unknown component: " + packageName + "/" + className); 19934 } 19935 } 19936 19937 // Limit who can change which apps 19938 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19939 // Don't allow apps that don't have permission to modify other apps 19940 if (!allowedByPermission) { 19941 throw new SecurityException( 19942 "Permission Denial: attempt to change component state from pid=" 19943 + Binder.getCallingPid() 19944 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19945 } 19946 // Don't allow changing protected packages. 19947 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19948 throw new SecurityException("Cannot disable a protected package: " + packageName); 19949 } 19950 } 19951 19952 synchronized (mPackages) { 19953 if (uid == Process.SHELL_UID 19954 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19955 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19956 // unless it is a test package. 19957 int oldState = pkgSetting.getEnabled(userId); 19958 if (className == null 19959 && 19960 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19961 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19962 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19963 && 19964 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19965 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19966 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19967 // ok 19968 } else { 19969 throw new SecurityException( 19970 "Shell cannot change component state for " + packageName + "/" 19971 + className + " to " + newState); 19972 } 19973 } 19974 if (className == null) { 19975 // We're dealing with an application/package level state change 19976 if (pkgSetting.getEnabled(userId) == newState) { 19977 // Nothing to do 19978 return; 19979 } 19980 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19981 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19982 // Don't care about who enables an app. 19983 callingPackage = null; 19984 } 19985 pkgSetting.setEnabled(newState, userId, callingPackage); 19986 // pkgSetting.pkg.mSetEnabled = newState; 19987 } else { 19988 // We're dealing with a component level state change 19989 // First, verify that this is a valid class name. 19990 PackageParser.Package pkg = pkgSetting.pkg; 19991 if (pkg == null || !pkg.hasComponentClassName(className)) { 19992 if (pkg != null && 19993 pkg.applicationInfo.targetSdkVersion >= 19994 Build.VERSION_CODES.JELLY_BEAN) { 19995 throw new IllegalArgumentException("Component class " + className 19996 + " does not exist in " + packageName); 19997 } else { 19998 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19999 + className + " does not exist in " + packageName); 20000 } 20001 } 20002 switch (newState) { 20003 case COMPONENT_ENABLED_STATE_ENABLED: 20004 if (!pkgSetting.enableComponentLPw(className, userId)) { 20005 return; 20006 } 20007 break; 20008 case COMPONENT_ENABLED_STATE_DISABLED: 20009 if (!pkgSetting.disableComponentLPw(className, userId)) { 20010 return; 20011 } 20012 break; 20013 case COMPONENT_ENABLED_STATE_DEFAULT: 20014 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20015 return; 20016 } 20017 break; 20018 default: 20019 Slog.e(TAG, "Invalid new component state: " + newState); 20020 return; 20021 } 20022 } 20023 scheduleWritePackageRestrictionsLocked(userId); 20024 updateSequenceNumberLP(packageName, new int[] { userId }); 20025 final long callingId = Binder.clearCallingIdentity(); 20026 try { 20027 updateInstantAppInstallerLocked(); 20028 } finally { 20029 Binder.restoreCallingIdentity(callingId); 20030 } 20031 components = mPendingBroadcasts.get(userId, packageName); 20032 final boolean newPackage = components == null; 20033 if (newPackage) { 20034 components = new ArrayList<String>(); 20035 } 20036 if (!components.contains(componentName)) { 20037 components.add(componentName); 20038 } 20039 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20040 sendNow = true; 20041 // Purge entry from pending broadcast list if another one exists already 20042 // since we are sending one right away. 20043 mPendingBroadcasts.remove(userId, packageName); 20044 } else { 20045 if (newPackage) { 20046 mPendingBroadcasts.put(userId, packageName, components); 20047 } 20048 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20049 // Schedule a message 20050 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20051 } 20052 } 20053 } 20054 20055 long callingId = Binder.clearCallingIdentity(); 20056 try { 20057 if (sendNow) { 20058 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20059 sendPackageChangedBroadcast(packageName, 20060 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20061 } 20062 } finally { 20063 Binder.restoreCallingIdentity(callingId); 20064 } 20065 } 20066 20067 @Override 20068 public void flushPackageRestrictionsAsUser(int userId) { 20069 if (!sUserManager.exists(userId)) { 20070 return; 20071 } 20072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20073 false /* checkShell */, "flushPackageRestrictions"); 20074 synchronized (mPackages) { 20075 mSettings.writePackageRestrictionsLPr(userId); 20076 mDirtyUsers.remove(userId); 20077 if (mDirtyUsers.isEmpty()) { 20078 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20079 } 20080 } 20081 } 20082 20083 private void sendPackageChangedBroadcast(String packageName, 20084 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20085 if (DEBUG_INSTALL) 20086 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20087 + componentNames); 20088 Bundle extras = new Bundle(4); 20089 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20090 String nameList[] = new String[componentNames.size()]; 20091 componentNames.toArray(nameList); 20092 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20093 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20094 extras.putInt(Intent.EXTRA_UID, packageUid); 20095 // If this is not reporting a change of the overall package, then only send it 20096 // to registered receivers. We don't want to launch a swath of apps for every 20097 // little component state change. 20098 final int flags = !componentNames.contains(packageName) 20099 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20100 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20101 new int[] {UserHandle.getUserId(packageUid)}); 20102 } 20103 20104 @Override 20105 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20106 if (!sUserManager.exists(userId)) return; 20107 final int uid = Binder.getCallingUid(); 20108 final int permission = mContext.checkCallingOrSelfPermission( 20109 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20110 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20111 enforceCrossUserPermission(uid, userId, 20112 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20113 // writer 20114 synchronized (mPackages) { 20115 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20116 allowedByPermission, uid, userId)) { 20117 scheduleWritePackageRestrictionsLocked(userId); 20118 } 20119 } 20120 } 20121 20122 @Override 20123 public String getInstallerPackageName(String packageName) { 20124 // reader 20125 synchronized (mPackages) { 20126 return mSettings.getInstallerPackageNameLPr(packageName); 20127 } 20128 } 20129 20130 public boolean isOrphaned(String packageName) { 20131 // reader 20132 synchronized (mPackages) { 20133 return mSettings.isOrphaned(packageName); 20134 } 20135 } 20136 20137 @Override 20138 public int getApplicationEnabledSetting(String packageName, int userId) { 20139 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20140 int uid = Binder.getCallingUid(); 20141 enforceCrossUserPermission(uid, userId, 20142 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20143 // reader 20144 synchronized (mPackages) { 20145 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20146 } 20147 } 20148 20149 @Override 20150 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20151 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20152 int uid = Binder.getCallingUid(); 20153 enforceCrossUserPermission(uid, userId, 20154 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20155 // reader 20156 synchronized (mPackages) { 20157 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20158 } 20159 } 20160 20161 @Override 20162 public void enterSafeMode() { 20163 enforceSystemOrRoot("Only the system can request entering safe mode"); 20164 20165 if (!mSystemReady) { 20166 mSafeMode = true; 20167 } 20168 } 20169 20170 @Override 20171 public void systemReady() { 20172 mSystemReady = true; 20173 20174 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20175 // disabled after already being started. 20176 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20177 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20178 20179 // Read the compatibilty setting when the system is ready. 20180 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20181 mContext.getContentResolver(), 20182 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20183 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20184 if (DEBUG_SETTINGS) { 20185 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20186 } 20187 20188 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20189 20190 synchronized (mPackages) { 20191 // Verify that all of the preferred activity components actually 20192 // exist. It is possible for applications to be updated and at 20193 // that point remove a previously declared activity component that 20194 // had been set as a preferred activity. We try to clean this up 20195 // the next time we encounter that preferred activity, but it is 20196 // possible for the user flow to never be able to return to that 20197 // situation so here we do a sanity check to make sure we haven't 20198 // left any junk around. 20199 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20200 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20201 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20202 removed.clear(); 20203 for (PreferredActivity pa : pir.filterSet()) { 20204 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20205 removed.add(pa); 20206 } 20207 } 20208 if (removed.size() > 0) { 20209 for (int r=0; r<removed.size(); r++) { 20210 PreferredActivity pa = removed.get(r); 20211 Slog.w(TAG, "Removing dangling preferred activity: " 20212 + pa.mPref.mComponent); 20213 pir.removeFilter(pa); 20214 } 20215 mSettings.writePackageRestrictionsLPr( 20216 mSettings.mPreferredActivities.keyAt(i)); 20217 } 20218 } 20219 20220 for (int userId : UserManagerService.getInstance().getUserIds()) { 20221 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20222 grantPermissionsUserIds = ArrayUtils.appendInt( 20223 grantPermissionsUserIds, userId); 20224 } 20225 } 20226 } 20227 sUserManager.systemReady(); 20228 20229 // If we upgraded grant all default permissions before kicking off. 20230 for (int userId : grantPermissionsUserIds) { 20231 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20232 } 20233 20234 // If we did not grant default permissions, we preload from this the 20235 // default permission exceptions lazily to ensure we don't hit the 20236 // disk on a new user creation. 20237 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20238 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20239 } 20240 20241 // Kick off any messages waiting for system ready 20242 if (mPostSystemReadyMessages != null) { 20243 for (Message msg : mPostSystemReadyMessages) { 20244 msg.sendToTarget(); 20245 } 20246 mPostSystemReadyMessages = null; 20247 } 20248 20249 // Watch for external volumes that come and go over time 20250 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20251 storage.registerListener(mStorageListener); 20252 20253 mInstallerService.systemReady(); 20254 mPackageDexOptimizer.systemReady(); 20255 20256 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20257 StorageManagerInternal.class); 20258 StorageManagerInternal.addExternalStoragePolicy( 20259 new StorageManagerInternal.ExternalStorageMountPolicy() { 20260 @Override 20261 public int getMountMode(int uid, String packageName) { 20262 if (Process.isIsolated(uid)) { 20263 return Zygote.MOUNT_EXTERNAL_NONE; 20264 } 20265 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20266 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20267 } 20268 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20269 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20270 } 20271 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20272 return Zygote.MOUNT_EXTERNAL_READ; 20273 } 20274 return Zygote.MOUNT_EXTERNAL_WRITE; 20275 } 20276 20277 @Override 20278 public boolean hasExternalStorage(int uid, String packageName) { 20279 return true; 20280 } 20281 }); 20282 20283 // Now that we're mostly running, clean up stale users and apps 20284 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20285 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20286 20287 if (mPrivappPermissionsViolations != null) { 20288 Slog.wtf(TAG,"Signature|privileged permissions not in " 20289 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20290 mPrivappPermissionsViolations = null; 20291 } 20292 } 20293 20294 public void waitForAppDataPrepared() { 20295 if (mPrepareAppDataFuture == null) { 20296 return; 20297 } 20298 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20299 mPrepareAppDataFuture = null; 20300 } 20301 20302 @Override 20303 public boolean isSafeMode() { 20304 return mSafeMode; 20305 } 20306 20307 @Override 20308 public boolean hasSystemUidErrors() { 20309 return mHasSystemUidErrors; 20310 } 20311 20312 static String arrayToString(int[] array) { 20313 StringBuffer buf = new StringBuffer(128); 20314 buf.append('['); 20315 if (array != null) { 20316 for (int i=0; i<array.length; i++) { 20317 if (i > 0) buf.append(", "); 20318 buf.append(array[i]); 20319 } 20320 } 20321 buf.append(']'); 20322 return buf.toString(); 20323 } 20324 20325 static class DumpState { 20326 public static final int DUMP_LIBS = 1 << 0; 20327 public static final int DUMP_FEATURES = 1 << 1; 20328 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20329 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20330 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20331 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20332 public static final int DUMP_PERMISSIONS = 1 << 6; 20333 public static final int DUMP_PACKAGES = 1 << 7; 20334 public static final int DUMP_SHARED_USERS = 1 << 8; 20335 public static final int DUMP_MESSAGES = 1 << 9; 20336 public static final int DUMP_PROVIDERS = 1 << 10; 20337 public static final int DUMP_VERIFIERS = 1 << 11; 20338 public static final int DUMP_PREFERRED = 1 << 12; 20339 public static final int DUMP_PREFERRED_XML = 1 << 13; 20340 public static final int DUMP_KEYSETS = 1 << 14; 20341 public static final int DUMP_VERSION = 1 << 15; 20342 public static final int DUMP_INSTALLS = 1 << 16; 20343 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20344 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20345 public static final int DUMP_FROZEN = 1 << 19; 20346 public static final int DUMP_DEXOPT = 1 << 20; 20347 public static final int DUMP_COMPILER_STATS = 1 << 21; 20348 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20349 20350 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20351 20352 private int mTypes; 20353 20354 private int mOptions; 20355 20356 private boolean mTitlePrinted; 20357 20358 private SharedUserSetting mSharedUser; 20359 20360 public boolean isDumping(int type) { 20361 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20362 return true; 20363 } 20364 20365 return (mTypes & type) != 0; 20366 } 20367 20368 public void setDump(int type) { 20369 mTypes |= type; 20370 } 20371 20372 public boolean isOptionEnabled(int option) { 20373 return (mOptions & option) != 0; 20374 } 20375 20376 public void setOptionEnabled(int option) { 20377 mOptions |= option; 20378 } 20379 20380 public boolean onTitlePrinted() { 20381 final boolean printed = mTitlePrinted; 20382 mTitlePrinted = true; 20383 return printed; 20384 } 20385 20386 public boolean getTitlePrinted() { 20387 return mTitlePrinted; 20388 } 20389 20390 public void setTitlePrinted(boolean enabled) { 20391 mTitlePrinted = enabled; 20392 } 20393 20394 public SharedUserSetting getSharedUser() { 20395 return mSharedUser; 20396 } 20397 20398 public void setSharedUser(SharedUserSetting user) { 20399 mSharedUser = user; 20400 } 20401 } 20402 20403 @Override 20404 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20405 FileDescriptor err, String[] args, ShellCallback callback, 20406 ResultReceiver resultReceiver) { 20407 (new PackageManagerShellCommand(this)).exec( 20408 this, in, out, err, args, callback, resultReceiver); 20409 } 20410 20411 @Override 20412 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20413 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20414 20415 DumpState dumpState = new DumpState(); 20416 boolean fullPreferred = false; 20417 boolean checkin = false; 20418 20419 String packageName = null; 20420 ArraySet<String> permissionNames = null; 20421 20422 int opti = 0; 20423 while (opti < args.length) { 20424 String opt = args[opti]; 20425 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20426 break; 20427 } 20428 opti++; 20429 20430 if ("-a".equals(opt)) { 20431 // Right now we only know how to print all. 20432 } else if ("-h".equals(opt)) { 20433 pw.println("Package manager dump options:"); 20434 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20435 pw.println(" --checkin: dump for a checkin"); 20436 pw.println(" -f: print details of intent filters"); 20437 pw.println(" -h: print this help"); 20438 pw.println(" cmd may be one of:"); 20439 pw.println(" l[ibraries]: list known shared libraries"); 20440 pw.println(" f[eatures]: list device features"); 20441 pw.println(" k[eysets]: print known keysets"); 20442 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20443 pw.println(" perm[issions]: dump permissions"); 20444 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20445 pw.println(" pref[erred]: print preferred package settings"); 20446 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20447 pw.println(" prov[iders]: dump content providers"); 20448 pw.println(" p[ackages]: dump installed packages"); 20449 pw.println(" s[hared-users]: dump shared user IDs"); 20450 pw.println(" m[essages]: print collected runtime messages"); 20451 pw.println(" v[erifiers]: print package verifier info"); 20452 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20453 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20454 pw.println(" version: print database version info"); 20455 pw.println(" write: write current settings now"); 20456 pw.println(" installs: details about install sessions"); 20457 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20458 pw.println(" dexopt: dump dexopt state"); 20459 pw.println(" compiler-stats: dump compiler statistics"); 20460 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20461 pw.println(" <package.name>: info about given package"); 20462 return; 20463 } else if ("--checkin".equals(opt)) { 20464 checkin = true; 20465 } else if ("-f".equals(opt)) { 20466 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20467 } else if ("--proto".equals(opt)) { 20468 dumpProto(fd); 20469 return; 20470 } else { 20471 pw.println("Unknown argument: " + opt + "; use -h for help"); 20472 } 20473 } 20474 20475 // Is the caller requesting to dump a particular piece of data? 20476 if (opti < args.length) { 20477 String cmd = args[opti]; 20478 opti++; 20479 // Is this a package name? 20480 if ("android".equals(cmd) || cmd.contains(".")) { 20481 packageName = cmd; 20482 // When dumping a single package, we always dump all of its 20483 // filter information since the amount of data will be reasonable. 20484 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20485 } else if ("check-permission".equals(cmd)) { 20486 if (opti >= args.length) { 20487 pw.println("Error: check-permission missing permission argument"); 20488 return; 20489 } 20490 String perm = args[opti]; 20491 opti++; 20492 if (opti >= args.length) { 20493 pw.println("Error: check-permission missing package argument"); 20494 return; 20495 } 20496 20497 String pkg = args[opti]; 20498 opti++; 20499 int user = UserHandle.getUserId(Binder.getCallingUid()); 20500 if (opti < args.length) { 20501 try { 20502 user = Integer.parseInt(args[opti]); 20503 } catch (NumberFormatException e) { 20504 pw.println("Error: check-permission user argument is not a number: " 20505 + args[opti]); 20506 return; 20507 } 20508 } 20509 20510 // Normalize package name to handle renamed packages and static libs 20511 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20512 20513 pw.println(checkPermission(perm, pkg, user)); 20514 return; 20515 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20516 dumpState.setDump(DumpState.DUMP_LIBS); 20517 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20518 dumpState.setDump(DumpState.DUMP_FEATURES); 20519 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20520 if (opti >= args.length) { 20521 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20522 | DumpState.DUMP_SERVICE_RESOLVERS 20523 | DumpState.DUMP_RECEIVER_RESOLVERS 20524 | DumpState.DUMP_CONTENT_RESOLVERS); 20525 } else { 20526 while (opti < args.length) { 20527 String name = args[opti]; 20528 if ("a".equals(name) || "activity".equals(name)) { 20529 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20530 } else if ("s".equals(name) || "service".equals(name)) { 20531 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20532 } else if ("r".equals(name) || "receiver".equals(name)) { 20533 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20534 } else if ("c".equals(name) || "content".equals(name)) { 20535 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20536 } else { 20537 pw.println("Error: unknown resolver table type: " + name); 20538 return; 20539 } 20540 opti++; 20541 } 20542 } 20543 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20544 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20545 } else if ("permission".equals(cmd)) { 20546 if (opti >= args.length) { 20547 pw.println("Error: permission requires permission name"); 20548 return; 20549 } 20550 permissionNames = new ArraySet<>(); 20551 while (opti < args.length) { 20552 permissionNames.add(args[opti]); 20553 opti++; 20554 } 20555 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20556 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20557 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20558 dumpState.setDump(DumpState.DUMP_PREFERRED); 20559 } else if ("preferred-xml".equals(cmd)) { 20560 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20561 if (opti < args.length && "--full".equals(args[opti])) { 20562 fullPreferred = true; 20563 opti++; 20564 } 20565 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20566 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20567 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20568 dumpState.setDump(DumpState.DUMP_PACKAGES); 20569 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20570 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20571 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20572 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20573 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20574 dumpState.setDump(DumpState.DUMP_MESSAGES); 20575 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20576 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20577 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20578 || "intent-filter-verifiers".equals(cmd)) { 20579 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20580 } else if ("version".equals(cmd)) { 20581 dumpState.setDump(DumpState.DUMP_VERSION); 20582 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20583 dumpState.setDump(DumpState.DUMP_KEYSETS); 20584 } else if ("installs".equals(cmd)) { 20585 dumpState.setDump(DumpState.DUMP_INSTALLS); 20586 } else if ("frozen".equals(cmd)) { 20587 dumpState.setDump(DumpState.DUMP_FROZEN); 20588 } else if ("dexopt".equals(cmd)) { 20589 dumpState.setDump(DumpState.DUMP_DEXOPT); 20590 } else if ("compiler-stats".equals(cmd)) { 20591 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20592 } else if ("enabled-overlays".equals(cmd)) { 20593 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20594 } else if ("write".equals(cmd)) { 20595 synchronized (mPackages) { 20596 mSettings.writeLPr(); 20597 pw.println("Settings written."); 20598 return; 20599 } 20600 } 20601 } 20602 20603 if (checkin) { 20604 pw.println("vers,1"); 20605 } 20606 20607 // reader 20608 synchronized (mPackages) { 20609 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20610 if (!checkin) { 20611 if (dumpState.onTitlePrinted()) 20612 pw.println(); 20613 pw.println("Database versions:"); 20614 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20615 } 20616 } 20617 20618 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20619 if (!checkin) { 20620 if (dumpState.onTitlePrinted()) 20621 pw.println(); 20622 pw.println("Verifiers:"); 20623 pw.print(" Required: "); 20624 pw.print(mRequiredVerifierPackage); 20625 pw.print(" (uid="); 20626 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20627 UserHandle.USER_SYSTEM)); 20628 pw.println(")"); 20629 } else if (mRequiredVerifierPackage != null) { 20630 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20631 pw.print(","); 20632 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20633 UserHandle.USER_SYSTEM)); 20634 } 20635 } 20636 20637 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20638 packageName == null) { 20639 if (mIntentFilterVerifierComponent != null) { 20640 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20641 if (!checkin) { 20642 if (dumpState.onTitlePrinted()) 20643 pw.println(); 20644 pw.println("Intent Filter Verifier:"); 20645 pw.print(" Using: "); 20646 pw.print(verifierPackageName); 20647 pw.print(" (uid="); 20648 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20649 UserHandle.USER_SYSTEM)); 20650 pw.println(")"); 20651 } else if (verifierPackageName != null) { 20652 pw.print("ifv,"); pw.print(verifierPackageName); 20653 pw.print(","); 20654 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20655 UserHandle.USER_SYSTEM)); 20656 } 20657 } else { 20658 pw.println(); 20659 pw.println("No Intent Filter Verifier available!"); 20660 } 20661 } 20662 20663 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20664 boolean printedHeader = false; 20665 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20666 while (it.hasNext()) { 20667 String libName = it.next(); 20668 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20669 if (versionedLib == null) { 20670 continue; 20671 } 20672 final int versionCount = versionedLib.size(); 20673 for (int i = 0; i < versionCount; i++) { 20674 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20675 if (!checkin) { 20676 if (!printedHeader) { 20677 if (dumpState.onTitlePrinted()) 20678 pw.println(); 20679 pw.println("Libraries:"); 20680 printedHeader = true; 20681 } 20682 pw.print(" "); 20683 } else { 20684 pw.print("lib,"); 20685 } 20686 pw.print(libEntry.info.getName()); 20687 if (libEntry.info.isStatic()) { 20688 pw.print(" version=" + libEntry.info.getVersion()); 20689 } 20690 if (!checkin) { 20691 pw.print(" -> "); 20692 } 20693 if (libEntry.path != null) { 20694 pw.print(" (jar) "); 20695 pw.print(libEntry.path); 20696 } else { 20697 pw.print(" (apk) "); 20698 pw.print(libEntry.apk); 20699 } 20700 pw.println(); 20701 } 20702 } 20703 } 20704 20705 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20706 if (dumpState.onTitlePrinted()) 20707 pw.println(); 20708 if (!checkin) { 20709 pw.println("Features:"); 20710 } 20711 20712 synchronized (mAvailableFeatures) { 20713 for (FeatureInfo feat : mAvailableFeatures.values()) { 20714 if (checkin) { 20715 pw.print("feat,"); 20716 pw.print(feat.name); 20717 pw.print(","); 20718 pw.println(feat.version); 20719 } else { 20720 pw.print(" "); 20721 pw.print(feat.name); 20722 if (feat.version > 0) { 20723 pw.print(" version="); 20724 pw.print(feat.version); 20725 } 20726 pw.println(); 20727 } 20728 } 20729 } 20730 } 20731 20732 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20733 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20734 : "Activity Resolver Table:", " ", packageName, 20735 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20736 dumpState.setTitlePrinted(true); 20737 } 20738 } 20739 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20740 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20741 : "Receiver Resolver Table:", " ", packageName, 20742 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20743 dumpState.setTitlePrinted(true); 20744 } 20745 } 20746 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20747 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20748 : "Service Resolver Table:", " ", packageName, 20749 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20750 dumpState.setTitlePrinted(true); 20751 } 20752 } 20753 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20754 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20755 : "Provider Resolver Table:", " ", packageName, 20756 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20757 dumpState.setTitlePrinted(true); 20758 } 20759 } 20760 20761 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20762 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20763 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20764 int user = mSettings.mPreferredActivities.keyAt(i); 20765 if (pir.dump(pw, 20766 dumpState.getTitlePrinted() 20767 ? "\nPreferred Activities User " + user + ":" 20768 : "Preferred Activities User " + user + ":", " ", 20769 packageName, true, false)) { 20770 dumpState.setTitlePrinted(true); 20771 } 20772 } 20773 } 20774 20775 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20776 pw.flush(); 20777 FileOutputStream fout = new FileOutputStream(fd); 20778 BufferedOutputStream str = new BufferedOutputStream(fout); 20779 XmlSerializer serializer = new FastXmlSerializer(); 20780 try { 20781 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20782 serializer.startDocument(null, true); 20783 serializer.setFeature( 20784 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20785 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20786 serializer.endDocument(); 20787 serializer.flush(); 20788 } catch (IllegalArgumentException e) { 20789 pw.println("Failed writing: " + e); 20790 } catch (IllegalStateException e) { 20791 pw.println("Failed writing: " + e); 20792 } catch (IOException e) { 20793 pw.println("Failed writing: " + e); 20794 } 20795 } 20796 20797 if (!checkin 20798 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20799 && packageName == null) { 20800 pw.println(); 20801 int count = mSettings.mPackages.size(); 20802 if (count == 0) { 20803 pw.println("No applications!"); 20804 pw.println(); 20805 } else { 20806 final String prefix = " "; 20807 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20808 if (allPackageSettings.size() == 0) { 20809 pw.println("No domain preferred apps!"); 20810 pw.println(); 20811 } else { 20812 pw.println("App verification status:"); 20813 pw.println(); 20814 count = 0; 20815 for (PackageSetting ps : allPackageSettings) { 20816 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20817 if (ivi == null || ivi.getPackageName() == null) continue; 20818 pw.println(prefix + "Package: " + ivi.getPackageName()); 20819 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20820 pw.println(prefix + "Status: " + ivi.getStatusString()); 20821 pw.println(); 20822 count++; 20823 } 20824 if (count == 0) { 20825 pw.println(prefix + "No app verification established."); 20826 pw.println(); 20827 } 20828 for (int userId : sUserManager.getUserIds()) { 20829 pw.println("App linkages for user " + userId + ":"); 20830 pw.println(); 20831 count = 0; 20832 for (PackageSetting ps : allPackageSettings) { 20833 final long status = ps.getDomainVerificationStatusForUser(userId); 20834 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20835 && !DEBUG_DOMAIN_VERIFICATION) { 20836 continue; 20837 } 20838 pw.println(prefix + "Package: " + ps.name); 20839 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20840 String statusStr = IntentFilterVerificationInfo. 20841 getStatusStringFromValue(status); 20842 pw.println(prefix + "Status: " + statusStr); 20843 pw.println(); 20844 count++; 20845 } 20846 if (count == 0) { 20847 pw.println(prefix + "No configured app linkages."); 20848 pw.println(); 20849 } 20850 } 20851 } 20852 } 20853 } 20854 20855 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20856 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20857 if (packageName == null && permissionNames == null) { 20858 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20859 if (iperm == 0) { 20860 if (dumpState.onTitlePrinted()) 20861 pw.println(); 20862 pw.println("AppOp Permissions:"); 20863 } 20864 pw.print(" AppOp Permission "); 20865 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20866 pw.println(":"); 20867 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20868 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20869 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20870 } 20871 } 20872 } 20873 } 20874 20875 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20876 boolean printedSomething = false; 20877 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20878 if (packageName != null && !packageName.equals(p.info.packageName)) { 20879 continue; 20880 } 20881 if (!printedSomething) { 20882 if (dumpState.onTitlePrinted()) 20883 pw.println(); 20884 pw.println("Registered ContentProviders:"); 20885 printedSomething = true; 20886 } 20887 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20888 pw.print(" "); pw.println(p.toString()); 20889 } 20890 printedSomething = false; 20891 for (Map.Entry<String, PackageParser.Provider> entry : 20892 mProvidersByAuthority.entrySet()) { 20893 PackageParser.Provider p = entry.getValue(); 20894 if (packageName != null && !packageName.equals(p.info.packageName)) { 20895 continue; 20896 } 20897 if (!printedSomething) { 20898 if (dumpState.onTitlePrinted()) 20899 pw.println(); 20900 pw.println("ContentProvider Authorities:"); 20901 printedSomething = true; 20902 } 20903 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20904 pw.print(" "); pw.println(p.toString()); 20905 if (p.info != null && p.info.applicationInfo != null) { 20906 final String appInfo = p.info.applicationInfo.toString(); 20907 pw.print(" applicationInfo="); pw.println(appInfo); 20908 } 20909 } 20910 } 20911 20912 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20913 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20914 } 20915 20916 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20917 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20918 } 20919 20920 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20921 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20922 } 20923 20924 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20925 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20926 } 20927 20928 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20929 // XXX should handle packageName != null by dumping only install data that 20930 // the given package is involved with. 20931 if (dumpState.onTitlePrinted()) pw.println(); 20932 20933 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20934 ipw.println(); 20935 ipw.println("Frozen packages:"); 20936 ipw.increaseIndent(); 20937 if (mFrozenPackages.size() == 0) { 20938 ipw.println("(none)"); 20939 } else { 20940 for (int i = 0; i < mFrozenPackages.size(); i++) { 20941 ipw.println(mFrozenPackages.valueAt(i)); 20942 } 20943 } 20944 ipw.decreaseIndent(); 20945 } 20946 20947 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20948 if (dumpState.onTitlePrinted()) pw.println(); 20949 dumpDexoptStateLPr(pw, packageName); 20950 } 20951 20952 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20953 if (dumpState.onTitlePrinted()) pw.println(); 20954 dumpCompilerStatsLPr(pw, packageName); 20955 } 20956 20957 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20958 if (dumpState.onTitlePrinted()) pw.println(); 20959 dumpEnabledOverlaysLPr(pw); 20960 } 20961 20962 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20963 if (dumpState.onTitlePrinted()) pw.println(); 20964 mSettings.dumpReadMessagesLPr(pw, dumpState); 20965 20966 pw.println(); 20967 pw.println("Package warning messages:"); 20968 BufferedReader in = null; 20969 String line = null; 20970 try { 20971 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20972 while ((line = in.readLine()) != null) { 20973 if (line.contains("ignored: updated version")) continue; 20974 pw.println(line); 20975 } 20976 } catch (IOException ignored) { 20977 } finally { 20978 IoUtils.closeQuietly(in); 20979 } 20980 } 20981 20982 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20983 BufferedReader in = null; 20984 String line = null; 20985 try { 20986 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20987 while ((line = in.readLine()) != null) { 20988 if (line.contains("ignored: updated version")) continue; 20989 pw.print("msg,"); 20990 pw.println(line); 20991 } 20992 } catch (IOException ignored) { 20993 } finally { 20994 IoUtils.closeQuietly(in); 20995 } 20996 } 20997 } 20998 20999 // PackageInstaller should be called outside of mPackages lock 21000 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21001 // XXX should handle packageName != null by dumping only install data that 21002 // the given package is involved with. 21003 if (dumpState.onTitlePrinted()) pw.println(); 21004 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21005 } 21006 } 21007 21008 private void dumpProto(FileDescriptor fd) { 21009 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21010 21011 synchronized (mPackages) { 21012 final long requiredVerifierPackageToken = 21013 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21014 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21015 proto.write( 21016 PackageServiceDumpProto.PackageShortProto.UID, 21017 getPackageUid( 21018 mRequiredVerifierPackage, 21019 MATCH_DEBUG_TRIAGED_MISSING, 21020 UserHandle.USER_SYSTEM)); 21021 proto.end(requiredVerifierPackageToken); 21022 21023 if (mIntentFilterVerifierComponent != null) { 21024 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21025 final long verifierPackageToken = 21026 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21027 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21028 proto.write( 21029 PackageServiceDumpProto.PackageShortProto.UID, 21030 getPackageUid( 21031 verifierPackageName, 21032 MATCH_DEBUG_TRIAGED_MISSING, 21033 UserHandle.USER_SYSTEM)); 21034 proto.end(verifierPackageToken); 21035 } 21036 21037 dumpSharedLibrariesProto(proto); 21038 dumpFeaturesProto(proto); 21039 mSettings.dumpPackagesProto(proto); 21040 mSettings.dumpSharedUsersProto(proto); 21041 dumpMessagesProto(proto); 21042 } 21043 proto.flush(); 21044 } 21045 21046 private void dumpMessagesProto(ProtoOutputStream proto) { 21047 BufferedReader in = null; 21048 String line = null; 21049 try { 21050 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21051 while ((line = in.readLine()) != null) { 21052 if (line.contains("ignored: updated version")) continue; 21053 proto.write(PackageServiceDumpProto.MESSAGES, line); 21054 } 21055 } catch (IOException ignored) { 21056 } finally { 21057 IoUtils.closeQuietly(in); 21058 } 21059 } 21060 21061 private void dumpFeaturesProto(ProtoOutputStream proto) { 21062 synchronized (mAvailableFeatures) { 21063 final int count = mAvailableFeatures.size(); 21064 for (int i = 0; i < count; i++) { 21065 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21066 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21067 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21068 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21069 proto.end(featureToken); 21070 } 21071 } 21072 } 21073 21074 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21075 final int count = mSharedLibraries.size(); 21076 for (int i = 0; i < count; i++) { 21077 final String libName = mSharedLibraries.keyAt(i); 21078 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21079 if (versionedLib == null) { 21080 continue; 21081 } 21082 final int versionCount = versionedLib.size(); 21083 for (int j = 0; j < versionCount; j++) { 21084 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21085 final long sharedLibraryToken = 21086 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21087 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21088 final boolean isJar = (libEntry.path != null); 21089 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21090 if (isJar) { 21091 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21092 } else { 21093 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21094 } 21095 proto.end(sharedLibraryToken); 21096 } 21097 } 21098 } 21099 21100 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21101 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21102 ipw.println(); 21103 ipw.println("Dexopt state:"); 21104 ipw.increaseIndent(); 21105 Collection<PackageParser.Package> packages = null; 21106 if (packageName != null) { 21107 PackageParser.Package targetPackage = mPackages.get(packageName); 21108 if (targetPackage != null) { 21109 packages = Collections.singletonList(targetPackage); 21110 } else { 21111 ipw.println("Unable to find package: " + packageName); 21112 return; 21113 } 21114 } else { 21115 packages = mPackages.values(); 21116 } 21117 21118 for (PackageParser.Package pkg : packages) { 21119 ipw.println("[" + pkg.packageName + "]"); 21120 ipw.increaseIndent(); 21121 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21122 ipw.decreaseIndent(); 21123 } 21124 } 21125 21126 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21127 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21128 ipw.println(); 21129 ipw.println("Compiler stats:"); 21130 ipw.increaseIndent(); 21131 Collection<PackageParser.Package> packages = null; 21132 if (packageName != null) { 21133 PackageParser.Package targetPackage = mPackages.get(packageName); 21134 if (targetPackage != null) { 21135 packages = Collections.singletonList(targetPackage); 21136 } else { 21137 ipw.println("Unable to find package: " + packageName); 21138 return; 21139 } 21140 } else { 21141 packages = mPackages.values(); 21142 } 21143 21144 for (PackageParser.Package pkg : packages) { 21145 ipw.println("[" + pkg.packageName + "]"); 21146 ipw.increaseIndent(); 21147 21148 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21149 if (stats == null) { 21150 ipw.println("(No recorded stats)"); 21151 } else { 21152 stats.dump(ipw); 21153 } 21154 ipw.decreaseIndent(); 21155 } 21156 } 21157 21158 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21159 pw.println("Enabled overlay paths:"); 21160 final int N = mEnabledOverlayPaths.size(); 21161 for (int i = 0; i < N; i++) { 21162 final int userId = mEnabledOverlayPaths.keyAt(i); 21163 pw.println(String.format(" User %d:", userId)); 21164 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21165 mEnabledOverlayPaths.valueAt(i); 21166 final int M = userSpecificOverlays.size(); 21167 for (int j = 0; j < M; j++) { 21168 final String targetPackageName = userSpecificOverlays.keyAt(j); 21169 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21170 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21171 } 21172 } 21173 } 21174 21175 private String dumpDomainString(String packageName) { 21176 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21177 .getList(); 21178 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21179 21180 ArraySet<String> result = new ArraySet<>(); 21181 if (iviList.size() > 0) { 21182 for (IntentFilterVerificationInfo ivi : iviList) { 21183 for (String host : ivi.getDomains()) { 21184 result.add(host); 21185 } 21186 } 21187 } 21188 if (filters != null && filters.size() > 0) { 21189 for (IntentFilter filter : filters) { 21190 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21191 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21192 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21193 result.addAll(filter.getHostsList()); 21194 } 21195 } 21196 } 21197 21198 StringBuilder sb = new StringBuilder(result.size() * 16); 21199 for (String domain : result) { 21200 if (sb.length() > 0) sb.append(" "); 21201 sb.append(domain); 21202 } 21203 return sb.toString(); 21204 } 21205 21206 // ------- apps on sdcard specific code ------- 21207 static final boolean DEBUG_SD_INSTALL = false; 21208 21209 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21210 21211 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21212 21213 private boolean mMediaMounted = false; 21214 21215 static String getEncryptKey() { 21216 try { 21217 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21218 SD_ENCRYPTION_KEYSTORE_NAME); 21219 if (sdEncKey == null) { 21220 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21221 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21222 if (sdEncKey == null) { 21223 Slog.e(TAG, "Failed to create encryption keys"); 21224 return null; 21225 } 21226 } 21227 return sdEncKey; 21228 } catch (NoSuchAlgorithmException nsae) { 21229 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21230 return null; 21231 } catch (IOException ioe) { 21232 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21233 return null; 21234 } 21235 } 21236 21237 /* 21238 * Update media status on PackageManager. 21239 */ 21240 @Override 21241 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21242 int callingUid = Binder.getCallingUid(); 21243 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21244 throw new SecurityException("Media status can only be updated by the system"); 21245 } 21246 // reader; this apparently protects mMediaMounted, but should probably 21247 // be a different lock in that case. 21248 synchronized (mPackages) { 21249 Log.i(TAG, "Updating external media status from " 21250 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21251 + (mediaStatus ? "mounted" : "unmounted")); 21252 if (DEBUG_SD_INSTALL) 21253 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21254 + ", mMediaMounted=" + mMediaMounted); 21255 if (mediaStatus == mMediaMounted) { 21256 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21257 : 0, -1); 21258 mHandler.sendMessage(msg); 21259 return; 21260 } 21261 mMediaMounted = mediaStatus; 21262 } 21263 // Queue up an async operation since the package installation may take a 21264 // little while. 21265 mHandler.post(new Runnable() { 21266 public void run() { 21267 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21268 } 21269 }); 21270 } 21271 21272 /** 21273 * Called by StorageManagerService when the initial ASECs to scan are available. 21274 * Should block until all the ASEC containers are finished being scanned. 21275 */ 21276 public void scanAvailableAsecs() { 21277 updateExternalMediaStatusInner(true, false, false); 21278 } 21279 21280 /* 21281 * Collect information of applications on external media, map them against 21282 * existing containers and update information based on current mount status. 21283 * Please note that we always have to report status if reportStatus has been 21284 * set to true especially when unloading packages. 21285 */ 21286 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21287 boolean externalStorage) { 21288 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21289 int[] uidArr = EmptyArray.INT; 21290 21291 final String[] list = PackageHelper.getSecureContainerList(); 21292 if (ArrayUtils.isEmpty(list)) { 21293 Log.i(TAG, "No secure containers found"); 21294 } else { 21295 // Process list of secure containers and categorize them 21296 // as active or stale based on their package internal state. 21297 21298 // reader 21299 synchronized (mPackages) { 21300 for (String cid : list) { 21301 // Leave stages untouched for now; installer service owns them 21302 if (PackageInstallerService.isStageName(cid)) continue; 21303 21304 if (DEBUG_SD_INSTALL) 21305 Log.i(TAG, "Processing container " + cid); 21306 String pkgName = getAsecPackageName(cid); 21307 if (pkgName == null) { 21308 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21309 continue; 21310 } 21311 if (DEBUG_SD_INSTALL) 21312 Log.i(TAG, "Looking for pkg : " + pkgName); 21313 21314 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21315 if (ps == null) { 21316 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21317 continue; 21318 } 21319 21320 /* 21321 * Skip packages that are not external if we're unmounting 21322 * external storage. 21323 */ 21324 if (externalStorage && !isMounted && !isExternal(ps)) { 21325 continue; 21326 } 21327 21328 final AsecInstallArgs args = new AsecInstallArgs(cid, 21329 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21330 // The package status is changed only if the code path 21331 // matches between settings and the container id. 21332 if (ps.codePathString != null 21333 && ps.codePathString.startsWith(args.getCodePath())) { 21334 if (DEBUG_SD_INSTALL) { 21335 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21336 + " at code path: " + ps.codePathString); 21337 } 21338 21339 // We do have a valid package installed on sdcard 21340 processCids.put(args, ps.codePathString); 21341 final int uid = ps.appId; 21342 if (uid != -1) { 21343 uidArr = ArrayUtils.appendInt(uidArr, uid); 21344 } 21345 } else { 21346 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21347 + ps.codePathString); 21348 } 21349 } 21350 } 21351 21352 Arrays.sort(uidArr); 21353 } 21354 21355 // Process packages with valid entries. 21356 if (isMounted) { 21357 if (DEBUG_SD_INSTALL) 21358 Log.i(TAG, "Loading packages"); 21359 loadMediaPackages(processCids, uidArr, externalStorage); 21360 startCleaningPackages(); 21361 mInstallerService.onSecureContainersAvailable(); 21362 } else { 21363 if (DEBUG_SD_INSTALL) 21364 Log.i(TAG, "Unloading packages"); 21365 unloadMediaPackages(processCids, uidArr, reportStatus); 21366 } 21367 } 21368 21369 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21370 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21371 final int size = infos.size(); 21372 final String[] packageNames = new String[size]; 21373 final int[] packageUids = new int[size]; 21374 for (int i = 0; i < size; i++) { 21375 final ApplicationInfo info = infos.get(i); 21376 packageNames[i] = info.packageName; 21377 packageUids[i] = info.uid; 21378 } 21379 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21380 finishedReceiver); 21381 } 21382 21383 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21384 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21385 sendResourcesChangedBroadcast(mediaStatus, replacing, 21386 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21387 } 21388 21389 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21390 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21391 int size = pkgList.length; 21392 if (size > 0) { 21393 // Send broadcasts here 21394 Bundle extras = new Bundle(); 21395 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21396 if (uidArr != null) { 21397 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21398 } 21399 if (replacing) { 21400 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21401 } 21402 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21403 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21404 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21405 } 21406 } 21407 21408 /* 21409 * Look at potentially valid container ids from processCids If package 21410 * information doesn't match the one on record or package scanning fails, 21411 * the cid is added to list of removeCids. We currently don't delete stale 21412 * containers. 21413 */ 21414 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21415 boolean externalStorage) { 21416 ArrayList<String> pkgList = new ArrayList<String>(); 21417 Set<AsecInstallArgs> keys = processCids.keySet(); 21418 21419 for (AsecInstallArgs args : keys) { 21420 String codePath = processCids.get(args); 21421 if (DEBUG_SD_INSTALL) 21422 Log.i(TAG, "Loading container : " + args.cid); 21423 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21424 try { 21425 // Make sure there are no container errors first. 21426 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21427 Slog.e(TAG, "Failed to mount cid : " + args.cid 21428 + " when installing from sdcard"); 21429 continue; 21430 } 21431 // Check code path here. 21432 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21433 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21434 + " does not match one in settings " + codePath); 21435 continue; 21436 } 21437 // Parse package 21438 int parseFlags = mDefParseFlags; 21439 if (args.isExternalAsec()) { 21440 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21441 } 21442 if (args.isFwdLocked()) { 21443 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21444 } 21445 21446 synchronized (mInstallLock) { 21447 PackageParser.Package pkg = null; 21448 try { 21449 // Sadly we don't know the package name yet to freeze it 21450 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21451 SCAN_IGNORE_FROZEN, 0, null); 21452 } catch (PackageManagerException e) { 21453 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21454 } 21455 // Scan the package 21456 if (pkg != null) { 21457 /* 21458 * TODO why is the lock being held? doPostInstall is 21459 * called in other places without the lock. This needs 21460 * to be straightened out. 21461 */ 21462 // writer 21463 synchronized (mPackages) { 21464 retCode = PackageManager.INSTALL_SUCCEEDED; 21465 pkgList.add(pkg.packageName); 21466 // Post process args 21467 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21468 pkg.applicationInfo.uid); 21469 } 21470 } else { 21471 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21472 } 21473 } 21474 21475 } finally { 21476 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21477 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21478 } 21479 } 21480 } 21481 // writer 21482 synchronized (mPackages) { 21483 // If the platform SDK has changed since the last time we booted, 21484 // we need to re-grant app permission to catch any new ones that 21485 // appear. This is really a hack, and means that apps can in some 21486 // cases get permissions that the user didn't initially explicitly 21487 // allow... it would be nice to have some better way to handle 21488 // this situation. 21489 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21490 : mSettings.getInternalVersion(); 21491 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21492 : StorageManager.UUID_PRIVATE_INTERNAL; 21493 21494 int updateFlags = UPDATE_PERMISSIONS_ALL; 21495 if (ver.sdkVersion != mSdkVersion) { 21496 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21497 + mSdkVersion + "; regranting permissions for external"); 21498 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21499 } 21500 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21501 21502 // Yay, everything is now upgraded 21503 ver.forceCurrent(); 21504 21505 // can downgrade to reader 21506 // Persist settings 21507 mSettings.writeLPr(); 21508 } 21509 // Send a broadcast to let everyone know we are done processing 21510 if (pkgList.size() > 0) { 21511 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21512 } 21513 } 21514 21515 /* 21516 * Utility method to unload a list of specified containers 21517 */ 21518 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21519 // Just unmount all valid containers. 21520 for (AsecInstallArgs arg : cidArgs) { 21521 synchronized (mInstallLock) { 21522 arg.doPostDeleteLI(false); 21523 } 21524 } 21525 } 21526 21527 /* 21528 * Unload packages mounted on external media. This involves deleting package 21529 * data from internal structures, sending broadcasts about disabled packages, 21530 * gc'ing to free up references, unmounting all secure containers 21531 * corresponding to packages on external media, and posting a 21532 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21533 * that we always have to post this message if status has been requested no 21534 * matter what. 21535 */ 21536 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21537 final boolean reportStatus) { 21538 if (DEBUG_SD_INSTALL) 21539 Log.i(TAG, "unloading media packages"); 21540 ArrayList<String> pkgList = new ArrayList<String>(); 21541 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21542 final Set<AsecInstallArgs> keys = processCids.keySet(); 21543 for (AsecInstallArgs args : keys) { 21544 String pkgName = args.getPackageName(); 21545 if (DEBUG_SD_INSTALL) 21546 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21547 // Delete package internally 21548 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21549 synchronized (mInstallLock) { 21550 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21551 final boolean res; 21552 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21553 "unloadMediaPackages")) { 21554 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21555 null); 21556 } 21557 if (res) { 21558 pkgList.add(pkgName); 21559 } else { 21560 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21561 failedList.add(args); 21562 } 21563 } 21564 } 21565 21566 // reader 21567 synchronized (mPackages) { 21568 // We didn't update the settings after removing each package; 21569 // write them now for all packages. 21570 mSettings.writeLPr(); 21571 } 21572 21573 // We have to absolutely send UPDATED_MEDIA_STATUS only 21574 // after confirming that all the receivers processed the ordered 21575 // broadcast when packages get disabled, force a gc to clean things up. 21576 // and unload all the containers. 21577 if (pkgList.size() > 0) { 21578 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21579 new IIntentReceiver.Stub() { 21580 public void performReceive(Intent intent, int resultCode, String data, 21581 Bundle extras, boolean ordered, boolean sticky, 21582 int sendingUser) throws RemoteException { 21583 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21584 reportStatus ? 1 : 0, 1, keys); 21585 mHandler.sendMessage(msg); 21586 } 21587 }); 21588 } else { 21589 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21590 keys); 21591 mHandler.sendMessage(msg); 21592 } 21593 } 21594 21595 private void loadPrivatePackages(final VolumeInfo vol) { 21596 mHandler.post(new Runnable() { 21597 @Override 21598 public void run() { 21599 loadPrivatePackagesInner(vol); 21600 } 21601 }); 21602 } 21603 21604 private void loadPrivatePackagesInner(VolumeInfo vol) { 21605 final String volumeUuid = vol.fsUuid; 21606 if (TextUtils.isEmpty(volumeUuid)) { 21607 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21608 return; 21609 } 21610 21611 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21612 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21613 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21614 21615 final VersionInfo ver; 21616 final List<PackageSetting> packages; 21617 synchronized (mPackages) { 21618 ver = mSettings.findOrCreateVersion(volumeUuid); 21619 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21620 } 21621 21622 for (PackageSetting ps : packages) { 21623 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21624 synchronized (mInstallLock) { 21625 final PackageParser.Package pkg; 21626 try { 21627 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21628 loaded.add(pkg.applicationInfo); 21629 21630 } catch (PackageManagerException e) { 21631 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21632 } 21633 21634 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21635 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21636 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21637 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21638 } 21639 } 21640 } 21641 21642 // Reconcile app data for all started/unlocked users 21643 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21644 final UserManager um = mContext.getSystemService(UserManager.class); 21645 UserManagerInternal umInternal = getUserManagerInternal(); 21646 for (UserInfo user : um.getUsers()) { 21647 final int flags; 21648 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21649 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21650 } else if (umInternal.isUserRunning(user.id)) { 21651 flags = StorageManager.FLAG_STORAGE_DE; 21652 } else { 21653 continue; 21654 } 21655 21656 try { 21657 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21658 synchronized (mInstallLock) { 21659 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21660 } 21661 } catch (IllegalStateException e) { 21662 // Device was probably ejected, and we'll process that event momentarily 21663 Slog.w(TAG, "Failed to prepare storage: " + e); 21664 } 21665 } 21666 21667 synchronized (mPackages) { 21668 int updateFlags = UPDATE_PERMISSIONS_ALL; 21669 if (ver.sdkVersion != mSdkVersion) { 21670 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21671 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21672 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21673 } 21674 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21675 21676 // Yay, everything is now upgraded 21677 ver.forceCurrent(); 21678 21679 mSettings.writeLPr(); 21680 } 21681 21682 for (PackageFreezer freezer : freezers) { 21683 freezer.close(); 21684 } 21685 21686 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21687 sendResourcesChangedBroadcast(true, false, loaded, null); 21688 } 21689 21690 private void unloadPrivatePackages(final VolumeInfo vol) { 21691 mHandler.post(new Runnable() { 21692 @Override 21693 public void run() { 21694 unloadPrivatePackagesInner(vol); 21695 } 21696 }); 21697 } 21698 21699 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21700 final String volumeUuid = vol.fsUuid; 21701 if (TextUtils.isEmpty(volumeUuid)) { 21702 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21703 return; 21704 } 21705 21706 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21707 synchronized (mInstallLock) { 21708 synchronized (mPackages) { 21709 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21710 for (PackageSetting ps : packages) { 21711 if (ps.pkg == null) continue; 21712 21713 final ApplicationInfo info = ps.pkg.applicationInfo; 21714 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21715 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21716 21717 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21718 "unloadPrivatePackagesInner")) { 21719 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21720 false, null)) { 21721 unloaded.add(info); 21722 } else { 21723 Slog.w(TAG, "Failed to unload " + ps.codePath); 21724 } 21725 } 21726 21727 // Try very hard to release any references to this package 21728 // so we don't risk the system server being killed due to 21729 // open FDs 21730 AttributeCache.instance().removePackage(ps.name); 21731 } 21732 21733 mSettings.writeLPr(); 21734 } 21735 } 21736 21737 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21738 sendResourcesChangedBroadcast(false, false, unloaded, null); 21739 21740 // Try very hard to release any references to this path so we don't risk 21741 // the system server being killed due to open FDs 21742 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21743 21744 for (int i = 0; i < 3; i++) { 21745 System.gc(); 21746 System.runFinalization(); 21747 } 21748 } 21749 21750 private void assertPackageKnown(String volumeUuid, String packageName) 21751 throws PackageManagerException { 21752 synchronized (mPackages) { 21753 // Normalize package name to handle renamed packages 21754 packageName = normalizePackageNameLPr(packageName); 21755 21756 final PackageSetting ps = mSettings.mPackages.get(packageName); 21757 if (ps == null) { 21758 throw new PackageManagerException("Package " + packageName + " is unknown"); 21759 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21760 throw new PackageManagerException( 21761 "Package " + packageName + " found on unknown volume " + volumeUuid 21762 + "; expected volume " + ps.volumeUuid); 21763 } 21764 } 21765 } 21766 21767 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21768 throws PackageManagerException { 21769 synchronized (mPackages) { 21770 // Normalize package name to handle renamed packages 21771 packageName = normalizePackageNameLPr(packageName); 21772 21773 final PackageSetting ps = mSettings.mPackages.get(packageName); 21774 if (ps == null) { 21775 throw new PackageManagerException("Package " + packageName + " is unknown"); 21776 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21777 throw new PackageManagerException( 21778 "Package " + packageName + " found on unknown volume " + volumeUuid 21779 + "; expected volume " + ps.volumeUuid); 21780 } else if (!ps.getInstalled(userId)) { 21781 throw new PackageManagerException( 21782 "Package " + packageName + " not installed for user " + userId); 21783 } 21784 } 21785 } 21786 21787 private List<String> collectAbsoluteCodePaths() { 21788 synchronized (mPackages) { 21789 List<String> codePaths = new ArrayList<>(); 21790 final int packageCount = mSettings.mPackages.size(); 21791 for (int i = 0; i < packageCount; i++) { 21792 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21793 codePaths.add(ps.codePath.getAbsolutePath()); 21794 } 21795 return codePaths; 21796 } 21797 } 21798 21799 /** 21800 * Examine all apps present on given mounted volume, and destroy apps that 21801 * aren't expected, either due to uninstallation or reinstallation on 21802 * another volume. 21803 */ 21804 private void reconcileApps(String volumeUuid) { 21805 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21806 List<File> filesToDelete = null; 21807 21808 final File[] files = FileUtils.listFilesOrEmpty( 21809 Environment.getDataAppDirectory(volumeUuid)); 21810 for (File file : files) { 21811 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21812 && !PackageInstallerService.isStageName(file.getName()); 21813 if (!isPackage) { 21814 // Ignore entries which are not packages 21815 continue; 21816 } 21817 21818 String absolutePath = file.getAbsolutePath(); 21819 21820 boolean pathValid = false; 21821 final int absoluteCodePathCount = absoluteCodePaths.size(); 21822 for (int i = 0; i < absoluteCodePathCount; i++) { 21823 String absoluteCodePath = absoluteCodePaths.get(i); 21824 if (absolutePath.startsWith(absoluteCodePath)) { 21825 pathValid = true; 21826 break; 21827 } 21828 } 21829 21830 if (!pathValid) { 21831 if (filesToDelete == null) { 21832 filesToDelete = new ArrayList<>(); 21833 } 21834 filesToDelete.add(file); 21835 } 21836 } 21837 21838 if (filesToDelete != null) { 21839 final int fileToDeleteCount = filesToDelete.size(); 21840 for (int i = 0; i < fileToDeleteCount; i++) { 21841 File fileToDelete = filesToDelete.get(i); 21842 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21843 synchronized (mInstallLock) { 21844 removeCodePathLI(fileToDelete); 21845 } 21846 } 21847 } 21848 } 21849 21850 /** 21851 * Reconcile all app data for the given user. 21852 * <p> 21853 * Verifies that directories exist and that ownership and labeling is 21854 * correct for all installed apps on all mounted volumes. 21855 */ 21856 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21857 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21858 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21859 final String volumeUuid = vol.getFsUuid(); 21860 synchronized (mInstallLock) { 21861 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21862 } 21863 } 21864 } 21865 21866 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21867 boolean migrateAppData) { 21868 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21869 } 21870 21871 /** 21872 * Reconcile all app data on given mounted volume. 21873 * <p> 21874 * Destroys app data that isn't expected, either due to uninstallation or 21875 * reinstallation on another volume. 21876 * <p> 21877 * Verifies that directories exist and that ownership and labeling is 21878 * correct for all installed apps. 21879 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21880 */ 21881 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21882 boolean migrateAppData, boolean onlyCoreApps) { 21883 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21884 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21885 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21886 21887 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21888 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21889 21890 // First look for stale data that doesn't belong, and check if things 21891 // have changed since we did our last restorecon 21892 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21893 if (StorageManager.isFileEncryptedNativeOrEmulated() 21894 && !StorageManager.isUserKeyUnlocked(userId)) { 21895 throw new RuntimeException( 21896 "Yikes, someone asked us to reconcile CE storage while " + userId 21897 + " was still locked; this would have caused massive data loss!"); 21898 } 21899 21900 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21901 for (File file : files) { 21902 final String packageName = file.getName(); 21903 try { 21904 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21905 } catch (PackageManagerException e) { 21906 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21907 try { 21908 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21909 StorageManager.FLAG_STORAGE_CE, 0); 21910 } catch (InstallerException e2) { 21911 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21912 } 21913 } 21914 } 21915 } 21916 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21917 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21918 for (File file : files) { 21919 final String packageName = file.getName(); 21920 try { 21921 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21922 } catch (PackageManagerException e) { 21923 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21924 try { 21925 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21926 StorageManager.FLAG_STORAGE_DE, 0); 21927 } catch (InstallerException e2) { 21928 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21929 } 21930 } 21931 } 21932 } 21933 21934 // Ensure that data directories are ready to roll for all packages 21935 // installed for this volume and user 21936 final List<PackageSetting> packages; 21937 synchronized (mPackages) { 21938 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21939 } 21940 int preparedCount = 0; 21941 for (PackageSetting ps : packages) { 21942 final String packageName = ps.name; 21943 if (ps.pkg == null) { 21944 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21945 // TODO: might be due to legacy ASEC apps; we should circle back 21946 // and reconcile again once they're scanned 21947 continue; 21948 } 21949 // Skip non-core apps if requested 21950 if (onlyCoreApps && !ps.pkg.coreApp) { 21951 result.add(packageName); 21952 continue; 21953 } 21954 21955 if (ps.getInstalled(userId)) { 21956 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21957 preparedCount++; 21958 } 21959 } 21960 21961 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21962 return result; 21963 } 21964 21965 /** 21966 * Prepare app data for the given app just after it was installed or 21967 * upgraded. This method carefully only touches users that it's installed 21968 * for, and it forces a restorecon to handle any seinfo changes. 21969 * <p> 21970 * Verifies that directories exist and that ownership and labeling is 21971 * correct for all installed apps. If there is an ownership mismatch, it 21972 * will try recovering system apps by wiping data; third-party app data is 21973 * left intact. 21974 * <p> 21975 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21976 */ 21977 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21978 final PackageSetting ps; 21979 synchronized (mPackages) { 21980 ps = mSettings.mPackages.get(pkg.packageName); 21981 mSettings.writeKernelMappingLPr(ps); 21982 } 21983 21984 final UserManager um = mContext.getSystemService(UserManager.class); 21985 UserManagerInternal umInternal = getUserManagerInternal(); 21986 for (UserInfo user : um.getUsers()) { 21987 final int flags; 21988 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21989 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21990 } else if (umInternal.isUserRunning(user.id)) { 21991 flags = StorageManager.FLAG_STORAGE_DE; 21992 } else { 21993 continue; 21994 } 21995 21996 if (ps.getInstalled(user.id)) { 21997 // TODO: when user data is locked, mark that we're still dirty 21998 prepareAppDataLIF(pkg, user.id, flags); 21999 } 22000 } 22001 } 22002 22003 /** 22004 * Prepare app data for the given app. 22005 * <p> 22006 * Verifies that directories exist and that ownership and labeling is 22007 * correct for all installed apps. If there is an ownership mismatch, this 22008 * will try recovering system apps by wiping data; third-party app data is 22009 * left intact. 22010 */ 22011 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22012 if (pkg == null) { 22013 Slog.wtf(TAG, "Package was null!", new Throwable()); 22014 return; 22015 } 22016 prepareAppDataLeafLIF(pkg, userId, flags); 22017 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22018 for (int i = 0; i < childCount; i++) { 22019 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22020 } 22021 } 22022 22023 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22024 boolean maybeMigrateAppData) { 22025 prepareAppDataLIF(pkg, userId, flags); 22026 22027 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22028 // We may have just shuffled around app data directories, so 22029 // prepare them one more time 22030 prepareAppDataLIF(pkg, userId, flags); 22031 } 22032 } 22033 22034 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22035 if (DEBUG_APP_DATA) { 22036 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22037 + Integer.toHexString(flags)); 22038 } 22039 22040 final String volumeUuid = pkg.volumeUuid; 22041 final String packageName = pkg.packageName; 22042 final ApplicationInfo app = pkg.applicationInfo; 22043 final int appId = UserHandle.getAppId(app.uid); 22044 22045 Preconditions.checkNotNull(app.seInfo); 22046 22047 long ceDataInode = -1; 22048 try { 22049 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22050 appId, app.seInfo, app.targetSdkVersion); 22051 } catch (InstallerException e) { 22052 if (app.isSystemApp()) { 22053 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22054 + ", but trying to recover: " + e); 22055 destroyAppDataLeafLIF(pkg, userId, flags); 22056 try { 22057 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22058 appId, app.seInfo, app.targetSdkVersion); 22059 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22060 } catch (InstallerException e2) { 22061 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22062 } 22063 } else { 22064 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22065 } 22066 } 22067 22068 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22069 // TODO: mark this structure as dirty so we persist it! 22070 synchronized (mPackages) { 22071 final PackageSetting ps = mSettings.mPackages.get(packageName); 22072 if (ps != null) { 22073 ps.setCeDataInode(ceDataInode, userId); 22074 } 22075 } 22076 } 22077 22078 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22079 } 22080 22081 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22082 if (pkg == null) { 22083 Slog.wtf(TAG, "Package was null!", new Throwable()); 22084 return; 22085 } 22086 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22087 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22088 for (int i = 0; i < childCount; i++) { 22089 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22090 } 22091 } 22092 22093 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22094 final String volumeUuid = pkg.volumeUuid; 22095 final String packageName = pkg.packageName; 22096 final ApplicationInfo app = pkg.applicationInfo; 22097 22098 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22099 // Create a native library symlink only if we have native libraries 22100 // and if the native libraries are 32 bit libraries. We do not provide 22101 // this symlink for 64 bit libraries. 22102 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22103 final String nativeLibPath = app.nativeLibraryDir; 22104 try { 22105 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22106 nativeLibPath, userId); 22107 } catch (InstallerException e) { 22108 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22109 } 22110 } 22111 } 22112 } 22113 22114 /** 22115 * For system apps on non-FBE devices, this method migrates any existing 22116 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22117 * requested by the app. 22118 */ 22119 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22120 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22121 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22122 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22123 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22124 try { 22125 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22126 storageTarget); 22127 } catch (InstallerException e) { 22128 logCriticalInfo(Log.WARN, 22129 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22130 } 22131 return true; 22132 } else { 22133 return false; 22134 } 22135 } 22136 22137 public PackageFreezer freezePackage(String packageName, String killReason) { 22138 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22139 } 22140 22141 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22142 return new PackageFreezer(packageName, userId, killReason); 22143 } 22144 22145 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22146 String killReason) { 22147 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22148 } 22149 22150 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22151 String killReason) { 22152 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22153 return new PackageFreezer(); 22154 } else { 22155 return freezePackage(packageName, userId, killReason); 22156 } 22157 } 22158 22159 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22160 String killReason) { 22161 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22162 } 22163 22164 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22165 String killReason) { 22166 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22167 return new PackageFreezer(); 22168 } else { 22169 return freezePackage(packageName, userId, killReason); 22170 } 22171 } 22172 22173 /** 22174 * Class that freezes and kills the given package upon creation, and 22175 * unfreezes it upon closing. This is typically used when doing surgery on 22176 * app code/data to prevent the app from running while you're working. 22177 */ 22178 private class PackageFreezer implements AutoCloseable { 22179 private final String mPackageName; 22180 private final PackageFreezer[] mChildren; 22181 22182 private final boolean mWeFroze; 22183 22184 private final AtomicBoolean mClosed = new AtomicBoolean(); 22185 private final CloseGuard mCloseGuard = CloseGuard.get(); 22186 22187 /** 22188 * Create and return a stub freezer that doesn't actually do anything, 22189 * typically used when someone requested 22190 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22191 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22192 */ 22193 public PackageFreezer() { 22194 mPackageName = null; 22195 mChildren = null; 22196 mWeFroze = false; 22197 mCloseGuard.open("close"); 22198 } 22199 22200 public PackageFreezer(String packageName, int userId, String killReason) { 22201 synchronized (mPackages) { 22202 mPackageName = packageName; 22203 mWeFroze = mFrozenPackages.add(mPackageName); 22204 22205 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22206 if (ps != null) { 22207 killApplication(ps.name, ps.appId, userId, killReason); 22208 } 22209 22210 final PackageParser.Package p = mPackages.get(packageName); 22211 if (p != null && p.childPackages != null) { 22212 final int N = p.childPackages.size(); 22213 mChildren = new PackageFreezer[N]; 22214 for (int i = 0; i < N; i++) { 22215 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22216 userId, killReason); 22217 } 22218 } else { 22219 mChildren = null; 22220 } 22221 } 22222 mCloseGuard.open("close"); 22223 } 22224 22225 @Override 22226 protected void finalize() throws Throwable { 22227 try { 22228 mCloseGuard.warnIfOpen(); 22229 close(); 22230 } finally { 22231 super.finalize(); 22232 } 22233 } 22234 22235 @Override 22236 public void close() { 22237 mCloseGuard.close(); 22238 if (mClosed.compareAndSet(false, true)) { 22239 synchronized (mPackages) { 22240 if (mWeFroze) { 22241 mFrozenPackages.remove(mPackageName); 22242 } 22243 22244 if (mChildren != null) { 22245 for (PackageFreezer freezer : mChildren) { 22246 freezer.close(); 22247 } 22248 } 22249 } 22250 } 22251 } 22252 } 22253 22254 /** 22255 * Verify that given package is currently frozen. 22256 */ 22257 private void checkPackageFrozen(String packageName) { 22258 synchronized (mPackages) { 22259 if (!mFrozenPackages.contains(packageName)) { 22260 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22261 } 22262 } 22263 } 22264 22265 @Override 22266 public int movePackage(final String packageName, final String volumeUuid) { 22267 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22268 22269 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22270 final int moveId = mNextMoveId.getAndIncrement(); 22271 mHandler.post(new Runnable() { 22272 @Override 22273 public void run() { 22274 try { 22275 movePackageInternal(packageName, volumeUuid, moveId, user); 22276 } catch (PackageManagerException e) { 22277 Slog.w(TAG, "Failed to move " + packageName, e); 22278 mMoveCallbacks.notifyStatusChanged(moveId, 22279 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22280 } 22281 } 22282 }); 22283 return moveId; 22284 } 22285 22286 private void movePackageInternal(final String packageName, final String volumeUuid, 22287 final int moveId, UserHandle user) throws PackageManagerException { 22288 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22289 final PackageManager pm = mContext.getPackageManager(); 22290 22291 final boolean currentAsec; 22292 final String currentVolumeUuid; 22293 final File codeFile; 22294 final String installerPackageName; 22295 final String packageAbiOverride; 22296 final int appId; 22297 final String seinfo; 22298 final String label; 22299 final int targetSdkVersion; 22300 final PackageFreezer freezer; 22301 final int[] installedUserIds; 22302 22303 // reader 22304 synchronized (mPackages) { 22305 final PackageParser.Package pkg = mPackages.get(packageName); 22306 final PackageSetting ps = mSettings.mPackages.get(packageName); 22307 if (pkg == null || ps == null) { 22308 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22309 } 22310 22311 if (pkg.applicationInfo.isSystemApp()) { 22312 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22313 "Cannot move system application"); 22314 } 22315 22316 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22317 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22318 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22319 if (isInternalStorage && !allow3rdPartyOnInternal) { 22320 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22321 "3rd party apps are not allowed on internal storage"); 22322 } 22323 22324 if (pkg.applicationInfo.isExternalAsec()) { 22325 currentAsec = true; 22326 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22327 } else if (pkg.applicationInfo.isForwardLocked()) { 22328 currentAsec = true; 22329 currentVolumeUuid = "forward_locked"; 22330 } else { 22331 currentAsec = false; 22332 currentVolumeUuid = ps.volumeUuid; 22333 22334 final File probe = new File(pkg.codePath); 22335 final File probeOat = new File(probe, "oat"); 22336 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22337 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22338 "Move only supported for modern cluster style installs"); 22339 } 22340 } 22341 22342 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22343 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22344 "Package already moved to " + volumeUuid); 22345 } 22346 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22347 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22348 "Device admin cannot be moved"); 22349 } 22350 22351 if (mFrozenPackages.contains(packageName)) { 22352 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22353 "Failed to move already frozen package"); 22354 } 22355 22356 codeFile = new File(pkg.codePath); 22357 installerPackageName = ps.installerPackageName; 22358 packageAbiOverride = ps.cpuAbiOverrideString; 22359 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22360 seinfo = pkg.applicationInfo.seInfo; 22361 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22362 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22363 freezer = freezePackage(packageName, "movePackageInternal"); 22364 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22365 } 22366 22367 final Bundle extras = new Bundle(); 22368 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22369 extras.putString(Intent.EXTRA_TITLE, label); 22370 mMoveCallbacks.notifyCreated(moveId, extras); 22371 22372 int installFlags; 22373 final boolean moveCompleteApp; 22374 final File measurePath; 22375 22376 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22377 installFlags = INSTALL_INTERNAL; 22378 moveCompleteApp = !currentAsec; 22379 measurePath = Environment.getDataAppDirectory(volumeUuid); 22380 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22381 installFlags = INSTALL_EXTERNAL; 22382 moveCompleteApp = false; 22383 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22384 } else { 22385 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22386 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22387 || !volume.isMountedWritable()) { 22388 freezer.close(); 22389 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22390 "Move location not mounted private volume"); 22391 } 22392 22393 Preconditions.checkState(!currentAsec); 22394 22395 installFlags = INSTALL_INTERNAL; 22396 moveCompleteApp = true; 22397 measurePath = Environment.getDataAppDirectory(volumeUuid); 22398 } 22399 22400 final PackageStats stats = new PackageStats(null, -1); 22401 synchronized (mInstaller) { 22402 for (int userId : installedUserIds) { 22403 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22404 freezer.close(); 22405 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22406 "Failed to measure package size"); 22407 } 22408 } 22409 } 22410 22411 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22412 + stats.dataSize); 22413 22414 final long startFreeBytes = measurePath.getUsableSpace(); 22415 final long sizeBytes; 22416 if (moveCompleteApp) { 22417 sizeBytes = stats.codeSize + stats.dataSize; 22418 } else { 22419 sizeBytes = stats.codeSize; 22420 } 22421 22422 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22423 freezer.close(); 22424 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22425 "Not enough free space to move"); 22426 } 22427 22428 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22429 22430 final CountDownLatch installedLatch = new CountDownLatch(1); 22431 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22432 @Override 22433 public void onUserActionRequired(Intent intent) throws RemoteException { 22434 throw new IllegalStateException(); 22435 } 22436 22437 @Override 22438 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22439 Bundle extras) throws RemoteException { 22440 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22441 + PackageManager.installStatusToString(returnCode, msg)); 22442 22443 installedLatch.countDown(); 22444 freezer.close(); 22445 22446 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22447 switch (status) { 22448 case PackageInstaller.STATUS_SUCCESS: 22449 mMoveCallbacks.notifyStatusChanged(moveId, 22450 PackageManager.MOVE_SUCCEEDED); 22451 break; 22452 case PackageInstaller.STATUS_FAILURE_STORAGE: 22453 mMoveCallbacks.notifyStatusChanged(moveId, 22454 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22455 break; 22456 default: 22457 mMoveCallbacks.notifyStatusChanged(moveId, 22458 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22459 break; 22460 } 22461 } 22462 }; 22463 22464 final MoveInfo move; 22465 if (moveCompleteApp) { 22466 // Kick off a thread to report progress estimates 22467 new Thread() { 22468 @Override 22469 public void run() { 22470 while (true) { 22471 try { 22472 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22473 break; 22474 } 22475 } catch (InterruptedException ignored) { 22476 } 22477 22478 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22479 final int progress = 10 + (int) MathUtils.constrain( 22480 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22481 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22482 } 22483 } 22484 }.start(); 22485 22486 final String dataAppName = codeFile.getName(); 22487 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22488 dataAppName, appId, seinfo, targetSdkVersion); 22489 } else { 22490 move = null; 22491 } 22492 22493 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22494 22495 final Message msg = mHandler.obtainMessage(INIT_COPY); 22496 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22497 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22498 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22499 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22500 PackageManager.INSTALL_REASON_UNKNOWN); 22501 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22502 msg.obj = params; 22503 22504 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22505 System.identityHashCode(msg.obj)); 22506 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22507 System.identityHashCode(msg.obj)); 22508 22509 mHandler.sendMessage(msg); 22510 } 22511 22512 @Override 22513 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22514 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22515 22516 final int realMoveId = mNextMoveId.getAndIncrement(); 22517 final Bundle extras = new Bundle(); 22518 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22519 mMoveCallbacks.notifyCreated(realMoveId, extras); 22520 22521 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22522 @Override 22523 public void onCreated(int moveId, Bundle extras) { 22524 // Ignored 22525 } 22526 22527 @Override 22528 public void onStatusChanged(int moveId, int status, long estMillis) { 22529 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22530 } 22531 }; 22532 22533 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22534 storage.setPrimaryStorageUuid(volumeUuid, callback); 22535 return realMoveId; 22536 } 22537 22538 @Override 22539 public int getMoveStatus(int moveId) { 22540 mContext.enforceCallingOrSelfPermission( 22541 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22542 return mMoveCallbacks.mLastStatus.get(moveId); 22543 } 22544 22545 @Override 22546 public void registerMoveCallback(IPackageMoveObserver callback) { 22547 mContext.enforceCallingOrSelfPermission( 22548 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22549 mMoveCallbacks.register(callback); 22550 } 22551 22552 @Override 22553 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22554 mContext.enforceCallingOrSelfPermission( 22555 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22556 mMoveCallbacks.unregister(callback); 22557 } 22558 22559 @Override 22560 public boolean setInstallLocation(int loc) { 22561 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22562 null); 22563 if (getInstallLocation() == loc) { 22564 return true; 22565 } 22566 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22567 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22568 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22569 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22570 return true; 22571 } 22572 return false; 22573 } 22574 22575 @Override 22576 public int getInstallLocation() { 22577 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22578 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22579 PackageHelper.APP_INSTALL_AUTO); 22580 } 22581 22582 /** Called by UserManagerService */ 22583 void cleanUpUser(UserManagerService userManager, int userHandle) { 22584 synchronized (mPackages) { 22585 mDirtyUsers.remove(userHandle); 22586 mUserNeedsBadging.delete(userHandle); 22587 mSettings.removeUserLPw(userHandle); 22588 mPendingBroadcasts.remove(userHandle); 22589 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22590 removeUnusedPackagesLPw(userManager, userHandle); 22591 } 22592 } 22593 22594 /** 22595 * We're removing userHandle and would like to remove any downloaded packages 22596 * that are no longer in use by any other user. 22597 * @param userHandle the user being removed 22598 */ 22599 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22600 final boolean DEBUG_CLEAN_APKS = false; 22601 int [] users = userManager.getUserIds(); 22602 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22603 while (psit.hasNext()) { 22604 PackageSetting ps = psit.next(); 22605 if (ps.pkg == null) { 22606 continue; 22607 } 22608 final String packageName = ps.pkg.packageName; 22609 // Skip over if system app 22610 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22611 continue; 22612 } 22613 if (DEBUG_CLEAN_APKS) { 22614 Slog.i(TAG, "Checking package " + packageName); 22615 } 22616 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22617 if (keep) { 22618 if (DEBUG_CLEAN_APKS) { 22619 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22620 } 22621 } else { 22622 for (int i = 0; i < users.length; i++) { 22623 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22624 keep = true; 22625 if (DEBUG_CLEAN_APKS) { 22626 Slog.i(TAG, " Keeping package " + packageName + " for user " 22627 + users[i]); 22628 } 22629 break; 22630 } 22631 } 22632 } 22633 if (!keep) { 22634 if (DEBUG_CLEAN_APKS) { 22635 Slog.i(TAG, " Removing package " + packageName); 22636 } 22637 mHandler.post(new Runnable() { 22638 public void run() { 22639 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22640 userHandle, 0); 22641 } //end run 22642 }); 22643 } 22644 } 22645 } 22646 22647 /** Called by UserManagerService */ 22648 void createNewUser(int userId, String[] disallowedPackages) { 22649 synchronized (mInstallLock) { 22650 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22651 } 22652 synchronized (mPackages) { 22653 scheduleWritePackageRestrictionsLocked(userId); 22654 scheduleWritePackageListLocked(userId); 22655 applyFactoryDefaultBrowserLPw(userId); 22656 primeDomainVerificationsLPw(userId); 22657 } 22658 } 22659 22660 void onNewUserCreated(final int userId) { 22661 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22662 // If permission review for legacy apps is required, we represent 22663 // dagerous permissions for such apps as always granted runtime 22664 // permissions to keep per user flag state whether review is needed. 22665 // Hence, if a new user is added we have to propagate dangerous 22666 // permission grants for these legacy apps. 22667 if (mPermissionReviewRequired) { 22668 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22669 | UPDATE_PERMISSIONS_REPLACE_ALL); 22670 } 22671 } 22672 22673 @Override 22674 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22675 mContext.enforceCallingOrSelfPermission( 22676 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22677 "Only package verification agents can read the verifier device identity"); 22678 22679 synchronized (mPackages) { 22680 return mSettings.getVerifierDeviceIdentityLPw(); 22681 } 22682 } 22683 22684 @Override 22685 public void setPermissionEnforced(String permission, boolean enforced) { 22686 // TODO: Now that we no longer change GID for storage, this should to away. 22687 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22688 "setPermissionEnforced"); 22689 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22690 synchronized (mPackages) { 22691 if (mSettings.mReadExternalStorageEnforced == null 22692 || mSettings.mReadExternalStorageEnforced != enforced) { 22693 mSettings.mReadExternalStorageEnforced = enforced; 22694 mSettings.writeLPr(); 22695 } 22696 } 22697 // kill any non-foreground processes so we restart them and 22698 // grant/revoke the GID. 22699 final IActivityManager am = ActivityManager.getService(); 22700 if (am != null) { 22701 final long token = Binder.clearCallingIdentity(); 22702 try { 22703 am.killProcessesBelowForeground("setPermissionEnforcement"); 22704 } catch (RemoteException e) { 22705 } finally { 22706 Binder.restoreCallingIdentity(token); 22707 } 22708 } 22709 } else { 22710 throw new IllegalArgumentException("No selective enforcement for " + permission); 22711 } 22712 } 22713 22714 @Override 22715 @Deprecated 22716 public boolean isPermissionEnforced(String permission) { 22717 return true; 22718 } 22719 22720 @Override 22721 public boolean isStorageLow() { 22722 final long token = Binder.clearCallingIdentity(); 22723 try { 22724 final DeviceStorageMonitorInternal 22725 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22726 if (dsm != null) { 22727 return dsm.isMemoryLow(); 22728 } else { 22729 return false; 22730 } 22731 } finally { 22732 Binder.restoreCallingIdentity(token); 22733 } 22734 } 22735 22736 @Override 22737 public IPackageInstaller getPackageInstaller() { 22738 return mInstallerService; 22739 } 22740 22741 private boolean userNeedsBadging(int userId) { 22742 int index = mUserNeedsBadging.indexOfKey(userId); 22743 if (index < 0) { 22744 final UserInfo userInfo; 22745 final long token = Binder.clearCallingIdentity(); 22746 try { 22747 userInfo = sUserManager.getUserInfo(userId); 22748 } finally { 22749 Binder.restoreCallingIdentity(token); 22750 } 22751 final boolean b; 22752 if (userInfo != null && userInfo.isManagedProfile()) { 22753 b = true; 22754 } else { 22755 b = false; 22756 } 22757 mUserNeedsBadging.put(userId, b); 22758 return b; 22759 } 22760 return mUserNeedsBadging.valueAt(index); 22761 } 22762 22763 @Override 22764 public KeySet getKeySetByAlias(String packageName, String alias) { 22765 if (packageName == null || alias == null) { 22766 return null; 22767 } 22768 synchronized(mPackages) { 22769 final PackageParser.Package pkg = mPackages.get(packageName); 22770 if (pkg == null) { 22771 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22772 throw new IllegalArgumentException("Unknown package: " + packageName); 22773 } 22774 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22775 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22776 } 22777 } 22778 22779 @Override 22780 public KeySet getSigningKeySet(String packageName) { 22781 if (packageName == null) { 22782 return null; 22783 } 22784 synchronized(mPackages) { 22785 final PackageParser.Package pkg = mPackages.get(packageName); 22786 if (pkg == null) { 22787 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22788 throw new IllegalArgumentException("Unknown package: " + packageName); 22789 } 22790 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22791 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22792 throw new SecurityException("May not access signing KeySet of other apps."); 22793 } 22794 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22795 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22796 } 22797 } 22798 22799 @Override 22800 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22801 if (packageName == null || ks == null) { 22802 return false; 22803 } 22804 synchronized(mPackages) { 22805 final PackageParser.Package pkg = mPackages.get(packageName); 22806 if (pkg == null) { 22807 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22808 throw new IllegalArgumentException("Unknown package: " + packageName); 22809 } 22810 IBinder ksh = ks.getToken(); 22811 if (ksh instanceof KeySetHandle) { 22812 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22813 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22814 } 22815 return false; 22816 } 22817 } 22818 22819 @Override 22820 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22821 if (packageName == null || ks == null) { 22822 return false; 22823 } 22824 synchronized(mPackages) { 22825 final PackageParser.Package pkg = mPackages.get(packageName); 22826 if (pkg == null) { 22827 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22828 throw new IllegalArgumentException("Unknown package: " + packageName); 22829 } 22830 IBinder ksh = ks.getToken(); 22831 if (ksh instanceof KeySetHandle) { 22832 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22833 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22834 } 22835 return false; 22836 } 22837 } 22838 22839 private void deletePackageIfUnusedLPr(final String packageName) { 22840 PackageSetting ps = mSettings.mPackages.get(packageName); 22841 if (ps == null) { 22842 return; 22843 } 22844 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22845 // TODO Implement atomic delete if package is unused 22846 // It is currently possible that the package will be deleted even if it is installed 22847 // after this method returns. 22848 mHandler.post(new Runnable() { 22849 public void run() { 22850 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22851 0, PackageManager.DELETE_ALL_USERS); 22852 } 22853 }); 22854 } 22855 } 22856 22857 /** 22858 * Check and throw if the given before/after packages would be considered a 22859 * downgrade. 22860 */ 22861 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22862 throws PackageManagerException { 22863 if (after.versionCode < before.mVersionCode) { 22864 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22865 "Update version code " + after.versionCode + " is older than current " 22866 + before.mVersionCode); 22867 } else if (after.versionCode == before.mVersionCode) { 22868 if (after.baseRevisionCode < before.baseRevisionCode) { 22869 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22870 "Update base revision code " + after.baseRevisionCode 22871 + " is older than current " + before.baseRevisionCode); 22872 } 22873 22874 if (!ArrayUtils.isEmpty(after.splitNames)) { 22875 for (int i = 0; i < after.splitNames.length; i++) { 22876 final String splitName = after.splitNames[i]; 22877 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22878 if (j != -1) { 22879 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22880 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22881 "Update split " + splitName + " revision code " 22882 + after.splitRevisionCodes[i] + " is older than current " 22883 + before.splitRevisionCodes[j]); 22884 } 22885 } 22886 } 22887 } 22888 } 22889 } 22890 22891 private static class MoveCallbacks extends Handler { 22892 private static final int MSG_CREATED = 1; 22893 private static final int MSG_STATUS_CHANGED = 2; 22894 22895 private final RemoteCallbackList<IPackageMoveObserver> 22896 mCallbacks = new RemoteCallbackList<>(); 22897 22898 private final SparseIntArray mLastStatus = new SparseIntArray(); 22899 22900 public MoveCallbacks(Looper looper) { 22901 super(looper); 22902 } 22903 22904 public void register(IPackageMoveObserver callback) { 22905 mCallbacks.register(callback); 22906 } 22907 22908 public void unregister(IPackageMoveObserver callback) { 22909 mCallbacks.unregister(callback); 22910 } 22911 22912 @Override 22913 public void handleMessage(Message msg) { 22914 final SomeArgs args = (SomeArgs) msg.obj; 22915 final int n = mCallbacks.beginBroadcast(); 22916 for (int i = 0; i < n; i++) { 22917 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22918 try { 22919 invokeCallback(callback, msg.what, args); 22920 } catch (RemoteException ignored) { 22921 } 22922 } 22923 mCallbacks.finishBroadcast(); 22924 args.recycle(); 22925 } 22926 22927 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22928 throws RemoteException { 22929 switch (what) { 22930 case MSG_CREATED: { 22931 callback.onCreated(args.argi1, (Bundle) args.arg2); 22932 break; 22933 } 22934 case MSG_STATUS_CHANGED: { 22935 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22936 break; 22937 } 22938 } 22939 } 22940 22941 private void notifyCreated(int moveId, Bundle extras) { 22942 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22943 22944 final SomeArgs args = SomeArgs.obtain(); 22945 args.argi1 = moveId; 22946 args.arg2 = extras; 22947 obtainMessage(MSG_CREATED, args).sendToTarget(); 22948 } 22949 22950 private void notifyStatusChanged(int moveId, int status) { 22951 notifyStatusChanged(moveId, status, -1); 22952 } 22953 22954 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22955 Slog.v(TAG, "Move " + moveId + " status " + status); 22956 22957 final SomeArgs args = SomeArgs.obtain(); 22958 args.argi1 = moveId; 22959 args.argi2 = status; 22960 args.arg3 = estMillis; 22961 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22962 22963 synchronized (mLastStatus) { 22964 mLastStatus.put(moveId, status); 22965 } 22966 } 22967 } 22968 22969 private final static class OnPermissionChangeListeners extends Handler { 22970 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22971 22972 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22973 new RemoteCallbackList<>(); 22974 22975 public OnPermissionChangeListeners(Looper looper) { 22976 super(looper); 22977 } 22978 22979 @Override 22980 public void handleMessage(Message msg) { 22981 switch (msg.what) { 22982 case MSG_ON_PERMISSIONS_CHANGED: { 22983 final int uid = msg.arg1; 22984 handleOnPermissionsChanged(uid); 22985 } break; 22986 } 22987 } 22988 22989 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22990 mPermissionListeners.register(listener); 22991 22992 } 22993 22994 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22995 mPermissionListeners.unregister(listener); 22996 } 22997 22998 public void onPermissionsChanged(int uid) { 22999 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23000 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23001 } 23002 } 23003 23004 private void handleOnPermissionsChanged(int uid) { 23005 final int count = mPermissionListeners.beginBroadcast(); 23006 try { 23007 for (int i = 0; i < count; i++) { 23008 IOnPermissionsChangeListener callback = mPermissionListeners 23009 .getBroadcastItem(i); 23010 try { 23011 callback.onPermissionsChanged(uid); 23012 } catch (RemoteException e) { 23013 Log.e(TAG, "Permission listener is dead", e); 23014 } 23015 } 23016 } finally { 23017 mPermissionListeners.finishBroadcast(); 23018 } 23019 } 23020 } 23021 23022 private class PackageManagerInternalImpl extends PackageManagerInternal { 23023 @Override 23024 public void setLocationPackagesProvider(PackagesProvider provider) { 23025 synchronized (mPackages) { 23026 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23027 } 23028 } 23029 23030 @Override 23031 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23032 synchronized (mPackages) { 23033 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23034 } 23035 } 23036 23037 @Override 23038 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23039 synchronized (mPackages) { 23040 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23041 } 23042 } 23043 23044 @Override 23045 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23046 synchronized (mPackages) { 23047 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23048 } 23049 } 23050 23051 @Override 23052 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23053 synchronized (mPackages) { 23054 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23055 } 23056 } 23057 23058 @Override 23059 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23060 synchronized (mPackages) { 23061 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23062 } 23063 } 23064 23065 @Override 23066 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23067 synchronized (mPackages) { 23068 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23069 packageName, userId); 23070 } 23071 } 23072 23073 @Override 23074 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23075 synchronized (mPackages) { 23076 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23077 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23078 packageName, userId); 23079 } 23080 } 23081 23082 @Override 23083 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23084 synchronized (mPackages) { 23085 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23086 packageName, userId); 23087 } 23088 } 23089 23090 @Override 23091 public void setKeepUninstalledPackages(final List<String> packageList) { 23092 Preconditions.checkNotNull(packageList); 23093 List<String> removedFromList = null; 23094 synchronized (mPackages) { 23095 if (mKeepUninstalledPackages != null) { 23096 final int packagesCount = mKeepUninstalledPackages.size(); 23097 for (int i = 0; i < packagesCount; i++) { 23098 String oldPackage = mKeepUninstalledPackages.get(i); 23099 if (packageList != null && packageList.contains(oldPackage)) { 23100 continue; 23101 } 23102 if (removedFromList == null) { 23103 removedFromList = new ArrayList<>(); 23104 } 23105 removedFromList.add(oldPackage); 23106 } 23107 } 23108 mKeepUninstalledPackages = new ArrayList<>(packageList); 23109 if (removedFromList != null) { 23110 final int removedCount = removedFromList.size(); 23111 for (int i = 0; i < removedCount; i++) { 23112 deletePackageIfUnusedLPr(removedFromList.get(i)); 23113 } 23114 } 23115 } 23116 } 23117 23118 @Override 23119 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23120 synchronized (mPackages) { 23121 // If we do not support permission review, done. 23122 if (!mPermissionReviewRequired) { 23123 return false; 23124 } 23125 23126 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23127 if (packageSetting == null) { 23128 return false; 23129 } 23130 23131 // Permission review applies only to apps not supporting the new permission model. 23132 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23133 return false; 23134 } 23135 23136 // Legacy apps have the permission and get user consent on launch. 23137 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23138 return permissionsState.isPermissionReviewRequired(userId); 23139 } 23140 } 23141 23142 @Override 23143 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23144 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23145 } 23146 23147 @Override 23148 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23149 int userId) { 23150 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23151 } 23152 23153 @Override 23154 public void setDeviceAndProfileOwnerPackages( 23155 int deviceOwnerUserId, String deviceOwnerPackage, 23156 SparseArray<String> profileOwnerPackages) { 23157 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23158 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23159 } 23160 23161 @Override 23162 public boolean isPackageDataProtected(int userId, String packageName) { 23163 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23164 } 23165 23166 @Override 23167 public boolean isPackageEphemeral(int userId, String packageName) { 23168 synchronized (mPackages) { 23169 final PackageSetting ps = mSettings.mPackages.get(packageName); 23170 return ps != null ? ps.getInstantApp(userId) : false; 23171 } 23172 } 23173 23174 @Override 23175 public boolean wasPackageEverLaunched(String packageName, int userId) { 23176 synchronized (mPackages) { 23177 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23178 } 23179 } 23180 23181 @Override 23182 public void grantRuntimePermission(String packageName, String name, int userId, 23183 boolean overridePolicy) { 23184 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23185 overridePolicy); 23186 } 23187 23188 @Override 23189 public void revokeRuntimePermission(String packageName, String name, int userId, 23190 boolean overridePolicy) { 23191 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23192 overridePolicy); 23193 } 23194 23195 @Override 23196 public String getNameForUid(int uid) { 23197 return PackageManagerService.this.getNameForUid(uid); 23198 } 23199 23200 @Override 23201 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23202 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23203 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23204 responseObj, origIntent, resolvedType, callingPackage, userId); 23205 } 23206 23207 @Override 23208 public void grantEphemeralAccess(int userId, Intent intent, 23209 int targetAppId, int ephemeralAppId) { 23210 synchronized (mPackages) { 23211 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23212 targetAppId, ephemeralAppId); 23213 } 23214 } 23215 23216 @Override 23217 public boolean isInstantAppInstallerComponent(ComponentName component) { 23218 synchronized (mPackages) { 23219 return component != null && component.equals(mInstantAppInstallerComponent); 23220 } 23221 } 23222 23223 @Override 23224 public void pruneInstantApps() { 23225 synchronized (mPackages) { 23226 mInstantAppRegistry.pruneInstantAppsLPw(); 23227 } 23228 } 23229 23230 @Override 23231 public String getSetupWizardPackageName() { 23232 return mSetupWizardPackage; 23233 } 23234 23235 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23236 if (policy != null) { 23237 mExternalSourcesPolicy = policy; 23238 } 23239 } 23240 23241 @Override 23242 public boolean isPackagePersistent(String packageName) { 23243 synchronized (mPackages) { 23244 PackageParser.Package pkg = mPackages.get(packageName); 23245 return pkg != null 23246 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23247 | ApplicationInfo.FLAG_PERSISTENT)) == 23248 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23249 : false; 23250 } 23251 } 23252 23253 @Override 23254 public List<PackageInfo> getOverlayPackages(int userId) { 23255 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23256 synchronized (mPackages) { 23257 for (PackageParser.Package p : mPackages.values()) { 23258 if (p.mOverlayTarget != null) { 23259 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23260 if (pkg != null) { 23261 overlayPackages.add(pkg); 23262 } 23263 } 23264 } 23265 } 23266 return overlayPackages; 23267 } 23268 23269 @Override 23270 public List<String> getTargetPackageNames(int userId) { 23271 List<String> targetPackages = new ArrayList<>(); 23272 synchronized (mPackages) { 23273 for (PackageParser.Package p : mPackages.values()) { 23274 if (p.mOverlayTarget == null) { 23275 targetPackages.add(p.packageName); 23276 } 23277 } 23278 } 23279 return targetPackages; 23280 } 23281 23282 @Override 23283 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23284 @Nullable List<String> overlayPackageNames) { 23285 synchronized (mPackages) { 23286 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23287 Slog.e(TAG, "failed to find package " + targetPackageName); 23288 return false; 23289 } 23290 23291 ArrayList<String> paths = null; 23292 if (overlayPackageNames != null) { 23293 final int N = overlayPackageNames.size(); 23294 paths = new ArrayList<>(N); 23295 for (int i = 0; i < N; i++) { 23296 final String packageName = overlayPackageNames.get(i); 23297 final PackageParser.Package pkg = mPackages.get(packageName); 23298 if (pkg == null) { 23299 Slog.e(TAG, "failed to find package " + packageName); 23300 return false; 23301 } 23302 paths.add(pkg.baseCodePath); 23303 } 23304 } 23305 23306 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23307 mEnabledOverlayPaths.get(userId); 23308 if (userSpecificOverlays == null) { 23309 userSpecificOverlays = new ArrayMap<>(); 23310 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23311 } 23312 23313 if (paths != null && paths.size() > 0) { 23314 userSpecificOverlays.put(targetPackageName, paths); 23315 } else { 23316 userSpecificOverlays.remove(targetPackageName); 23317 } 23318 return true; 23319 } 23320 } 23321 23322 @Override 23323 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23324 int flags, int userId) { 23325 return resolveIntentInternal( 23326 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23327 } 23328 23329 @Override 23330 public ResolveInfo resolveService(Intent intent, String resolvedType, 23331 int flags, int userId, int callingUid) { 23332 return resolveServiceInternal( 23333 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23334 } 23335 23336 23337 @Override 23338 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23339 synchronized (mPackages) { 23340 mIsolatedOwners.put(isolatedUid, ownerUid); 23341 } 23342 } 23343 23344 @Override 23345 public void removeIsolatedUid(int isolatedUid) { 23346 synchronized (mPackages) { 23347 mIsolatedOwners.delete(isolatedUid); 23348 } 23349 } 23350 } 23351 23352 @Override 23353 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23354 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23355 synchronized (mPackages) { 23356 final long identity = Binder.clearCallingIdentity(); 23357 try { 23358 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23359 packageNames, userId); 23360 } finally { 23361 Binder.restoreCallingIdentity(identity); 23362 } 23363 } 23364 } 23365 23366 @Override 23367 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23368 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23369 synchronized (mPackages) { 23370 final long identity = Binder.clearCallingIdentity(); 23371 try { 23372 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23373 packageNames, userId); 23374 } finally { 23375 Binder.restoreCallingIdentity(identity); 23376 } 23377 } 23378 } 23379 23380 private static void enforceSystemOrPhoneCaller(String tag) { 23381 int callingUid = Binder.getCallingUid(); 23382 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23383 throw new SecurityException( 23384 "Cannot call " + tag + " from UID " + callingUid); 23385 } 23386 } 23387 23388 boolean isHistoricalPackageUsageAvailable() { 23389 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23390 } 23391 23392 /** 23393 * Return a <b>copy</b> of the collection of packages known to the package manager. 23394 * @return A copy of the values of mPackages. 23395 */ 23396 Collection<PackageParser.Package> getPackages() { 23397 synchronized (mPackages) { 23398 return new ArrayList<>(mPackages.values()); 23399 } 23400 } 23401 23402 /** 23403 * Logs process start information (including base APK hash) to the security log. 23404 * @hide 23405 */ 23406 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23407 String apkFile, int pid) { 23408 if (!SecurityLog.isLoggingEnabled()) { 23409 return; 23410 } 23411 Bundle data = new Bundle(); 23412 data.putLong("startTimestamp", System.currentTimeMillis()); 23413 data.putString("processName", processName); 23414 data.putInt("uid", uid); 23415 data.putString("seinfo", seinfo); 23416 data.putString("apkFile", apkFile); 23417 data.putInt("pid", pid); 23418 Message msg = mProcessLoggingHandler.obtainMessage( 23419 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23420 msg.setData(data); 23421 mProcessLoggingHandler.sendMessage(msg); 23422 } 23423 23424 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23425 return mCompilerStats.getPackageStats(pkgName); 23426 } 23427 23428 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23429 return getOrCreateCompilerPackageStats(pkg.packageName); 23430 } 23431 23432 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23433 return mCompilerStats.getOrCreatePackageStats(pkgName); 23434 } 23435 23436 public void deleteCompilerPackageStats(String pkgName) { 23437 mCompilerStats.deletePackageStats(pkgName); 23438 } 23439 23440 @Override 23441 public int getInstallReason(String packageName, int userId) { 23442 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23443 true /* requireFullPermission */, false /* checkShell */, 23444 "get install reason"); 23445 synchronized (mPackages) { 23446 final PackageSetting ps = mSettings.mPackages.get(packageName); 23447 if (ps != null) { 23448 return ps.getInstallReason(userId); 23449 } 23450 } 23451 return PackageManager.INSTALL_REASON_UNKNOWN; 23452 } 23453 23454 @Override 23455 public boolean canRequestPackageInstalls(String packageName, int userId) { 23456 int callingUid = Binder.getCallingUid(); 23457 int uid = getPackageUid(packageName, 0, userId); 23458 if (callingUid != uid && callingUid != Process.ROOT_UID 23459 && callingUid != Process.SYSTEM_UID) { 23460 throw new SecurityException( 23461 "Caller uid " + callingUid + " does not own package " + packageName); 23462 } 23463 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23464 if (info == null) { 23465 return false; 23466 } 23467 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23468 throw new UnsupportedOperationException( 23469 "Operation only supported on apps targeting Android O or higher"); 23470 } 23471 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23472 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23473 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23474 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23475 } 23476 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23477 return false; 23478 } 23479 if (mExternalSourcesPolicy != null) { 23480 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23481 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23482 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23483 } 23484 } 23485 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23486 } 23487 23488 @Override 23489 public ComponentName getInstantAppResolverSettingsComponent() { 23490 return mInstantAppResolverSettingsComponent; 23491 } 23492} 23493