PackageManagerService.java revision a1ff00157c0ba3aa7ad93d5a4695fed97e18c430
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.BootTimingsTraceLog; 225import android.util.DisplayMetrics; 226import android.util.EventLog; 227import android.util.ExceptionUtils; 228import android.util.Log; 229import android.util.LogPrinter; 230import android.util.MathUtils; 231import android.util.PackageUtils; 232import android.util.Pair; 233import android.util.PrintStreamPrinter; 234import android.util.Slog; 235import android.util.SparseArray; 236import android.util.SparseBooleanArray; 237import android.util.SparseIntArray; 238import android.util.Xml; 239import android.util.jar.StrictJarFile; 240import android.util.proto.ProtoOutputStream; 241import android.view.Display; 242 243import com.android.internal.R; 244import com.android.internal.annotations.GuardedBy; 245import com.android.internal.app.IMediaContainerService; 246import com.android.internal.app.ResolverActivity; 247import com.android.internal.content.NativeLibraryHelper; 248import com.android.internal.content.PackageHelper; 249import com.android.internal.logging.MetricsLogger; 250import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 251import com.android.internal.os.IParcelFileDescriptorFactory; 252import com.android.internal.os.RoSystemProperties; 253import com.android.internal.os.SomeArgs; 254import com.android.internal.os.Zygote; 255import com.android.internal.telephony.CarrierAppUtils; 256import com.android.internal.util.ArrayUtils; 257import com.android.internal.util.ConcurrentUtils; 258import com.android.internal.util.DumpUtils; 259import com.android.internal.util.FastPrintWriter; 260import com.android.internal.util.FastXmlSerializer; 261import com.android.internal.util.IndentingPrintWriter; 262import com.android.internal.util.Preconditions; 263import com.android.internal.util.XmlUtils; 264import com.android.server.AttributeCache; 265import com.android.server.DeviceIdleController; 266import com.android.server.EventLogTags; 267import com.android.server.FgThread; 268import com.android.server.IntentResolver; 269import com.android.server.LocalServices; 270import com.android.server.LockGuard; 271import com.android.server.ServiceThread; 272import com.android.server.SystemConfig; 273import com.android.server.SystemServerInitThreadPool; 274import com.android.server.Watchdog; 275import com.android.server.net.NetworkPolicyManagerInternal; 276import com.android.server.pm.BackgroundDexOptService; 277import com.android.server.pm.Installer.InstallerException; 278import com.android.server.pm.PermissionsState.PermissionState; 279import com.android.server.pm.Settings.DatabaseVersion; 280import com.android.server.pm.Settings.VersionInfo; 281import com.android.server.pm.dex.DexManager; 282import com.android.server.storage.DeviceStorageMonitorInternal; 283 284import dalvik.system.CloseGuard; 285import dalvik.system.DexFile; 286import dalvik.system.VMRuntime; 287 288import libcore.io.IoUtils; 289import libcore.util.EmptyArray; 290 291import org.xmlpull.v1.XmlPullParser; 292import org.xmlpull.v1.XmlPullParserException; 293import org.xmlpull.v1.XmlSerializer; 294 295import java.io.BufferedOutputStream; 296import java.io.BufferedReader; 297import java.io.ByteArrayInputStream; 298import java.io.ByteArrayOutputStream; 299import java.io.File; 300import java.io.FileDescriptor; 301import java.io.FileInputStream; 302import java.io.FileNotFoundException; 303import java.io.FileOutputStream; 304import java.io.FileReader; 305import java.io.FilenameFilter; 306import java.io.IOException; 307import java.io.PrintWriter; 308import java.nio.charset.StandardCharsets; 309import java.security.DigestInputStream; 310import java.security.MessageDigest; 311import java.security.NoSuchAlgorithmException; 312import java.security.PublicKey; 313import java.security.SecureRandom; 314import java.security.cert.Certificate; 315import java.security.cert.CertificateEncodingException; 316import java.security.cert.CertificateException; 317import java.text.SimpleDateFormat; 318import java.util.ArrayList; 319import java.util.Arrays; 320import java.util.Collection; 321import java.util.Collections; 322import java.util.Comparator; 323import java.util.Date; 324import java.util.HashMap; 325import java.util.HashSet; 326import java.util.Iterator; 327import java.util.List; 328import java.util.Map; 329import java.util.Objects; 330import java.util.Set; 331import java.util.concurrent.CountDownLatch; 332import java.util.concurrent.Future; 333import java.util.concurrent.TimeUnit; 334import java.util.concurrent.atomic.AtomicBoolean; 335import java.util.concurrent.atomic.AtomicInteger; 336 337/** 338 * Keep track of all those APKs everywhere. 339 * <p> 340 * Internally there are two important locks: 341 * <ul> 342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 343 * and other related state. It is a fine-grained lock that should only be held 344 * momentarily, as it's one of the most contended locks in the system. 345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 346 * operations typically involve heavy lifting of application data on disk. Since 347 * {@code installd} is single-threaded, and it's operations can often be slow, 348 * this lock should never be acquired while already holding {@link #mPackages}. 349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 350 * holding {@link #mInstallLock}. 351 * </ul> 352 * Many internal methods rely on the caller to hold the appropriate locks, and 353 * this contract is expressed through method name suffixes: 354 * <ul> 355 * <li>fooLI(): the caller must hold {@link #mInstallLock} 356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 357 * being modified must be frozen 358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 360 * </ul> 361 * <p> 362 * Because this class is very central to the platform's security; please run all 363 * CTS and unit tests whenever making modifications: 364 * 365 * <pre> 366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 368 * </pre> 369 */ 370public class PackageManagerService extends IPackageManager.Stub { 371 static final String TAG = "PackageManager"; 372 static final boolean DEBUG_SETTINGS = false; 373 static final boolean DEBUG_PREFERRED = false; 374 static final boolean DEBUG_UPGRADE = false; 375 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 376 private static final boolean DEBUG_BACKUP = false; 377 private static final boolean DEBUG_INSTALL = false; 378 private static final boolean DEBUG_REMOVE = false; 379 private static final boolean DEBUG_BROADCASTS = false; 380 private static final boolean DEBUG_SHOW_INFO = false; 381 private static final boolean DEBUG_PACKAGE_INFO = false; 382 private static final boolean DEBUG_INTENT_MATCHING = false; 383 private static final boolean DEBUG_PACKAGE_SCANNING = false; 384 private static final boolean DEBUG_VERIFY = false; 385 private static final boolean DEBUG_FILTERS = false; 386 387 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 388 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 389 // user, but by default initialize to this. 390 public static final boolean DEBUG_DEXOPT = false; 391 392 private static final boolean DEBUG_ABI_SELECTION = false; 393 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 394 private static final boolean DEBUG_TRIAGED_MISSING = false; 395 private static final boolean DEBUG_APP_DATA = false; 396 397 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 398 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 399 400 private static final boolean DISABLE_EPHEMERAL_APPS = false; 401 private static final boolean HIDE_EPHEMERAL_APIS = false; 402 403 private static final boolean ENABLE_FREE_CACHE_V2 = 404 SystemProperties.getBoolean("fw.free_cache_v2", true); 405 406 private static final int RADIO_UID = Process.PHONE_UID; 407 private static final int LOG_UID = Process.LOG_UID; 408 private static final int NFC_UID = Process.NFC_UID; 409 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 410 private static final int SHELL_UID = Process.SHELL_UID; 411 412 // Cap the size of permission trees that 3rd party apps can define 413 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 414 415 // Suffix used during package installation when copying/moving 416 // package apks to install directory. 417 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 418 419 static final int SCAN_NO_DEX = 1<<1; 420 static final int SCAN_FORCE_DEX = 1<<2; 421 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 422 static final int SCAN_NEW_INSTALL = 1<<4; 423 static final int SCAN_UPDATE_TIME = 1<<5; 424 static final int SCAN_BOOTING = 1<<6; 425 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 426 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 427 static final int SCAN_REPLACING = 1<<9; 428 static final int SCAN_REQUIRE_KNOWN = 1<<10; 429 static final int SCAN_MOVE = 1<<11; 430 static final int SCAN_INITIAL = 1<<12; 431 static final int SCAN_CHECK_ONLY = 1<<13; 432 static final int SCAN_DONT_KILL_APP = 1<<14; 433 static final int SCAN_IGNORE_FROZEN = 1<<15; 434 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 435 static final int SCAN_AS_INSTANT_APP = 1<<17; 436 static final int SCAN_AS_FULL_APP = 1<<18; 437 /** Should not be with the scan flags */ 438 static final int FLAGS_REMOVE_CHATTY = 1<<31; 439 440 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 441 442 private static final int[] EMPTY_INT_ARRAY = new int[0]; 443 444 /** 445 * Timeout (in milliseconds) after which the watchdog should declare that 446 * our handler thread is wedged. The usual default for such things is one 447 * minute but we sometimes do very lengthy I/O operations on this thread, 448 * such as installing multi-gigabyte applications, so ours needs to be longer. 449 */ 450 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 451 452 /** 453 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 454 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 455 * settings entry if available, otherwise we use the hardcoded default. If it's been 456 * more than this long since the last fstrim, we force one during the boot sequence. 457 * 458 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 459 * one gets run at the next available charging+idle time. This final mandatory 460 * no-fstrim check kicks in only of the other scheduling criteria is never met. 461 */ 462 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 463 464 /** 465 * Whether verification is enabled by default. 466 */ 467 private static final boolean DEFAULT_VERIFY_ENABLE = true; 468 469 /** 470 * The default maximum time to wait for the verification agent to return in 471 * milliseconds. 472 */ 473 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 474 475 /** 476 * The default response for package verification timeout. 477 * 478 * This can be either PackageManager.VERIFICATION_ALLOW or 479 * PackageManager.VERIFICATION_REJECT. 480 */ 481 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 482 483 static final String PLATFORM_PACKAGE_NAME = "android"; 484 485 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 486 487 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 488 DEFAULT_CONTAINER_PACKAGE, 489 "com.android.defcontainer.DefaultContainerService"); 490 491 private static final String KILL_APP_REASON_GIDS_CHANGED = 492 "permission grant or revoke changed gids"; 493 494 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 495 "permissions revoked"; 496 497 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 498 499 private static final String PACKAGE_SCHEME = "package"; 500 501 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 502 503 /** Permission grant: not grant the permission. */ 504 private static final int GRANT_DENIED = 1; 505 506 /** Permission grant: grant the permission as an install permission. */ 507 private static final int GRANT_INSTALL = 2; 508 509 /** Permission grant: grant the permission as a runtime one. */ 510 private static final int GRANT_RUNTIME = 3; 511 512 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 513 private static final int GRANT_UPGRADE = 4; 514 515 /** Canonical intent used to identify what counts as a "web browser" app */ 516 private static final Intent sBrowserIntent; 517 static { 518 sBrowserIntent = new Intent(); 519 sBrowserIntent.setAction(Intent.ACTION_VIEW); 520 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 521 sBrowserIntent.setData(Uri.parse("http:")); 522 } 523 524 /** 525 * The set of all protected actions [i.e. those actions for which a high priority 526 * intent filter is disallowed]. 527 */ 528 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 529 static { 530 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 531 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 532 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 533 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 534 } 535 536 // Compilation reasons. 537 public static final int REASON_FIRST_BOOT = 0; 538 public static final int REASON_BOOT = 1; 539 public static final int REASON_INSTALL = 2; 540 public static final int REASON_BACKGROUND_DEXOPT = 3; 541 public static final int REASON_AB_OTA = 4; 542 public static final int REASON_FORCED_DEXOPT = 5; 543 544 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 545 546 /** All dangerous permission names in the same order as the events in MetricsEvent */ 547 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 548 Manifest.permission.READ_CALENDAR, 549 Manifest.permission.WRITE_CALENDAR, 550 Manifest.permission.CAMERA, 551 Manifest.permission.READ_CONTACTS, 552 Manifest.permission.WRITE_CONTACTS, 553 Manifest.permission.GET_ACCOUNTS, 554 Manifest.permission.ACCESS_FINE_LOCATION, 555 Manifest.permission.ACCESS_COARSE_LOCATION, 556 Manifest.permission.RECORD_AUDIO, 557 Manifest.permission.READ_PHONE_STATE, 558 Manifest.permission.CALL_PHONE, 559 Manifest.permission.READ_CALL_LOG, 560 Manifest.permission.WRITE_CALL_LOG, 561 Manifest.permission.ADD_VOICEMAIL, 562 Manifest.permission.USE_SIP, 563 Manifest.permission.PROCESS_OUTGOING_CALLS, 564 Manifest.permission.READ_CELL_BROADCASTS, 565 Manifest.permission.BODY_SENSORS, 566 Manifest.permission.SEND_SMS, 567 Manifest.permission.RECEIVE_SMS, 568 Manifest.permission.READ_SMS, 569 Manifest.permission.RECEIVE_WAP_PUSH, 570 Manifest.permission.RECEIVE_MMS, 571 Manifest.permission.READ_EXTERNAL_STORAGE, 572 Manifest.permission.WRITE_EXTERNAL_STORAGE, 573 Manifest.permission.READ_PHONE_NUMBERS, 574 Manifest.permission.ANSWER_PHONE_CALLS); 575 576 577 /** 578 * Version number for the package parser cache. Increment this whenever the format or 579 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 580 */ 581 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 582 583 /** 584 * Whether the package parser cache is enabled. 585 */ 586 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 587 588 final ServiceThread mHandlerThread; 589 590 final PackageHandler mHandler; 591 592 private final ProcessLoggingHandler mProcessLoggingHandler; 593 594 /** 595 * Messages for {@link #mHandler} that need to wait for system ready before 596 * being dispatched. 597 */ 598 private ArrayList<Message> mPostSystemReadyMessages; 599 600 final int mSdkVersion = Build.VERSION.SDK_INT; 601 602 final Context mContext; 603 final boolean mFactoryTest; 604 final boolean mOnlyCore; 605 final DisplayMetrics mMetrics; 606 final int mDefParseFlags; 607 final String[] mSeparateProcesses; 608 final boolean mIsUpgrade; 609 final boolean mIsPreNUpgrade; 610 final boolean mIsPreNMR1Upgrade; 611 612 // Have we told the Activity Manager to whitelist the default container service by uid yet? 613 @GuardedBy("mPackages") 614 boolean mDefaultContainerWhitelisted = false; 615 616 @GuardedBy("mPackages") 617 private boolean mDexOptDialogShown; 618 619 /** The location for ASEC container files on internal storage. */ 620 final String mAsecInternalPath; 621 622 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 623 // LOCK HELD. Can be called with mInstallLock held. 624 @GuardedBy("mInstallLock") 625 final Installer mInstaller; 626 627 /** Directory where installed third-party apps stored */ 628 final File mAppInstallDir; 629 630 /** 631 * Directory to which applications installed internally have their 632 * 32 bit native libraries copied. 633 */ 634 private File mAppLib32InstallDir; 635 636 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 637 // apps. 638 final File mDrmAppPrivateInstallDir; 639 640 // ---------------------------------------------------------------- 641 642 // Lock for state used when installing and doing other long running 643 // operations. Methods that must be called with this lock held have 644 // the suffix "LI". 645 final Object mInstallLock = new Object(); 646 647 // ---------------------------------------------------------------- 648 649 // Keys are String (package name), values are Package. This also serves 650 // as the lock for the global state. Methods that must be called with 651 // this lock held have the prefix "LP". 652 @GuardedBy("mPackages") 653 final ArrayMap<String, PackageParser.Package> mPackages = 654 new ArrayMap<String, PackageParser.Package>(); 655 656 final ArrayMap<String, Set<String>> mKnownCodebase = 657 new ArrayMap<String, Set<String>>(); 658 659 // Keys are isolated uids and values are the uid of the application 660 // that created the isolated proccess. 661 @GuardedBy("mPackages") 662 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 663 664 // List of APK paths to load for each user and package. This data is never 665 // persisted by the package manager. Instead, the overlay manager will 666 // ensure the data is up-to-date in runtime. 667 @GuardedBy("mPackages") 668 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 669 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 670 671 /** 672 * Tracks new system packages [received in an OTA] that we expect to 673 * find updated user-installed versions. Keys are package name, values 674 * are package location. 675 */ 676 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 677 /** 678 * Tracks high priority intent filters for protected actions. During boot, certain 679 * filter actions are protected and should never be allowed to have a high priority 680 * intent filter for them. However, there is one, and only one exception -- the 681 * setup wizard. It must be able to define a high priority intent filter for these 682 * actions to ensure there are no escapes from the wizard. We need to delay processing 683 * of these during boot as we need to look at all of the system packages in order 684 * to know which component is the setup wizard. 685 */ 686 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 687 /** 688 * Whether or not processing protected filters should be deferred. 689 */ 690 private boolean mDeferProtectedFilters = true; 691 692 /** 693 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 694 */ 695 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 696 /** 697 * Whether or not system app permissions should be promoted from install to runtime. 698 */ 699 boolean mPromoteSystemApps; 700 701 @GuardedBy("mPackages") 702 final Settings mSettings; 703 704 /** 705 * Set of package names that are currently "frozen", which means active 706 * surgery is being done on the code/data for that package. The platform 707 * will refuse to launch frozen packages to avoid race conditions. 708 * 709 * @see PackageFreezer 710 */ 711 @GuardedBy("mPackages") 712 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 713 714 final ProtectedPackages mProtectedPackages; 715 716 boolean mFirstBoot; 717 718 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 719 720 // System configuration read by SystemConfig. 721 final int[] mGlobalGids; 722 final SparseArray<ArraySet<String>> mSystemPermissions; 723 @GuardedBy("mAvailableFeatures") 724 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 725 726 // If mac_permissions.xml was found for seinfo labeling. 727 boolean mFoundPolicyFile; 728 729 private final InstantAppRegistry mInstantAppRegistry; 730 731 @GuardedBy("mPackages") 732 int mChangedPackagesSequenceNumber; 733 /** 734 * List of changed [installed, removed or updated] packages. 735 * mapping from user id -> sequence number -> package name 736 */ 737 @GuardedBy("mPackages") 738 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 739 /** 740 * The sequence number of the last change to a package. 741 * mapping from user id -> package name -> sequence number 742 */ 743 @GuardedBy("mPackages") 744 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 745 746 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 747 @Override public boolean hasFeature(String feature) { 748 return PackageManagerService.this.hasSystemFeature(feature, 0); 749 } 750 }; 751 752 public static final class SharedLibraryEntry { 753 public final String path; 754 public final String apk; 755 public final SharedLibraryInfo info; 756 757 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 758 String declaringPackageName, int declaringPackageVersionCode) { 759 path = _path; 760 apk = _apk; 761 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 762 declaringPackageName, declaringPackageVersionCode), null); 763 } 764 } 765 766 // Currently known shared libraries. 767 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 768 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 769 new ArrayMap<>(); 770 771 // All available activities, for your resolving pleasure. 772 final ActivityIntentResolver mActivities = 773 new ActivityIntentResolver(); 774 775 // All available receivers, for your resolving pleasure. 776 final ActivityIntentResolver mReceivers = 777 new ActivityIntentResolver(); 778 779 // All available services, for your resolving pleasure. 780 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 781 782 // All available providers, for your resolving pleasure. 783 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 784 785 // Mapping from provider base names (first directory in content URI codePath) 786 // to the provider information. 787 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 788 new ArrayMap<String, PackageParser.Provider>(); 789 790 // Mapping from instrumentation class names to info about them. 791 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 792 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 793 794 // Mapping from permission names to info about them. 795 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 796 new ArrayMap<String, PackageParser.PermissionGroup>(); 797 798 // Packages whose data we have transfered into another package, thus 799 // should no longer exist. 800 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 801 802 // Broadcast actions that are only available to the system. 803 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 804 805 /** List of packages waiting for verification. */ 806 final SparseArray<PackageVerificationState> mPendingVerification 807 = new SparseArray<PackageVerificationState>(); 808 809 /** Set of packages associated with each app op permission. */ 810 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 811 812 final PackageInstallerService mInstallerService; 813 814 private final PackageDexOptimizer mPackageDexOptimizer; 815 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 816 // is used by other apps). 817 private final DexManager mDexManager; 818 819 private AtomicInteger mNextMoveId = new AtomicInteger(); 820 private final MoveCallbacks mMoveCallbacks; 821 822 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 823 824 // Cache of users who need badging. 825 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 826 827 /** Token for keys in mPendingVerification. */ 828 private int mPendingVerificationToken = 0; 829 830 volatile boolean mSystemReady; 831 volatile boolean mSafeMode; 832 volatile boolean mHasSystemUidErrors; 833 834 ApplicationInfo mAndroidApplication; 835 final ActivityInfo mResolveActivity = new ActivityInfo(); 836 final ResolveInfo mResolveInfo = new ResolveInfo(); 837 ComponentName mResolveComponentName; 838 PackageParser.Package mPlatformPackage; 839 ComponentName mCustomResolverComponentName; 840 841 boolean mResolverReplaced = false; 842 843 private final @Nullable ComponentName mIntentFilterVerifierComponent; 844 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 845 846 private int mIntentFilterVerificationToken = 0; 847 848 /** The service connection to the ephemeral resolver */ 849 final EphemeralResolverConnection mInstantAppResolverConnection; 850 /** Component used to show resolver settings for Instant Apps */ 851 final ComponentName mInstantAppResolverSettingsComponent; 852 853 /** Activity used to install instant applications */ 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 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2064 && (grantedPermissions == null 2065 || ArrayUtils.contains(grantedPermissions, permission))) { 2066 final int flags = permissionsState.getPermissionFlags(permission, userId); 2067 if (supportsRuntimePermissions) { 2068 // Installer cannot change immutable permissions. 2069 if ((flags & immutableFlags) == 0) { 2070 grantRuntimePermission(pkg.packageName, permission, userId); 2071 } 2072 } else if (mPermissionReviewRequired) { 2073 // In permission review mode we clear the review flag when we 2074 // are asked to install the app with all permissions granted. 2075 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2076 updatePermissionFlags(permission, pkg.packageName, 2077 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2078 } 2079 } 2080 } 2081 } 2082 } 2083 2084 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2085 Bundle extras = null; 2086 switch (res.returnCode) { 2087 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2088 extras = new Bundle(); 2089 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2090 res.origPermission); 2091 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2092 res.origPackage); 2093 break; 2094 } 2095 case PackageManager.INSTALL_SUCCEEDED: { 2096 extras = new Bundle(); 2097 extras.putBoolean(Intent.EXTRA_REPLACING, 2098 res.removedInfo != null && res.removedInfo.removedPackage != null); 2099 break; 2100 } 2101 } 2102 return extras; 2103 } 2104 2105 void scheduleWriteSettingsLocked() { 2106 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2107 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2108 } 2109 } 2110 2111 void scheduleWritePackageListLocked(int userId) { 2112 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2113 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2114 msg.arg1 = userId; 2115 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2116 } 2117 } 2118 2119 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2120 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2121 scheduleWritePackageRestrictionsLocked(userId); 2122 } 2123 2124 void scheduleWritePackageRestrictionsLocked(int userId) { 2125 final int[] userIds = (userId == UserHandle.USER_ALL) 2126 ? sUserManager.getUserIds() : new int[]{userId}; 2127 for (int nextUserId : userIds) { 2128 if (!sUserManager.exists(nextUserId)) return; 2129 mDirtyUsers.add(nextUserId); 2130 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2131 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2132 } 2133 } 2134 } 2135 2136 public static PackageManagerService main(Context context, Installer installer, 2137 boolean factoryTest, boolean onlyCore) { 2138 // Self-check for initial settings. 2139 PackageManagerServiceCompilerMapping.checkProperties(); 2140 2141 PackageManagerService m = new PackageManagerService(context, installer, 2142 factoryTest, onlyCore); 2143 m.enableSystemUserPackages(); 2144 ServiceManager.addService("package", m); 2145 return m; 2146 } 2147 2148 private void enableSystemUserPackages() { 2149 if (!UserManager.isSplitSystemUser()) { 2150 return; 2151 } 2152 // For system user, enable apps based on the following conditions: 2153 // - app is whitelisted or belong to one of these groups: 2154 // -- system app which has no launcher icons 2155 // -- system app which has INTERACT_ACROSS_USERS permission 2156 // -- system IME app 2157 // - app is not in the blacklist 2158 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2159 Set<String> enableApps = new ArraySet<>(); 2160 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2161 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2162 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2163 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2164 enableApps.addAll(wlApps); 2165 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2166 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2167 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2168 enableApps.removeAll(blApps); 2169 Log.i(TAG, "Applications installed for system user: " + enableApps); 2170 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2171 UserHandle.SYSTEM); 2172 final int allAppsSize = allAps.size(); 2173 synchronized (mPackages) { 2174 for (int i = 0; i < allAppsSize; i++) { 2175 String pName = allAps.get(i); 2176 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2177 // Should not happen, but we shouldn't be failing if it does 2178 if (pkgSetting == null) { 2179 continue; 2180 } 2181 boolean install = enableApps.contains(pName); 2182 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2183 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2184 + " for system user"); 2185 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2186 } 2187 } 2188 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2189 } 2190 } 2191 2192 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2193 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2194 Context.DISPLAY_SERVICE); 2195 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2196 } 2197 2198 /** 2199 * Requests that files preopted on a secondary system partition be copied to the data partition 2200 * if possible. Note that the actual copying of the files is accomplished by init for security 2201 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2202 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2203 */ 2204 private static void requestCopyPreoptedFiles() { 2205 final int WAIT_TIME_MS = 100; 2206 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2207 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2208 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2209 // We will wait for up to 100 seconds. 2210 final long timeStart = SystemClock.uptimeMillis(); 2211 final long timeEnd = timeStart + 100 * 1000; 2212 long timeNow = timeStart; 2213 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2214 try { 2215 Thread.sleep(WAIT_TIME_MS); 2216 } catch (InterruptedException e) { 2217 // Do nothing 2218 } 2219 timeNow = SystemClock.uptimeMillis(); 2220 if (timeNow > timeEnd) { 2221 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2222 Slog.wtf(TAG, "cppreopt did not finish!"); 2223 break; 2224 } 2225 } 2226 2227 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2228 } 2229 } 2230 2231 public PackageManagerService(Context context, Installer installer, 2232 boolean factoryTest, boolean onlyCore) { 2233 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2235 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2236 SystemClock.uptimeMillis()); 2237 2238 if (mSdkVersion <= 0) { 2239 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2240 } 2241 2242 mContext = context; 2243 2244 mPermissionReviewRequired = context.getResources().getBoolean( 2245 R.bool.config_permissionReviewRequired); 2246 2247 mFactoryTest = factoryTest; 2248 mOnlyCore = onlyCore; 2249 mMetrics = new DisplayMetrics(); 2250 mSettings = new Settings(mPackages); 2251 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2252 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2253 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2254 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2255 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2256 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2257 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2258 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2259 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2260 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2261 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2262 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2263 2264 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2265 if (separateProcesses != null && separateProcesses.length() > 0) { 2266 if ("*".equals(separateProcesses)) { 2267 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2268 mSeparateProcesses = null; 2269 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2270 } else { 2271 mDefParseFlags = 0; 2272 mSeparateProcesses = separateProcesses.split(","); 2273 Slog.w(TAG, "Running with debug.separate_processes: " 2274 + separateProcesses); 2275 } 2276 } else { 2277 mDefParseFlags = 0; 2278 mSeparateProcesses = null; 2279 } 2280 2281 mInstaller = installer; 2282 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2283 "*dexopt*"); 2284 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2285 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2286 2287 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2288 FgThread.get().getLooper()); 2289 2290 getDefaultDisplayMetrics(context, mMetrics); 2291 2292 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2293 SystemConfig systemConfig = SystemConfig.getInstance(); 2294 mGlobalGids = systemConfig.getGlobalGids(); 2295 mSystemPermissions = systemConfig.getSystemPermissions(); 2296 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2298 2299 mProtectedPackages = new ProtectedPackages(mContext); 2300 2301 synchronized (mInstallLock) { 2302 // writer 2303 synchronized (mPackages) { 2304 mHandlerThread = new ServiceThread(TAG, 2305 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2306 mHandlerThread.start(); 2307 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2308 mProcessLoggingHandler = new ProcessLoggingHandler(); 2309 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2310 2311 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2312 mInstantAppRegistry = new InstantAppRegistry(this); 2313 2314 File dataDir = Environment.getDataDirectory(); 2315 mAppInstallDir = new File(dataDir, "app"); 2316 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2317 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2318 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2319 sUserManager = new UserManagerService(context, this, 2320 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2321 2322 // Propagate permission configuration in to package manager. 2323 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2324 = systemConfig.getPermissions(); 2325 for (int i=0; i<permConfig.size(); i++) { 2326 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2327 BasePermission bp = mSettings.mPermissions.get(perm.name); 2328 if (bp == null) { 2329 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2330 mSettings.mPermissions.put(perm.name, bp); 2331 } 2332 if (perm.gids != null) { 2333 bp.setGids(perm.gids, perm.perUser); 2334 } 2335 } 2336 2337 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2338 final int builtInLibCount = libConfig.size(); 2339 for (int i = 0; i < builtInLibCount; i++) { 2340 String name = libConfig.keyAt(i); 2341 String path = libConfig.valueAt(i); 2342 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2343 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2344 } 2345 2346 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2347 2348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2349 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2350 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2351 2352 // Clean up orphaned packages for which the code path doesn't exist 2353 // and they are an update to a system app - caused by bug/32321269 2354 final int packageSettingCount = mSettings.mPackages.size(); 2355 for (int i = packageSettingCount - 1; i >= 0; i--) { 2356 PackageSetting ps = mSettings.mPackages.valueAt(i); 2357 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2358 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2359 mSettings.mPackages.removeAt(i); 2360 mSettings.enableSystemPackageLPw(ps.name); 2361 } 2362 } 2363 2364 if (mFirstBoot) { 2365 requestCopyPreoptedFiles(); 2366 } 2367 2368 String customResolverActivity = Resources.getSystem().getString( 2369 R.string.config_customResolverActivity); 2370 if (TextUtils.isEmpty(customResolverActivity)) { 2371 customResolverActivity = null; 2372 } else { 2373 mCustomResolverComponentName = ComponentName.unflattenFromString( 2374 customResolverActivity); 2375 } 2376 2377 long startTime = SystemClock.uptimeMillis(); 2378 2379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2380 startTime); 2381 2382 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2383 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2384 2385 if (bootClassPath == null) { 2386 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2387 } 2388 2389 if (systemServerClassPath == null) { 2390 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2391 } 2392 2393 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2394 2395 final VersionInfo ver = mSettings.getInternalVersion(); 2396 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2397 if (mIsUpgrade) { 2398 logCriticalInfo(Log.INFO, 2399 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2400 } 2401 2402 // when upgrading from pre-M, promote system app permissions from install to runtime 2403 mPromoteSystemApps = 2404 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2405 2406 // When upgrading from pre-N, we need to handle package extraction like first boot, 2407 // as there is no profiling data available. 2408 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2409 2410 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2411 2412 // save off the names of pre-existing system packages prior to scanning; we don't 2413 // want to automatically grant runtime permissions for new system apps 2414 if (mPromoteSystemApps) { 2415 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2416 while (pkgSettingIter.hasNext()) { 2417 PackageSetting ps = pkgSettingIter.next(); 2418 if (isSystemApp(ps)) { 2419 mExistingSystemPackages.add(ps.name); 2420 } 2421 } 2422 } 2423 2424 mCacheDir = preparePackageParserCache(mIsUpgrade); 2425 2426 // Set flag to monitor and not change apk file paths when 2427 // scanning install directories. 2428 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2429 2430 if (mIsUpgrade || mFirstBoot) { 2431 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2432 } 2433 2434 // Collect vendor overlay packages. (Do this before scanning any apps.) 2435 // For security and version matching reason, only consider 2436 // overlay packages if they reside in the right directory. 2437 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2438 | PackageParser.PARSE_IS_SYSTEM 2439 | PackageParser.PARSE_IS_SYSTEM_DIR 2440 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2441 2442 // Find base frameworks (resource packages without code). 2443 scanDirTracedLI(frameworkDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR 2446 | PackageParser.PARSE_IS_PRIVILEGED, 2447 scanFlags | SCAN_NO_DEX, 0); 2448 2449 // Collected privileged system packages. 2450 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2451 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2452 | PackageParser.PARSE_IS_SYSTEM 2453 | PackageParser.PARSE_IS_SYSTEM_DIR 2454 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2455 2456 // Collect ordinary system packages. 2457 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2458 scanDirTracedLI(systemAppDir, mDefParseFlags 2459 | PackageParser.PARSE_IS_SYSTEM 2460 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2461 2462 // Collect all vendor packages. 2463 File vendorAppDir = new File("/vendor/app"); 2464 try { 2465 vendorAppDir = vendorAppDir.getCanonicalFile(); 2466 } catch (IOException e) { 2467 // failed to look up canonical path, continue with original one 2468 } 2469 scanDirTracedLI(vendorAppDir, mDefParseFlags 2470 | PackageParser.PARSE_IS_SYSTEM 2471 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2472 2473 // Collect all OEM packages. 2474 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2475 scanDirTracedLI(oemAppDir, mDefParseFlags 2476 | PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2478 2479 // Prune any system packages that no longer exist. 2480 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2481 if (!mOnlyCore) { 2482 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2483 while (psit.hasNext()) { 2484 PackageSetting ps = psit.next(); 2485 2486 /* 2487 * If this is not a system app, it can't be a 2488 * disable system app. 2489 */ 2490 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2491 continue; 2492 } 2493 2494 /* 2495 * If the package is scanned, it's not erased. 2496 */ 2497 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2498 if (scannedPkg != null) { 2499 /* 2500 * If the system app is both scanned and in the 2501 * disabled packages list, then it must have been 2502 * added via OTA. Remove it from the currently 2503 * scanned package so the previously user-installed 2504 * application can be scanned. 2505 */ 2506 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2507 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2508 + ps.name + "; removing system app. Last known codePath=" 2509 + ps.codePathString + ", installStatus=" + ps.installStatus 2510 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2511 + scannedPkg.mVersionCode); 2512 removePackageLI(scannedPkg, true); 2513 mExpectingBetter.put(ps.name, ps.codePath); 2514 } 2515 2516 continue; 2517 } 2518 2519 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2520 psit.remove(); 2521 logCriticalInfo(Log.WARN, "System package " + ps.name 2522 + " no longer exists; it's data will be wiped"); 2523 // Actual deletion of code and data will be handled by later 2524 // reconciliation step 2525 } else { 2526 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2527 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2528 possiblyDeletedUpdatedSystemApps.add(ps.name); 2529 } 2530 } 2531 } 2532 } 2533 2534 //look for any incomplete package installations 2535 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2536 for (int i = 0; i < deletePkgsList.size(); i++) { 2537 // Actual deletion of code and data will be handled by later 2538 // reconciliation step 2539 final String packageName = deletePkgsList.get(i).name; 2540 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2541 synchronized (mPackages) { 2542 mSettings.removePackageLPw(packageName); 2543 } 2544 } 2545 2546 //delete tmp files 2547 deleteTempPackageFiles(); 2548 2549 // Remove any shared userIDs that have no associated packages 2550 mSettings.pruneSharedUsersLPw(); 2551 2552 if (!mOnlyCore) { 2553 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2554 SystemClock.uptimeMillis()); 2555 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2556 2557 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2558 | PackageParser.PARSE_FORWARD_LOCK, 2559 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2560 2561 /** 2562 * Remove disable package settings for any updated system 2563 * apps that were removed via an OTA. If they're not a 2564 * previously-updated app, remove them completely. 2565 * Otherwise, just revoke their system-level permissions. 2566 */ 2567 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2568 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2569 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2570 2571 String msg; 2572 if (deletedPkg == null) { 2573 msg = "Updated system package " + deletedAppName 2574 + " no longer exists; it's data will be wiped"; 2575 // Actual deletion of code and data will be handled by later 2576 // reconciliation step 2577 } else { 2578 msg = "Updated system app + " + deletedAppName 2579 + " no longer present; removing system privileges for " 2580 + deletedAppName; 2581 2582 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2583 2584 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2585 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2586 } 2587 logCriticalInfo(Log.WARN, msg); 2588 } 2589 2590 /** 2591 * Make sure all system apps that we expected to appear on 2592 * the userdata partition actually showed up. If they never 2593 * appeared, crawl back and revive the system version. 2594 */ 2595 for (int i = 0; i < mExpectingBetter.size(); i++) { 2596 final String packageName = mExpectingBetter.keyAt(i); 2597 if (!mPackages.containsKey(packageName)) { 2598 final File scanFile = mExpectingBetter.valueAt(i); 2599 2600 logCriticalInfo(Log.WARN, "Expected better " + packageName 2601 + " but never showed up; reverting to system"); 2602 2603 int reparseFlags = mDefParseFlags; 2604 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2605 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2606 | PackageParser.PARSE_IS_SYSTEM_DIR 2607 | PackageParser.PARSE_IS_PRIVILEGED; 2608 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2609 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2610 | PackageParser.PARSE_IS_SYSTEM_DIR; 2611 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2612 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2613 | PackageParser.PARSE_IS_SYSTEM_DIR; 2614 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2615 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2616 | PackageParser.PARSE_IS_SYSTEM_DIR; 2617 } else { 2618 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2619 continue; 2620 } 2621 2622 mSettings.enableSystemPackageLPw(packageName); 2623 2624 try { 2625 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2626 } catch (PackageManagerException e) { 2627 Slog.e(TAG, "Failed to parse original system package: " 2628 + e.getMessage()); 2629 } 2630 } 2631 } 2632 } 2633 mExpectingBetter.clear(); 2634 2635 // Resolve the storage manager. 2636 mStorageManagerPackage = getStorageManagerPackageName(); 2637 2638 // Resolve protected action filters. Only the setup wizard is allowed to 2639 // have a high priority filter for these actions. 2640 mSetupWizardPackage = getSetupWizardPackageName(); 2641 if (mProtectedFilters.size() > 0) { 2642 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2643 Slog.i(TAG, "No setup wizard;" 2644 + " All protected intents capped to priority 0"); 2645 } 2646 for (ActivityIntentInfo filter : mProtectedFilters) { 2647 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2648 if (DEBUG_FILTERS) { 2649 Slog.i(TAG, "Found setup wizard;" 2650 + " allow priority " + filter.getPriority() + ";" 2651 + " package: " + filter.activity.info.packageName 2652 + " activity: " + filter.activity.className 2653 + " priority: " + filter.getPriority()); 2654 } 2655 // skip setup wizard; allow it to keep the high priority filter 2656 continue; 2657 } 2658 Slog.w(TAG, "Protected action; cap priority to 0;" 2659 + " package: " + filter.activity.info.packageName 2660 + " activity: " + filter.activity.className 2661 + " origPrio: " + filter.getPriority()); 2662 filter.setPriority(0); 2663 } 2664 } 2665 mDeferProtectedFilters = false; 2666 mProtectedFilters.clear(); 2667 2668 // Now that we know all of the shared libraries, update all clients to have 2669 // the correct library paths. 2670 updateAllSharedLibrariesLPw(null); 2671 2672 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2673 // NOTE: We ignore potential failures here during a system scan (like 2674 // the rest of the commands above) because there's precious little we 2675 // can do about it. A settings error is reported, though. 2676 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2677 } 2678 2679 // Now that we know all the packages we are keeping, 2680 // read and update their last usage times. 2681 mPackageUsage.read(mPackages); 2682 mCompilerStats.read(); 2683 2684 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2685 SystemClock.uptimeMillis()); 2686 Slog.i(TAG, "Time to scan packages: " 2687 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2688 + " seconds"); 2689 2690 // If the platform SDK has changed since the last time we booted, 2691 // we need to re-grant app permission to catch any new ones that 2692 // appear. This is really a hack, and means that apps can in some 2693 // cases get permissions that the user didn't initially explicitly 2694 // allow... it would be nice to have some better way to handle 2695 // this situation. 2696 int updateFlags = UPDATE_PERMISSIONS_ALL; 2697 if (ver.sdkVersion != mSdkVersion) { 2698 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2699 + mSdkVersion + "; regranting permissions for internal storage"); 2700 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2701 } 2702 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2703 ver.sdkVersion = mSdkVersion; 2704 2705 // If this is the first boot or an update from pre-M, and it is a normal 2706 // boot, then we need to initialize the default preferred apps across 2707 // all defined users. 2708 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2709 for (UserInfo user : sUserManager.getUsers(true)) { 2710 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2711 applyFactoryDefaultBrowserLPw(user.id); 2712 primeDomainVerificationsLPw(user.id); 2713 } 2714 } 2715 2716 // Prepare storage for system user really early during boot, 2717 // since core system apps like SettingsProvider and SystemUI 2718 // can't wait for user to start 2719 final int storageFlags; 2720 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2721 storageFlags = StorageManager.FLAG_STORAGE_DE; 2722 } else { 2723 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2724 } 2725 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2726 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2727 true /* onlyCoreApps */); 2728 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2729 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2730 Trace.TRACE_TAG_PACKAGE_MANAGER); 2731 traceLog.traceBegin("AppDataFixup"); 2732 try { 2733 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2734 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2735 } catch (InstallerException e) { 2736 Slog.w(TAG, "Trouble fixing GIDs", e); 2737 } 2738 traceLog.traceEnd(); 2739 2740 traceLog.traceBegin("AppDataPrepare"); 2741 if (deferPackages == null || deferPackages.isEmpty()) { 2742 return; 2743 } 2744 int count = 0; 2745 for (String pkgName : deferPackages) { 2746 PackageParser.Package pkg = null; 2747 synchronized (mPackages) { 2748 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2749 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2750 pkg = ps.pkg; 2751 } 2752 } 2753 if (pkg != null) { 2754 synchronized (mInstallLock) { 2755 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2756 true /* maybeMigrateAppData */); 2757 } 2758 count++; 2759 } 2760 } 2761 traceLog.traceEnd(); 2762 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2763 }, "prepareAppData"); 2764 2765 // If this is first boot after an OTA, and a normal boot, then 2766 // we need to clear code cache directories. 2767 // Note that we do *not* clear the application profiles. These remain valid 2768 // across OTAs and are used to drive profile verification (post OTA) and 2769 // profile compilation (without waiting to collect a fresh set of profiles). 2770 if (mIsUpgrade && !onlyCore) { 2771 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2772 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2773 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2774 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2775 // No apps are running this early, so no need to freeze 2776 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2777 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2778 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2779 } 2780 } 2781 ver.fingerprint = Build.FINGERPRINT; 2782 } 2783 2784 checkDefaultBrowser(); 2785 2786 // clear only after permissions and other defaults have been updated 2787 mExistingSystemPackages.clear(); 2788 mPromoteSystemApps = false; 2789 2790 // All the changes are done during package scanning. 2791 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2792 2793 // can downgrade to reader 2794 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2795 mSettings.writeLPr(); 2796 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2797 2798 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2799 SystemClock.uptimeMillis()); 2800 2801 if (!mOnlyCore) { 2802 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2803 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2804 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2805 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2806 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2807 mIntentFilterVerifierComponent); 2808 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2809 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2810 SharedLibraryInfo.VERSION_UNDEFINED); 2811 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2812 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2813 SharedLibraryInfo.VERSION_UNDEFINED); 2814 } else { 2815 mRequiredVerifierPackage = null; 2816 mRequiredInstallerPackage = null; 2817 mRequiredUninstallerPackage = null; 2818 mIntentFilterVerifierComponent = null; 2819 mIntentFilterVerifier = null; 2820 mServicesSystemSharedLibraryPackageName = null; 2821 mSharedSystemSharedLibraryPackageName = null; 2822 } 2823 2824 mInstallerService = new PackageInstallerService(context, this); 2825 final Pair<ComponentName, String> instantAppResolverComponent = 2826 getInstantAppResolverLPr(); 2827 if (instantAppResolverComponent != null) { 2828 if (DEBUG_EPHEMERAL) { 2829 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2830 } 2831 mInstantAppResolverConnection = new EphemeralResolverConnection( 2832 mContext, instantAppResolverComponent.first, 2833 instantAppResolverComponent.second); 2834 mInstantAppResolverSettingsComponent = 2835 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2836 } else { 2837 mInstantAppResolverConnection = null; 2838 mInstantAppResolverSettingsComponent = null; 2839 } 2840 updateInstantAppInstallerLocked(null); 2841 2842 // Read and update the usage of dex files. 2843 // Do this at the end of PM init so that all the packages have their 2844 // data directory reconciled. 2845 // At this point we know the code paths of the packages, so we can validate 2846 // the disk file and build the internal cache. 2847 // The usage file is expected to be small so loading and verifying it 2848 // should take a fairly small time compare to the other activities (e.g. package 2849 // scanning). 2850 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2851 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2852 for (int userId : currentUserIds) { 2853 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2854 } 2855 mDexManager.load(userPackages); 2856 } // synchronized (mPackages) 2857 } // synchronized (mInstallLock) 2858 2859 // Now after opening every single application zip, make sure they 2860 // are all flushed. Not really needed, but keeps things nice and 2861 // tidy. 2862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2863 Runtime.getRuntime().gc(); 2864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2865 2866 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2867 FallbackCategoryProvider.loadFallbacks(); 2868 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2869 2870 // The initial scanning above does many calls into installd while 2871 // holding the mPackages lock, but we're mostly interested in yelling 2872 // once we have a booted system. 2873 mInstaller.setWarnIfHeld(mPackages); 2874 2875 // Expose private service for system components to use. 2876 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2877 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2878 } 2879 2880 private void updateInstantAppInstallerLocked(String modifiedPackage) { 2881 // we're only interested in updating the installer appliction when 1) it's not 2882 // already set or 2) the modified package is the installer 2883 if (mInstantAppInstallerActivity != null 2884 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 2885 .equals(modifiedPackage)) { 2886 return; 2887 } 2888 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 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 Pair<ComponentName, String> getInstantAppResolverLPr() { 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 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3068 final Intent resolverIntent = new Intent(actionName); 3069 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3070 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3071 // temporarily look for the old action 3072 if (resolvers.size() == 0) { 3073 if (DEBUG_EPHEMERAL) { 3074 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3075 } 3076 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3077 resolverIntent.setAction(actionName); 3078 resolvers = queryIntentServicesInternal(resolverIntent, null, 3079 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3080 } 3081 final int N = resolvers.size(); 3082 if (N == 0) { 3083 if (DEBUG_EPHEMERAL) { 3084 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3085 } 3086 return null; 3087 } 3088 3089 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3090 for (int i = 0; i < N; i++) { 3091 final ResolveInfo info = resolvers.get(i); 3092 3093 if (info.serviceInfo == null) { 3094 continue; 3095 } 3096 3097 final String packageName = info.serviceInfo.packageName; 3098 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3099 if (DEBUG_EPHEMERAL) { 3100 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3101 + " pkg: " + packageName + ", info:" + info); 3102 } 3103 continue; 3104 } 3105 3106 if (DEBUG_EPHEMERAL) { 3107 Slog.v(TAG, "Ephemeral resolver found;" 3108 + " pkg: " + packageName + ", info:" + info); 3109 } 3110 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3111 } 3112 if (DEBUG_EPHEMERAL) { 3113 Slog.v(TAG, "Ephemeral resolver NOT found"); 3114 } 3115 return null; 3116 } 3117 3118 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3119 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3120 intent.addCategory(Intent.CATEGORY_DEFAULT); 3121 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3122 3123 final int resolveFlags = 3124 MATCH_DIRECT_BOOT_AWARE 3125 | MATCH_DIRECT_BOOT_UNAWARE 3126 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3127 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3128 resolveFlags, UserHandle.USER_SYSTEM); 3129 // temporarily look for the old action 3130 if (matches.isEmpty()) { 3131 if (DEBUG_EPHEMERAL) { 3132 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3133 } 3134 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3135 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3136 resolveFlags, UserHandle.USER_SYSTEM); 3137 } 3138 Iterator<ResolveInfo> iter = matches.iterator(); 3139 while (iter.hasNext()) { 3140 final ResolveInfo rInfo = iter.next(); 3141 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3142 if (ps != null) { 3143 final PermissionsState permissionsState = ps.getPermissionsState(); 3144 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3145 continue; 3146 } 3147 } 3148 iter.remove(); 3149 } 3150 if (matches.size() == 0) { 3151 return null; 3152 } else if (matches.size() == 1) { 3153 return (ActivityInfo) matches.get(0).getComponentInfo(); 3154 } else { 3155 throw new RuntimeException( 3156 "There must be at most one ephemeral installer; found " + matches); 3157 } 3158 } 3159 3160 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3161 @NonNull ComponentName resolver) { 3162 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3163 .addCategory(Intent.CATEGORY_DEFAULT) 3164 .setPackage(resolver.getPackageName()); 3165 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3166 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3167 UserHandle.USER_SYSTEM); 3168 // temporarily look for the old action 3169 if (matches.isEmpty()) { 3170 if (DEBUG_EPHEMERAL) { 3171 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3172 } 3173 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3174 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3175 UserHandle.USER_SYSTEM); 3176 } 3177 if (matches.isEmpty()) { 3178 return null; 3179 } 3180 return matches.get(0).getComponentInfo().getComponentName(); 3181 } 3182 3183 private void primeDomainVerificationsLPw(int userId) { 3184 if (DEBUG_DOMAIN_VERIFICATION) { 3185 Slog.d(TAG, "Priming domain verifications in user " + userId); 3186 } 3187 3188 SystemConfig systemConfig = SystemConfig.getInstance(); 3189 ArraySet<String> packages = systemConfig.getLinkedApps(); 3190 3191 for (String packageName : packages) { 3192 PackageParser.Package pkg = mPackages.get(packageName); 3193 if (pkg != null) { 3194 if (!pkg.isSystemApp()) { 3195 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3196 continue; 3197 } 3198 3199 ArraySet<String> domains = null; 3200 for (PackageParser.Activity a : pkg.activities) { 3201 for (ActivityIntentInfo filter : a.intents) { 3202 if (hasValidDomains(filter)) { 3203 if (domains == null) { 3204 domains = new ArraySet<String>(); 3205 } 3206 domains.addAll(filter.getHostsList()); 3207 } 3208 } 3209 } 3210 3211 if (domains != null && domains.size() > 0) { 3212 if (DEBUG_DOMAIN_VERIFICATION) { 3213 Slog.v(TAG, " + " + packageName); 3214 } 3215 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3216 // state w.r.t. the formal app-linkage "no verification attempted" state; 3217 // and then 'always' in the per-user state actually used for intent resolution. 3218 final IntentFilterVerificationInfo ivi; 3219 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3220 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3221 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3222 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3223 } else { 3224 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3225 + "' does not handle web links"); 3226 } 3227 } else { 3228 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3229 } 3230 } 3231 3232 scheduleWritePackageRestrictionsLocked(userId); 3233 scheduleWriteSettingsLocked(); 3234 } 3235 3236 private void applyFactoryDefaultBrowserLPw(int userId) { 3237 // The default browser app's package name is stored in a string resource, 3238 // with a product-specific overlay used for vendor customization. 3239 String browserPkg = mContext.getResources().getString( 3240 com.android.internal.R.string.default_browser); 3241 if (!TextUtils.isEmpty(browserPkg)) { 3242 // non-empty string => required to be a known package 3243 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3244 if (ps == null) { 3245 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3246 browserPkg = null; 3247 } else { 3248 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3249 } 3250 } 3251 3252 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3253 // default. If there's more than one, just leave everything alone. 3254 if (browserPkg == null) { 3255 calculateDefaultBrowserLPw(userId); 3256 } 3257 } 3258 3259 private void calculateDefaultBrowserLPw(int userId) { 3260 List<String> allBrowsers = resolveAllBrowserApps(userId); 3261 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3262 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3263 } 3264 3265 private List<String> resolveAllBrowserApps(int userId) { 3266 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3267 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3268 PackageManager.MATCH_ALL, userId); 3269 3270 final int count = list.size(); 3271 List<String> result = new ArrayList<String>(count); 3272 for (int i=0; i<count; i++) { 3273 ResolveInfo info = list.get(i); 3274 if (info.activityInfo == null 3275 || !info.handleAllWebDataURI 3276 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3277 || result.contains(info.activityInfo.packageName)) { 3278 continue; 3279 } 3280 result.add(info.activityInfo.packageName); 3281 } 3282 3283 return result; 3284 } 3285 3286 private boolean packageIsBrowser(String packageName, int userId) { 3287 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3288 PackageManager.MATCH_ALL, userId); 3289 final int N = list.size(); 3290 for (int i = 0; i < N; i++) { 3291 ResolveInfo info = list.get(i); 3292 if (packageName.equals(info.activityInfo.packageName)) { 3293 return true; 3294 } 3295 } 3296 return false; 3297 } 3298 3299 private void checkDefaultBrowser() { 3300 final int myUserId = UserHandle.myUserId(); 3301 final String packageName = getDefaultBrowserPackageName(myUserId); 3302 if (packageName != null) { 3303 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3304 if (info == null) { 3305 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3306 synchronized (mPackages) { 3307 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3308 } 3309 } 3310 } 3311 } 3312 3313 @Override 3314 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3315 throws RemoteException { 3316 try { 3317 return super.onTransact(code, data, reply, flags); 3318 } catch (RuntimeException e) { 3319 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3320 Slog.wtf(TAG, "Package Manager Crash", e); 3321 } 3322 throw e; 3323 } 3324 } 3325 3326 static int[] appendInts(int[] cur, int[] add) { 3327 if (add == null) return cur; 3328 if (cur == null) return add; 3329 final int N = add.length; 3330 for (int i=0; i<N; i++) { 3331 cur = appendInt(cur, add[i]); 3332 } 3333 return cur; 3334 } 3335 3336 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3337 if (!sUserManager.exists(userId)) return null; 3338 if (ps == null) { 3339 return null; 3340 } 3341 final PackageParser.Package p = ps.pkg; 3342 if (p == null) { 3343 return null; 3344 } 3345 // Filter out ephemeral app metadata: 3346 // * The system/shell/root can see metadata for any app 3347 // * An installed app can see metadata for 1) other installed apps 3348 // and 2) ephemeral apps that have explicitly interacted with it 3349 // * Ephemeral apps can only see their own data and exposed installed apps 3350 // * Holding a signature permission allows seeing instant apps 3351 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3352 if (callingAppId != Process.SYSTEM_UID 3353 && callingAppId != Process.SHELL_UID 3354 && callingAppId != Process.ROOT_UID 3355 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3356 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3357 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3358 if (instantAppPackageName != null) { 3359 // ephemeral apps can only get information on themselves or 3360 // installed apps that are exposed. 3361 if (!instantAppPackageName.equals(p.packageName) 3362 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3363 return null; 3364 } 3365 } else { 3366 if (ps.getInstantApp(userId)) { 3367 // only get access to the ephemeral app if we've been granted access 3368 if (!mInstantAppRegistry.isInstantAccessGranted( 3369 userId, callingAppId, ps.appId)) { 3370 return null; 3371 } 3372 } 3373 } 3374 } 3375 3376 final PermissionsState permissionsState = ps.getPermissionsState(); 3377 3378 // Compute GIDs only if requested 3379 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3380 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3381 // Compute granted permissions only if package has requested permissions 3382 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3383 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3384 final PackageUserState state = ps.readUserState(userId); 3385 3386 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3387 && ps.isSystem()) { 3388 flags |= MATCH_ANY_USER; 3389 } 3390 3391 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3392 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3393 3394 if (packageInfo == null) { 3395 return null; 3396 } 3397 3398 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3399 3400 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3401 resolveExternalPackageNameLPr(p); 3402 3403 return packageInfo; 3404 } 3405 3406 @Override 3407 public void checkPackageStartable(String packageName, int userId) { 3408 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3409 3410 synchronized (mPackages) { 3411 final PackageSetting ps = mSettings.mPackages.get(packageName); 3412 if (ps == null) { 3413 throw new SecurityException("Package " + packageName + " was not found!"); 3414 } 3415 3416 if (!ps.getInstalled(userId)) { 3417 throw new SecurityException( 3418 "Package " + packageName + " was not installed for user " + userId + "!"); 3419 } 3420 3421 if (mSafeMode && !ps.isSystem()) { 3422 throw new SecurityException("Package " + packageName + " not a system app!"); 3423 } 3424 3425 if (mFrozenPackages.contains(packageName)) { 3426 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3427 } 3428 3429 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3430 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3431 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3432 } 3433 } 3434 } 3435 3436 @Override 3437 public boolean isPackageAvailable(String packageName, int userId) { 3438 if (!sUserManager.exists(userId)) return false; 3439 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3440 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3441 synchronized (mPackages) { 3442 PackageParser.Package p = mPackages.get(packageName); 3443 if (p != null) { 3444 final PackageSetting ps = (PackageSetting) p.mExtras; 3445 if (ps != null) { 3446 final PackageUserState state = ps.readUserState(userId); 3447 if (state != null) { 3448 return PackageParser.isAvailable(state); 3449 } 3450 } 3451 } 3452 } 3453 return false; 3454 } 3455 3456 @Override 3457 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3458 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3459 flags, userId); 3460 } 3461 3462 @Override 3463 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3464 int flags, int userId) { 3465 return getPackageInfoInternal(versionedPackage.getPackageName(), 3466 // TODO: We will change version code to long, so in the new API it is long 3467 (int) versionedPackage.getVersionCode(), flags, userId); 3468 } 3469 3470 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3471 int flags, int userId) { 3472 if (!sUserManager.exists(userId)) return null; 3473 flags = updateFlagsForPackage(flags, userId, packageName); 3474 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3475 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3476 3477 // reader 3478 synchronized (mPackages) { 3479 // Normalize package name to handle renamed packages and static libs 3480 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3481 3482 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3483 if (matchFactoryOnly) { 3484 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3485 if (ps != null) { 3486 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3487 return null; 3488 } 3489 return generatePackageInfo(ps, flags, userId); 3490 } 3491 } 3492 3493 PackageParser.Package p = mPackages.get(packageName); 3494 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3495 return null; 3496 } 3497 if (DEBUG_PACKAGE_INFO) 3498 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3499 if (p != null) { 3500 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3501 Binder.getCallingUid(), userId)) { 3502 return null; 3503 } 3504 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3505 } 3506 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3507 final PackageSetting ps = mSettings.mPackages.get(packageName); 3508 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3509 return null; 3510 } 3511 return generatePackageInfo(ps, flags, userId); 3512 } 3513 } 3514 return null; 3515 } 3516 3517 3518 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3519 // System/shell/root get to see all static libs 3520 final int appId = UserHandle.getAppId(uid); 3521 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3522 || appId == Process.ROOT_UID) { 3523 return false; 3524 } 3525 3526 // No package means no static lib as it is always on internal storage 3527 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3528 return false; 3529 } 3530 3531 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3532 ps.pkg.staticSharedLibVersion); 3533 if (libEntry == null) { 3534 return false; 3535 } 3536 3537 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3538 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3539 if (uidPackageNames == null) { 3540 return true; 3541 } 3542 3543 for (String uidPackageName : uidPackageNames) { 3544 if (ps.name.equals(uidPackageName)) { 3545 return false; 3546 } 3547 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3548 if (uidPs != null) { 3549 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3550 libEntry.info.getName()); 3551 if (index < 0) { 3552 continue; 3553 } 3554 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3555 return false; 3556 } 3557 } 3558 } 3559 return true; 3560 } 3561 3562 @Override 3563 public String[] currentToCanonicalPackageNames(String[] names) { 3564 String[] out = new String[names.length]; 3565 // reader 3566 synchronized (mPackages) { 3567 for (int i=names.length-1; i>=0; i--) { 3568 PackageSetting ps = mSettings.mPackages.get(names[i]); 3569 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3570 } 3571 } 3572 return out; 3573 } 3574 3575 @Override 3576 public String[] canonicalToCurrentPackageNames(String[] names) { 3577 String[] out = new String[names.length]; 3578 // reader 3579 synchronized (mPackages) { 3580 for (int i=names.length-1; i>=0; i--) { 3581 String cur = mSettings.getRenamedPackageLPr(names[i]); 3582 out[i] = cur != null ? cur : names[i]; 3583 } 3584 } 3585 return out; 3586 } 3587 3588 @Override 3589 public int getPackageUid(String packageName, int flags, int userId) { 3590 if (!sUserManager.exists(userId)) return -1; 3591 flags = updateFlagsForPackage(flags, userId, packageName); 3592 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3593 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3594 3595 // reader 3596 synchronized (mPackages) { 3597 final PackageParser.Package p = mPackages.get(packageName); 3598 if (p != null && p.isMatch(flags)) { 3599 return UserHandle.getUid(userId, p.applicationInfo.uid); 3600 } 3601 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3602 final PackageSetting ps = mSettings.mPackages.get(packageName); 3603 if (ps != null && ps.isMatch(flags)) { 3604 return UserHandle.getUid(userId, ps.appId); 3605 } 3606 } 3607 } 3608 3609 return -1; 3610 } 3611 3612 @Override 3613 public int[] getPackageGids(String packageName, int flags, int userId) { 3614 if (!sUserManager.exists(userId)) return null; 3615 flags = updateFlagsForPackage(flags, userId, packageName); 3616 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3617 false /* requireFullPermission */, false /* checkShell */, 3618 "getPackageGids"); 3619 3620 // reader 3621 synchronized (mPackages) { 3622 final PackageParser.Package p = mPackages.get(packageName); 3623 if (p != null && p.isMatch(flags)) { 3624 PackageSetting ps = (PackageSetting) p.mExtras; 3625 // TODO: Shouldn't this be checking for package installed state for userId and 3626 // return null? 3627 return ps.getPermissionsState().computeGids(userId); 3628 } 3629 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3630 final PackageSetting ps = mSettings.mPackages.get(packageName); 3631 if (ps != null && ps.isMatch(flags)) { 3632 return ps.getPermissionsState().computeGids(userId); 3633 } 3634 } 3635 } 3636 3637 return null; 3638 } 3639 3640 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3641 if (bp.perm != null) { 3642 return PackageParser.generatePermissionInfo(bp.perm, flags); 3643 } 3644 PermissionInfo pi = new PermissionInfo(); 3645 pi.name = bp.name; 3646 pi.packageName = bp.sourcePackage; 3647 pi.nonLocalizedLabel = bp.name; 3648 pi.protectionLevel = bp.protectionLevel; 3649 return pi; 3650 } 3651 3652 @Override 3653 public PermissionInfo getPermissionInfo(String name, int flags) { 3654 // reader 3655 synchronized (mPackages) { 3656 final BasePermission p = mSettings.mPermissions.get(name); 3657 if (p != null) { 3658 return generatePermissionInfo(p, flags); 3659 } 3660 return null; 3661 } 3662 } 3663 3664 @Override 3665 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3666 int flags) { 3667 // reader 3668 synchronized (mPackages) { 3669 if (group != null && !mPermissionGroups.containsKey(group)) { 3670 // This is thrown as NameNotFoundException 3671 return null; 3672 } 3673 3674 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3675 for (BasePermission p : mSettings.mPermissions.values()) { 3676 if (group == null) { 3677 if (p.perm == null || p.perm.info.group == null) { 3678 out.add(generatePermissionInfo(p, flags)); 3679 } 3680 } else { 3681 if (p.perm != null && group.equals(p.perm.info.group)) { 3682 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3683 } 3684 } 3685 } 3686 return new ParceledListSlice<>(out); 3687 } 3688 } 3689 3690 @Override 3691 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3692 // reader 3693 synchronized (mPackages) { 3694 return PackageParser.generatePermissionGroupInfo( 3695 mPermissionGroups.get(name), flags); 3696 } 3697 } 3698 3699 @Override 3700 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3701 // reader 3702 synchronized (mPackages) { 3703 final int N = mPermissionGroups.size(); 3704 ArrayList<PermissionGroupInfo> out 3705 = new ArrayList<PermissionGroupInfo>(N); 3706 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3707 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3708 } 3709 return new ParceledListSlice<>(out); 3710 } 3711 } 3712 3713 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3714 int uid, int userId) { 3715 if (!sUserManager.exists(userId)) return null; 3716 PackageSetting ps = mSettings.mPackages.get(packageName); 3717 if (ps != null) { 3718 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3719 return null; 3720 } 3721 if (ps.pkg == null) { 3722 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3723 if (pInfo != null) { 3724 return pInfo.applicationInfo; 3725 } 3726 return null; 3727 } 3728 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3729 ps.readUserState(userId), userId); 3730 if (ai != null) { 3731 rebaseEnabledOverlays(ai, userId); 3732 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3733 } 3734 return ai; 3735 } 3736 return null; 3737 } 3738 3739 @Override 3740 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3741 if (!sUserManager.exists(userId)) return null; 3742 flags = updateFlagsForApplication(flags, userId, packageName); 3743 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3744 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3745 3746 // writer 3747 synchronized (mPackages) { 3748 // Normalize package name to handle renamed packages and static libs 3749 packageName = resolveInternalPackageNameLPr(packageName, 3750 PackageManager.VERSION_CODE_HIGHEST); 3751 3752 PackageParser.Package p = mPackages.get(packageName); 3753 if (DEBUG_PACKAGE_INFO) Log.v( 3754 TAG, "getApplicationInfo " + packageName 3755 + ": " + p); 3756 if (p != null) { 3757 PackageSetting ps = mSettings.mPackages.get(packageName); 3758 if (ps == null) return null; 3759 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3760 return null; 3761 } 3762 // Note: isEnabledLP() does not apply here - always return info 3763 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3764 p, flags, ps.readUserState(userId), userId); 3765 if (ai != null) { 3766 rebaseEnabledOverlays(ai, userId); 3767 ai.packageName = resolveExternalPackageNameLPr(p); 3768 } 3769 return ai; 3770 } 3771 if ("android".equals(packageName)||"system".equals(packageName)) { 3772 return mAndroidApplication; 3773 } 3774 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3775 // Already generates the external package name 3776 return generateApplicationInfoFromSettingsLPw(packageName, 3777 Binder.getCallingUid(), flags, userId); 3778 } 3779 } 3780 return null; 3781 } 3782 3783 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3784 List<String> paths = new ArrayList<>(); 3785 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3786 mEnabledOverlayPaths.get(userId); 3787 if (userSpecificOverlays != null) { 3788 if (!"android".equals(ai.packageName)) { 3789 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3790 if (frameworkOverlays != null) { 3791 paths.addAll(frameworkOverlays); 3792 } 3793 } 3794 3795 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3796 if (appOverlays != null) { 3797 paths.addAll(appOverlays); 3798 } 3799 } 3800 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3801 } 3802 3803 private String normalizePackageNameLPr(String packageName) { 3804 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3805 return normalizedPackageName != null ? normalizedPackageName : packageName; 3806 } 3807 3808 @Override 3809 public void deletePreloadsFileCache() { 3810 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3811 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3812 } 3813 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3814 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3815 FileUtils.deleteContents(dir); 3816 } 3817 3818 @Override 3819 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3820 final IPackageDataObserver observer) { 3821 mContext.enforceCallingOrSelfPermission( 3822 android.Manifest.permission.CLEAR_APP_CACHE, null); 3823 mHandler.post(() -> { 3824 boolean success = false; 3825 try { 3826 freeStorage(volumeUuid, freeStorageSize, 0); 3827 success = true; 3828 } catch (IOException e) { 3829 Slog.w(TAG, e); 3830 } 3831 if (observer != null) { 3832 try { 3833 observer.onRemoveCompleted(null, success); 3834 } catch (RemoteException e) { 3835 Slog.w(TAG, e); 3836 } 3837 } 3838 }); 3839 } 3840 3841 @Override 3842 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3843 final IntentSender pi) { 3844 mContext.enforceCallingOrSelfPermission( 3845 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3846 mHandler.post(() -> { 3847 boolean success = false; 3848 try { 3849 freeStorage(volumeUuid, freeStorageSize, 0); 3850 success = true; 3851 } catch (IOException e) { 3852 Slog.w(TAG, e); 3853 } 3854 if (pi != null) { 3855 try { 3856 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3857 } catch (SendIntentException e) { 3858 Slog.w(TAG, e); 3859 } 3860 } 3861 }); 3862 } 3863 3864 /** 3865 * Blocking call to clear various types of cached data across the system 3866 * until the requested bytes are available. 3867 */ 3868 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3869 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3870 final File file = storage.findPathForUuid(volumeUuid); 3871 if (file.getUsableSpace() >= bytes) return; 3872 3873 if (ENABLE_FREE_CACHE_V2) { 3874 final boolean aggressive = (storageFlags 3875 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3876 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3877 volumeUuid); 3878 3879 // 1. Pre-flight to determine if we have any chance to succeed 3880 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3881 if (internalVolume && (aggressive || SystemProperties 3882 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3883 deletePreloadsFileCache(); 3884 if (file.getUsableSpace() >= bytes) return; 3885 } 3886 3887 // 3. Consider parsed APK data (aggressive only) 3888 if (internalVolume && aggressive) { 3889 FileUtils.deleteContents(mCacheDir); 3890 if (file.getUsableSpace() >= bytes) return; 3891 } 3892 3893 // 4. Consider cached app data (above quotas) 3894 try { 3895 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3896 } catch (InstallerException ignored) { 3897 } 3898 if (file.getUsableSpace() >= bytes) return; 3899 3900 // 5. Consider shared libraries with refcount=0 and age>2h 3901 // 6. Consider dexopt output (aggressive only) 3902 // 7. Consider ephemeral apps not used in last week 3903 3904 // 8. Consider cached app data (below quotas) 3905 try { 3906 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3907 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3908 } catch (InstallerException ignored) { 3909 } 3910 if (file.getUsableSpace() >= bytes) return; 3911 3912 // 9. Consider DropBox entries 3913 // 10. Consider ephemeral cookies 3914 3915 } else { 3916 try { 3917 mInstaller.freeCache(volumeUuid, bytes, 0); 3918 } catch (InstallerException ignored) { 3919 } 3920 if (file.getUsableSpace() >= bytes) return; 3921 } 3922 3923 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3924 } 3925 3926 /** 3927 * Update given flags based on encryption status of current user. 3928 */ 3929 private int updateFlags(int flags, int userId) { 3930 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3931 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3932 // Caller expressed an explicit opinion about what encryption 3933 // aware/unaware components they want to see, so fall through and 3934 // give them what they want 3935 } else { 3936 // Caller expressed no opinion, so match based on user state 3937 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3938 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3939 } else { 3940 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3941 } 3942 } 3943 return flags; 3944 } 3945 3946 private UserManagerInternal getUserManagerInternal() { 3947 if (mUserManagerInternal == null) { 3948 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3949 } 3950 return mUserManagerInternal; 3951 } 3952 3953 private DeviceIdleController.LocalService getDeviceIdleController() { 3954 if (mDeviceIdleController == null) { 3955 mDeviceIdleController = 3956 LocalServices.getService(DeviceIdleController.LocalService.class); 3957 } 3958 return mDeviceIdleController; 3959 } 3960 3961 /** 3962 * Update given flags when being used to request {@link PackageInfo}. 3963 */ 3964 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3965 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3966 boolean triaged = true; 3967 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3968 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3969 // Caller is asking for component details, so they'd better be 3970 // asking for specific encryption matching behavior, or be triaged 3971 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3972 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3973 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3974 triaged = false; 3975 } 3976 } 3977 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3978 | PackageManager.MATCH_SYSTEM_ONLY 3979 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3980 triaged = false; 3981 } 3982 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3984 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3985 + Debug.getCallers(5)); 3986 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3987 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3988 // If the caller wants all packages and has a restricted profile associated with it, 3989 // then match all users. This is to make sure that launchers that need to access work 3990 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3991 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3992 flags |= PackageManager.MATCH_ANY_USER; 3993 } 3994 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3995 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3996 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3997 } 3998 return updateFlags(flags, userId); 3999 } 4000 4001 /** 4002 * Update given flags when being used to request {@link ApplicationInfo}. 4003 */ 4004 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4005 return updateFlagsForPackage(flags, userId, cookie); 4006 } 4007 4008 /** 4009 * Update given flags when being used to request {@link ComponentInfo}. 4010 */ 4011 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4012 if (cookie instanceof Intent) { 4013 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4014 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4015 } 4016 } 4017 4018 boolean triaged = true; 4019 // Caller is asking for component details, so they'd better be 4020 // asking for specific encryption matching behavior, or be triaged 4021 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4022 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4023 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4024 triaged = false; 4025 } 4026 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4027 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4028 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4029 } 4030 4031 return updateFlags(flags, userId); 4032 } 4033 4034 /** 4035 * Update given intent when being used to request {@link ResolveInfo}. 4036 */ 4037 private Intent updateIntentForResolve(Intent intent) { 4038 if (intent.getSelector() != null) { 4039 intent = intent.getSelector(); 4040 } 4041 if (DEBUG_PREFERRED) { 4042 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4043 } 4044 return intent; 4045 } 4046 4047 /** 4048 * Update given flags when being used to request {@link ResolveInfo}. 4049 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4050 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4051 * flag set. However, this flag is only honoured in three circumstances: 4052 * <ul> 4053 * <li>when called from a system process</li> 4054 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4055 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4056 * action and a {@code android.intent.category.BROWSABLE} category</li> 4057 * </ul> 4058 */ 4059 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4060 boolean includeInstantApps) { 4061 // Safe mode means we shouldn't match any third-party components 4062 if (mSafeMode) { 4063 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4064 } 4065 if (getInstantAppPackageName(callingUid) != null) { 4066 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4067 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4068 flags |= PackageManager.MATCH_INSTANT; 4069 } else { 4070 // Otherwise, prevent leaking ephemeral components 4071 final boolean isSpecialProcess = 4072 callingUid == Process.SYSTEM_UID 4073 || callingUid == Process.SHELL_UID 4074 || callingUid == 0; 4075 final boolean allowMatchInstant = 4076 (includeInstantApps 4077 && Intent.ACTION_VIEW.equals(intent.getAction()) 4078 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4079 && hasWebURI(intent)) 4080 || isSpecialProcess 4081 || mContext.checkCallingOrSelfPermission( 4082 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4083 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4084 if (!allowMatchInstant) { 4085 flags &= ~PackageManager.MATCH_INSTANT; 4086 } 4087 } 4088 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4089 } 4090 4091 @Override 4092 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4093 if (!sUserManager.exists(userId)) return null; 4094 flags = updateFlagsForComponent(flags, userId, component); 4095 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4096 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4097 synchronized (mPackages) { 4098 PackageParser.Activity a = mActivities.mActivities.get(component); 4099 4100 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4101 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4102 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4103 if (ps == null) return null; 4104 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4105 userId); 4106 } 4107 if (mResolveComponentName.equals(component)) { 4108 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4109 new PackageUserState(), userId); 4110 } 4111 } 4112 return null; 4113 } 4114 4115 @Override 4116 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4117 String resolvedType) { 4118 synchronized (mPackages) { 4119 if (component.equals(mResolveComponentName)) { 4120 // The resolver supports EVERYTHING! 4121 return true; 4122 } 4123 PackageParser.Activity a = mActivities.mActivities.get(component); 4124 if (a == null) { 4125 return false; 4126 } 4127 for (int i=0; i<a.intents.size(); i++) { 4128 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4129 intent.getData(), intent.getCategories(), TAG) >= 0) { 4130 return true; 4131 } 4132 } 4133 return false; 4134 } 4135 } 4136 4137 @Override 4138 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4139 if (!sUserManager.exists(userId)) return null; 4140 flags = updateFlagsForComponent(flags, userId, component); 4141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4142 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4143 synchronized (mPackages) { 4144 PackageParser.Activity a = mReceivers.mActivities.get(component); 4145 if (DEBUG_PACKAGE_INFO) Log.v( 4146 TAG, "getReceiverInfo " + component + ": " + a); 4147 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4148 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4149 if (ps == null) return null; 4150 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4151 ps.readUserState(userId), userId); 4152 if (ri != null) { 4153 rebaseEnabledOverlays(ri.applicationInfo, userId); 4154 } 4155 return ri; 4156 } 4157 } 4158 return null; 4159 } 4160 4161 @Override 4162 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4163 if (!sUserManager.exists(userId)) return null; 4164 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4165 4166 flags = updateFlagsForPackage(flags, userId, null); 4167 4168 final boolean canSeeStaticLibraries = 4169 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4170 == PERMISSION_GRANTED 4171 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4172 == PERMISSION_GRANTED 4173 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4174 == PERMISSION_GRANTED 4175 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4176 == PERMISSION_GRANTED; 4177 4178 synchronized (mPackages) { 4179 List<SharedLibraryInfo> result = null; 4180 4181 final int libCount = mSharedLibraries.size(); 4182 for (int i = 0; i < libCount; i++) { 4183 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4184 if (versionedLib == null) { 4185 continue; 4186 } 4187 4188 final int versionCount = versionedLib.size(); 4189 for (int j = 0; j < versionCount; j++) { 4190 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4191 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4192 break; 4193 } 4194 final long identity = Binder.clearCallingIdentity(); 4195 try { 4196 // TODO: We will change version code to long, so in the new API it is long 4197 PackageInfo packageInfo = getPackageInfoVersioned( 4198 libInfo.getDeclaringPackage(), flags, userId); 4199 if (packageInfo == null) { 4200 continue; 4201 } 4202 } finally { 4203 Binder.restoreCallingIdentity(identity); 4204 } 4205 4206 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4207 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4208 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4209 4210 if (result == null) { 4211 result = new ArrayList<>(); 4212 } 4213 result.add(resLibInfo); 4214 } 4215 } 4216 4217 return result != null ? new ParceledListSlice<>(result) : null; 4218 } 4219 } 4220 4221 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4222 SharedLibraryInfo libInfo, int flags, int userId) { 4223 List<VersionedPackage> versionedPackages = null; 4224 final int packageCount = mSettings.mPackages.size(); 4225 for (int i = 0; i < packageCount; i++) { 4226 PackageSetting ps = mSettings.mPackages.valueAt(i); 4227 4228 if (ps == null) { 4229 continue; 4230 } 4231 4232 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4233 continue; 4234 } 4235 4236 final String libName = libInfo.getName(); 4237 if (libInfo.isStatic()) { 4238 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4239 if (libIdx < 0) { 4240 continue; 4241 } 4242 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4243 continue; 4244 } 4245 if (versionedPackages == null) { 4246 versionedPackages = new ArrayList<>(); 4247 } 4248 // If the dependent is a static shared lib, use the public package name 4249 String dependentPackageName = ps.name; 4250 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4251 dependentPackageName = ps.pkg.manifestPackageName; 4252 } 4253 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4254 } else if (ps.pkg != null) { 4255 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4256 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4257 if (versionedPackages == null) { 4258 versionedPackages = new ArrayList<>(); 4259 } 4260 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4261 } 4262 } 4263 } 4264 4265 return versionedPackages; 4266 } 4267 4268 @Override 4269 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4270 if (!sUserManager.exists(userId)) return null; 4271 flags = updateFlagsForComponent(flags, userId, component); 4272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4273 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4274 synchronized (mPackages) { 4275 PackageParser.Service s = mServices.mServices.get(component); 4276 if (DEBUG_PACKAGE_INFO) Log.v( 4277 TAG, "getServiceInfo " + component + ": " + s); 4278 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4279 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4280 if (ps == null) return null; 4281 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4282 ps.readUserState(userId), userId); 4283 if (si != null) { 4284 rebaseEnabledOverlays(si.applicationInfo, userId); 4285 } 4286 return si; 4287 } 4288 } 4289 return null; 4290 } 4291 4292 @Override 4293 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4294 if (!sUserManager.exists(userId)) return null; 4295 flags = updateFlagsForComponent(flags, userId, component); 4296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4297 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4298 synchronized (mPackages) { 4299 PackageParser.Provider p = mProviders.mProviders.get(component); 4300 if (DEBUG_PACKAGE_INFO) Log.v( 4301 TAG, "getProviderInfo " + component + ": " + p); 4302 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4303 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4304 if (ps == null) return null; 4305 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4306 ps.readUserState(userId), userId); 4307 if (pi != null) { 4308 rebaseEnabledOverlays(pi.applicationInfo, userId); 4309 } 4310 return pi; 4311 } 4312 } 4313 return null; 4314 } 4315 4316 @Override 4317 public String[] getSystemSharedLibraryNames() { 4318 synchronized (mPackages) { 4319 Set<String> libs = null; 4320 final int libCount = mSharedLibraries.size(); 4321 for (int i = 0; i < libCount; i++) { 4322 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4323 if (versionedLib == null) { 4324 continue; 4325 } 4326 final int versionCount = versionedLib.size(); 4327 for (int j = 0; j < versionCount; j++) { 4328 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4329 if (!libEntry.info.isStatic()) { 4330 if (libs == null) { 4331 libs = new ArraySet<>(); 4332 } 4333 libs.add(libEntry.info.getName()); 4334 break; 4335 } 4336 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4337 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4338 UserHandle.getUserId(Binder.getCallingUid()))) { 4339 if (libs == null) { 4340 libs = new ArraySet<>(); 4341 } 4342 libs.add(libEntry.info.getName()); 4343 break; 4344 } 4345 } 4346 } 4347 4348 if (libs != null) { 4349 String[] libsArray = new String[libs.size()]; 4350 libs.toArray(libsArray); 4351 return libsArray; 4352 } 4353 4354 return null; 4355 } 4356 } 4357 4358 @Override 4359 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4360 synchronized (mPackages) { 4361 return mServicesSystemSharedLibraryPackageName; 4362 } 4363 } 4364 4365 @Override 4366 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4367 synchronized (mPackages) { 4368 return mSharedSystemSharedLibraryPackageName; 4369 } 4370 } 4371 4372 private void updateSequenceNumberLP(String packageName, int[] userList) { 4373 for (int i = userList.length - 1; i >= 0; --i) { 4374 final int userId = userList[i]; 4375 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4376 if (changedPackages == null) { 4377 changedPackages = new SparseArray<>(); 4378 mChangedPackages.put(userId, changedPackages); 4379 } 4380 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4381 if (sequenceNumbers == null) { 4382 sequenceNumbers = new HashMap<>(); 4383 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4384 } 4385 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4386 if (sequenceNumber != null) { 4387 changedPackages.remove(sequenceNumber); 4388 } 4389 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4390 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4391 } 4392 mChangedPackagesSequenceNumber++; 4393 } 4394 4395 @Override 4396 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4397 synchronized (mPackages) { 4398 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4399 return null; 4400 } 4401 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4402 if (changedPackages == null) { 4403 return null; 4404 } 4405 final List<String> packageNames = 4406 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4407 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4408 final String packageName = changedPackages.get(i); 4409 if (packageName != null) { 4410 packageNames.add(packageName); 4411 } 4412 } 4413 return packageNames.isEmpty() 4414 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4415 } 4416 } 4417 4418 @Override 4419 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4420 ArrayList<FeatureInfo> res; 4421 synchronized (mAvailableFeatures) { 4422 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4423 res.addAll(mAvailableFeatures.values()); 4424 } 4425 final FeatureInfo fi = new FeatureInfo(); 4426 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4427 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4428 res.add(fi); 4429 4430 return new ParceledListSlice<>(res); 4431 } 4432 4433 @Override 4434 public boolean hasSystemFeature(String name, int version) { 4435 synchronized (mAvailableFeatures) { 4436 final FeatureInfo feat = mAvailableFeatures.get(name); 4437 if (feat == null) { 4438 return false; 4439 } else { 4440 return feat.version >= version; 4441 } 4442 } 4443 } 4444 4445 @Override 4446 public int checkPermission(String permName, String pkgName, int userId) { 4447 if (!sUserManager.exists(userId)) { 4448 return PackageManager.PERMISSION_DENIED; 4449 } 4450 4451 synchronized (mPackages) { 4452 final PackageParser.Package p = mPackages.get(pkgName); 4453 if (p != null && p.mExtras != null) { 4454 final PackageSetting ps = (PackageSetting) p.mExtras; 4455 final PermissionsState permissionsState = ps.getPermissionsState(); 4456 if (permissionsState.hasPermission(permName, userId)) { 4457 return PackageManager.PERMISSION_GRANTED; 4458 } 4459 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4460 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4461 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4462 return PackageManager.PERMISSION_GRANTED; 4463 } 4464 } 4465 } 4466 4467 return PackageManager.PERMISSION_DENIED; 4468 } 4469 4470 @Override 4471 public int checkUidPermission(String permName, int uid) { 4472 final int userId = UserHandle.getUserId(uid); 4473 4474 if (!sUserManager.exists(userId)) { 4475 return PackageManager.PERMISSION_DENIED; 4476 } 4477 4478 synchronized (mPackages) { 4479 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4480 if (obj != null) { 4481 final SettingBase ps = (SettingBase) obj; 4482 final PermissionsState permissionsState = ps.getPermissionsState(); 4483 if (permissionsState.hasPermission(permName, userId)) { 4484 return PackageManager.PERMISSION_GRANTED; 4485 } 4486 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4487 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4488 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4489 return PackageManager.PERMISSION_GRANTED; 4490 } 4491 } else { 4492 ArraySet<String> perms = mSystemPermissions.get(uid); 4493 if (perms != null) { 4494 if (perms.contains(permName)) { 4495 return PackageManager.PERMISSION_GRANTED; 4496 } 4497 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4498 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4499 return PackageManager.PERMISSION_GRANTED; 4500 } 4501 } 4502 } 4503 } 4504 4505 return PackageManager.PERMISSION_DENIED; 4506 } 4507 4508 @Override 4509 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4510 if (UserHandle.getCallingUserId() != userId) { 4511 mContext.enforceCallingPermission( 4512 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4513 "isPermissionRevokedByPolicy for user " + userId); 4514 } 4515 4516 if (checkPermission(permission, packageName, userId) 4517 == PackageManager.PERMISSION_GRANTED) { 4518 return false; 4519 } 4520 4521 final long identity = Binder.clearCallingIdentity(); 4522 try { 4523 final int flags = getPermissionFlags(permission, packageName, userId); 4524 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4525 } finally { 4526 Binder.restoreCallingIdentity(identity); 4527 } 4528 } 4529 4530 @Override 4531 public String getPermissionControllerPackageName() { 4532 synchronized (mPackages) { 4533 return mRequiredInstallerPackage; 4534 } 4535 } 4536 4537 /** 4538 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4539 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4540 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4541 * @param message the message to log on security exception 4542 */ 4543 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4544 boolean checkShell, String message) { 4545 if (userId < 0) { 4546 throw new IllegalArgumentException("Invalid userId " + userId); 4547 } 4548 if (checkShell) { 4549 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4550 } 4551 if (userId == UserHandle.getUserId(callingUid)) return; 4552 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4553 if (requireFullPermission) { 4554 mContext.enforceCallingOrSelfPermission( 4555 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4556 } else { 4557 try { 4558 mContext.enforceCallingOrSelfPermission( 4559 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4560 } catch (SecurityException se) { 4561 mContext.enforceCallingOrSelfPermission( 4562 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4563 } 4564 } 4565 } 4566 } 4567 4568 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4569 if (callingUid == Process.SHELL_UID) { 4570 if (userHandle >= 0 4571 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4572 throw new SecurityException("Shell does not have permission to access user " 4573 + userHandle); 4574 } else if (userHandle < 0) { 4575 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4576 + Debug.getCallers(3)); 4577 } 4578 } 4579 } 4580 4581 private BasePermission findPermissionTreeLP(String permName) { 4582 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4583 if (permName.startsWith(bp.name) && 4584 permName.length() > bp.name.length() && 4585 permName.charAt(bp.name.length()) == '.') { 4586 return bp; 4587 } 4588 } 4589 return null; 4590 } 4591 4592 private BasePermission checkPermissionTreeLP(String permName) { 4593 if (permName != null) { 4594 BasePermission bp = findPermissionTreeLP(permName); 4595 if (bp != null) { 4596 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4597 return bp; 4598 } 4599 throw new SecurityException("Calling uid " 4600 + Binder.getCallingUid() 4601 + " is not allowed to add to permission tree " 4602 + bp.name + " owned by uid " + bp.uid); 4603 } 4604 } 4605 throw new SecurityException("No permission tree found for " + permName); 4606 } 4607 4608 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4609 if (s1 == null) { 4610 return s2 == null; 4611 } 4612 if (s2 == null) { 4613 return false; 4614 } 4615 if (s1.getClass() != s2.getClass()) { 4616 return false; 4617 } 4618 return s1.equals(s2); 4619 } 4620 4621 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4622 if (pi1.icon != pi2.icon) return false; 4623 if (pi1.logo != pi2.logo) return false; 4624 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4625 if (!compareStrings(pi1.name, pi2.name)) return false; 4626 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4627 // We'll take care of setting this one. 4628 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4629 // These are not currently stored in settings. 4630 //if (!compareStrings(pi1.group, pi2.group)) return false; 4631 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4632 //if (pi1.labelRes != pi2.labelRes) return false; 4633 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4634 return true; 4635 } 4636 4637 int permissionInfoFootprint(PermissionInfo info) { 4638 int size = info.name.length(); 4639 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4640 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4641 return size; 4642 } 4643 4644 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4645 int size = 0; 4646 for (BasePermission perm : mSettings.mPermissions.values()) { 4647 if (perm.uid == tree.uid) { 4648 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4649 } 4650 } 4651 return size; 4652 } 4653 4654 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4655 // We calculate the max size of permissions defined by this uid and throw 4656 // if that plus the size of 'info' would exceed our stated maximum. 4657 if (tree.uid != Process.SYSTEM_UID) { 4658 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4659 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4660 throw new SecurityException("Permission tree size cap exceeded"); 4661 } 4662 } 4663 } 4664 4665 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4666 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4667 throw new SecurityException("Label must be specified in permission"); 4668 } 4669 BasePermission tree = checkPermissionTreeLP(info.name); 4670 BasePermission bp = mSettings.mPermissions.get(info.name); 4671 boolean added = bp == null; 4672 boolean changed = true; 4673 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4674 if (added) { 4675 enforcePermissionCapLocked(info, tree); 4676 bp = new BasePermission(info.name, tree.sourcePackage, 4677 BasePermission.TYPE_DYNAMIC); 4678 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4679 throw new SecurityException( 4680 "Not allowed to modify non-dynamic permission " 4681 + info.name); 4682 } else { 4683 if (bp.protectionLevel == fixedLevel 4684 && bp.perm.owner.equals(tree.perm.owner) 4685 && bp.uid == tree.uid 4686 && comparePermissionInfos(bp.perm.info, info)) { 4687 changed = false; 4688 } 4689 } 4690 bp.protectionLevel = fixedLevel; 4691 info = new PermissionInfo(info); 4692 info.protectionLevel = fixedLevel; 4693 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4694 bp.perm.info.packageName = tree.perm.info.packageName; 4695 bp.uid = tree.uid; 4696 if (added) { 4697 mSettings.mPermissions.put(info.name, bp); 4698 } 4699 if (changed) { 4700 if (!async) { 4701 mSettings.writeLPr(); 4702 } else { 4703 scheduleWriteSettingsLocked(); 4704 } 4705 } 4706 return added; 4707 } 4708 4709 @Override 4710 public boolean addPermission(PermissionInfo info) { 4711 synchronized (mPackages) { 4712 return addPermissionLocked(info, false); 4713 } 4714 } 4715 4716 @Override 4717 public boolean addPermissionAsync(PermissionInfo info) { 4718 synchronized (mPackages) { 4719 return addPermissionLocked(info, true); 4720 } 4721 } 4722 4723 @Override 4724 public void removePermission(String name) { 4725 synchronized (mPackages) { 4726 checkPermissionTreeLP(name); 4727 BasePermission bp = mSettings.mPermissions.get(name); 4728 if (bp != null) { 4729 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4730 throw new SecurityException( 4731 "Not allowed to modify non-dynamic permission " 4732 + name); 4733 } 4734 mSettings.mPermissions.remove(name); 4735 mSettings.writeLPr(); 4736 } 4737 } 4738 } 4739 4740 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4741 BasePermission bp) { 4742 int index = pkg.requestedPermissions.indexOf(bp.name); 4743 if (index == -1) { 4744 throw new SecurityException("Package " + pkg.packageName 4745 + " has not requested permission " + bp.name); 4746 } 4747 if (!bp.isRuntime() && !bp.isDevelopment()) { 4748 throw new SecurityException("Permission " + bp.name 4749 + " is not a changeable permission type"); 4750 } 4751 } 4752 4753 @Override 4754 public void grantRuntimePermission(String packageName, String name, final int userId) { 4755 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4756 } 4757 4758 private void grantRuntimePermission(String packageName, String name, final int userId, 4759 boolean overridePolicy) { 4760 if (!sUserManager.exists(userId)) { 4761 Log.e(TAG, "No such user:" + userId); 4762 return; 4763 } 4764 4765 mContext.enforceCallingOrSelfPermission( 4766 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4767 "grantRuntimePermission"); 4768 4769 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4770 true /* requireFullPermission */, true /* checkShell */, 4771 "grantRuntimePermission"); 4772 4773 final int uid; 4774 final SettingBase sb; 4775 4776 synchronized (mPackages) { 4777 final PackageParser.Package pkg = mPackages.get(packageName); 4778 if (pkg == null) { 4779 throw new IllegalArgumentException("Unknown package: " + packageName); 4780 } 4781 4782 final BasePermission bp = mSettings.mPermissions.get(name); 4783 if (bp == null) { 4784 throw new IllegalArgumentException("Unknown permission: " + name); 4785 } 4786 4787 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4788 4789 // If a permission review is required for legacy apps we represent 4790 // their permissions as always granted runtime ones since we need 4791 // to keep the review required permission flag per user while an 4792 // install permission's state is shared across all users. 4793 if (mPermissionReviewRequired 4794 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4795 && bp.isRuntime()) { 4796 return; 4797 } 4798 4799 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4800 sb = (SettingBase) pkg.mExtras; 4801 if (sb == null) { 4802 throw new IllegalArgumentException("Unknown package: " + packageName); 4803 } 4804 4805 final PermissionsState permissionsState = sb.getPermissionsState(); 4806 4807 final int flags = permissionsState.getPermissionFlags(name, userId); 4808 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4809 throw new SecurityException("Cannot grant system fixed permission " 4810 + name + " for package " + packageName); 4811 } 4812 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4813 throw new SecurityException("Cannot grant policy fixed permission " 4814 + name + " for package " + packageName); 4815 } 4816 4817 if (bp.isDevelopment()) { 4818 // Development permissions must be handled specially, since they are not 4819 // normal runtime permissions. For now they apply to all users. 4820 if (permissionsState.grantInstallPermission(bp) != 4821 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4822 scheduleWriteSettingsLocked(); 4823 } 4824 return; 4825 } 4826 4827 final PackageSetting ps = mSettings.mPackages.get(packageName); 4828 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4829 throw new SecurityException("Cannot grant non-ephemeral permission" 4830 + name + " for package " + packageName); 4831 } 4832 4833 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4834 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4835 return; 4836 } 4837 4838 final int result = permissionsState.grantRuntimePermission(bp, userId); 4839 switch (result) { 4840 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4841 return; 4842 } 4843 4844 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4845 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4846 mHandler.post(new Runnable() { 4847 @Override 4848 public void run() { 4849 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4850 } 4851 }); 4852 } 4853 break; 4854 } 4855 4856 if (bp.isRuntime()) { 4857 logPermissionGranted(mContext, name, packageName); 4858 } 4859 4860 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4861 4862 // Not critical if that is lost - app has to request again. 4863 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4864 } 4865 4866 // Only need to do this if user is initialized. Otherwise it's a new user 4867 // and there are no processes running as the user yet and there's no need 4868 // to make an expensive call to remount processes for the changed permissions. 4869 if (READ_EXTERNAL_STORAGE.equals(name) 4870 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4871 final long token = Binder.clearCallingIdentity(); 4872 try { 4873 if (sUserManager.isInitialized(userId)) { 4874 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4875 StorageManagerInternal.class); 4876 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4877 } 4878 } finally { 4879 Binder.restoreCallingIdentity(token); 4880 } 4881 } 4882 } 4883 4884 @Override 4885 public void revokeRuntimePermission(String packageName, String name, int userId) { 4886 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4887 } 4888 4889 private void revokeRuntimePermission(String packageName, String name, int userId, 4890 boolean overridePolicy) { 4891 if (!sUserManager.exists(userId)) { 4892 Log.e(TAG, "No such user:" + userId); 4893 return; 4894 } 4895 4896 mContext.enforceCallingOrSelfPermission( 4897 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4898 "revokeRuntimePermission"); 4899 4900 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4901 true /* requireFullPermission */, true /* checkShell */, 4902 "revokeRuntimePermission"); 4903 4904 final int appId; 4905 4906 synchronized (mPackages) { 4907 final PackageParser.Package pkg = mPackages.get(packageName); 4908 if (pkg == null) { 4909 throw new IllegalArgumentException("Unknown package: " + packageName); 4910 } 4911 4912 final BasePermission bp = mSettings.mPermissions.get(name); 4913 if (bp == null) { 4914 throw new IllegalArgumentException("Unknown permission: " + name); 4915 } 4916 4917 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4918 4919 // If a permission review is required for legacy apps we represent 4920 // their permissions as always granted runtime ones since we need 4921 // to keep the review required permission flag per user while an 4922 // install permission's state is shared across all users. 4923 if (mPermissionReviewRequired 4924 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4925 && bp.isRuntime()) { 4926 return; 4927 } 4928 4929 SettingBase sb = (SettingBase) pkg.mExtras; 4930 if (sb == null) { 4931 throw new IllegalArgumentException("Unknown package: " + packageName); 4932 } 4933 4934 final PermissionsState permissionsState = sb.getPermissionsState(); 4935 4936 final int flags = permissionsState.getPermissionFlags(name, userId); 4937 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4938 throw new SecurityException("Cannot revoke system fixed permission " 4939 + name + " for package " + packageName); 4940 } 4941 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4942 throw new SecurityException("Cannot revoke policy fixed permission " 4943 + name + " for package " + packageName); 4944 } 4945 4946 if (bp.isDevelopment()) { 4947 // Development permissions must be handled specially, since they are not 4948 // normal runtime permissions. For now they apply to all users. 4949 if (permissionsState.revokeInstallPermission(bp) != 4950 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4951 scheduleWriteSettingsLocked(); 4952 } 4953 return; 4954 } 4955 4956 if (permissionsState.revokeRuntimePermission(bp, userId) == 4957 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4958 return; 4959 } 4960 4961 if (bp.isRuntime()) { 4962 logPermissionRevoked(mContext, name, packageName); 4963 } 4964 4965 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4966 4967 // Critical, after this call app should never have the permission. 4968 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4969 4970 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4971 } 4972 4973 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4974 } 4975 4976 /** 4977 * Get the first event id for the permission. 4978 * 4979 * <p>There are four events for each permission: <ul> 4980 * <li>Request permission: first id + 0</li> 4981 * <li>Grant permission: first id + 1</li> 4982 * <li>Request for permission denied: first id + 2</li> 4983 * <li>Revoke permission: first id + 3</li> 4984 * </ul></p> 4985 * 4986 * @param name name of the permission 4987 * 4988 * @return The first event id for the permission 4989 */ 4990 private static int getBaseEventId(@NonNull String name) { 4991 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4992 4993 if (eventIdIndex == -1) { 4994 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4995 || "user".equals(Build.TYPE)) { 4996 Log.i(TAG, "Unknown permission " + name); 4997 4998 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4999 } else { 5000 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5001 // 5002 // Also update 5003 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5004 // - metrics_constants.proto 5005 throw new IllegalStateException("Unknown permission " + name); 5006 } 5007 } 5008 5009 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5010 } 5011 5012 /** 5013 * Log that a permission was revoked. 5014 * 5015 * @param context Context of the caller 5016 * @param name name of the permission 5017 * @param packageName package permission if for 5018 */ 5019 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5020 @NonNull String packageName) { 5021 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5022 } 5023 5024 /** 5025 * Log that a permission request was granted. 5026 * 5027 * @param context Context of the caller 5028 * @param name name of the permission 5029 * @param packageName package permission if for 5030 */ 5031 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5032 @NonNull String packageName) { 5033 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5034 } 5035 5036 @Override 5037 public void resetRuntimePermissions() { 5038 mContext.enforceCallingOrSelfPermission( 5039 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5040 "revokeRuntimePermission"); 5041 5042 int callingUid = Binder.getCallingUid(); 5043 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5044 mContext.enforceCallingOrSelfPermission( 5045 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5046 "resetRuntimePermissions"); 5047 } 5048 5049 synchronized (mPackages) { 5050 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5051 for (int userId : UserManagerService.getInstance().getUserIds()) { 5052 final int packageCount = mPackages.size(); 5053 for (int i = 0; i < packageCount; i++) { 5054 PackageParser.Package pkg = mPackages.valueAt(i); 5055 if (!(pkg.mExtras instanceof PackageSetting)) { 5056 continue; 5057 } 5058 PackageSetting ps = (PackageSetting) pkg.mExtras; 5059 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5060 } 5061 } 5062 } 5063 } 5064 5065 @Override 5066 public int getPermissionFlags(String name, String packageName, int userId) { 5067 if (!sUserManager.exists(userId)) { 5068 return 0; 5069 } 5070 5071 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5072 5073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5074 true /* requireFullPermission */, false /* checkShell */, 5075 "getPermissionFlags"); 5076 5077 synchronized (mPackages) { 5078 final PackageParser.Package pkg = mPackages.get(packageName); 5079 if (pkg == null) { 5080 return 0; 5081 } 5082 5083 final BasePermission bp = mSettings.mPermissions.get(name); 5084 if (bp == null) { 5085 return 0; 5086 } 5087 5088 SettingBase sb = (SettingBase) pkg.mExtras; 5089 if (sb == null) { 5090 return 0; 5091 } 5092 5093 PermissionsState permissionsState = sb.getPermissionsState(); 5094 return permissionsState.getPermissionFlags(name, userId); 5095 } 5096 } 5097 5098 @Override 5099 public void updatePermissionFlags(String name, String packageName, int flagMask, 5100 int flagValues, int userId) { 5101 if (!sUserManager.exists(userId)) { 5102 return; 5103 } 5104 5105 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5106 5107 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5108 true /* requireFullPermission */, true /* checkShell */, 5109 "updatePermissionFlags"); 5110 5111 // Only the system can change these flags and nothing else. 5112 if (getCallingUid() != Process.SYSTEM_UID) { 5113 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5114 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5115 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5116 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5117 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5118 } 5119 5120 synchronized (mPackages) { 5121 final PackageParser.Package pkg = mPackages.get(packageName); 5122 if (pkg == null) { 5123 throw new IllegalArgumentException("Unknown package: " + packageName); 5124 } 5125 5126 final BasePermission bp = mSettings.mPermissions.get(name); 5127 if (bp == null) { 5128 throw new IllegalArgumentException("Unknown permission: " + name); 5129 } 5130 5131 SettingBase sb = (SettingBase) pkg.mExtras; 5132 if (sb == null) { 5133 throw new IllegalArgumentException("Unknown package: " + packageName); 5134 } 5135 5136 PermissionsState permissionsState = sb.getPermissionsState(); 5137 5138 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5139 5140 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5141 // Install and runtime permissions are stored in different places, 5142 // so figure out what permission changed and persist the change. 5143 if (permissionsState.getInstallPermissionState(name) != null) { 5144 scheduleWriteSettingsLocked(); 5145 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5146 || hadState) { 5147 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5148 } 5149 } 5150 } 5151 } 5152 5153 /** 5154 * Update the permission flags for all packages and runtime permissions of a user in order 5155 * to allow device or profile owner to remove POLICY_FIXED. 5156 */ 5157 @Override 5158 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5159 if (!sUserManager.exists(userId)) { 5160 return; 5161 } 5162 5163 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5164 5165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5166 true /* requireFullPermission */, true /* checkShell */, 5167 "updatePermissionFlagsForAllApps"); 5168 5169 // Only the system can change system fixed flags. 5170 if (getCallingUid() != Process.SYSTEM_UID) { 5171 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5172 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5173 } 5174 5175 synchronized (mPackages) { 5176 boolean changed = false; 5177 final int packageCount = mPackages.size(); 5178 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5179 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5180 SettingBase sb = (SettingBase) pkg.mExtras; 5181 if (sb == null) { 5182 continue; 5183 } 5184 PermissionsState permissionsState = sb.getPermissionsState(); 5185 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5186 userId, flagMask, flagValues); 5187 } 5188 if (changed) { 5189 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5190 } 5191 } 5192 } 5193 5194 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5195 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5196 != PackageManager.PERMISSION_GRANTED 5197 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5198 != PackageManager.PERMISSION_GRANTED) { 5199 throw new SecurityException(message + " requires " 5200 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5201 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5202 } 5203 } 5204 5205 @Override 5206 public boolean shouldShowRequestPermissionRationale(String permissionName, 5207 String packageName, int userId) { 5208 if (UserHandle.getCallingUserId() != userId) { 5209 mContext.enforceCallingPermission( 5210 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5211 "canShowRequestPermissionRationale for user " + userId); 5212 } 5213 5214 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5215 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5216 return false; 5217 } 5218 5219 if (checkPermission(permissionName, packageName, userId) 5220 == PackageManager.PERMISSION_GRANTED) { 5221 return false; 5222 } 5223 5224 final int flags; 5225 5226 final long identity = Binder.clearCallingIdentity(); 5227 try { 5228 flags = getPermissionFlags(permissionName, 5229 packageName, userId); 5230 } finally { 5231 Binder.restoreCallingIdentity(identity); 5232 } 5233 5234 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5235 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5236 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5237 5238 if ((flags & fixedFlags) != 0) { 5239 return false; 5240 } 5241 5242 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5243 } 5244 5245 @Override 5246 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5247 mContext.enforceCallingOrSelfPermission( 5248 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5249 "addOnPermissionsChangeListener"); 5250 5251 synchronized (mPackages) { 5252 mOnPermissionChangeListeners.addListenerLocked(listener); 5253 } 5254 } 5255 5256 @Override 5257 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5258 synchronized (mPackages) { 5259 mOnPermissionChangeListeners.removeListenerLocked(listener); 5260 } 5261 } 5262 5263 @Override 5264 public boolean isProtectedBroadcast(String actionName) { 5265 synchronized (mPackages) { 5266 if (mProtectedBroadcasts.contains(actionName)) { 5267 return true; 5268 } else if (actionName != null) { 5269 // TODO: remove these terrible hacks 5270 if (actionName.startsWith("android.net.netmon.lingerExpired") 5271 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5272 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5273 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5274 return true; 5275 } 5276 } 5277 } 5278 return false; 5279 } 5280 5281 @Override 5282 public int checkSignatures(String pkg1, String pkg2) { 5283 synchronized (mPackages) { 5284 final PackageParser.Package p1 = mPackages.get(pkg1); 5285 final PackageParser.Package p2 = mPackages.get(pkg2); 5286 if (p1 == null || p1.mExtras == null 5287 || p2 == null || p2.mExtras == null) { 5288 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5289 } 5290 return compareSignatures(p1.mSignatures, p2.mSignatures); 5291 } 5292 } 5293 5294 @Override 5295 public int checkUidSignatures(int uid1, int uid2) { 5296 // Map to base uids. 5297 uid1 = UserHandle.getAppId(uid1); 5298 uid2 = UserHandle.getAppId(uid2); 5299 // reader 5300 synchronized (mPackages) { 5301 Signature[] s1; 5302 Signature[] s2; 5303 Object obj = mSettings.getUserIdLPr(uid1); 5304 if (obj != null) { 5305 if (obj instanceof SharedUserSetting) { 5306 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5307 } else if (obj instanceof PackageSetting) { 5308 s1 = ((PackageSetting)obj).signatures.mSignatures; 5309 } else { 5310 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5311 } 5312 } else { 5313 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5314 } 5315 obj = mSettings.getUserIdLPr(uid2); 5316 if (obj != null) { 5317 if (obj instanceof SharedUserSetting) { 5318 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5319 } else if (obj instanceof PackageSetting) { 5320 s2 = ((PackageSetting)obj).signatures.mSignatures; 5321 } else { 5322 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5323 } 5324 } else { 5325 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5326 } 5327 return compareSignatures(s1, s2); 5328 } 5329 } 5330 5331 /** 5332 * This method should typically only be used when granting or revoking 5333 * permissions, since the app may immediately restart after this call. 5334 * <p> 5335 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5336 * guard your work against the app being relaunched. 5337 */ 5338 private void killUid(int appId, int userId, String reason) { 5339 final long identity = Binder.clearCallingIdentity(); 5340 try { 5341 IActivityManager am = ActivityManager.getService(); 5342 if (am != null) { 5343 try { 5344 am.killUid(appId, userId, reason); 5345 } catch (RemoteException e) { 5346 /* ignore - same process */ 5347 } 5348 } 5349 } finally { 5350 Binder.restoreCallingIdentity(identity); 5351 } 5352 } 5353 5354 /** 5355 * Compares two sets of signatures. Returns: 5356 * <br /> 5357 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5358 * <br /> 5359 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5360 * <br /> 5361 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5362 * <br /> 5363 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5364 * <br /> 5365 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5366 */ 5367 static int compareSignatures(Signature[] s1, Signature[] s2) { 5368 if (s1 == null) { 5369 return s2 == null 5370 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5371 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5372 } 5373 5374 if (s2 == null) { 5375 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5376 } 5377 5378 if (s1.length != s2.length) { 5379 return PackageManager.SIGNATURE_NO_MATCH; 5380 } 5381 5382 // Since both signature sets are of size 1, we can compare without HashSets. 5383 if (s1.length == 1) { 5384 return s1[0].equals(s2[0]) ? 5385 PackageManager.SIGNATURE_MATCH : 5386 PackageManager.SIGNATURE_NO_MATCH; 5387 } 5388 5389 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5390 for (Signature sig : s1) { 5391 set1.add(sig); 5392 } 5393 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5394 for (Signature sig : s2) { 5395 set2.add(sig); 5396 } 5397 // Make sure s2 contains all signatures in s1. 5398 if (set1.equals(set2)) { 5399 return PackageManager.SIGNATURE_MATCH; 5400 } 5401 return PackageManager.SIGNATURE_NO_MATCH; 5402 } 5403 5404 /** 5405 * If the database version for this type of package (internal storage or 5406 * external storage) is less than the version where package signatures 5407 * were updated, return true. 5408 */ 5409 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5410 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5411 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5412 } 5413 5414 /** 5415 * Used for backward compatibility to make sure any packages with 5416 * certificate chains get upgraded to the new style. {@code existingSigs} 5417 * will be in the old format (since they were stored on disk from before the 5418 * system upgrade) and {@code scannedSigs} will be in the newer format. 5419 */ 5420 private int compareSignaturesCompat(PackageSignatures existingSigs, 5421 PackageParser.Package scannedPkg) { 5422 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5423 return PackageManager.SIGNATURE_NO_MATCH; 5424 } 5425 5426 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5427 for (Signature sig : existingSigs.mSignatures) { 5428 existingSet.add(sig); 5429 } 5430 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5431 for (Signature sig : scannedPkg.mSignatures) { 5432 try { 5433 Signature[] chainSignatures = sig.getChainSignatures(); 5434 for (Signature chainSig : chainSignatures) { 5435 scannedCompatSet.add(chainSig); 5436 } 5437 } catch (CertificateEncodingException e) { 5438 scannedCompatSet.add(sig); 5439 } 5440 } 5441 /* 5442 * Make sure the expanded scanned set contains all signatures in the 5443 * existing one. 5444 */ 5445 if (scannedCompatSet.equals(existingSet)) { 5446 // Migrate the old signatures to the new scheme. 5447 existingSigs.assignSignatures(scannedPkg.mSignatures); 5448 // The new KeySets will be re-added later in the scanning process. 5449 synchronized (mPackages) { 5450 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5451 } 5452 return PackageManager.SIGNATURE_MATCH; 5453 } 5454 return PackageManager.SIGNATURE_NO_MATCH; 5455 } 5456 5457 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5458 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5459 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5460 } 5461 5462 private int compareSignaturesRecover(PackageSignatures existingSigs, 5463 PackageParser.Package scannedPkg) { 5464 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5465 return PackageManager.SIGNATURE_NO_MATCH; 5466 } 5467 5468 String msg = null; 5469 try { 5470 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5471 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5472 + scannedPkg.packageName); 5473 return PackageManager.SIGNATURE_MATCH; 5474 } 5475 } catch (CertificateException e) { 5476 msg = e.getMessage(); 5477 } 5478 5479 logCriticalInfo(Log.INFO, 5480 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5481 return PackageManager.SIGNATURE_NO_MATCH; 5482 } 5483 5484 @Override 5485 public List<String> getAllPackages() { 5486 synchronized (mPackages) { 5487 return new ArrayList<String>(mPackages.keySet()); 5488 } 5489 } 5490 5491 @Override 5492 public String[] getPackagesForUid(int uid) { 5493 final int userId = UserHandle.getUserId(uid); 5494 uid = UserHandle.getAppId(uid); 5495 // reader 5496 synchronized (mPackages) { 5497 Object obj = mSettings.getUserIdLPr(uid); 5498 if (obj instanceof SharedUserSetting) { 5499 final SharedUserSetting sus = (SharedUserSetting) obj; 5500 final int N = sus.packages.size(); 5501 String[] res = new String[N]; 5502 final Iterator<PackageSetting> it = sus.packages.iterator(); 5503 int i = 0; 5504 while (it.hasNext()) { 5505 PackageSetting ps = it.next(); 5506 if (ps.getInstalled(userId)) { 5507 res[i++] = ps.name; 5508 } else { 5509 res = ArrayUtils.removeElement(String.class, res, res[i]); 5510 } 5511 } 5512 return res; 5513 } else if (obj instanceof PackageSetting) { 5514 final PackageSetting ps = (PackageSetting) obj; 5515 if (ps.getInstalled(userId)) { 5516 return new String[]{ps.name}; 5517 } 5518 } 5519 } 5520 return null; 5521 } 5522 5523 @Override 5524 public String getNameForUid(int uid) { 5525 // reader 5526 synchronized (mPackages) { 5527 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5528 if (obj instanceof SharedUserSetting) { 5529 final SharedUserSetting sus = (SharedUserSetting) obj; 5530 return sus.name + ":" + sus.userId; 5531 } else if (obj instanceof PackageSetting) { 5532 final PackageSetting ps = (PackageSetting) obj; 5533 return ps.name; 5534 } 5535 } 5536 return null; 5537 } 5538 5539 @Override 5540 public int getUidForSharedUser(String sharedUserName) { 5541 if(sharedUserName == null) { 5542 return -1; 5543 } 5544 // reader 5545 synchronized (mPackages) { 5546 SharedUserSetting suid; 5547 try { 5548 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5549 if (suid != null) { 5550 return suid.userId; 5551 } 5552 } catch (PackageManagerException ignore) { 5553 // can't happen, but, still need to catch it 5554 } 5555 return -1; 5556 } 5557 } 5558 5559 @Override 5560 public int getFlagsForUid(int uid) { 5561 synchronized (mPackages) { 5562 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5563 if (obj instanceof SharedUserSetting) { 5564 final SharedUserSetting sus = (SharedUserSetting) obj; 5565 return sus.pkgFlags; 5566 } else if (obj instanceof PackageSetting) { 5567 final PackageSetting ps = (PackageSetting) obj; 5568 return ps.pkgFlags; 5569 } 5570 } 5571 return 0; 5572 } 5573 5574 @Override 5575 public int getPrivateFlagsForUid(int uid) { 5576 synchronized (mPackages) { 5577 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5578 if (obj instanceof SharedUserSetting) { 5579 final SharedUserSetting sus = (SharedUserSetting) obj; 5580 return sus.pkgPrivateFlags; 5581 } else if (obj instanceof PackageSetting) { 5582 final PackageSetting ps = (PackageSetting) obj; 5583 return ps.pkgPrivateFlags; 5584 } 5585 } 5586 return 0; 5587 } 5588 5589 @Override 5590 public boolean isUidPrivileged(int uid) { 5591 uid = UserHandle.getAppId(uid); 5592 // reader 5593 synchronized (mPackages) { 5594 Object obj = mSettings.getUserIdLPr(uid); 5595 if (obj instanceof SharedUserSetting) { 5596 final SharedUserSetting sus = (SharedUserSetting) obj; 5597 final Iterator<PackageSetting> it = sus.packages.iterator(); 5598 while (it.hasNext()) { 5599 if (it.next().isPrivileged()) { 5600 return true; 5601 } 5602 } 5603 } else if (obj instanceof PackageSetting) { 5604 final PackageSetting ps = (PackageSetting) obj; 5605 return ps.isPrivileged(); 5606 } 5607 } 5608 return false; 5609 } 5610 5611 @Override 5612 public String[] getAppOpPermissionPackages(String permissionName) { 5613 synchronized (mPackages) { 5614 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5615 if (pkgs == null) { 5616 return null; 5617 } 5618 return pkgs.toArray(new String[pkgs.size()]); 5619 } 5620 } 5621 5622 @Override 5623 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5624 int flags, int userId) { 5625 return resolveIntentInternal( 5626 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5627 } 5628 5629 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5630 int flags, int userId, boolean includeInstantApps) { 5631 try { 5632 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5633 5634 if (!sUserManager.exists(userId)) return null; 5635 final int callingUid = Binder.getCallingUid(); 5636 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5637 enforceCrossUserPermission(callingUid, userId, 5638 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5639 5640 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5641 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5642 flags, userId, includeInstantApps); 5643 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5644 5645 final ResolveInfo bestChoice = 5646 chooseBestActivity(intent, resolvedType, flags, query, userId); 5647 return bestChoice; 5648 } finally { 5649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5650 } 5651 } 5652 5653 @Override 5654 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5655 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5656 throw new SecurityException( 5657 "findPersistentPreferredActivity can only be run by the system"); 5658 } 5659 if (!sUserManager.exists(userId)) { 5660 return null; 5661 } 5662 final int callingUid = Binder.getCallingUid(); 5663 intent = updateIntentForResolve(intent); 5664 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5665 final int flags = updateFlagsForResolve( 5666 0, userId, intent, callingUid, false /*includeInstantApps*/); 5667 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5668 userId); 5669 synchronized (mPackages) { 5670 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5671 userId); 5672 } 5673 } 5674 5675 @Override 5676 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5677 IntentFilter filter, int match, ComponentName activity) { 5678 final int userId = UserHandle.getCallingUserId(); 5679 if (DEBUG_PREFERRED) { 5680 Log.v(TAG, "setLastChosenActivity intent=" + intent 5681 + " resolvedType=" + resolvedType 5682 + " flags=" + flags 5683 + " filter=" + filter 5684 + " match=" + match 5685 + " activity=" + activity); 5686 filter.dump(new PrintStreamPrinter(System.out), " "); 5687 } 5688 intent.setComponent(null); 5689 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5690 userId); 5691 // Find any earlier preferred or last chosen entries and nuke them 5692 findPreferredActivity(intent, resolvedType, 5693 flags, query, 0, false, true, false, userId); 5694 // Add the new activity as the last chosen for this filter 5695 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5696 "Setting last chosen"); 5697 } 5698 5699 @Override 5700 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5701 final int userId = UserHandle.getCallingUserId(); 5702 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5703 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5704 userId); 5705 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5706 false, false, false, userId); 5707 } 5708 5709 /** 5710 * Returns whether or not instant apps have been disabled remotely. 5711 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5712 * held. Otherwise we run the risk of deadlock. 5713 */ 5714 private boolean isEphemeralDisabled() { 5715 // ephemeral apps have been disabled across the board 5716 if (DISABLE_EPHEMERAL_APPS) { 5717 return true; 5718 } 5719 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5720 if (!mSystemReady) { 5721 return true; 5722 } 5723 // we can't get a content resolver until the system is ready; these checks must happen last 5724 final ContentResolver resolver = mContext.getContentResolver(); 5725 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5726 return true; 5727 } 5728 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5729 } 5730 5731 private boolean isEphemeralAllowed( 5732 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5733 boolean skipPackageCheck) { 5734 final int callingUser = UserHandle.getCallingUserId(); 5735 if (callingUser != UserHandle.USER_SYSTEM) { 5736 return false; 5737 } 5738 if (mInstantAppResolverConnection == null) { 5739 return false; 5740 } 5741 if (mInstantAppInstallerActivity == null) { 5742 return false; 5743 } 5744 if (intent.getComponent() != null) { 5745 return false; 5746 } 5747 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5748 return false; 5749 } 5750 if (!skipPackageCheck && intent.getPackage() != null) { 5751 return false; 5752 } 5753 final boolean isWebUri = hasWebURI(intent); 5754 if (!isWebUri || intent.getData().getHost() == null) { 5755 return false; 5756 } 5757 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5758 // Or if there's already an ephemeral app installed that handles the action 5759 synchronized (mPackages) { 5760 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5761 for (int n = 0; n < count; n++) { 5762 final ResolveInfo info = resolvedActivities.get(n); 5763 final String packageName = info.activityInfo.packageName; 5764 final PackageSetting ps = mSettings.mPackages.get(packageName); 5765 if (ps != null) { 5766 // only check domain verification status if the app is not a browser 5767 if (!info.handleAllWebDataURI) { 5768 // Try to get the status from User settings first 5769 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5770 final int status = (int) (packedStatus >> 32); 5771 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5772 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5773 if (DEBUG_EPHEMERAL) { 5774 Slog.v(TAG, "DENY instant app;" 5775 + " pkg: " + packageName + ", status: " + status); 5776 } 5777 return false; 5778 } 5779 } 5780 if (ps.getInstantApp(userId)) { 5781 if (DEBUG_EPHEMERAL) { 5782 Slog.v(TAG, "DENY instant app installed;" 5783 + " pkg: " + packageName); 5784 } 5785 return false; 5786 } 5787 } 5788 } 5789 } 5790 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5791 return true; 5792 } 5793 5794 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5795 Intent origIntent, String resolvedType, String callingPackage, 5796 int userId) { 5797 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5798 new InstantAppRequest(responseObj, origIntent, resolvedType, 5799 callingPackage, userId)); 5800 mHandler.sendMessage(msg); 5801 } 5802 5803 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5804 int flags, List<ResolveInfo> query, int userId) { 5805 if (query != null) { 5806 final int N = query.size(); 5807 if (N == 1) { 5808 return query.get(0); 5809 } else if (N > 1) { 5810 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5811 // If there is more than one activity with the same priority, 5812 // then let the user decide between them. 5813 ResolveInfo r0 = query.get(0); 5814 ResolveInfo r1 = query.get(1); 5815 if (DEBUG_INTENT_MATCHING || debug) { 5816 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5817 + r1.activityInfo.name + "=" + r1.priority); 5818 } 5819 // If the first activity has a higher priority, or a different 5820 // default, then it is always desirable to pick it. 5821 if (r0.priority != r1.priority 5822 || r0.preferredOrder != r1.preferredOrder 5823 || r0.isDefault != r1.isDefault) { 5824 return query.get(0); 5825 } 5826 // If we have saved a preference for a preferred activity for 5827 // this Intent, use that. 5828 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5829 flags, query, r0.priority, true, false, debug, userId); 5830 if (ri != null) { 5831 return ri; 5832 } 5833 // If we have an ephemeral app, use it 5834 for (int i = 0; i < N; i++) { 5835 ri = query.get(i); 5836 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5837 return ri; 5838 } 5839 } 5840 ri = new ResolveInfo(mResolveInfo); 5841 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5842 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5843 // If all of the options come from the same package, show the application's 5844 // label and icon instead of the generic resolver's. 5845 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5846 // and then throw away the ResolveInfo itself, meaning that the caller loses 5847 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5848 // a fallback for this case; we only set the target package's resources on 5849 // the ResolveInfo, not the ActivityInfo. 5850 final String intentPackage = intent.getPackage(); 5851 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5852 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5853 ri.resolvePackageName = intentPackage; 5854 if (userNeedsBadging(userId)) { 5855 ri.noResourceId = true; 5856 } else { 5857 ri.icon = appi.icon; 5858 } 5859 ri.iconResourceId = appi.icon; 5860 ri.labelRes = appi.labelRes; 5861 } 5862 ri.activityInfo.applicationInfo = new ApplicationInfo( 5863 ri.activityInfo.applicationInfo); 5864 if (userId != 0) { 5865 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5866 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5867 } 5868 // Make sure that the resolver is displayable in car mode 5869 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5870 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5871 return ri; 5872 } 5873 } 5874 return null; 5875 } 5876 5877 /** 5878 * Return true if the given list is not empty and all of its contents have 5879 * an activityInfo with the given package name. 5880 */ 5881 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5882 if (ArrayUtils.isEmpty(list)) { 5883 return false; 5884 } 5885 for (int i = 0, N = list.size(); i < N; i++) { 5886 final ResolveInfo ri = list.get(i); 5887 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5888 if (ai == null || !packageName.equals(ai.packageName)) { 5889 return false; 5890 } 5891 } 5892 return true; 5893 } 5894 5895 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5896 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5897 final int N = query.size(); 5898 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5899 .get(userId); 5900 // Get the list of persistent preferred activities that handle the intent 5901 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5902 List<PersistentPreferredActivity> pprefs = ppir != null 5903 ? ppir.queryIntent(intent, resolvedType, 5904 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5905 userId) 5906 : null; 5907 if (pprefs != null && pprefs.size() > 0) { 5908 final int M = pprefs.size(); 5909 for (int i=0; i<M; i++) { 5910 final PersistentPreferredActivity ppa = pprefs.get(i); 5911 if (DEBUG_PREFERRED || debug) { 5912 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5913 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5914 + "\n component=" + ppa.mComponent); 5915 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5916 } 5917 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5918 flags | MATCH_DISABLED_COMPONENTS, userId); 5919 if (DEBUG_PREFERRED || debug) { 5920 Slog.v(TAG, "Found persistent preferred activity:"); 5921 if (ai != null) { 5922 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5923 } else { 5924 Slog.v(TAG, " null"); 5925 } 5926 } 5927 if (ai == null) { 5928 // This previously registered persistent preferred activity 5929 // component is no longer known. Ignore it and do NOT remove it. 5930 continue; 5931 } 5932 for (int j=0; j<N; j++) { 5933 final ResolveInfo ri = query.get(j); 5934 if (!ri.activityInfo.applicationInfo.packageName 5935 .equals(ai.applicationInfo.packageName)) { 5936 continue; 5937 } 5938 if (!ri.activityInfo.name.equals(ai.name)) { 5939 continue; 5940 } 5941 // Found a persistent preference that can handle the intent. 5942 if (DEBUG_PREFERRED || debug) { 5943 Slog.v(TAG, "Returning persistent preferred activity: " + 5944 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5945 } 5946 return ri; 5947 } 5948 } 5949 } 5950 return null; 5951 } 5952 5953 // TODO: handle preferred activities missing while user has amnesia 5954 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5955 List<ResolveInfo> query, int priority, boolean always, 5956 boolean removeMatches, boolean debug, int userId) { 5957 if (!sUserManager.exists(userId)) return null; 5958 final int callingUid = Binder.getCallingUid(); 5959 flags = updateFlagsForResolve( 5960 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5961 intent = updateIntentForResolve(intent); 5962 // writer 5963 synchronized (mPackages) { 5964 // Try to find a matching persistent preferred activity. 5965 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5966 debug, userId); 5967 5968 // If a persistent preferred activity matched, use it. 5969 if (pri != null) { 5970 return pri; 5971 } 5972 5973 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5974 // Get the list of preferred activities that handle the intent 5975 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5976 List<PreferredActivity> prefs = pir != null 5977 ? pir.queryIntent(intent, resolvedType, 5978 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5979 userId) 5980 : null; 5981 if (prefs != null && prefs.size() > 0) { 5982 boolean changed = false; 5983 try { 5984 // First figure out how good the original match set is. 5985 // We will only allow preferred activities that came 5986 // from the same match quality. 5987 int match = 0; 5988 5989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5990 5991 final int N = query.size(); 5992 for (int j=0; j<N; j++) { 5993 final ResolveInfo ri = query.get(j); 5994 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5995 + ": 0x" + Integer.toHexString(match)); 5996 if (ri.match > match) { 5997 match = ri.match; 5998 } 5999 } 6000 6001 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6002 + Integer.toHexString(match)); 6003 6004 match &= IntentFilter.MATCH_CATEGORY_MASK; 6005 final int M = prefs.size(); 6006 for (int i=0; i<M; i++) { 6007 final PreferredActivity pa = prefs.get(i); 6008 if (DEBUG_PREFERRED || debug) { 6009 Slog.v(TAG, "Checking PreferredActivity ds=" 6010 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6011 + "\n component=" + pa.mPref.mComponent); 6012 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6013 } 6014 if (pa.mPref.mMatch != match) { 6015 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6016 + Integer.toHexString(pa.mPref.mMatch)); 6017 continue; 6018 } 6019 // If it's not an "always" type preferred activity and that's what we're 6020 // looking for, skip it. 6021 if (always && !pa.mPref.mAlways) { 6022 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6023 continue; 6024 } 6025 final ActivityInfo ai = getActivityInfo( 6026 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6027 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6028 userId); 6029 if (DEBUG_PREFERRED || debug) { 6030 Slog.v(TAG, "Found preferred activity:"); 6031 if (ai != null) { 6032 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6033 } else { 6034 Slog.v(TAG, " null"); 6035 } 6036 } 6037 if (ai == null) { 6038 // This previously registered preferred activity 6039 // component is no longer known. Most likely an update 6040 // to the app was installed and in the new version this 6041 // component no longer exists. Clean it up by removing 6042 // it from the preferred activities list, and skip it. 6043 Slog.w(TAG, "Removing dangling preferred activity: " 6044 + pa.mPref.mComponent); 6045 pir.removeFilter(pa); 6046 changed = true; 6047 continue; 6048 } 6049 for (int j=0; j<N; j++) { 6050 final ResolveInfo ri = query.get(j); 6051 if (!ri.activityInfo.applicationInfo.packageName 6052 .equals(ai.applicationInfo.packageName)) { 6053 continue; 6054 } 6055 if (!ri.activityInfo.name.equals(ai.name)) { 6056 continue; 6057 } 6058 6059 if (removeMatches) { 6060 pir.removeFilter(pa); 6061 changed = true; 6062 if (DEBUG_PREFERRED) { 6063 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6064 } 6065 break; 6066 } 6067 6068 // Okay we found a previously set preferred or last chosen app. 6069 // If the result set is different from when this 6070 // was created, we need to clear it and re-ask the 6071 // user their preference, if we're looking for an "always" type entry. 6072 if (always && !pa.mPref.sameSet(query)) { 6073 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6074 + intent + " type " + resolvedType); 6075 if (DEBUG_PREFERRED) { 6076 Slog.v(TAG, "Removing preferred activity since set changed " 6077 + pa.mPref.mComponent); 6078 } 6079 pir.removeFilter(pa); 6080 // Re-add the filter as a "last chosen" entry (!always) 6081 PreferredActivity lastChosen = new PreferredActivity( 6082 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6083 pir.addFilter(lastChosen); 6084 changed = true; 6085 return null; 6086 } 6087 6088 // Yay! Either the set matched or we're looking for the last chosen 6089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6090 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6091 return ri; 6092 } 6093 } 6094 } finally { 6095 if (changed) { 6096 if (DEBUG_PREFERRED) { 6097 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6098 } 6099 scheduleWritePackageRestrictionsLocked(userId); 6100 } 6101 } 6102 } 6103 } 6104 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6105 return null; 6106 } 6107 6108 /* 6109 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6110 */ 6111 @Override 6112 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6113 int targetUserId) { 6114 mContext.enforceCallingOrSelfPermission( 6115 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6116 List<CrossProfileIntentFilter> matches = 6117 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6118 if (matches != null) { 6119 int size = matches.size(); 6120 for (int i = 0; i < size; i++) { 6121 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6122 } 6123 } 6124 if (hasWebURI(intent)) { 6125 // cross-profile app linking works only towards the parent. 6126 final int callingUid = Binder.getCallingUid(); 6127 final UserInfo parent = getProfileParent(sourceUserId); 6128 synchronized(mPackages) { 6129 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6130 false /*includeInstantApps*/); 6131 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6132 intent, resolvedType, flags, sourceUserId, parent.id); 6133 return xpDomainInfo != null; 6134 } 6135 } 6136 return false; 6137 } 6138 6139 private UserInfo getProfileParent(int userId) { 6140 final long identity = Binder.clearCallingIdentity(); 6141 try { 6142 return sUserManager.getProfileParent(userId); 6143 } finally { 6144 Binder.restoreCallingIdentity(identity); 6145 } 6146 } 6147 6148 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6149 String resolvedType, int userId) { 6150 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6151 if (resolver != null) { 6152 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6153 } 6154 return null; 6155 } 6156 6157 @Override 6158 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6159 String resolvedType, int flags, int userId) { 6160 try { 6161 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6162 6163 return new ParceledListSlice<>( 6164 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6165 } finally { 6166 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6167 } 6168 } 6169 6170 /** 6171 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6172 * instant, returns {@code null}. 6173 */ 6174 private String getInstantAppPackageName(int callingUid) { 6175 // If the caller is an isolated app use the owner's uid for the lookup. 6176 if (Process.isIsolated(callingUid)) { 6177 callingUid = mIsolatedOwners.get(callingUid); 6178 } 6179 final int appId = UserHandle.getAppId(callingUid); 6180 synchronized (mPackages) { 6181 final Object obj = mSettings.getUserIdLPr(appId); 6182 if (obj instanceof PackageSetting) { 6183 final PackageSetting ps = (PackageSetting) obj; 6184 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6185 return isInstantApp ? ps.pkg.packageName : null; 6186 } 6187 } 6188 return null; 6189 } 6190 6191 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6192 String resolvedType, int flags, int userId) { 6193 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6194 } 6195 6196 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6197 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6198 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6199 final int callingUid = Binder.getCallingUid(); 6200 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6201 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6202 enforceCrossUserPermission(callingUid, userId, 6203 false /* requireFullPermission */, false /* checkShell */, 6204 "query intent activities"); 6205 ComponentName comp = intent.getComponent(); 6206 if (comp == null) { 6207 if (intent.getSelector() != null) { 6208 intent = intent.getSelector(); 6209 comp = intent.getComponent(); 6210 } 6211 } 6212 6213 if (comp != null) { 6214 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6215 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6216 if (ai != null) { 6217 // When specifying an explicit component, we prevent the activity from being 6218 // used when either 1) the calling package is normal and the activity is within 6219 // an ephemeral application or 2) the calling package is ephemeral and the 6220 // activity is not visible to ephemeral applications. 6221 final boolean matchInstantApp = 6222 (flags & PackageManager.MATCH_INSTANT) != 0; 6223 final boolean matchVisibleToInstantAppOnly = 6224 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6225 final boolean isCallerInstantApp = 6226 instantAppPkgName != null; 6227 final boolean isTargetSameInstantApp = 6228 comp.getPackageName().equals(instantAppPkgName); 6229 final boolean isTargetInstantApp = 6230 (ai.applicationInfo.privateFlags 6231 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6232 final boolean isTargetHiddenFromInstantApp = 6233 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6234 final boolean blockResolution = 6235 !isTargetSameInstantApp 6236 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6237 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6238 && isTargetHiddenFromInstantApp)); 6239 if (!blockResolution) { 6240 final ResolveInfo ri = new ResolveInfo(); 6241 ri.activityInfo = ai; 6242 list.add(ri); 6243 } 6244 } 6245 return applyPostResolutionFilter(list, instantAppPkgName); 6246 } 6247 6248 // reader 6249 boolean sortResult = false; 6250 boolean addEphemeral = false; 6251 List<ResolveInfo> result; 6252 final String pkgName = intent.getPackage(); 6253 final boolean ephemeralDisabled = isEphemeralDisabled(); 6254 synchronized (mPackages) { 6255 if (pkgName == null) { 6256 List<CrossProfileIntentFilter> matchingFilters = 6257 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6258 // Check for results that need to skip the current profile. 6259 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6260 resolvedType, flags, userId); 6261 if (xpResolveInfo != null) { 6262 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6263 xpResult.add(xpResolveInfo); 6264 return applyPostResolutionFilter( 6265 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6266 } 6267 6268 // Check for results in the current profile. 6269 result = filterIfNotSystemUser(mActivities.queryIntent( 6270 intent, resolvedType, flags, userId), userId); 6271 addEphemeral = !ephemeralDisabled 6272 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6273 // Check for cross profile results. 6274 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6275 xpResolveInfo = queryCrossProfileIntents( 6276 matchingFilters, intent, resolvedType, flags, userId, 6277 hasNonNegativePriorityResult); 6278 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6279 boolean isVisibleToUser = filterIfNotSystemUser( 6280 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6281 if (isVisibleToUser) { 6282 result.add(xpResolveInfo); 6283 sortResult = true; 6284 } 6285 } 6286 if (hasWebURI(intent)) { 6287 CrossProfileDomainInfo xpDomainInfo = null; 6288 final UserInfo parent = getProfileParent(userId); 6289 if (parent != null) { 6290 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6291 flags, userId, parent.id); 6292 } 6293 if (xpDomainInfo != null) { 6294 if (xpResolveInfo != null) { 6295 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6296 // in the result. 6297 result.remove(xpResolveInfo); 6298 } 6299 if (result.size() == 0 && !addEphemeral) { 6300 // No result in current profile, but found candidate in parent user. 6301 // And we are not going to add emphemeral app, so we can return the 6302 // result straight away. 6303 result.add(xpDomainInfo.resolveInfo); 6304 return applyPostResolutionFilter(result, instantAppPkgName); 6305 } 6306 } else if (result.size() <= 1 && !addEphemeral) { 6307 // No result in parent user and <= 1 result in current profile, and we 6308 // are not going to add emphemeral app, so we can return the result without 6309 // further processing. 6310 return applyPostResolutionFilter(result, instantAppPkgName); 6311 } 6312 // We have more than one candidate (combining results from current and parent 6313 // profile), so we need filtering and sorting. 6314 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6315 intent, flags, result, xpDomainInfo, userId); 6316 sortResult = true; 6317 } 6318 } else { 6319 final PackageParser.Package pkg = mPackages.get(pkgName); 6320 if (pkg != null) { 6321 return applyPostResolutionFilter(filterIfNotSystemUser( 6322 mActivities.queryIntentForPackage( 6323 intent, resolvedType, flags, pkg.activities, userId), 6324 userId), instantAppPkgName); 6325 } else { 6326 // the caller wants to resolve for a particular package; however, there 6327 // were no installed results, so, try to find an ephemeral result 6328 addEphemeral = !ephemeralDisabled 6329 && isEphemeralAllowed( 6330 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6331 result = new ArrayList<ResolveInfo>(); 6332 } 6333 } 6334 } 6335 if (addEphemeral) { 6336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6337 final InstantAppRequest requestObject = new InstantAppRequest( 6338 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6339 null /*callingPackage*/, userId); 6340 final AuxiliaryResolveInfo auxiliaryResponse = 6341 InstantAppResolver.doInstantAppResolutionPhaseOne( 6342 mContext, mInstantAppResolverConnection, requestObject); 6343 if (auxiliaryResponse != null) { 6344 if (DEBUG_EPHEMERAL) { 6345 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6346 } 6347 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6348 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6349 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6350 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6351 // make sure this resolver is the default 6352 ephemeralInstaller.isDefault = true; 6353 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6354 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6355 // add a non-generic filter 6356 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6357 ephemeralInstaller.filter.addDataPath( 6358 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6359 ephemeralInstaller.instantAppAvailable = true; 6360 result.add(ephemeralInstaller); 6361 } 6362 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6363 } 6364 if (sortResult) { 6365 Collections.sort(result, mResolvePrioritySorter); 6366 } 6367 return applyPostResolutionFilter(result, instantAppPkgName); 6368 } 6369 6370 private static class CrossProfileDomainInfo { 6371 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6372 ResolveInfo resolveInfo; 6373 /* Best domain verification status of the activities found in the other profile */ 6374 int bestDomainVerificationStatus; 6375 } 6376 6377 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6378 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6379 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6380 sourceUserId)) { 6381 return null; 6382 } 6383 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6384 resolvedType, flags, parentUserId); 6385 6386 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6387 return null; 6388 } 6389 CrossProfileDomainInfo result = null; 6390 int size = resultTargetUser.size(); 6391 for (int i = 0; i < size; i++) { 6392 ResolveInfo riTargetUser = resultTargetUser.get(i); 6393 // Intent filter verification is only for filters that specify a host. So don't return 6394 // those that handle all web uris. 6395 if (riTargetUser.handleAllWebDataURI) { 6396 continue; 6397 } 6398 String packageName = riTargetUser.activityInfo.packageName; 6399 PackageSetting ps = mSettings.mPackages.get(packageName); 6400 if (ps == null) { 6401 continue; 6402 } 6403 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6404 int status = (int)(verificationState >> 32); 6405 if (result == null) { 6406 result = new CrossProfileDomainInfo(); 6407 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6408 sourceUserId, parentUserId); 6409 result.bestDomainVerificationStatus = status; 6410 } else { 6411 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6412 result.bestDomainVerificationStatus); 6413 } 6414 } 6415 // Don't consider matches with status NEVER across profiles. 6416 if (result != null && result.bestDomainVerificationStatus 6417 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6418 return null; 6419 } 6420 return result; 6421 } 6422 6423 /** 6424 * Verification statuses are ordered from the worse to the best, except for 6425 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6426 */ 6427 private int bestDomainVerificationStatus(int status1, int status2) { 6428 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6429 return status2; 6430 } 6431 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6432 return status1; 6433 } 6434 return (int) MathUtils.max(status1, status2); 6435 } 6436 6437 private boolean isUserEnabled(int userId) { 6438 long callingId = Binder.clearCallingIdentity(); 6439 try { 6440 UserInfo userInfo = sUserManager.getUserInfo(userId); 6441 return userInfo != null && userInfo.isEnabled(); 6442 } finally { 6443 Binder.restoreCallingIdentity(callingId); 6444 } 6445 } 6446 6447 /** 6448 * Filter out activities with systemUserOnly flag set, when current user is not System. 6449 * 6450 * @return filtered list 6451 */ 6452 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6453 if (userId == UserHandle.USER_SYSTEM) { 6454 return resolveInfos; 6455 } 6456 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6457 ResolveInfo info = resolveInfos.get(i); 6458 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6459 resolveInfos.remove(i); 6460 } 6461 } 6462 return resolveInfos; 6463 } 6464 6465 /** 6466 * Filters out ephemeral activities. 6467 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6468 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6469 * 6470 * @param resolveInfos The pre-filtered list of resolved activities 6471 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6472 * is performed. 6473 * @return A filtered list of resolved activities. 6474 */ 6475 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6476 String ephemeralPkgName) { 6477 // TODO: When adding on-demand split support for non-instant apps, remove this check 6478 // and always apply post filtering 6479 if (ephemeralPkgName == null) { 6480 return resolveInfos; 6481 } 6482 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6483 final ResolveInfo info = resolveInfos.get(i); 6484 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6485 // allow activities that are defined in the provided package 6486 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6487 if (info.activityInfo.splitName != null 6488 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6489 info.activityInfo.splitName)) { 6490 // requested activity is defined in a split that hasn't been installed yet. 6491 // add the installer to the resolve list 6492 if (DEBUG_EPHEMERAL) { 6493 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6494 } 6495 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6496 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6497 info.activityInfo.packageName, info.activityInfo.splitName, 6498 info.activityInfo.applicationInfo.versionCode); 6499 // make sure this resolver is the default 6500 installerInfo.isDefault = true; 6501 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6502 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6503 // add a non-generic filter 6504 installerInfo.filter = new IntentFilter(); 6505 // load resources from the correct package 6506 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6507 resolveInfos.set(i, installerInfo); 6508 } 6509 continue; 6510 } 6511 // allow activities that have been explicitly exposed to ephemeral apps 6512 if (!isEphemeralApp 6513 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6514 continue; 6515 } 6516 resolveInfos.remove(i); 6517 } 6518 return resolveInfos; 6519 } 6520 6521 /** 6522 * @param resolveInfos list of resolve infos in descending priority order 6523 * @return if the list contains a resolve info with non-negative priority 6524 */ 6525 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6526 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6527 } 6528 6529 private static boolean hasWebURI(Intent intent) { 6530 if (intent.getData() == null) { 6531 return false; 6532 } 6533 final String scheme = intent.getScheme(); 6534 if (TextUtils.isEmpty(scheme)) { 6535 return false; 6536 } 6537 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6538 } 6539 6540 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6541 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6542 int userId) { 6543 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6544 6545 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6546 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6547 candidates.size()); 6548 } 6549 6550 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6551 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6552 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6553 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6554 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6555 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6556 6557 synchronized (mPackages) { 6558 final int count = candidates.size(); 6559 // First, try to use linked apps. Partition the candidates into four lists: 6560 // one for the final results, one for the "do not use ever", one for "undefined status" 6561 // and finally one for "browser app type". 6562 for (int n=0; n<count; n++) { 6563 ResolveInfo info = candidates.get(n); 6564 String packageName = info.activityInfo.packageName; 6565 PackageSetting ps = mSettings.mPackages.get(packageName); 6566 if (ps != null) { 6567 // Add to the special match all list (Browser use case) 6568 if (info.handleAllWebDataURI) { 6569 matchAllList.add(info); 6570 continue; 6571 } 6572 // Try to get the status from User settings first 6573 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6574 int status = (int)(packedStatus >> 32); 6575 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6576 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6577 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6578 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6579 + " : linkgen=" + linkGeneration); 6580 } 6581 // Use link-enabled generation as preferredOrder, i.e. 6582 // prefer newly-enabled over earlier-enabled. 6583 info.preferredOrder = linkGeneration; 6584 alwaysList.add(info); 6585 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6586 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6587 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6588 } 6589 neverList.add(info); 6590 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6591 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6592 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6593 } 6594 alwaysAskList.add(info); 6595 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6596 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6597 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6598 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6599 } 6600 undefinedList.add(info); 6601 } 6602 } 6603 } 6604 6605 // We'll want to include browser possibilities in a few cases 6606 boolean includeBrowser = false; 6607 6608 // First try to add the "always" resolution(s) for the current user, if any 6609 if (alwaysList.size() > 0) { 6610 result.addAll(alwaysList); 6611 } else { 6612 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6613 result.addAll(undefinedList); 6614 // Maybe add one for the other profile. 6615 if (xpDomainInfo != null && ( 6616 xpDomainInfo.bestDomainVerificationStatus 6617 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6618 result.add(xpDomainInfo.resolveInfo); 6619 } 6620 includeBrowser = true; 6621 } 6622 6623 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6624 // If there were 'always' entries their preferred order has been set, so we also 6625 // back that off to make the alternatives equivalent 6626 if (alwaysAskList.size() > 0) { 6627 for (ResolveInfo i : result) { 6628 i.preferredOrder = 0; 6629 } 6630 result.addAll(alwaysAskList); 6631 includeBrowser = true; 6632 } 6633 6634 if (includeBrowser) { 6635 // Also add browsers (all of them or only the default one) 6636 if (DEBUG_DOMAIN_VERIFICATION) { 6637 Slog.v(TAG, " ...including browsers in candidate set"); 6638 } 6639 if ((matchFlags & MATCH_ALL) != 0) { 6640 result.addAll(matchAllList); 6641 } else { 6642 // Browser/generic handling case. If there's a default browser, go straight 6643 // to that (but only if there is no other higher-priority match). 6644 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6645 int maxMatchPrio = 0; 6646 ResolveInfo defaultBrowserMatch = null; 6647 final int numCandidates = matchAllList.size(); 6648 for (int n = 0; n < numCandidates; n++) { 6649 ResolveInfo info = matchAllList.get(n); 6650 // track the highest overall match priority... 6651 if (info.priority > maxMatchPrio) { 6652 maxMatchPrio = info.priority; 6653 } 6654 // ...and the highest-priority default browser match 6655 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6656 if (defaultBrowserMatch == null 6657 || (defaultBrowserMatch.priority < info.priority)) { 6658 if (debug) { 6659 Slog.v(TAG, "Considering default browser match " + info); 6660 } 6661 defaultBrowserMatch = info; 6662 } 6663 } 6664 } 6665 if (defaultBrowserMatch != null 6666 && defaultBrowserMatch.priority >= maxMatchPrio 6667 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6668 { 6669 if (debug) { 6670 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6671 } 6672 result.add(defaultBrowserMatch); 6673 } else { 6674 result.addAll(matchAllList); 6675 } 6676 } 6677 6678 // If there is nothing selected, add all candidates and remove the ones that the user 6679 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6680 if (result.size() == 0) { 6681 result.addAll(candidates); 6682 result.removeAll(neverList); 6683 } 6684 } 6685 } 6686 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6687 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6688 result.size()); 6689 for (ResolveInfo info : result) { 6690 Slog.v(TAG, " + " + info.activityInfo); 6691 } 6692 } 6693 return result; 6694 } 6695 6696 // Returns a packed value as a long: 6697 // 6698 // high 'int'-sized word: link status: undefined/ask/never/always. 6699 // low 'int'-sized word: relative priority among 'always' results. 6700 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6701 long result = ps.getDomainVerificationStatusForUser(userId); 6702 // if none available, get the master status 6703 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6704 if (ps.getIntentFilterVerificationInfo() != null) { 6705 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6706 } 6707 } 6708 return result; 6709 } 6710 6711 private ResolveInfo querySkipCurrentProfileIntents( 6712 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6713 int flags, int sourceUserId) { 6714 if (matchingFilters != null) { 6715 int size = matchingFilters.size(); 6716 for (int i = 0; i < size; i ++) { 6717 CrossProfileIntentFilter filter = matchingFilters.get(i); 6718 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6719 // Checking if there are activities in the target user that can handle the 6720 // intent. 6721 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6722 resolvedType, flags, sourceUserId); 6723 if (resolveInfo != null) { 6724 return resolveInfo; 6725 } 6726 } 6727 } 6728 } 6729 return null; 6730 } 6731 6732 // Return matching ResolveInfo in target user if any. 6733 private ResolveInfo queryCrossProfileIntents( 6734 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6735 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6736 if (matchingFilters != null) { 6737 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6738 // match the same intent. For performance reasons, it is better not to 6739 // run queryIntent twice for the same userId 6740 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6741 int size = matchingFilters.size(); 6742 for (int i = 0; i < size; i++) { 6743 CrossProfileIntentFilter filter = matchingFilters.get(i); 6744 int targetUserId = filter.getTargetUserId(); 6745 boolean skipCurrentProfile = 6746 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6747 boolean skipCurrentProfileIfNoMatchFound = 6748 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6749 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6750 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6751 // Checking if there are activities in the target user that can handle the 6752 // intent. 6753 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6754 resolvedType, flags, sourceUserId); 6755 if (resolveInfo != null) return resolveInfo; 6756 alreadyTriedUserIds.put(targetUserId, true); 6757 } 6758 } 6759 } 6760 return null; 6761 } 6762 6763 /** 6764 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6765 * will forward the intent to the filter's target user. 6766 * Otherwise, returns null. 6767 */ 6768 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6769 String resolvedType, int flags, int sourceUserId) { 6770 int targetUserId = filter.getTargetUserId(); 6771 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6772 resolvedType, flags, targetUserId); 6773 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6774 // If all the matches in the target profile are suspended, return null. 6775 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6776 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6777 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6778 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6779 targetUserId); 6780 } 6781 } 6782 } 6783 return null; 6784 } 6785 6786 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6787 int sourceUserId, int targetUserId) { 6788 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6789 long ident = Binder.clearCallingIdentity(); 6790 boolean targetIsProfile; 6791 try { 6792 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6793 } finally { 6794 Binder.restoreCallingIdentity(ident); 6795 } 6796 String className; 6797 if (targetIsProfile) { 6798 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6799 } else { 6800 className = FORWARD_INTENT_TO_PARENT; 6801 } 6802 ComponentName forwardingActivityComponentName = new ComponentName( 6803 mAndroidApplication.packageName, className); 6804 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6805 sourceUserId); 6806 if (!targetIsProfile) { 6807 forwardingActivityInfo.showUserIcon = targetUserId; 6808 forwardingResolveInfo.noResourceId = true; 6809 } 6810 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6811 forwardingResolveInfo.priority = 0; 6812 forwardingResolveInfo.preferredOrder = 0; 6813 forwardingResolveInfo.match = 0; 6814 forwardingResolveInfo.isDefault = true; 6815 forwardingResolveInfo.filter = filter; 6816 forwardingResolveInfo.targetUserId = targetUserId; 6817 return forwardingResolveInfo; 6818 } 6819 6820 @Override 6821 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6822 Intent[] specifics, String[] specificTypes, Intent intent, 6823 String resolvedType, int flags, int userId) { 6824 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6825 specificTypes, intent, resolvedType, flags, userId)); 6826 } 6827 6828 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6829 Intent[] specifics, String[] specificTypes, Intent intent, 6830 String resolvedType, int flags, int userId) { 6831 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6832 final int callingUid = Binder.getCallingUid(); 6833 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6834 false /*includeInstantApps*/); 6835 enforceCrossUserPermission(callingUid, userId, 6836 false /*requireFullPermission*/, false /*checkShell*/, 6837 "query intent activity options"); 6838 final String resultsAction = intent.getAction(); 6839 6840 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6841 | PackageManager.GET_RESOLVED_FILTER, userId); 6842 6843 if (DEBUG_INTENT_MATCHING) { 6844 Log.v(TAG, "Query " + intent + ": " + results); 6845 } 6846 6847 int specificsPos = 0; 6848 int N; 6849 6850 // todo: note that the algorithm used here is O(N^2). This 6851 // isn't a problem in our current environment, but if we start running 6852 // into situations where we have more than 5 or 10 matches then this 6853 // should probably be changed to something smarter... 6854 6855 // First we go through and resolve each of the specific items 6856 // that were supplied, taking care of removing any corresponding 6857 // duplicate items in the generic resolve list. 6858 if (specifics != null) { 6859 for (int i=0; i<specifics.length; i++) { 6860 final Intent sintent = specifics[i]; 6861 if (sintent == null) { 6862 continue; 6863 } 6864 6865 if (DEBUG_INTENT_MATCHING) { 6866 Log.v(TAG, "Specific #" + i + ": " + sintent); 6867 } 6868 6869 String action = sintent.getAction(); 6870 if (resultsAction != null && resultsAction.equals(action)) { 6871 // If this action was explicitly requested, then don't 6872 // remove things that have it. 6873 action = null; 6874 } 6875 6876 ResolveInfo ri = null; 6877 ActivityInfo ai = null; 6878 6879 ComponentName comp = sintent.getComponent(); 6880 if (comp == null) { 6881 ri = resolveIntent( 6882 sintent, 6883 specificTypes != null ? specificTypes[i] : null, 6884 flags, userId); 6885 if (ri == null) { 6886 continue; 6887 } 6888 if (ri == mResolveInfo) { 6889 // ACK! Must do something better with this. 6890 } 6891 ai = ri.activityInfo; 6892 comp = new ComponentName(ai.applicationInfo.packageName, 6893 ai.name); 6894 } else { 6895 ai = getActivityInfo(comp, flags, userId); 6896 if (ai == null) { 6897 continue; 6898 } 6899 } 6900 6901 // Look for any generic query activities that are duplicates 6902 // of this specific one, and remove them from the results. 6903 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6904 N = results.size(); 6905 int j; 6906 for (j=specificsPos; j<N; j++) { 6907 ResolveInfo sri = results.get(j); 6908 if ((sri.activityInfo.name.equals(comp.getClassName()) 6909 && sri.activityInfo.applicationInfo.packageName.equals( 6910 comp.getPackageName())) 6911 || (action != null && sri.filter.matchAction(action))) { 6912 results.remove(j); 6913 if (DEBUG_INTENT_MATCHING) Log.v( 6914 TAG, "Removing duplicate item from " + j 6915 + " due to specific " + specificsPos); 6916 if (ri == null) { 6917 ri = sri; 6918 } 6919 j--; 6920 N--; 6921 } 6922 } 6923 6924 // Add this specific item to its proper place. 6925 if (ri == null) { 6926 ri = new ResolveInfo(); 6927 ri.activityInfo = ai; 6928 } 6929 results.add(specificsPos, ri); 6930 ri.specificIndex = i; 6931 specificsPos++; 6932 } 6933 } 6934 6935 // Now we go through the remaining generic results and remove any 6936 // duplicate actions that are found here. 6937 N = results.size(); 6938 for (int i=specificsPos; i<N-1; i++) { 6939 final ResolveInfo rii = results.get(i); 6940 if (rii.filter == null) { 6941 continue; 6942 } 6943 6944 // Iterate over all of the actions of this result's intent 6945 // filter... typically this should be just one. 6946 final Iterator<String> it = rii.filter.actionsIterator(); 6947 if (it == null) { 6948 continue; 6949 } 6950 while (it.hasNext()) { 6951 final String action = it.next(); 6952 if (resultsAction != null && resultsAction.equals(action)) { 6953 // If this action was explicitly requested, then don't 6954 // remove things that have it. 6955 continue; 6956 } 6957 for (int j=i+1; j<N; j++) { 6958 final ResolveInfo rij = results.get(j); 6959 if (rij.filter != null && rij.filter.hasAction(action)) { 6960 results.remove(j); 6961 if (DEBUG_INTENT_MATCHING) Log.v( 6962 TAG, "Removing duplicate item from " + j 6963 + " due to action " + action + " at " + i); 6964 j--; 6965 N--; 6966 } 6967 } 6968 } 6969 6970 // If the caller didn't request filter information, drop it now 6971 // so we don't have to marshall/unmarshall it. 6972 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6973 rii.filter = null; 6974 } 6975 } 6976 6977 // Filter out the caller activity if so requested. 6978 if (caller != null) { 6979 N = results.size(); 6980 for (int i=0; i<N; i++) { 6981 ActivityInfo ainfo = results.get(i).activityInfo; 6982 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6983 && caller.getClassName().equals(ainfo.name)) { 6984 results.remove(i); 6985 break; 6986 } 6987 } 6988 } 6989 6990 // If the caller didn't request filter information, 6991 // drop them now so we don't have to 6992 // marshall/unmarshall it. 6993 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6994 N = results.size(); 6995 for (int i=0; i<N; i++) { 6996 results.get(i).filter = null; 6997 } 6998 } 6999 7000 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7001 return results; 7002 } 7003 7004 @Override 7005 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7006 String resolvedType, int flags, int userId) { 7007 return new ParceledListSlice<>( 7008 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7009 } 7010 7011 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7012 String resolvedType, int flags, int userId) { 7013 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7014 final int callingUid = Binder.getCallingUid(); 7015 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7016 false /*includeInstantApps*/); 7017 ComponentName comp = intent.getComponent(); 7018 if (comp == null) { 7019 if (intent.getSelector() != null) { 7020 intent = intent.getSelector(); 7021 comp = intent.getComponent(); 7022 } 7023 } 7024 if (comp != null) { 7025 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7026 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7027 if (ai != null) { 7028 ResolveInfo ri = new ResolveInfo(); 7029 ri.activityInfo = ai; 7030 list.add(ri); 7031 } 7032 return list; 7033 } 7034 7035 // reader 7036 synchronized (mPackages) { 7037 String pkgName = intent.getPackage(); 7038 if (pkgName == null) { 7039 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7040 } 7041 final PackageParser.Package pkg = mPackages.get(pkgName); 7042 if (pkg != null) { 7043 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7044 userId); 7045 } 7046 return Collections.emptyList(); 7047 } 7048 } 7049 7050 @Override 7051 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7052 final int callingUid = Binder.getCallingUid(); 7053 return resolveServiceInternal( 7054 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7055 } 7056 7057 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7058 int userId, int callingUid, boolean includeInstantApps) { 7059 if (!sUserManager.exists(userId)) return null; 7060 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7061 List<ResolveInfo> query = queryIntentServicesInternal( 7062 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7063 if (query != null) { 7064 if (query.size() >= 1) { 7065 // If there is more than one service with the same priority, 7066 // just arbitrarily pick the first one. 7067 return query.get(0); 7068 } 7069 } 7070 return null; 7071 } 7072 7073 @Override 7074 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7075 String resolvedType, int flags, int userId) { 7076 final int callingUid = Binder.getCallingUid(); 7077 return new ParceledListSlice<>(queryIntentServicesInternal( 7078 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7079 } 7080 7081 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7082 String resolvedType, int flags, int userId, int callingUid, 7083 boolean includeInstantApps) { 7084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7085 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7086 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7087 ComponentName comp = intent.getComponent(); 7088 if (comp == null) { 7089 if (intent.getSelector() != null) { 7090 intent = intent.getSelector(); 7091 comp = intent.getComponent(); 7092 } 7093 } 7094 if (comp != null) { 7095 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7096 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7097 if (si != null) { 7098 // When specifying an explicit component, we prevent the service from being 7099 // used when either 1) the service is in an instant application and the 7100 // caller is not the same instant application or 2) the calling package is 7101 // ephemeral and the activity is not visible to ephemeral applications. 7102 final boolean matchVisibleToInstantAppOnly = 7103 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7104 final boolean isCallerInstantApp = 7105 instantAppPkgName != null; 7106 final boolean isTargetSameInstantApp = 7107 comp.getPackageName().equals(instantAppPkgName); 7108 final boolean isTargetHiddenFromInstantApp = 7109 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7110 final boolean blockResolution = 7111 !isTargetSameInstantApp 7112 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7113 && isTargetHiddenFromInstantApp)); 7114 if (!blockResolution) { 7115 final ResolveInfo ri = new ResolveInfo(); 7116 ri.serviceInfo = si; 7117 list.add(ri); 7118 } 7119 } 7120 return list; 7121 } 7122 7123 // reader 7124 synchronized (mPackages) { 7125 String pkgName = intent.getPackage(); 7126 if (pkgName == null) { 7127 return applyPostServiceResolutionFilter( 7128 mServices.queryIntent(intent, resolvedType, flags, userId), 7129 instantAppPkgName); 7130 } 7131 final PackageParser.Package pkg = mPackages.get(pkgName); 7132 if (pkg != null) { 7133 return applyPostServiceResolutionFilter( 7134 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7135 userId), 7136 instantAppPkgName); 7137 } 7138 return Collections.emptyList(); 7139 } 7140 } 7141 7142 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7143 String instantAppPkgName) { 7144 // TODO: When adding on-demand split support for non-instant apps, remove this check 7145 // and always apply post filtering 7146 if (instantAppPkgName == null) { 7147 return resolveInfos; 7148 } 7149 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7150 final ResolveInfo info = resolveInfos.get(i); 7151 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7152 // allow services that are defined in the provided package 7153 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7154 if (info.serviceInfo.splitName != null 7155 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7156 info.serviceInfo.splitName)) { 7157 // requested service is defined in a split that hasn't been installed yet. 7158 // add the installer to the resolve list 7159 if (DEBUG_EPHEMERAL) { 7160 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7161 } 7162 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7163 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7164 info.serviceInfo.packageName, info.serviceInfo.splitName, 7165 info.serviceInfo.applicationInfo.versionCode); 7166 // make sure this resolver is the default 7167 installerInfo.isDefault = true; 7168 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7169 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7170 // add a non-generic filter 7171 installerInfo.filter = new IntentFilter(); 7172 // load resources from the correct package 7173 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7174 resolveInfos.set(i, installerInfo); 7175 } 7176 continue; 7177 } 7178 // allow services that have been explicitly exposed to ephemeral apps 7179 if (!isEphemeralApp 7180 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7181 continue; 7182 } 7183 resolveInfos.remove(i); 7184 } 7185 return resolveInfos; 7186 } 7187 7188 @Override 7189 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7190 String resolvedType, int flags, int userId) { 7191 return new ParceledListSlice<>( 7192 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7193 } 7194 7195 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7196 Intent intent, String resolvedType, int flags, int userId) { 7197 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7198 final int callingUid = Binder.getCallingUid(); 7199 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7200 false /*includeInstantApps*/); 7201 ComponentName comp = intent.getComponent(); 7202 if (comp == null) { 7203 if (intent.getSelector() != null) { 7204 intent = intent.getSelector(); 7205 comp = intent.getComponent(); 7206 } 7207 } 7208 if (comp != null) { 7209 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7210 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7211 if (pi != null) { 7212 final ResolveInfo ri = new ResolveInfo(); 7213 ri.providerInfo = pi; 7214 list.add(ri); 7215 } 7216 return list; 7217 } 7218 7219 // reader 7220 synchronized (mPackages) { 7221 String pkgName = intent.getPackage(); 7222 if (pkgName == null) { 7223 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7224 } 7225 final PackageParser.Package pkg = mPackages.get(pkgName); 7226 if (pkg != null) { 7227 return mProviders.queryIntentForPackage( 7228 intent, resolvedType, flags, pkg.providers, userId); 7229 } 7230 return Collections.emptyList(); 7231 } 7232 } 7233 7234 @Override 7235 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7236 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7237 flags = updateFlagsForPackage(flags, userId, null); 7238 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7239 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7240 true /* requireFullPermission */, false /* checkShell */, 7241 "get installed packages"); 7242 7243 // writer 7244 synchronized (mPackages) { 7245 ArrayList<PackageInfo> list; 7246 if (listUninstalled) { 7247 list = new ArrayList<>(mSettings.mPackages.size()); 7248 for (PackageSetting ps : mSettings.mPackages.values()) { 7249 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7250 continue; 7251 } 7252 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7253 if (pi != null) { 7254 list.add(pi); 7255 } 7256 } 7257 } else { 7258 list = new ArrayList<>(mPackages.size()); 7259 for (PackageParser.Package p : mPackages.values()) { 7260 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7261 Binder.getCallingUid(), userId)) { 7262 continue; 7263 } 7264 final PackageInfo pi = generatePackageInfo((PackageSetting) 7265 p.mExtras, flags, userId); 7266 if (pi != null) { 7267 list.add(pi); 7268 } 7269 } 7270 } 7271 7272 return new ParceledListSlice<>(list); 7273 } 7274 } 7275 7276 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7277 String[] permissions, boolean[] tmp, int flags, int userId) { 7278 int numMatch = 0; 7279 final PermissionsState permissionsState = ps.getPermissionsState(); 7280 for (int i=0; i<permissions.length; i++) { 7281 final String permission = permissions[i]; 7282 if (permissionsState.hasPermission(permission, userId)) { 7283 tmp[i] = true; 7284 numMatch++; 7285 } else { 7286 tmp[i] = false; 7287 } 7288 } 7289 if (numMatch == 0) { 7290 return; 7291 } 7292 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7293 7294 // The above might return null in cases of uninstalled apps or install-state 7295 // skew across users/profiles. 7296 if (pi != null) { 7297 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7298 if (numMatch == permissions.length) { 7299 pi.requestedPermissions = permissions; 7300 } else { 7301 pi.requestedPermissions = new String[numMatch]; 7302 numMatch = 0; 7303 for (int i=0; i<permissions.length; i++) { 7304 if (tmp[i]) { 7305 pi.requestedPermissions[numMatch] = permissions[i]; 7306 numMatch++; 7307 } 7308 } 7309 } 7310 } 7311 list.add(pi); 7312 } 7313 } 7314 7315 @Override 7316 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7317 String[] permissions, int flags, int userId) { 7318 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7319 flags = updateFlagsForPackage(flags, userId, permissions); 7320 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7321 true /* requireFullPermission */, false /* checkShell */, 7322 "get packages holding permissions"); 7323 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7324 7325 // writer 7326 synchronized (mPackages) { 7327 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7328 boolean[] tmpBools = new boolean[permissions.length]; 7329 if (listUninstalled) { 7330 for (PackageSetting ps : mSettings.mPackages.values()) { 7331 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7332 userId); 7333 } 7334 } else { 7335 for (PackageParser.Package pkg : mPackages.values()) { 7336 PackageSetting ps = (PackageSetting)pkg.mExtras; 7337 if (ps != null) { 7338 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7339 userId); 7340 } 7341 } 7342 } 7343 7344 return new ParceledListSlice<PackageInfo>(list); 7345 } 7346 } 7347 7348 @Override 7349 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7350 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7351 flags = updateFlagsForApplication(flags, userId, null); 7352 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7353 7354 // writer 7355 synchronized (mPackages) { 7356 ArrayList<ApplicationInfo> list; 7357 if (listUninstalled) { 7358 list = new ArrayList<>(mSettings.mPackages.size()); 7359 for (PackageSetting ps : mSettings.mPackages.values()) { 7360 ApplicationInfo ai; 7361 int effectiveFlags = flags; 7362 if (ps.isSystem()) { 7363 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7364 } 7365 if (ps.pkg != null) { 7366 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7367 continue; 7368 } 7369 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7370 ps.readUserState(userId), userId); 7371 if (ai != null) { 7372 rebaseEnabledOverlays(ai, userId); 7373 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7374 } 7375 } else { 7376 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7377 // and already converts to externally visible package name 7378 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7379 Binder.getCallingUid(), effectiveFlags, userId); 7380 } 7381 if (ai != null) { 7382 list.add(ai); 7383 } 7384 } 7385 } else { 7386 list = new ArrayList<>(mPackages.size()); 7387 for (PackageParser.Package p : mPackages.values()) { 7388 if (p.mExtras != null) { 7389 PackageSetting ps = (PackageSetting) p.mExtras; 7390 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7391 continue; 7392 } 7393 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7394 ps.readUserState(userId), userId); 7395 if (ai != null) { 7396 rebaseEnabledOverlays(ai, userId); 7397 ai.packageName = resolveExternalPackageNameLPr(p); 7398 list.add(ai); 7399 } 7400 } 7401 } 7402 } 7403 7404 return new ParceledListSlice<>(list); 7405 } 7406 } 7407 7408 @Override 7409 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7410 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7411 return null; 7412 } 7413 7414 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7415 "getEphemeralApplications"); 7416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7417 true /* requireFullPermission */, false /* checkShell */, 7418 "getEphemeralApplications"); 7419 synchronized (mPackages) { 7420 List<InstantAppInfo> instantApps = mInstantAppRegistry 7421 .getInstantAppsLPr(userId); 7422 if (instantApps != null) { 7423 return new ParceledListSlice<>(instantApps); 7424 } 7425 } 7426 return null; 7427 } 7428 7429 @Override 7430 public boolean isInstantApp(String packageName, int userId) { 7431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7432 true /* requireFullPermission */, false /* checkShell */, 7433 "isInstantApp"); 7434 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7435 return false; 7436 } 7437 int uid = Binder.getCallingUid(); 7438 if (Process.isIsolated(uid)) { 7439 uid = mIsolatedOwners.get(uid); 7440 } 7441 7442 synchronized (mPackages) { 7443 final PackageSetting ps = mSettings.mPackages.get(packageName); 7444 PackageParser.Package pkg = mPackages.get(packageName); 7445 final boolean returnAllowed = 7446 ps != null 7447 && (isCallerSameApp(packageName, uid) 7448 || mContext.checkCallingOrSelfPermission( 7449 android.Manifest.permission.ACCESS_INSTANT_APPS) 7450 == PERMISSION_GRANTED 7451 || mInstantAppRegistry.isInstantAccessGranted( 7452 userId, UserHandle.getAppId(uid), ps.appId)); 7453 if (returnAllowed) { 7454 return ps.getInstantApp(userId); 7455 } 7456 } 7457 return false; 7458 } 7459 7460 @Override 7461 public byte[] getInstantAppCookie(String packageName, int userId) { 7462 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7463 return null; 7464 } 7465 7466 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7467 true /* requireFullPermission */, false /* checkShell */, 7468 "getInstantAppCookie"); 7469 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7470 return null; 7471 } 7472 synchronized (mPackages) { 7473 return mInstantAppRegistry.getInstantAppCookieLPw( 7474 packageName, userId); 7475 } 7476 } 7477 7478 @Override 7479 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7480 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7481 return true; 7482 } 7483 7484 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7485 true /* requireFullPermission */, true /* checkShell */, 7486 "setInstantAppCookie"); 7487 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7488 return false; 7489 } 7490 synchronized (mPackages) { 7491 return mInstantAppRegistry.setInstantAppCookieLPw( 7492 packageName, cookie, userId); 7493 } 7494 } 7495 7496 @Override 7497 public Bitmap getInstantAppIcon(String packageName, int userId) { 7498 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7499 return null; 7500 } 7501 7502 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7503 "getInstantAppIcon"); 7504 7505 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7506 true /* requireFullPermission */, false /* checkShell */, 7507 "getInstantAppIcon"); 7508 7509 synchronized (mPackages) { 7510 return mInstantAppRegistry.getInstantAppIconLPw( 7511 packageName, userId); 7512 } 7513 } 7514 7515 private boolean isCallerSameApp(String packageName, int uid) { 7516 PackageParser.Package pkg = mPackages.get(packageName); 7517 return pkg != null 7518 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7519 } 7520 7521 @Override 7522 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7523 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7524 } 7525 7526 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7527 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7528 7529 // reader 7530 synchronized (mPackages) { 7531 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7532 final int userId = UserHandle.getCallingUserId(); 7533 while (i.hasNext()) { 7534 final PackageParser.Package p = i.next(); 7535 if (p.applicationInfo == null) continue; 7536 7537 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7538 && !p.applicationInfo.isDirectBootAware(); 7539 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7540 && p.applicationInfo.isDirectBootAware(); 7541 7542 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7543 && (!mSafeMode || isSystemApp(p)) 7544 && (matchesUnaware || matchesAware)) { 7545 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7546 if (ps != null) { 7547 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7548 ps.readUserState(userId), userId); 7549 if (ai != null) { 7550 rebaseEnabledOverlays(ai, userId); 7551 finalList.add(ai); 7552 } 7553 } 7554 } 7555 } 7556 } 7557 7558 return finalList; 7559 } 7560 7561 @Override 7562 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7563 if (!sUserManager.exists(userId)) return null; 7564 flags = updateFlagsForComponent(flags, userId, name); 7565 // reader 7566 synchronized (mPackages) { 7567 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7568 PackageSetting ps = provider != null 7569 ? mSettings.mPackages.get(provider.owner.packageName) 7570 : null; 7571 return ps != null 7572 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7573 ? PackageParser.generateProviderInfo(provider, flags, 7574 ps.readUserState(userId), userId) 7575 : null; 7576 } 7577 } 7578 7579 /** 7580 * @deprecated 7581 */ 7582 @Deprecated 7583 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7584 // reader 7585 synchronized (mPackages) { 7586 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7587 .entrySet().iterator(); 7588 final int userId = UserHandle.getCallingUserId(); 7589 while (i.hasNext()) { 7590 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7591 PackageParser.Provider p = entry.getValue(); 7592 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7593 7594 if (ps != null && p.syncable 7595 && (!mSafeMode || (p.info.applicationInfo.flags 7596 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7597 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7598 ps.readUserState(userId), userId); 7599 if (info != null) { 7600 outNames.add(entry.getKey()); 7601 outInfo.add(info); 7602 } 7603 } 7604 } 7605 } 7606 } 7607 7608 @Override 7609 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7610 int uid, int flags, String metaDataKey) { 7611 final int userId = processName != null ? UserHandle.getUserId(uid) 7612 : UserHandle.getCallingUserId(); 7613 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7614 flags = updateFlagsForComponent(flags, userId, processName); 7615 7616 ArrayList<ProviderInfo> finalList = null; 7617 // reader 7618 synchronized (mPackages) { 7619 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7620 while (i.hasNext()) { 7621 final PackageParser.Provider p = i.next(); 7622 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7623 if (ps != null && p.info.authority != null 7624 && (processName == null 7625 || (p.info.processName.equals(processName) 7626 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7627 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7628 7629 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7630 // parameter. 7631 if (metaDataKey != null 7632 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7633 continue; 7634 } 7635 7636 if (finalList == null) { 7637 finalList = new ArrayList<ProviderInfo>(3); 7638 } 7639 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7640 ps.readUserState(userId), userId); 7641 if (info != null) { 7642 finalList.add(info); 7643 } 7644 } 7645 } 7646 } 7647 7648 if (finalList != null) { 7649 Collections.sort(finalList, mProviderInitOrderSorter); 7650 return new ParceledListSlice<ProviderInfo>(finalList); 7651 } 7652 7653 return ParceledListSlice.emptyList(); 7654 } 7655 7656 @Override 7657 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7658 // reader 7659 synchronized (mPackages) { 7660 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7661 return PackageParser.generateInstrumentationInfo(i, flags); 7662 } 7663 } 7664 7665 @Override 7666 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7667 String targetPackage, int flags) { 7668 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7669 } 7670 7671 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7672 int flags) { 7673 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7674 7675 // reader 7676 synchronized (mPackages) { 7677 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7678 while (i.hasNext()) { 7679 final PackageParser.Instrumentation p = i.next(); 7680 if (targetPackage == null 7681 || targetPackage.equals(p.info.targetPackage)) { 7682 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7683 flags); 7684 if (ii != null) { 7685 finalList.add(ii); 7686 } 7687 } 7688 } 7689 } 7690 7691 return finalList; 7692 } 7693 7694 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7695 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7696 try { 7697 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7698 } finally { 7699 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7700 } 7701 } 7702 7703 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7704 final File[] files = dir.listFiles(); 7705 if (ArrayUtils.isEmpty(files)) { 7706 Log.d(TAG, "No files in app dir " + dir); 7707 return; 7708 } 7709 7710 if (DEBUG_PACKAGE_SCANNING) { 7711 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7712 + " flags=0x" + Integer.toHexString(parseFlags)); 7713 } 7714 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7715 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7716 7717 // Submit files for parsing in parallel 7718 int fileCount = 0; 7719 for (File file : files) { 7720 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7721 && !PackageInstallerService.isStageName(file.getName()); 7722 if (!isPackage) { 7723 // Ignore entries which are not packages 7724 continue; 7725 } 7726 parallelPackageParser.submit(file, parseFlags); 7727 fileCount++; 7728 } 7729 7730 // Process results one by one 7731 for (; fileCount > 0; fileCount--) { 7732 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7733 Throwable throwable = parseResult.throwable; 7734 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7735 7736 if (throwable == null) { 7737 // Static shared libraries have synthetic package names 7738 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7739 renameStaticSharedLibraryPackage(parseResult.pkg); 7740 } 7741 try { 7742 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7743 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7744 currentTime, null); 7745 } 7746 } catch (PackageManagerException e) { 7747 errorCode = e.error; 7748 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7749 } 7750 } else if (throwable instanceof PackageParser.PackageParserException) { 7751 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7752 throwable; 7753 errorCode = e.error; 7754 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7755 } else { 7756 throw new IllegalStateException("Unexpected exception occurred while parsing " 7757 + parseResult.scanFile, throwable); 7758 } 7759 7760 // Delete invalid userdata apps 7761 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7762 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7763 logCriticalInfo(Log.WARN, 7764 "Deleting invalid package at " + parseResult.scanFile); 7765 removeCodePathLI(parseResult.scanFile); 7766 } 7767 } 7768 parallelPackageParser.close(); 7769 } 7770 7771 private static File getSettingsProblemFile() { 7772 File dataDir = Environment.getDataDirectory(); 7773 File systemDir = new File(dataDir, "system"); 7774 File fname = new File(systemDir, "uiderrors.txt"); 7775 return fname; 7776 } 7777 7778 static void reportSettingsProblem(int priority, String msg) { 7779 logCriticalInfo(priority, msg); 7780 } 7781 7782 public static void logCriticalInfo(int priority, String msg) { 7783 Slog.println(priority, TAG, msg); 7784 EventLogTags.writePmCriticalInfo(msg); 7785 try { 7786 File fname = getSettingsProblemFile(); 7787 FileOutputStream out = new FileOutputStream(fname, true); 7788 PrintWriter pw = new FastPrintWriter(out); 7789 SimpleDateFormat formatter = new SimpleDateFormat(); 7790 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7791 pw.println(dateString + ": " + msg); 7792 pw.close(); 7793 FileUtils.setPermissions( 7794 fname.toString(), 7795 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7796 -1, -1); 7797 } catch (java.io.IOException e) { 7798 } 7799 } 7800 7801 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7802 if (srcFile.isDirectory()) { 7803 final File baseFile = new File(pkg.baseCodePath); 7804 long maxModifiedTime = baseFile.lastModified(); 7805 if (pkg.splitCodePaths != null) { 7806 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7807 final File splitFile = new File(pkg.splitCodePaths[i]); 7808 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7809 } 7810 } 7811 return maxModifiedTime; 7812 } 7813 return srcFile.lastModified(); 7814 } 7815 7816 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7817 final int policyFlags) throws PackageManagerException { 7818 // When upgrading from pre-N MR1, verify the package time stamp using the package 7819 // directory and not the APK file. 7820 final long lastModifiedTime = mIsPreNMR1Upgrade 7821 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7822 if (ps != null 7823 && ps.codePath.equals(srcFile) 7824 && ps.timeStamp == lastModifiedTime 7825 && !isCompatSignatureUpdateNeeded(pkg) 7826 && !isRecoverSignatureUpdateNeeded(pkg)) { 7827 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7828 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7829 ArraySet<PublicKey> signingKs; 7830 synchronized (mPackages) { 7831 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7832 } 7833 if (ps.signatures.mSignatures != null 7834 && ps.signatures.mSignatures.length != 0 7835 && signingKs != null) { 7836 // Optimization: reuse the existing cached certificates 7837 // if the package appears to be unchanged. 7838 pkg.mSignatures = ps.signatures.mSignatures; 7839 pkg.mSigningKeys = signingKs; 7840 return; 7841 } 7842 7843 Slog.w(TAG, "PackageSetting for " + ps.name 7844 + " is missing signatures. Collecting certs again to recover them."); 7845 } else { 7846 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7847 } 7848 7849 try { 7850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7851 PackageParser.collectCertificates(pkg, policyFlags); 7852 } catch (PackageParserException e) { 7853 throw PackageManagerException.from(e); 7854 } finally { 7855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7856 } 7857 } 7858 7859 /** 7860 * Traces a package scan. 7861 * @see #scanPackageLI(File, int, int, long, UserHandle) 7862 */ 7863 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7864 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7865 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7866 try { 7867 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7868 } finally { 7869 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7870 } 7871 } 7872 7873 /** 7874 * Scans a package and returns the newly parsed package. 7875 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7876 */ 7877 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7878 long currentTime, UserHandle user) throws PackageManagerException { 7879 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7880 PackageParser pp = new PackageParser(); 7881 pp.setSeparateProcesses(mSeparateProcesses); 7882 pp.setOnlyCoreApps(mOnlyCore); 7883 pp.setDisplayMetrics(mMetrics); 7884 pp.setCallback(mPackageParserCallback); 7885 7886 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7887 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7888 } 7889 7890 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7891 final PackageParser.Package pkg; 7892 try { 7893 pkg = pp.parsePackage(scanFile, parseFlags); 7894 } catch (PackageParserException e) { 7895 throw PackageManagerException.from(e); 7896 } finally { 7897 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7898 } 7899 7900 // Static shared libraries have synthetic package names 7901 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7902 renameStaticSharedLibraryPackage(pkg); 7903 } 7904 7905 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7906 } 7907 7908 /** 7909 * Scans a package and returns the newly parsed package. 7910 * @throws PackageManagerException on a parse error. 7911 */ 7912 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7913 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7914 throws PackageManagerException { 7915 // If the package has children and this is the first dive in the function 7916 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7917 // packages (parent and children) would be successfully scanned before the 7918 // actual scan since scanning mutates internal state and we want to atomically 7919 // install the package and its children. 7920 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7921 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7922 scanFlags |= SCAN_CHECK_ONLY; 7923 } 7924 } else { 7925 scanFlags &= ~SCAN_CHECK_ONLY; 7926 } 7927 7928 // Scan the parent 7929 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7930 scanFlags, currentTime, user); 7931 7932 // Scan the children 7933 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7934 for (int i = 0; i < childCount; i++) { 7935 PackageParser.Package childPackage = pkg.childPackages.get(i); 7936 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7937 currentTime, user); 7938 } 7939 7940 7941 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7942 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7943 } 7944 7945 return scannedPkg; 7946 } 7947 7948 /** 7949 * Scans a package and returns the newly parsed package. 7950 * @throws PackageManagerException on a parse error. 7951 */ 7952 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7953 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7954 throws PackageManagerException { 7955 PackageSetting ps = null; 7956 PackageSetting updatedPkg; 7957 // reader 7958 synchronized (mPackages) { 7959 // Look to see if we already know about this package. 7960 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7961 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7962 // This package has been renamed to its original name. Let's 7963 // use that. 7964 ps = mSettings.getPackageLPr(oldName); 7965 } 7966 // If there was no original package, see one for the real package name. 7967 if (ps == null) { 7968 ps = mSettings.getPackageLPr(pkg.packageName); 7969 } 7970 // Check to see if this package could be hiding/updating a system 7971 // package. Must look for it either under the original or real 7972 // package name depending on our state. 7973 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7974 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7975 7976 // If this is a package we don't know about on the system partition, we 7977 // may need to remove disabled child packages on the system partition 7978 // or may need to not add child packages if the parent apk is updated 7979 // on the data partition and no longer defines this child package. 7980 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7981 // If this is a parent package for an updated system app and this system 7982 // app got an OTA update which no longer defines some of the child packages 7983 // we have to prune them from the disabled system packages. 7984 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7985 if (disabledPs != null) { 7986 final int scannedChildCount = (pkg.childPackages != null) 7987 ? pkg.childPackages.size() : 0; 7988 final int disabledChildCount = disabledPs.childPackageNames != null 7989 ? disabledPs.childPackageNames.size() : 0; 7990 for (int i = 0; i < disabledChildCount; i++) { 7991 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7992 boolean disabledPackageAvailable = false; 7993 for (int j = 0; j < scannedChildCount; j++) { 7994 PackageParser.Package childPkg = pkg.childPackages.get(j); 7995 if (childPkg.packageName.equals(disabledChildPackageName)) { 7996 disabledPackageAvailable = true; 7997 break; 7998 } 7999 } 8000 if (!disabledPackageAvailable) { 8001 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8002 } 8003 } 8004 } 8005 } 8006 } 8007 8008 boolean updatedPkgBetter = false; 8009 // First check if this is a system package that may involve an update 8010 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8011 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8012 // it needs to drop FLAG_PRIVILEGED. 8013 if (locationIsPrivileged(scanFile)) { 8014 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8015 } else { 8016 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8017 } 8018 8019 if (ps != null && !ps.codePath.equals(scanFile)) { 8020 // The path has changed from what was last scanned... check the 8021 // version of the new path against what we have stored to determine 8022 // what to do. 8023 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8024 if (pkg.mVersionCode <= ps.versionCode) { 8025 // The system package has been updated and the code path does not match 8026 // Ignore entry. Skip it. 8027 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8028 + " ignored: updated version " + ps.versionCode 8029 + " better than this " + pkg.mVersionCode); 8030 if (!updatedPkg.codePath.equals(scanFile)) { 8031 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8032 + ps.name + " changing from " + updatedPkg.codePathString 8033 + " to " + scanFile); 8034 updatedPkg.codePath = scanFile; 8035 updatedPkg.codePathString = scanFile.toString(); 8036 updatedPkg.resourcePath = scanFile; 8037 updatedPkg.resourcePathString = scanFile.toString(); 8038 } 8039 updatedPkg.pkg = pkg; 8040 updatedPkg.versionCode = pkg.mVersionCode; 8041 8042 // Update the disabled system child packages to point to the package too. 8043 final int childCount = updatedPkg.childPackageNames != null 8044 ? updatedPkg.childPackageNames.size() : 0; 8045 for (int i = 0; i < childCount; i++) { 8046 String childPackageName = updatedPkg.childPackageNames.get(i); 8047 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8048 childPackageName); 8049 if (updatedChildPkg != null) { 8050 updatedChildPkg.pkg = pkg; 8051 updatedChildPkg.versionCode = pkg.mVersionCode; 8052 } 8053 } 8054 8055 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8056 + scanFile + " ignored: updated version " + ps.versionCode 8057 + " better than this " + pkg.mVersionCode); 8058 } else { 8059 // The current app on the system partition is better than 8060 // what we have updated to on the data partition; switch 8061 // back to the system partition version. 8062 // At this point, its safely assumed that package installation for 8063 // apps in system partition will go through. If not there won't be a working 8064 // version of the app 8065 // writer 8066 synchronized (mPackages) { 8067 // Just remove the loaded entries from package lists. 8068 mPackages.remove(ps.name); 8069 } 8070 8071 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8072 + " reverting from " + ps.codePathString 8073 + ": new version " + pkg.mVersionCode 8074 + " better than installed " + ps.versionCode); 8075 8076 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8077 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8078 synchronized (mInstallLock) { 8079 args.cleanUpResourcesLI(); 8080 } 8081 synchronized (mPackages) { 8082 mSettings.enableSystemPackageLPw(ps.name); 8083 } 8084 updatedPkgBetter = true; 8085 } 8086 } 8087 } 8088 8089 if (updatedPkg != null) { 8090 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8091 // initially 8092 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8093 8094 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8095 // flag set initially 8096 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8097 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8098 } 8099 } 8100 8101 // Verify certificates against what was last scanned 8102 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8103 8104 /* 8105 * A new system app appeared, but we already had a non-system one of the 8106 * same name installed earlier. 8107 */ 8108 boolean shouldHideSystemApp = false; 8109 if (updatedPkg == null && ps != null 8110 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8111 /* 8112 * Check to make sure the signatures match first. If they don't, 8113 * wipe the installed application and its data. 8114 */ 8115 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8116 != PackageManager.SIGNATURE_MATCH) { 8117 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8118 + " signatures don't match existing userdata copy; removing"); 8119 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8120 "scanPackageInternalLI")) { 8121 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8122 } 8123 ps = null; 8124 } else { 8125 /* 8126 * If the newly-added system app is an older version than the 8127 * already installed version, hide it. It will be scanned later 8128 * and re-added like an update. 8129 */ 8130 if (pkg.mVersionCode <= ps.versionCode) { 8131 shouldHideSystemApp = true; 8132 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8133 + " but new version " + pkg.mVersionCode + " better than installed " 8134 + ps.versionCode + "; hiding system"); 8135 } else { 8136 /* 8137 * The newly found system app is a newer version that the 8138 * one previously installed. Simply remove the 8139 * already-installed application and replace it with our own 8140 * while keeping the application data. 8141 */ 8142 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8143 + " reverting from " + ps.codePathString + ": new version " 8144 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8145 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8146 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8147 synchronized (mInstallLock) { 8148 args.cleanUpResourcesLI(); 8149 } 8150 } 8151 } 8152 } 8153 8154 // The apk is forward locked (not public) if its code and resources 8155 // are kept in different files. (except for app in either system or 8156 // vendor path). 8157 // TODO grab this value from PackageSettings 8158 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8159 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8160 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8161 } 8162 } 8163 8164 // TODO: extend to support forward-locked splits 8165 String resourcePath = null; 8166 String baseResourcePath = null; 8167 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8168 if (ps != null && ps.resourcePathString != null) { 8169 resourcePath = ps.resourcePathString; 8170 baseResourcePath = ps.resourcePathString; 8171 } else { 8172 // Should not happen at all. Just log an error. 8173 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8174 } 8175 } else { 8176 resourcePath = pkg.codePath; 8177 baseResourcePath = pkg.baseCodePath; 8178 } 8179 8180 // Set application objects path explicitly. 8181 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8182 pkg.setApplicationInfoCodePath(pkg.codePath); 8183 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8184 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8185 pkg.setApplicationInfoResourcePath(resourcePath); 8186 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8187 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8188 8189 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8190 if (ps != null && ps.getInstantApp(userId)) { 8191 scanFlags |= SCAN_AS_INSTANT_APP; 8192 } 8193 8194 // Note that we invoke the following method only if we are about to unpack an application 8195 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8196 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8197 8198 /* 8199 * If the system app should be overridden by a previously installed 8200 * data, hide the system app now and let the /data/app scan pick it up 8201 * again. 8202 */ 8203 if (shouldHideSystemApp) { 8204 synchronized (mPackages) { 8205 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8206 } 8207 } 8208 8209 return scannedPkg; 8210 } 8211 8212 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8213 // Derive the new package synthetic package name 8214 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8215 + pkg.staticSharedLibVersion); 8216 } 8217 8218 private static String fixProcessName(String defProcessName, 8219 String processName) { 8220 if (processName == null) { 8221 return defProcessName; 8222 } 8223 return processName; 8224 } 8225 8226 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8227 throws PackageManagerException { 8228 if (pkgSetting.signatures.mSignatures != null) { 8229 // Already existing package. Make sure signatures match 8230 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8231 == PackageManager.SIGNATURE_MATCH; 8232 if (!match) { 8233 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8234 == PackageManager.SIGNATURE_MATCH; 8235 } 8236 if (!match) { 8237 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8238 == PackageManager.SIGNATURE_MATCH; 8239 } 8240 if (!match) { 8241 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8242 + pkg.packageName + " signatures do not match the " 8243 + "previously installed version; ignoring!"); 8244 } 8245 } 8246 8247 // Check for shared user signatures 8248 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8249 // Already existing package. Make sure signatures match 8250 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8251 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8252 if (!match) { 8253 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8254 == PackageManager.SIGNATURE_MATCH; 8255 } 8256 if (!match) { 8257 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8258 == PackageManager.SIGNATURE_MATCH; 8259 } 8260 if (!match) { 8261 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8262 "Package " + pkg.packageName 8263 + " has no signatures that match those in shared user " 8264 + pkgSetting.sharedUser.name + "; ignoring!"); 8265 } 8266 } 8267 } 8268 8269 /** 8270 * Enforces that only the system UID or root's UID can call a method exposed 8271 * via Binder. 8272 * 8273 * @param message used as message if SecurityException is thrown 8274 * @throws SecurityException if the caller is not system or root 8275 */ 8276 private static final void enforceSystemOrRoot(String message) { 8277 final int uid = Binder.getCallingUid(); 8278 if (uid != Process.SYSTEM_UID && uid != 0) { 8279 throw new SecurityException(message); 8280 } 8281 } 8282 8283 @Override 8284 public void performFstrimIfNeeded() { 8285 enforceSystemOrRoot("Only the system can request fstrim"); 8286 8287 // Before everything else, see whether we need to fstrim. 8288 try { 8289 IStorageManager sm = PackageHelper.getStorageManager(); 8290 if (sm != null) { 8291 boolean doTrim = false; 8292 final long interval = android.provider.Settings.Global.getLong( 8293 mContext.getContentResolver(), 8294 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8295 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8296 if (interval > 0) { 8297 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8298 if (timeSinceLast > interval) { 8299 doTrim = true; 8300 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8301 + "; running immediately"); 8302 } 8303 } 8304 if (doTrim) { 8305 final boolean dexOptDialogShown; 8306 synchronized (mPackages) { 8307 dexOptDialogShown = mDexOptDialogShown; 8308 } 8309 if (!isFirstBoot() && dexOptDialogShown) { 8310 try { 8311 ActivityManager.getService().showBootMessage( 8312 mContext.getResources().getString( 8313 R.string.android_upgrading_fstrim), true); 8314 } catch (RemoteException e) { 8315 } 8316 } 8317 sm.runMaintenance(); 8318 } 8319 } else { 8320 Slog.e(TAG, "storageManager service unavailable!"); 8321 } 8322 } catch (RemoteException e) { 8323 // Can't happen; StorageManagerService is local 8324 } 8325 } 8326 8327 @Override 8328 public void updatePackagesIfNeeded() { 8329 enforceSystemOrRoot("Only the system can request package update"); 8330 8331 // We need to re-extract after an OTA. 8332 boolean causeUpgrade = isUpgrade(); 8333 8334 // First boot or factory reset. 8335 // Note: we also handle devices that are upgrading to N right now as if it is their 8336 // first boot, as they do not have profile data. 8337 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8338 8339 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8340 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8341 8342 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8343 return; 8344 } 8345 8346 List<PackageParser.Package> pkgs; 8347 synchronized (mPackages) { 8348 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8349 } 8350 8351 final long startTime = System.nanoTime(); 8352 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8353 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8354 8355 final int elapsedTimeSeconds = 8356 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8357 8358 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8359 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8360 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8361 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8362 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8363 } 8364 8365 /** 8366 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8367 * containing statistics about the invocation. The array consists of three elements, 8368 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8369 * and {@code numberOfPackagesFailed}. 8370 */ 8371 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8372 String compilerFilter) { 8373 8374 int numberOfPackagesVisited = 0; 8375 int numberOfPackagesOptimized = 0; 8376 int numberOfPackagesSkipped = 0; 8377 int numberOfPackagesFailed = 0; 8378 final int numberOfPackagesToDexopt = pkgs.size(); 8379 8380 for (PackageParser.Package pkg : pkgs) { 8381 numberOfPackagesVisited++; 8382 8383 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8384 if (DEBUG_DEXOPT) { 8385 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8386 } 8387 numberOfPackagesSkipped++; 8388 continue; 8389 } 8390 8391 if (DEBUG_DEXOPT) { 8392 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8393 numberOfPackagesToDexopt + ": " + pkg.packageName); 8394 } 8395 8396 if (showDialog) { 8397 try { 8398 ActivityManager.getService().showBootMessage( 8399 mContext.getResources().getString(R.string.android_upgrading_apk, 8400 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8401 } catch (RemoteException e) { 8402 } 8403 synchronized (mPackages) { 8404 mDexOptDialogShown = true; 8405 } 8406 } 8407 8408 // If the OTA updates a system app which was previously preopted to a non-preopted state 8409 // the app might end up being verified at runtime. That's because by default the apps 8410 // are verify-profile but for preopted apps there's no profile. 8411 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8412 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8413 // filter (by default interpret-only). 8414 // Note that at this stage unused apps are already filtered. 8415 if (isSystemApp(pkg) && 8416 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8417 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8418 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8419 } 8420 8421 // checkProfiles is false to avoid merging profiles during boot which 8422 // might interfere with background compilation (b/28612421). 8423 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8424 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8425 // trade-off worth doing to save boot time work. 8426 int dexOptStatus = performDexOptTraced(pkg.packageName, 8427 false /* checkProfiles */, 8428 compilerFilter, 8429 false /* force */); 8430 switch (dexOptStatus) { 8431 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8432 numberOfPackagesOptimized++; 8433 break; 8434 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8435 numberOfPackagesSkipped++; 8436 break; 8437 case PackageDexOptimizer.DEX_OPT_FAILED: 8438 numberOfPackagesFailed++; 8439 break; 8440 default: 8441 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8442 break; 8443 } 8444 } 8445 8446 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8447 numberOfPackagesFailed }; 8448 } 8449 8450 @Override 8451 public void notifyPackageUse(String packageName, int reason) { 8452 synchronized (mPackages) { 8453 PackageParser.Package p = mPackages.get(packageName); 8454 if (p == null) { 8455 return; 8456 } 8457 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8458 } 8459 } 8460 8461 @Override 8462 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8463 int userId = UserHandle.getCallingUserId(); 8464 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8465 if (ai == null) { 8466 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8467 + loadingPackageName + ", user=" + userId); 8468 return; 8469 } 8470 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8471 } 8472 8473 // TODO: this is not used nor needed. Delete it. 8474 @Override 8475 public boolean performDexOptIfNeeded(String packageName) { 8476 int dexOptStatus = performDexOptTraced(packageName, 8477 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8478 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8479 } 8480 8481 @Override 8482 public boolean performDexOpt(String packageName, 8483 boolean checkProfiles, int compileReason, boolean force) { 8484 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8485 getCompilerFilterForReason(compileReason), force); 8486 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8487 } 8488 8489 @Override 8490 public boolean performDexOptMode(String packageName, 8491 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8492 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8493 targetCompilerFilter, force); 8494 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8495 } 8496 8497 private int performDexOptTraced(String packageName, 8498 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8500 try { 8501 return performDexOptInternal(packageName, checkProfiles, 8502 targetCompilerFilter, force); 8503 } finally { 8504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8505 } 8506 } 8507 8508 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8509 // if the package can now be considered up to date for the given filter. 8510 private int performDexOptInternal(String packageName, 8511 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8512 PackageParser.Package p; 8513 synchronized (mPackages) { 8514 p = mPackages.get(packageName); 8515 if (p == null) { 8516 // Package could not be found. Report failure. 8517 return PackageDexOptimizer.DEX_OPT_FAILED; 8518 } 8519 mPackageUsage.maybeWriteAsync(mPackages); 8520 mCompilerStats.maybeWriteAsync(); 8521 } 8522 long callingId = Binder.clearCallingIdentity(); 8523 try { 8524 synchronized (mInstallLock) { 8525 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8526 targetCompilerFilter, force); 8527 } 8528 } finally { 8529 Binder.restoreCallingIdentity(callingId); 8530 } 8531 } 8532 8533 public ArraySet<String> getOptimizablePackages() { 8534 ArraySet<String> pkgs = new ArraySet<String>(); 8535 synchronized (mPackages) { 8536 for (PackageParser.Package p : mPackages.values()) { 8537 if (PackageDexOptimizer.canOptimizePackage(p)) { 8538 pkgs.add(p.packageName); 8539 } 8540 } 8541 } 8542 return pkgs; 8543 } 8544 8545 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8546 boolean checkProfiles, String targetCompilerFilter, 8547 boolean force) { 8548 // Select the dex optimizer based on the force parameter. 8549 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8550 // allocate an object here. 8551 PackageDexOptimizer pdo = force 8552 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8553 : mPackageDexOptimizer; 8554 8555 // Dexopt all dependencies first. Note: we ignore the return value and march on 8556 // on errors. 8557 // Note that we are going to call performDexOpt on those libraries as many times as 8558 // they are referenced in packages. When we do a batch of performDexOpt (for example 8559 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8560 // and the first package that uses the library will dexopt it. The 8561 // others will see that the compiled code for the library is up to date. 8562 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8563 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8564 if (!deps.isEmpty()) { 8565 for (PackageParser.Package depPackage : deps) { 8566 // TODO: Analyze and investigate if we (should) profile libraries. 8567 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8568 false /* checkProfiles */, 8569 targetCompilerFilter, 8570 getOrCreateCompilerPackageStats(depPackage), 8571 true /* isUsedByOtherApps */); 8572 } 8573 } 8574 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8575 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8576 mDexManager.isUsedByOtherApps(p.packageName)); 8577 } 8578 8579 // Performs dexopt on the used secondary dex files belonging to the given package. 8580 // Returns true if all dex files were process successfully (which could mean either dexopt or 8581 // skip). Returns false if any of the files caused errors. 8582 @Override 8583 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8584 boolean force) { 8585 mDexManager.reconcileSecondaryDexFiles(packageName); 8586 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8587 } 8588 8589 public boolean performDexOptSecondary(String packageName, int compileReason, 8590 boolean force) { 8591 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8592 } 8593 8594 /** 8595 * Reconcile the information we have about the secondary dex files belonging to 8596 * {@code packagName} and the actual dex files. For all dex files that were 8597 * deleted, update the internal records and delete the generated oat files. 8598 */ 8599 @Override 8600 public void reconcileSecondaryDexFiles(String packageName) { 8601 mDexManager.reconcileSecondaryDexFiles(packageName); 8602 } 8603 8604 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8605 // a reference there. 8606 /*package*/ DexManager getDexManager() { 8607 return mDexManager; 8608 } 8609 8610 /** 8611 * Execute the background dexopt job immediately. 8612 */ 8613 @Override 8614 public boolean runBackgroundDexoptJob() { 8615 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8616 } 8617 8618 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8619 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8620 || p.usesStaticLibraries != null) { 8621 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8622 Set<String> collectedNames = new HashSet<>(); 8623 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8624 8625 retValue.remove(p); 8626 8627 return retValue; 8628 } else { 8629 return Collections.emptyList(); 8630 } 8631 } 8632 8633 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8634 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8635 if (!collectedNames.contains(p.packageName)) { 8636 collectedNames.add(p.packageName); 8637 collected.add(p); 8638 8639 if (p.usesLibraries != null) { 8640 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8641 null, collected, collectedNames); 8642 } 8643 if (p.usesOptionalLibraries != null) { 8644 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8645 null, collected, collectedNames); 8646 } 8647 if (p.usesStaticLibraries != null) { 8648 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8649 p.usesStaticLibrariesVersions, collected, collectedNames); 8650 } 8651 } 8652 } 8653 8654 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8655 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8656 final int libNameCount = libs.size(); 8657 for (int i = 0; i < libNameCount; i++) { 8658 String libName = libs.get(i); 8659 int version = (versions != null && versions.length == libNameCount) 8660 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8661 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8662 if (libPkg != null) { 8663 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8664 } 8665 } 8666 } 8667 8668 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8669 synchronized (mPackages) { 8670 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8671 if (libEntry != null) { 8672 return mPackages.get(libEntry.apk); 8673 } 8674 return null; 8675 } 8676 } 8677 8678 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8679 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8680 if (versionedLib == null) { 8681 return null; 8682 } 8683 return versionedLib.get(version); 8684 } 8685 8686 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8687 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8688 pkg.staticSharedLibName); 8689 if (versionedLib == null) { 8690 return null; 8691 } 8692 int previousLibVersion = -1; 8693 final int versionCount = versionedLib.size(); 8694 for (int i = 0; i < versionCount; i++) { 8695 final int libVersion = versionedLib.keyAt(i); 8696 if (libVersion < pkg.staticSharedLibVersion) { 8697 previousLibVersion = Math.max(previousLibVersion, libVersion); 8698 } 8699 } 8700 if (previousLibVersion >= 0) { 8701 return versionedLib.get(previousLibVersion); 8702 } 8703 return null; 8704 } 8705 8706 public void shutdown() { 8707 mPackageUsage.writeNow(mPackages); 8708 mCompilerStats.writeNow(); 8709 } 8710 8711 @Override 8712 public void dumpProfiles(String packageName) { 8713 PackageParser.Package pkg; 8714 synchronized (mPackages) { 8715 pkg = mPackages.get(packageName); 8716 if (pkg == null) { 8717 throw new IllegalArgumentException("Unknown package: " + packageName); 8718 } 8719 } 8720 /* Only the shell, root, or the app user should be able to dump profiles. */ 8721 int callingUid = Binder.getCallingUid(); 8722 if (callingUid != Process.SHELL_UID && 8723 callingUid != Process.ROOT_UID && 8724 callingUid != pkg.applicationInfo.uid) { 8725 throw new SecurityException("dumpProfiles"); 8726 } 8727 8728 synchronized (mInstallLock) { 8729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8730 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8731 try { 8732 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8733 String codePaths = TextUtils.join(";", allCodePaths); 8734 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8735 } catch (InstallerException e) { 8736 Slog.w(TAG, "Failed to dump profiles", e); 8737 } 8738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8739 } 8740 } 8741 8742 @Override 8743 public void forceDexOpt(String packageName) { 8744 enforceSystemOrRoot("forceDexOpt"); 8745 8746 PackageParser.Package pkg; 8747 synchronized (mPackages) { 8748 pkg = mPackages.get(packageName); 8749 if (pkg == null) { 8750 throw new IllegalArgumentException("Unknown package: " + packageName); 8751 } 8752 } 8753 8754 synchronized (mInstallLock) { 8755 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8756 8757 // Whoever is calling forceDexOpt wants a fully compiled package. 8758 // Don't use profiles since that may cause compilation to be skipped. 8759 final int res = performDexOptInternalWithDependenciesLI(pkg, 8760 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8761 true /* force */); 8762 8763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8764 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8765 throw new IllegalStateException("Failed to dexopt: " + res); 8766 } 8767 } 8768 } 8769 8770 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8771 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8772 Slog.w(TAG, "Unable to update from " + oldPkg.name 8773 + " to " + newPkg.packageName 8774 + ": old package not in system partition"); 8775 return false; 8776 } else if (mPackages.get(oldPkg.name) != null) { 8777 Slog.w(TAG, "Unable to update from " + oldPkg.name 8778 + " to " + newPkg.packageName 8779 + ": old package still exists"); 8780 return false; 8781 } 8782 return true; 8783 } 8784 8785 void removeCodePathLI(File codePath) { 8786 if (codePath.isDirectory()) { 8787 try { 8788 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8789 } catch (InstallerException e) { 8790 Slog.w(TAG, "Failed to remove code path", e); 8791 } 8792 } else { 8793 codePath.delete(); 8794 } 8795 } 8796 8797 private int[] resolveUserIds(int userId) { 8798 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8799 } 8800 8801 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8802 if (pkg == null) { 8803 Slog.wtf(TAG, "Package was null!", new Throwable()); 8804 return; 8805 } 8806 clearAppDataLeafLIF(pkg, userId, flags); 8807 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8808 for (int i = 0; i < childCount; i++) { 8809 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8810 } 8811 } 8812 8813 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8814 final PackageSetting ps; 8815 synchronized (mPackages) { 8816 ps = mSettings.mPackages.get(pkg.packageName); 8817 } 8818 for (int realUserId : resolveUserIds(userId)) { 8819 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8820 try { 8821 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8822 ceDataInode); 8823 } catch (InstallerException e) { 8824 Slog.w(TAG, String.valueOf(e)); 8825 } 8826 } 8827 } 8828 8829 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8830 if (pkg == null) { 8831 Slog.wtf(TAG, "Package was null!", new Throwable()); 8832 return; 8833 } 8834 destroyAppDataLeafLIF(pkg, userId, flags); 8835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8836 for (int i = 0; i < childCount; i++) { 8837 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8838 } 8839 } 8840 8841 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8842 final PackageSetting ps; 8843 synchronized (mPackages) { 8844 ps = mSettings.mPackages.get(pkg.packageName); 8845 } 8846 for (int realUserId : resolveUserIds(userId)) { 8847 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8848 try { 8849 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8850 ceDataInode); 8851 } catch (InstallerException e) { 8852 Slog.w(TAG, String.valueOf(e)); 8853 } 8854 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8855 } 8856 } 8857 8858 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8859 if (pkg == null) { 8860 Slog.wtf(TAG, "Package was null!", new Throwable()); 8861 return; 8862 } 8863 destroyAppProfilesLeafLIF(pkg); 8864 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8865 for (int i = 0; i < childCount; i++) { 8866 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8867 } 8868 } 8869 8870 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8871 try { 8872 mInstaller.destroyAppProfiles(pkg.packageName); 8873 } catch (InstallerException e) { 8874 Slog.w(TAG, String.valueOf(e)); 8875 } 8876 } 8877 8878 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8879 if (pkg == null) { 8880 Slog.wtf(TAG, "Package was null!", new Throwable()); 8881 return; 8882 } 8883 clearAppProfilesLeafLIF(pkg); 8884 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8885 for (int i = 0; i < childCount; i++) { 8886 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8887 } 8888 } 8889 8890 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8891 try { 8892 mInstaller.clearAppProfiles(pkg.packageName); 8893 } catch (InstallerException e) { 8894 Slog.w(TAG, String.valueOf(e)); 8895 } 8896 } 8897 8898 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8899 long lastUpdateTime) { 8900 // Set parent install/update time 8901 PackageSetting ps = (PackageSetting) pkg.mExtras; 8902 if (ps != null) { 8903 ps.firstInstallTime = firstInstallTime; 8904 ps.lastUpdateTime = lastUpdateTime; 8905 } 8906 // Set children install/update time 8907 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8908 for (int i = 0; i < childCount; i++) { 8909 PackageParser.Package childPkg = pkg.childPackages.get(i); 8910 ps = (PackageSetting) childPkg.mExtras; 8911 if (ps != null) { 8912 ps.firstInstallTime = firstInstallTime; 8913 ps.lastUpdateTime = lastUpdateTime; 8914 } 8915 } 8916 } 8917 8918 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8919 PackageParser.Package changingLib) { 8920 if (file.path != null) { 8921 usesLibraryFiles.add(file.path); 8922 return; 8923 } 8924 PackageParser.Package p = mPackages.get(file.apk); 8925 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8926 // If we are doing this while in the middle of updating a library apk, 8927 // then we need to make sure to use that new apk for determining the 8928 // dependencies here. (We haven't yet finished committing the new apk 8929 // to the package manager state.) 8930 if (p == null || p.packageName.equals(changingLib.packageName)) { 8931 p = changingLib; 8932 } 8933 } 8934 if (p != null) { 8935 usesLibraryFiles.addAll(p.getAllCodePaths()); 8936 } 8937 } 8938 8939 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8940 PackageParser.Package changingLib) throws PackageManagerException { 8941 if (pkg == null) { 8942 return; 8943 } 8944 ArraySet<String> usesLibraryFiles = null; 8945 if (pkg.usesLibraries != null) { 8946 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8947 null, null, pkg.packageName, changingLib, true, null); 8948 } 8949 if (pkg.usesStaticLibraries != null) { 8950 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8951 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8952 pkg.packageName, changingLib, true, usesLibraryFiles); 8953 } 8954 if (pkg.usesOptionalLibraries != null) { 8955 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8956 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8957 } 8958 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8959 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8960 } else { 8961 pkg.usesLibraryFiles = null; 8962 } 8963 } 8964 8965 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8966 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8967 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8968 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8969 throws PackageManagerException { 8970 final int libCount = requestedLibraries.size(); 8971 for (int i = 0; i < libCount; i++) { 8972 final String libName = requestedLibraries.get(i); 8973 final int libVersion = requiredVersions != null ? requiredVersions[i] 8974 : SharedLibraryInfo.VERSION_UNDEFINED; 8975 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8976 if (libEntry == null) { 8977 if (required) { 8978 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8979 "Package " + packageName + " requires unavailable shared library " 8980 + libName + "; failing!"); 8981 } else { 8982 Slog.w(TAG, "Package " + packageName 8983 + " desires unavailable shared library " 8984 + libName + "; ignoring!"); 8985 } 8986 } else { 8987 if (requiredVersions != null && requiredCertDigests != null) { 8988 if (libEntry.info.getVersion() != requiredVersions[i]) { 8989 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8990 "Package " + packageName + " requires unavailable static shared" 8991 + " library " + libName + " version " 8992 + libEntry.info.getVersion() + "; failing!"); 8993 } 8994 8995 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8996 if (libPkg == null) { 8997 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8998 "Package " + packageName + " requires unavailable static shared" 8999 + " library; failing!"); 9000 } 9001 9002 String expectedCertDigest = requiredCertDigests[i]; 9003 String libCertDigest = PackageUtils.computeCertSha256Digest( 9004 libPkg.mSignatures[0]); 9005 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9006 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9007 "Package " + packageName + " requires differently signed" + 9008 " static shared library; failing!"); 9009 } 9010 } 9011 9012 if (outUsedLibraries == null) { 9013 outUsedLibraries = new ArraySet<>(); 9014 } 9015 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9016 } 9017 } 9018 return outUsedLibraries; 9019 } 9020 9021 private static boolean hasString(List<String> list, List<String> which) { 9022 if (list == null) { 9023 return false; 9024 } 9025 for (int i=list.size()-1; i>=0; i--) { 9026 for (int j=which.size()-1; j>=0; j--) { 9027 if (which.get(j).equals(list.get(i))) { 9028 return true; 9029 } 9030 } 9031 } 9032 return false; 9033 } 9034 9035 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9036 PackageParser.Package changingPkg) { 9037 ArrayList<PackageParser.Package> res = null; 9038 for (PackageParser.Package pkg : mPackages.values()) { 9039 if (changingPkg != null 9040 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9041 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9042 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9043 changingPkg.staticSharedLibName)) { 9044 return null; 9045 } 9046 if (res == null) { 9047 res = new ArrayList<>(); 9048 } 9049 res.add(pkg); 9050 try { 9051 updateSharedLibrariesLPr(pkg, changingPkg); 9052 } catch (PackageManagerException e) { 9053 // If a system app update or an app and a required lib missing we 9054 // delete the package and for updated system apps keep the data as 9055 // it is better for the user to reinstall than to be in an limbo 9056 // state. Also libs disappearing under an app should never happen 9057 // - just in case. 9058 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9059 final int flags = pkg.isUpdatedSystemApp() 9060 ? PackageManager.DELETE_KEEP_DATA : 0; 9061 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9062 flags , null, true, null); 9063 } 9064 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9065 } 9066 } 9067 return res; 9068 } 9069 9070 /** 9071 * Derive the value of the {@code cpuAbiOverride} based on the provided 9072 * value and an optional stored value from the package settings. 9073 */ 9074 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9075 String cpuAbiOverride = null; 9076 9077 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9078 cpuAbiOverride = null; 9079 } else if (abiOverride != null) { 9080 cpuAbiOverride = abiOverride; 9081 } else if (settings != null) { 9082 cpuAbiOverride = settings.cpuAbiOverrideString; 9083 } 9084 9085 return cpuAbiOverride; 9086 } 9087 9088 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9089 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9090 throws PackageManagerException { 9091 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9092 // If the package has children and this is the first dive in the function 9093 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9094 // whether all packages (parent and children) would be successfully scanned 9095 // before the actual scan since scanning mutates internal state and we want 9096 // to atomically install the package and its children. 9097 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9098 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9099 scanFlags |= SCAN_CHECK_ONLY; 9100 } 9101 } else { 9102 scanFlags &= ~SCAN_CHECK_ONLY; 9103 } 9104 9105 final PackageParser.Package scannedPkg; 9106 try { 9107 // Scan the parent 9108 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9109 // Scan the children 9110 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9111 for (int i = 0; i < childCount; i++) { 9112 PackageParser.Package childPkg = pkg.childPackages.get(i); 9113 scanPackageLI(childPkg, policyFlags, 9114 scanFlags, currentTime, user); 9115 } 9116 } finally { 9117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9118 } 9119 9120 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9121 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9122 } 9123 9124 return scannedPkg; 9125 } 9126 9127 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9128 int scanFlags, long currentTime, @Nullable UserHandle user) 9129 throws PackageManagerException { 9130 boolean success = false; 9131 try { 9132 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9133 currentTime, user); 9134 success = true; 9135 return res; 9136 } finally { 9137 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9138 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9139 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9140 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9141 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9142 } 9143 } 9144 } 9145 9146 /** 9147 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9148 */ 9149 private static boolean apkHasCode(String fileName) { 9150 StrictJarFile jarFile = null; 9151 try { 9152 jarFile = new StrictJarFile(fileName, 9153 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9154 return jarFile.findEntry("classes.dex") != null; 9155 } catch (IOException ignore) { 9156 } finally { 9157 try { 9158 if (jarFile != null) { 9159 jarFile.close(); 9160 } 9161 } catch (IOException ignore) {} 9162 } 9163 return false; 9164 } 9165 9166 /** 9167 * Enforces code policy for the package. This ensures that if an APK has 9168 * declared hasCode="true" in its manifest that the APK actually contains 9169 * code. 9170 * 9171 * @throws PackageManagerException If bytecode could not be found when it should exist 9172 */ 9173 private static void assertCodePolicy(PackageParser.Package pkg) 9174 throws PackageManagerException { 9175 final boolean shouldHaveCode = 9176 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9177 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9178 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9179 "Package " + pkg.baseCodePath + " code is missing"); 9180 } 9181 9182 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9183 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9184 final boolean splitShouldHaveCode = 9185 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9186 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9187 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9188 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9189 } 9190 } 9191 } 9192 } 9193 9194 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9195 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9196 throws PackageManagerException { 9197 if (DEBUG_PACKAGE_SCANNING) { 9198 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9199 Log.d(TAG, "Scanning package " + pkg.packageName); 9200 } 9201 9202 applyPolicy(pkg, policyFlags); 9203 9204 assertPackageIsValid(pkg, policyFlags, scanFlags); 9205 9206 // Initialize package source and resource directories 9207 final File scanFile = new File(pkg.codePath); 9208 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9209 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9210 9211 SharedUserSetting suid = null; 9212 PackageSetting pkgSetting = null; 9213 9214 // Getting the package setting may have a side-effect, so if we 9215 // are only checking if scan would succeed, stash a copy of the 9216 // old setting to restore at the end. 9217 PackageSetting nonMutatedPs = null; 9218 9219 // We keep references to the derived CPU Abis from settings in oder to reuse 9220 // them in the case where we're not upgrading or booting for the first time. 9221 String primaryCpuAbiFromSettings = null; 9222 String secondaryCpuAbiFromSettings = null; 9223 9224 // writer 9225 synchronized (mPackages) { 9226 if (pkg.mSharedUserId != null) { 9227 // SIDE EFFECTS; may potentially allocate a new shared user 9228 suid = mSettings.getSharedUserLPw( 9229 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9230 if (DEBUG_PACKAGE_SCANNING) { 9231 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9232 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9233 + "): packages=" + suid.packages); 9234 } 9235 } 9236 9237 // Check if we are renaming from an original package name. 9238 PackageSetting origPackage = null; 9239 String realName = null; 9240 if (pkg.mOriginalPackages != null) { 9241 // This package may need to be renamed to a previously 9242 // installed name. Let's check on that... 9243 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9244 if (pkg.mOriginalPackages.contains(renamed)) { 9245 // This package had originally been installed as the 9246 // original name, and we have already taken care of 9247 // transitioning to the new one. Just update the new 9248 // one to continue using the old name. 9249 realName = pkg.mRealPackage; 9250 if (!pkg.packageName.equals(renamed)) { 9251 // Callers into this function may have already taken 9252 // care of renaming the package; only do it here if 9253 // it is not already done. 9254 pkg.setPackageName(renamed); 9255 } 9256 } else { 9257 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9258 if ((origPackage = mSettings.getPackageLPr( 9259 pkg.mOriginalPackages.get(i))) != null) { 9260 // We do have the package already installed under its 9261 // original name... should we use it? 9262 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9263 // New package is not compatible with original. 9264 origPackage = null; 9265 continue; 9266 } else if (origPackage.sharedUser != null) { 9267 // Make sure uid is compatible between packages. 9268 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9269 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9270 + " to " + pkg.packageName + ": old uid " 9271 + origPackage.sharedUser.name 9272 + " differs from " + pkg.mSharedUserId); 9273 origPackage = null; 9274 continue; 9275 } 9276 // TODO: Add case when shared user id is added [b/28144775] 9277 } else { 9278 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9279 + pkg.packageName + " to old name " + origPackage.name); 9280 } 9281 break; 9282 } 9283 } 9284 } 9285 } 9286 9287 if (mTransferedPackages.contains(pkg.packageName)) { 9288 Slog.w(TAG, "Package " + pkg.packageName 9289 + " was transferred to another, but its .apk remains"); 9290 } 9291 9292 // See comments in nonMutatedPs declaration 9293 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9294 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9295 if (foundPs != null) { 9296 nonMutatedPs = new PackageSetting(foundPs); 9297 } 9298 } 9299 9300 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9301 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9302 if (foundPs != null) { 9303 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9304 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9305 } 9306 } 9307 9308 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9309 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9310 PackageManagerService.reportSettingsProblem(Log.WARN, 9311 "Package " + pkg.packageName + " shared user changed from " 9312 + (pkgSetting.sharedUser != null 9313 ? pkgSetting.sharedUser.name : "<nothing>") 9314 + " to " 9315 + (suid != null ? suid.name : "<nothing>") 9316 + "; replacing with new"); 9317 pkgSetting = null; 9318 } 9319 final PackageSetting oldPkgSetting = 9320 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9321 final PackageSetting disabledPkgSetting = 9322 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9323 9324 String[] usesStaticLibraries = null; 9325 if (pkg.usesStaticLibraries != null) { 9326 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9327 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9328 } 9329 9330 if (pkgSetting == null) { 9331 final String parentPackageName = (pkg.parentPackage != null) 9332 ? pkg.parentPackage.packageName : null; 9333 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9334 // REMOVE SharedUserSetting from method; update in a separate call 9335 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9336 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9337 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9338 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9339 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9340 true /*allowInstall*/, instantApp, parentPackageName, 9341 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9342 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9343 // SIDE EFFECTS; updates system state; move elsewhere 9344 if (origPackage != null) { 9345 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9346 } 9347 mSettings.addUserToSettingLPw(pkgSetting); 9348 } else { 9349 // REMOVE SharedUserSetting from method; update in a separate call. 9350 // 9351 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9352 // secondaryCpuAbi are not known at this point so we always update them 9353 // to null here, only to reset them at a later point. 9354 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9355 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9356 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9357 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9358 UserManagerService.getInstance(), usesStaticLibraries, 9359 pkg.usesStaticLibrariesVersions); 9360 } 9361 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9362 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9363 9364 // SIDE EFFECTS; modifies system state; move elsewhere 9365 if (pkgSetting.origPackage != null) { 9366 // If we are first transitioning from an original package, 9367 // fix up the new package's name now. We need to do this after 9368 // looking up the package under its new name, so getPackageLP 9369 // can take care of fiddling things correctly. 9370 pkg.setPackageName(origPackage.name); 9371 9372 // File a report about this. 9373 String msg = "New package " + pkgSetting.realName 9374 + " renamed to replace old package " + pkgSetting.name; 9375 reportSettingsProblem(Log.WARN, msg); 9376 9377 // Make a note of it. 9378 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9379 mTransferedPackages.add(origPackage.name); 9380 } 9381 9382 // No longer need to retain this. 9383 pkgSetting.origPackage = null; 9384 } 9385 9386 // SIDE EFFECTS; modifies system state; move elsewhere 9387 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9388 // Make a note of it. 9389 mTransferedPackages.add(pkg.packageName); 9390 } 9391 9392 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9393 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9394 } 9395 9396 if ((scanFlags & SCAN_BOOTING) == 0 9397 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9398 // Check all shared libraries and map to their actual file path. 9399 // We only do this here for apps not on a system dir, because those 9400 // are the only ones that can fail an install due to this. We 9401 // will take care of the system apps by updating all of their 9402 // library paths after the scan is done. Also during the initial 9403 // scan don't update any libs as we do this wholesale after all 9404 // apps are scanned to avoid dependency based scanning. 9405 updateSharedLibrariesLPr(pkg, null); 9406 } 9407 9408 if (mFoundPolicyFile) { 9409 SELinuxMMAC.assignSeInfoValue(pkg); 9410 } 9411 pkg.applicationInfo.uid = pkgSetting.appId; 9412 pkg.mExtras = pkgSetting; 9413 9414 9415 // Static shared libs have same package with different versions where 9416 // we internally use a synthetic package name to allow multiple versions 9417 // of the same package, therefore we need to compare signatures against 9418 // the package setting for the latest library version. 9419 PackageSetting signatureCheckPs = pkgSetting; 9420 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9421 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9422 if (libraryEntry != null) { 9423 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9424 } 9425 } 9426 9427 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9428 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9429 // We just determined the app is signed correctly, so bring 9430 // over the latest parsed certs. 9431 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9432 } else { 9433 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9434 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9435 "Package " + pkg.packageName + " upgrade keys do not match the " 9436 + "previously installed version"); 9437 } else { 9438 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9439 String msg = "System package " + pkg.packageName 9440 + " signature changed; retaining data."; 9441 reportSettingsProblem(Log.WARN, msg); 9442 } 9443 } 9444 } else { 9445 try { 9446 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9447 verifySignaturesLP(signatureCheckPs, pkg); 9448 // We just determined the app is signed correctly, so bring 9449 // over the latest parsed certs. 9450 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9451 } catch (PackageManagerException e) { 9452 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9453 throw e; 9454 } 9455 // The signature has changed, but this package is in the system 9456 // image... let's recover! 9457 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9458 // However... if this package is part of a shared user, but it 9459 // doesn't match the signature of the shared user, let's fail. 9460 // What this means is that you can't change the signatures 9461 // associated with an overall shared user, which doesn't seem all 9462 // that unreasonable. 9463 if (signatureCheckPs.sharedUser != null) { 9464 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9465 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9466 throw new PackageManagerException( 9467 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9468 "Signature mismatch for shared user: " 9469 + pkgSetting.sharedUser); 9470 } 9471 } 9472 // File a report about this. 9473 String msg = "System package " + pkg.packageName 9474 + " signature changed; retaining data."; 9475 reportSettingsProblem(Log.WARN, msg); 9476 } 9477 } 9478 9479 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9480 // This package wants to adopt ownership of permissions from 9481 // another package. 9482 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9483 final String origName = pkg.mAdoptPermissions.get(i); 9484 final PackageSetting orig = mSettings.getPackageLPr(origName); 9485 if (orig != null) { 9486 if (verifyPackageUpdateLPr(orig, pkg)) { 9487 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9488 + pkg.packageName); 9489 // SIDE EFFECTS; updates permissions system state; move elsewhere 9490 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9491 } 9492 } 9493 } 9494 } 9495 } 9496 9497 pkg.applicationInfo.processName = fixProcessName( 9498 pkg.applicationInfo.packageName, 9499 pkg.applicationInfo.processName); 9500 9501 if (pkg != mPlatformPackage) { 9502 // Get all of our default paths setup 9503 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9504 } 9505 9506 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9507 9508 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9509 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9510 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9511 derivePackageAbi( 9512 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9513 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9514 9515 // Some system apps still use directory structure for native libraries 9516 // in which case we might end up not detecting abi solely based on apk 9517 // structure. Try to detect abi based on directory structure. 9518 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9519 pkg.applicationInfo.primaryCpuAbi == null) { 9520 setBundledAppAbisAndRoots(pkg, pkgSetting); 9521 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9522 } 9523 } else { 9524 // This is not a first boot or an upgrade, don't bother deriving the 9525 // ABI during the scan. Instead, trust the value that was stored in the 9526 // package setting. 9527 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9528 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9529 9530 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9531 9532 if (DEBUG_ABI_SELECTION) { 9533 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9534 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9535 pkg.applicationInfo.secondaryCpuAbi); 9536 } 9537 } 9538 } else { 9539 if ((scanFlags & SCAN_MOVE) != 0) { 9540 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9541 // but we already have this packages package info in the PackageSetting. We just 9542 // use that and derive the native library path based on the new codepath. 9543 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9544 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9545 } 9546 9547 // Set native library paths again. For moves, the path will be updated based on the 9548 // ABIs we've determined above. For non-moves, the path will be updated based on the 9549 // ABIs we determined during compilation, but the path will depend on the final 9550 // package path (after the rename away from the stage path). 9551 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9552 } 9553 9554 // This is a special case for the "system" package, where the ABI is 9555 // dictated by the zygote configuration (and init.rc). We should keep track 9556 // of this ABI so that we can deal with "normal" applications that run under 9557 // the same UID correctly. 9558 if (mPlatformPackage == pkg) { 9559 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9560 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9561 } 9562 9563 // If there's a mismatch between the abi-override in the package setting 9564 // and the abiOverride specified for the install. Warn about this because we 9565 // would've already compiled the app without taking the package setting into 9566 // account. 9567 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9568 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9569 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9570 " for package " + pkg.packageName); 9571 } 9572 } 9573 9574 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9575 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9576 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9577 9578 // Copy the derived override back to the parsed package, so that we can 9579 // update the package settings accordingly. 9580 pkg.cpuAbiOverride = cpuAbiOverride; 9581 9582 if (DEBUG_ABI_SELECTION) { 9583 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9584 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9585 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9586 } 9587 9588 // Push the derived path down into PackageSettings so we know what to 9589 // clean up at uninstall time. 9590 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9591 9592 if (DEBUG_ABI_SELECTION) { 9593 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9594 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9595 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9596 } 9597 9598 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9599 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9600 // We don't do this here during boot because we can do it all 9601 // at once after scanning all existing packages. 9602 // 9603 // We also do this *before* we perform dexopt on this package, so that 9604 // we can avoid redundant dexopts, and also to make sure we've got the 9605 // code and package path correct. 9606 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9607 } 9608 9609 if (mFactoryTest && pkg.requestedPermissions.contains( 9610 android.Manifest.permission.FACTORY_TEST)) { 9611 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9612 } 9613 9614 if (isSystemApp(pkg)) { 9615 pkgSetting.isOrphaned = true; 9616 } 9617 9618 // Take care of first install / last update times. 9619 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9620 if (currentTime != 0) { 9621 if (pkgSetting.firstInstallTime == 0) { 9622 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9623 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9624 pkgSetting.lastUpdateTime = currentTime; 9625 } 9626 } else if (pkgSetting.firstInstallTime == 0) { 9627 // We need *something*. Take time time stamp of the file. 9628 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9629 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9630 if (scanFileTime != pkgSetting.timeStamp) { 9631 // A package on the system image has changed; consider this 9632 // to be an update. 9633 pkgSetting.lastUpdateTime = scanFileTime; 9634 } 9635 } 9636 pkgSetting.setTimeStamp(scanFileTime); 9637 9638 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9639 if (nonMutatedPs != null) { 9640 synchronized (mPackages) { 9641 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9642 } 9643 } 9644 } else { 9645 final int userId = user == null ? 0 : user.getIdentifier(); 9646 // Modify state for the given package setting 9647 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9648 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9649 if (pkgSetting.getInstantApp(userId)) { 9650 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9651 } 9652 } 9653 return pkg; 9654 } 9655 9656 /** 9657 * Applies policy to the parsed package based upon the given policy flags. 9658 * Ensures the package is in a good state. 9659 * <p> 9660 * Implementation detail: This method must NOT have any side effect. It would 9661 * ideally be static, but, it requires locks to read system state. 9662 */ 9663 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9664 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9665 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9666 if (pkg.applicationInfo.isDirectBootAware()) { 9667 // we're direct boot aware; set for all components 9668 for (PackageParser.Service s : pkg.services) { 9669 s.info.encryptionAware = s.info.directBootAware = true; 9670 } 9671 for (PackageParser.Provider p : pkg.providers) { 9672 p.info.encryptionAware = p.info.directBootAware = true; 9673 } 9674 for (PackageParser.Activity a : pkg.activities) { 9675 a.info.encryptionAware = a.info.directBootAware = true; 9676 } 9677 for (PackageParser.Activity r : pkg.receivers) { 9678 r.info.encryptionAware = r.info.directBootAware = true; 9679 } 9680 } 9681 } else { 9682 // Only allow system apps to be flagged as core apps. 9683 pkg.coreApp = false; 9684 // clear flags not applicable to regular apps 9685 pkg.applicationInfo.privateFlags &= 9686 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9687 pkg.applicationInfo.privateFlags &= 9688 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9689 } 9690 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9691 9692 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9693 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9694 } 9695 9696 if (!isSystemApp(pkg)) { 9697 // Only system apps can use these features. 9698 pkg.mOriginalPackages = null; 9699 pkg.mRealPackage = null; 9700 pkg.mAdoptPermissions = null; 9701 } 9702 } 9703 9704 /** 9705 * Asserts the parsed package is valid according to the given policy. If the 9706 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9707 * <p> 9708 * Implementation detail: This method must NOT have any side effects. It would 9709 * ideally be static, but, it requires locks to read system state. 9710 * 9711 * @throws PackageManagerException If the package fails any of the validation checks 9712 */ 9713 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9714 throws PackageManagerException { 9715 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9716 assertCodePolicy(pkg); 9717 } 9718 9719 if (pkg.applicationInfo.getCodePath() == null || 9720 pkg.applicationInfo.getResourcePath() == null) { 9721 // Bail out. The resource and code paths haven't been set. 9722 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9723 "Code and resource paths haven't been set correctly"); 9724 } 9725 9726 // Make sure we're not adding any bogus keyset info 9727 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9728 ksms.assertScannedPackageValid(pkg); 9729 9730 synchronized (mPackages) { 9731 // The special "android" package can only be defined once 9732 if (pkg.packageName.equals("android")) { 9733 if (mAndroidApplication != null) { 9734 Slog.w(TAG, "*************************************************"); 9735 Slog.w(TAG, "Core android package being redefined. Skipping."); 9736 Slog.w(TAG, " codePath=" + pkg.codePath); 9737 Slog.w(TAG, "*************************************************"); 9738 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9739 "Core android package being redefined. Skipping."); 9740 } 9741 } 9742 9743 // A package name must be unique; don't allow duplicates 9744 if (mPackages.containsKey(pkg.packageName)) { 9745 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9746 "Application package " + pkg.packageName 9747 + " already installed. Skipping duplicate."); 9748 } 9749 9750 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9751 // Static libs have a synthetic package name containing the version 9752 // but we still want the base name to be unique. 9753 if (mPackages.containsKey(pkg.manifestPackageName)) { 9754 throw new PackageManagerException( 9755 "Duplicate static shared lib provider package"); 9756 } 9757 9758 // Static shared libraries should have at least O target SDK 9759 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9760 throw new PackageManagerException( 9761 "Packages declaring static-shared libs must target O SDK or higher"); 9762 } 9763 9764 // Package declaring static a shared lib cannot be instant apps 9765 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9766 throw new PackageManagerException( 9767 "Packages declaring static-shared libs cannot be instant apps"); 9768 } 9769 9770 // Package declaring static a shared lib cannot be renamed since the package 9771 // name is synthetic and apps can't code around package manager internals. 9772 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9773 throw new PackageManagerException( 9774 "Packages declaring static-shared libs cannot be renamed"); 9775 } 9776 9777 // Package declaring static a shared lib cannot declare child packages 9778 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9779 throw new PackageManagerException( 9780 "Packages declaring static-shared libs cannot have child packages"); 9781 } 9782 9783 // Package declaring static a shared lib cannot declare dynamic libs 9784 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9785 throw new PackageManagerException( 9786 "Packages declaring static-shared libs cannot declare dynamic libs"); 9787 } 9788 9789 // Package declaring static a shared lib cannot declare shared users 9790 if (pkg.mSharedUserId != null) { 9791 throw new PackageManagerException( 9792 "Packages declaring static-shared libs cannot declare shared users"); 9793 } 9794 9795 // Static shared libs cannot declare activities 9796 if (!pkg.activities.isEmpty()) { 9797 throw new PackageManagerException( 9798 "Static shared libs cannot declare activities"); 9799 } 9800 9801 // Static shared libs cannot declare services 9802 if (!pkg.services.isEmpty()) { 9803 throw new PackageManagerException( 9804 "Static shared libs cannot declare services"); 9805 } 9806 9807 // Static shared libs cannot declare providers 9808 if (!pkg.providers.isEmpty()) { 9809 throw new PackageManagerException( 9810 "Static shared libs cannot declare content providers"); 9811 } 9812 9813 // Static shared libs cannot declare receivers 9814 if (!pkg.receivers.isEmpty()) { 9815 throw new PackageManagerException( 9816 "Static shared libs cannot declare broadcast receivers"); 9817 } 9818 9819 // Static shared libs cannot declare permission groups 9820 if (!pkg.permissionGroups.isEmpty()) { 9821 throw new PackageManagerException( 9822 "Static shared libs cannot declare permission groups"); 9823 } 9824 9825 // Static shared libs cannot declare permissions 9826 if (!pkg.permissions.isEmpty()) { 9827 throw new PackageManagerException( 9828 "Static shared libs cannot declare permissions"); 9829 } 9830 9831 // Static shared libs cannot declare protected broadcasts 9832 if (pkg.protectedBroadcasts != null) { 9833 throw new PackageManagerException( 9834 "Static shared libs cannot declare protected broadcasts"); 9835 } 9836 9837 // Static shared libs cannot be overlay targets 9838 if (pkg.mOverlayTarget != null) { 9839 throw new PackageManagerException( 9840 "Static shared libs cannot be overlay targets"); 9841 } 9842 9843 // The version codes must be ordered as lib versions 9844 int minVersionCode = Integer.MIN_VALUE; 9845 int maxVersionCode = Integer.MAX_VALUE; 9846 9847 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9848 pkg.staticSharedLibName); 9849 if (versionedLib != null) { 9850 final int versionCount = versionedLib.size(); 9851 for (int i = 0; i < versionCount; i++) { 9852 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9853 // TODO: We will change version code to long, so in the new API it is long 9854 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9855 .getVersionCode(); 9856 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9857 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9858 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9859 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9860 } else { 9861 minVersionCode = maxVersionCode = libVersionCode; 9862 break; 9863 } 9864 } 9865 } 9866 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9867 throw new PackageManagerException("Static shared" 9868 + " lib version codes must be ordered as lib versions"); 9869 } 9870 } 9871 9872 // Only privileged apps and updated privileged apps can add child packages. 9873 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9874 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9875 throw new PackageManagerException("Only privileged apps can add child " 9876 + "packages. Ignoring package " + pkg.packageName); 9877 } 9878 final int childCount = pkg.childPackages.size(); 9879 for (int i = 0; i < childCount; i++) { 9880 PackageParser.Package childPkg = pkg.childPackages.get(i); 9881 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9882 childPkg.packageName)) { 9883 throw new PackageManagerException("Can't override child of " 9884 + "another disabled app. Ignoring package " + pkg.packageName); 9885 } 9886 } 9887 } 9888 9889 // If we're only installing presumed-existing packages, require that the 9890 // scanned APK is both already known and at the path previously established 9891 // for it. Previously unknown packages we pick up normally, but if we have an 9892 // a priori expectation about this package's install presence, enforce it. 9893 // With a singular exception for new system packages. When an OTA contains 9894 // a new system package, we allow the codepath to change from a system location 9895 // to the user-installed location. If we don't allow this change, any newer, 9896 // user-installed version of the application will be ignored. 9897 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9898 if (mExpectingBetter.containsKey(pkg.packageName)) { 9899 logCriticalInfo(Log.WARN, 9900 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9901 } else { 9902 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9903 if (known != null) { 9904 if (DEBUG_PACKAGE_SCANNING) { 9905 Log.d(TAG, "Examining " + pkg.codePath 9906 + " and requiring known paths " + known.codePathString 9907 + " & " + known.resourcePathString); 9908 } 9909 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9910 || !pkg.applicationInfo.getResourcePath().equals( 9911 known.resourcePathString)) { 9912 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9913 "Application package " + pkg.packageName 9914 + " found at " + pkg.applicationInfo.getCodePath() 9915 + " but expected at " + known.codePathString 9916 + "; ignoring."); 9917 } 9918 } 9919 } 9920 } 9921 9922 // Verify that this new package doesn't have any content providers 9923 // that conflict with existing packages. Only do this if the 9924 // package isn't already installed, since we don't want to break 9925 // things that are installed. 9926 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9927 final int N = pkg.providers.size(); 9928 int i; 9929 for (i=0; i<N; i++) { 9930 PackageParser.Provider p = pkg.providers.get(i); 9931 if (p.info.authority != null) { 9932 String names[] = p.info.authority.split(";"); 9933 for (int j = 0; j < names.length; j++) { 9934 if (mProvidersByAuthority.containsKey(names[j])) { 9935 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9936 final String otherPackageName = 9937 ((other != null && other.getComponentName() != null) ? 9938 other.getComponentName().getPackageName() : "?"); 9939 throw new PackageManagerException( 9940 INSTALL_FAILED_CONFLICTING_PROVIDER, 9941 "Can't install because provider name " + names[j] 9942 + " (in package " + pkg.applicationInfo.packageName 9943 + ") is already used by " + otherPackageName); 9944 } 9945 } 9946 } 9947 } 9948 } 9949 } 9950 } 9951 9952 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9953 int type, String declaringPackageName, int declaringVersionCode) { 9954 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9955 if (versionedLib == null) { 9956 versionedLib = new SparseArray<>(); 9957 mSharedLibraries.put(name, versionedLib); 9958 if (type == SharedLibraryInfo.TYPE_STATIC) { 9959 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9960 } 9961 } else if (versionedLib.indexOfKey(version) >= 0) { 9962 return false; 9963 } 9964 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9965 version, type, declaringPackageName, declaringVersionCode); 9966 versionedLib.put(version, libEntry); 9967 return true; 9968 } 9969 9970 private boolean removeSharedLibraryLPw(String name, int version) { 9971 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9972 if (versionedLib == null) { 9973 return false; 9974 } 9975 final int libIdx = versionedLib.indexOfKey(version); 9976 if (libIdx < 0) { 9977 return false; 9978 } 9979 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9980 versionedLib.remove(version); 9981 if (versionedLib.size() <= 0) { 9982 mSharedLibraries.remove(name); 9983 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9984 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9985 .getPackageName()); 9986 } 9987 } 9988 return true; 9989 } 9990 9991 /** 9992 * Adds a scanned package to the system. When this method is finished, the package will 9993 * be available for query, resolution, etc... 9994 */ 9995 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9996 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9997 final String pkgName = pkg.packageName; 9998 if (mCustomResolverComponentName != null && 9999 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10000 setUpCustomResolverActivity(pkg); 10001 } 10002 10003 if (pkg.packageName.equals("android")) { 10004 synchronized (mPackages) { 10005 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10006 // Set up information for our fall-back user intent resolution activity. 10007 mPlatformPackage = pkg; 10008 pkg.mVersionCode = mSdkVersion; 10009 mAndroidApplication = pkg.applicationInfo; 10010 if (!mResolverReplaced) { 10011 mResolveActivity.applicationInfo = mAndroidApplication; 10012 mResolveActivity.name = ResolverActivity.class.getName(); 10013 mResolveActivity.packageName = mAndroidApplication.packageName; 10014 mResolveActivity.processName = "system:ui"; 10015 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10016 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10017 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10018 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10019 mResolveActivity.exported = true; 10020 mResolveActivity.enabled = true; 10021 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10022 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10023 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10024 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10025 | ActivityInfo.CONFIG_ORIENTATION 10026 | ActivityInfo.CONFIG_KEYBOARD 10027 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10028 mResolveInfo.activityInfo = mResolveActivity; 10029 mResolveInfo.priority = 0; 10030 mResolveInfo.preferredOrder = 0; 10031 mResolveInfo.match = 0; 10032 mResolveComponentName = new ComponentName( 10033 mAndroidApplication.packageName, mResolveActivity.name); 10034 } 10035 } 10036 } 10037 } 10038 10039 ArrayList<PackageParser.Package> clientLibPkgs = null; 10040 // writer 10041 synchronized (mPackages) { 10042 boolean hasStaticSharedLibs = false; 10043 10044 // Any app can add new static shared libraries 10045 if (pkg.staticSharedLibName != null) { 10046 // Static shared libs don't allow renaming as they have synthetic package 10047 // names to allow install of multiple versions, so use name from manifest. 10048 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10049 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10050 pkg.manifestPackageName, pkg.mVersionCode)) { 10051 hasStaticSharedLibs = true; 10052 } else { 10053 Slog.w(TAG, "Package " + pkg.packageName + " library " 10054 + pkg.staticSharedLibName + " already exists; skipping"); 10055 } 10056 // Static shared libs cannot be updated once installed since they 10057 // use synthetic package name which includes the version code, so 10058 // not need to update other packages's shared lib dependencies. 10059 } 10060 10061 if (!hasStaticSharedLibs 10062 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10063 // Only system apps can add new dynamic shared libraries. 10064 if (pkg.libraryNames != null) { 10065 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10066 String name = pkg.libraryNames.get(i); 10067 boolean allowed = false; 10068 if (pkg.isUpdatedSystemApp()) { 10069 // New library entries can only be added through the 10070 // system image. This is important to get rid of a lot 10071 // of nasty edge cases: for example if we allowed a non- 10072 // system update of the app to add a library, then uninstalling 10073 // the update would make the library go away, and assumptions 10074 // we made such as through app install filtering would now 10075 // have allowed apps on the device which aren't compatible 10076 // with it. Better to just have the restriction here, be 10077 // conservative, and create many fewer cases that can negatively 10078 // impact the user experience. 10079 final PackageSetting sysPs = mSettings 10080 .getDisabledSystemPkgLPr(pkg.packageName); 10081 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10082 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10083 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10084 allowed = true; 10085 break; 10086 } 10087 } 10088 } 10089 } else { 10090 allowed = true; 10091 } 10092 if (allowed) { 10093 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10094 SharedLibraryInfo.VERSION_UNDEFINED, 10095 SharedLibraryInfo.TYPE_DYNAMIC, 10096 pkg.packageName, pkg.mVersionCode)) { 10097 Slog.w(TAG, "Package " + pkg.packageName + " library " 10098 + name + " already exists; skipping"); 10099 } 10100 } else { 10101 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10102 + name + " that is not declared on system image; skipping"); 10103 } 10104 } 10105 10106 if ((scanFlags & SCAN_BOOTING) == 0) { 10107 // If we are not booting, we need to update any applications 10108 // that are clients of our shared library. If we are booting, 10109 // this will all be done once the scan is complete. 10110 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10111 } 10112 } 10113 } 10114 } 10115 10116 if ((scanFlags & SCAN_BOOTING) != 0) { 10117 // No apps can run during boot scan, so they don't need to be frozen 10118 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10119 // Caller asked to not kill app, so it's probably not frozen 10120 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10121 // Caller asked us to ignore frozen check for some reason; they 10122 // probably didn't know the package name 10123 } else { 10124 // We're doing major surgery on this package, so it better be frozen 10125 // right now to keep it from launching 10126 checkPackageFrozen(pkgName); 10127 } 10128 10129 // Also need to kill any apps that are dependent on the library. 10130 if (clientLibPkgs != null) { 10131 for (int i=0; i<clientLibPkgs.size(); i++) { 10132 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10133 killApplication(clientPkg.applicationInfo.packageName, 10134 clientPkg.applicationInfo.uid, "update lib"); 10135 } 10136 } 10137 10138 // writer 10139 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10140 10141 synchronized (mPackages) { 10142 // We don't expect installation to fail beyond this point 10143 10144 // Add the new setting to mSettings 10145 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10146 // Add the new setting to mPackages 10147 mPackages.put(pkg.applicationInfo.packageName, pkg); 10148 // Make sure we don't accidentally delete its data. 10149 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10150 while (iter.hasNext()) { 10151 PackageCleanItem item = iter.next(); 10152 if (pkgName.equals(item.packageName)) { 10153 iter.remove(); 10154 } 10155 } 10156 10157 // Add the package's KeySets to the global KeySetManagerService 10158 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10159 ksms.addScannedPackageLPw(pkg); 10160 10161 int N = pkg.providers.size(); 10162 StringBuilder r = null; 10163 int i; 10164 for (i=0; i<N; i++) { 10165 PackageParser.Provider p = pkg.providers.get(i); 10166 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10167 p.info.processName); 10168 mProviders.addProvider(p); 10169 p.syncable = p.info.isSyncable; 10170 if (p.info.authority != null) { 10171 String names[] = p.info.authority.split(";"); 10172 p.info.authority = null; 10173 for (int j = 0; j < names.length; j++) { 10174 if (j == 1 && p.syncable) { 10175 // We only want the first authority for a provider to possibly be 10176 // syncable, so if we already added this provider using a different 10177 // authority clear the syncable flag. We copy the provider before 10178 // changing it because the mProviders object contains a reference 10179 // to a provider that we don't want to change. 10180 // Only do this for the second authority since the resulting provider 10181 // object can be the same for all future authorities for this provider. 10182 p = new PackageParser.Provider(p); 10183 p.syncable = false; 10184 } 10185 if (!mProvidersByAuthority.containsKey(names[j])) { 10186 mProvidersByAuthority.put(names[j], p); 10187 if (p.info.authority == null) { 10188 p.info.authority = names[j]; 10189 } else { 10190 p.info.authority = p.info.authority + ";" + names[j]; 10191 } 10192 if (DEBUG_PACKAGE_SCANNING) { 10193 if (chatty) 10194 Log.d(TAG, "Registered content provider: " + names[j] 10195 + ", className = " + p.info.name + ", isSyncable = " 10196 + p.info.isSyncable); 10197 } 10198 } else { 10199 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10200 Slog.w(TAG, "Skipping provider name " + names[j] + 10201 " (in package " + pkg.applicationInfo.packageName + 10202 "): name already used by " 10203 + ((other != null && other.getComponentName() != null) 10204 ? other.getComponentName().getPackageName() : "?")); 10205 } 10206 } 10207 } 10208 if (chatty) { 10209 if (r == null) { 10210 r = new StringBuilder(256); 10211 } else { 10212 r.append(' '); 10213 } 10214 r.append(p.info.name); 10215 } 10216 } 10217 if (r != null) { 10218 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10219 } 10220 10221 N = pkg.services.size(); 10222 r = null; 10223 for (i=0; i<N; i++) { 10224 PackageParser.Service s = pkg.services.get(i); 10225 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10226 s.info.processName); 10227 mServices.addService(s); 10228 if (chatty) { 10229 if (r == null) { 10230 r = new StringBuilder(256); 10231 } else { 10232 r.append(' '); 10233 } 10234 r.append(s.info.name); 10235 } 10236 } 10237 if (r != null) { 10238 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10239 } 10240 10241 N = pkg.receivers.size(); 10242 r = null; 10243 for (i=0; i<N; i++) { 10244 PackageParser.Activity a = pkg.receivers.get(i); 10245 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10246 a.info.processName); 10247 mReceivers.addActivity(a, "receiver"); 10248 if (chatty) { 10249 if (r == null) { 10250 r = new StringBuilder(256); 10251 } else { 10252 r.append(' '); 10253 } 10254 r.append(a.info.name); 10255 } 10256 } 10257 if (r != null) { 10258 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10259 } 10260 10261 N = pkg.activities.size(); 10262 r = null; 10263 for (i=0; i<N; i++) { 10264 PackageParser.Activity a = pkg.activities.get(i); 10265 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10266 a.info.processName); 10267 mActivities.addActivity(a, "activity"); 10268 if (chatty) { 10269 if (r == null) { 10270 r = new StringBuilder(256); 10271 } else { 10272 r.append(' '); 10273 } 10274 r.append(a.info.name); 10275 } 10276 } 10277 if (r != null) { 10278 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10279 } 10280 10281 N = pkg.permissionGroups.size(); 10282 r = null; 10283 for (i=0; i<N; i++) { 10284 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10285 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10286 final String curPackageName = cur == null ? null : cur.info.packageName; 10287 // Dont allow ephemeral apps to define new permission groups. 10288 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10289 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10290 + pg.info.packageName 10291 + " ignored: instant apps cannot define new permission groups."); 10292 continue; 10293 } 10294 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10295 if (cur == null || isPackageUpdate) { 10296 mPermissionGroups.put(pg.info.name, pg); 10297 if (chatty) { 10298 if (r == null) { 10299 r = new StringBuilder(256); 10300 } else { 10301 r.append(' '); 10302 } 10303 if (isPackageUpdate) { 10304 r.append("UPD:"); 10305 } 10306 r.append(pg.info.name); 10307 } 10308 } else { 10309 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10310 + pg.info.packageName + " ignored: original from " 10311 + cur.info.packageName); 10312 if (chatty) { 10313 if (r == null) { 10314 r = new StringBuilder(256); 10315 } else { 10316 r.append(' '); 10317 } 10318 r.append("DUP:"); 10319 r.append(pg.info.name); 10320 } 10321 } 10322 } 10323 if (r != null) { 10324 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10325 } 10326 10327 N = pkg.permissions.size(); 10328 r = null; 10329 for (i=0; i<N; i++) { 10330 PackageParser.Permission p = pkg.permissions.get(i); 10331 10332 // Dont allow ephemeral apps to define new permissions. 10333 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10334 Slog.w(TAG, "Permission " + p.info.name + " from package " 10335 + p.info.packageName 10336 + " ignored: instant apps cannot define new permissions."); 10337 continue; 10338 } 10339 10340 // Assume by default that we did not install this permission into the system. 10341 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10342 10343 // Now that permission groups have a special meaning, we ignore permission 10344 // groups for legacy apps to prevent unexpected behavior. In particular, 10345 // permissions for one app being granted to someone just becase they happen 10346 // to be in a group defined by another app (before this had no implications). 10347 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10348 p.group = mPermissionGroups.get(p.info.group); 10349 // Warn for a permission in an unknown group. 10350 if (p.info.group != null && p.group == null) { 10351 Slog.w(TAG, "Permission " + p.info.name + " from package " 10352 + p.info.packageName + " in an unknown group " + p.info.group); 10353 } 10354 } 10355 10356 ArrayMap<String, BasePermission> permissionMap = 10357 p.tree ? mSettings.mPermissionTrees 10358 : mSettings.mPermissions; 10359 BasePermission bp = permissionMap.get(p.info.name); 10360 10361 // Allow system apps to redefine non-system permissions 10362 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10363 final boolean currentOwnerIsSystem = (bp.perm != null 10364 && isSystemApp(bp.perm.owner)); 10365 if (isSystemApp(p.owner)) { 10366 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10367 // It's a built-in permission and no owner, take ownership now 10368 bp.packageSetting = pkgSetting; 10369 bp.perm = p; 10370 bp.uid = pkg.applicationInfo.uid; 10371 bp.sourcePackage = p.info.packageName; 10372 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10373 } else if (!currentOwnerIsSystem) { 10374 String msg = "New decl " + p.owner + " of permission " 10375 + p.info.name + " is system; overriding " + bp.sourcePackage; 10376 reportSettingsProblem(Log.WARN, msg); 10377 bp = null; 10378 } 10379 } 10380 } 10381 10382 if (bp == null) { 10383 bp = new BasePermission(p.info.name, p.info.packageName, 10384 BasePermission.TYPE_NORMAL); 10385 permissionMap.put(p.info.name, bp); 10386 } 10387 10388 if (bp.perm == null) { 10389 if (bp.sourcePackage == null 10390 || bp.sourcePackage.equals(p.info.packageName)) { 10391 BasePermission tree = findPermissionTreeLP(p.info.name); 10392 if (tree == null 10393 || tree.sourcePackage.equals(p.info.packageName)) { 10394 bp.packageSetting = pkgSetting; 10395 bp.perm = p; 10396 bp.uid = pkg.applicationInfo.uid; 10397 bp.sourcePackage = p.info.packageName; 10398 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10399 if (chatty) { 10400 if (r == null) { 10401 r = new StringBuilder(256); 10402 } else { 10403 r.append(' '); 10404 } 10405 r.append(p.info.name); 10406 } 10407 } else { 10408 Slog.w(TAG, "Permission " + p.info.name + " from package " 10409 + p.info.packageName + " ignored: base tree " 10410 + tree.name + " is from package " 10411 + tree.sourcePackage); 10412 } 10413 } else { 10414 Slog.w(TAG, "Permission " + p.info.name + " from package " 10415 + p.info.packageName + " ignored: original from " 10416 + bp.sourcePackage); 10417 } 10418 } else if (chatty) { 10419 if (r == null) { 10420 r = new StringBuilder(256); 10421 } else { 10422 r.append(' '); 10423 } 10424 r.append("DUP:"); 10425 r.append(p.info.name); 10426 } 10427 if (bp.perm == p) { 10428 bp.protectionLevel = p.info.protectionLevel; 10429 } 10430 } 10431 10432 if (r != null) { 10433 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10434 } 10435 10436 N = pkg.instrumentation.size(); 10437 r = null; 10438 for (i=0; i<N; i++) { 10439 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10440 a.info.packageName = pkg.applicationInfo.packageName; 10441 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10442 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10443 a.info.splitNames = pkg.splitNames; 10444 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10445 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10446 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10447 a.info.dataDir = pkg.applicationInfo.dataDir; 10448 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10449 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10450 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10451 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10452 mInstrumentation.put(a.getComponentName(), a); 10453 if (chatty) { 10454 if (r == null) { 10455 r = new StringBuilder(256); 10456 } else { 10457 r.append(' '); 10458 } 10459 r.append(a.info.name); 10460 } 10461 } 10462 if (r != null) { 10463 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10464 } 10465 10466 if (pkg.protectedBroadcasts != null) { 10467 N = pkg.protectedBroadcasts.size(); 10468 for (i=0; i<N; i++) { 10469 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10470 } 10471 } 10472 } 10473 10474 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10475 } 10476 10477 /** 10478 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10479 * is derived purely on the basis of the contents of {@code scanFile} and 10480 * {@code cpuAbiOverride}. 10481 * 10482 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10483 */ 10484 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10485 String cpuAbiOverride, boolean extractLibs, 10486 File appLib32InstallDir) 10487 throws PackageManagerException { 10488 // Give ourselves some initial paths; we'll come back for another 10489 // pass once we've determined ABI below. 10490 setNativeLibraryPaths(pkg, appLib32InstallDir); 10491 10492 // We would never need to extract libs for forward-locked and external packages, 10493 // since the container service will do it for us. We shouldn't attempt to 10494 // extract libs from system app when it was not updated. 10495 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10496 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10497 extractLibs = false; 10498 } 10499 10500 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10501 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10502 10503 NativeLibraryHelper.Handle handle = null; 10504 try { 10505 handle = NativeLibraryHelper.Handle.create(pkg); 10506 // TODO(multiArch): This can be null for apps that didn't go through the 10507 // usual installation process. We can calculate it again, like we 10508 // do during install time. 10509 // 10510 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10511 // unnecessary. 10512 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10513 10514 // Null out the abis so that they can be recalculated. 10515 pkg.applicationInfo.primaryCpuAbi = null; 10516 pkg.applicationInfo.secondaryCpuAbi = null; 10517 if (isMultiArch(pkg.applicationInfo)) { 10518 // Warn if we've set an abiOverride for multi-lib packages.. 10519 // By definition, we need to copy both 32 and 64 bit libraries for 10520 // such packages. 10521 if (pkg.cpuAbiOverride != null 10522 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10523 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10524 } 10525 10526 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10527 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10528 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10529 if (extractLibs) { 10530 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10531 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10532 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10533 useIsaSpecificSubdirs); 10534 } else { 10535 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10536 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10537 } 10538 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10539 } 10540 10541 maybeThrowExceptionForMultiArchCopy( 10542 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10543 10544 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10545 if (extractLibs) { 10546 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10547 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10548 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10549 useIsaSpecificSubdirs); 10550 } else { 10551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10552 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10553 } 10554 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10555 } 10556 10557 maybeThrowExceptionForMultiArchCopy( 10558 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10559 10560 if (abi64 >= 0) { 10561 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10562 } 10563 10564 if (abi32 >= 0) { 10565 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10566 if (abi64 >= 0) { 10567 if (pkg.use32bitAbi) { 10568 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10569 pkg.applicationInfo.primaryCpuAbi = abi; 10570 } else { 10571 pkg.applicationInfo.secondaryCpuAbi = abi; 10572 } 10573 } else { 10574 pkg.applicationInfo.primaryCpuAbi = abi; 10575 } 10576 } 10577 10578 } else { 10579 String[] abiList = (cpuAbiOverride != null) ? 10580 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10581 10582 // Enable gross and lame hacks for apps that are built with old 10583 // SDK tools. We must scan their APKs for renderscript bitcode and 10584 // not launch them if it's present. Don't bother checking on devices 10585 // that don't have 64 bit support. 10586 boolean needsRenderScriptOverride = false; 10587 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10588 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10589 abiList = Build.SUPPORTED_32_BIT_ABIS; 10590 needsRenderScriptOverride = true; 10591 } 10592 10593 final int copyRet; 10594 if (extractLibs) { 10595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10596 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10597 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10598 } else { 10599 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10600 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10601 } 10602 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10603 10604 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10605 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10606 "Error unpackaging native libs for app, errorCode=" + copyRet); 10607 } 10608 10609 if (copyRet >= 0) { 10610 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10611 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10612 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10613 } else if (needsRenderScriptOverride) { 10614 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10615 } 10616 } 10617 } catch (IOException ioe) { 10618 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10619 } finally { 10620 IoUtils.closeQuietly(handle); 10621 } 10622 10623 // Now that we've calculated the ABIs and determined if it's an internal app, 10624 // we will go ahead and populate the nativeLibraryPath. 10625 setNativeLibraryPaths(pkg, appLib32InstallDir); 10626 } 10627 10628 /** 10629 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10630 * i.e, so that all packages can be run inside a single process if required. 10631 * 10632 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10633 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10634 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10635 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10636 * updating a package that belongs to a shared user. 10637 * 10638 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10639 * adds unnecessary complexity. 10640 */ 10641 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10642 PackageParser.Package scannedPackage) { 10643 String requiredInstructionSet = null; 10644 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10645 requiredInstructionSet = VMRuntime.getInstructionSet( 10646 scannedPackage.applicationInfo.primaryCpuAbi); 10647 } 10648 10649 PackageSetting requirer = null; 10650 for (PackageSetting ps : packagesForUser) { 10651 // If packagesForUser contains scannedPackage, we skip it. This will happen 10652 // when scannedPackage is an update of an existing package. Without this check, 10653 // we will never be able to change the ABI of any package belonging to a shared 10654 // user, even if it's compatible with other packages. 10655 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10656 if (ps.primaryCpuAbiString == null) { 10657 continue; 10658 } 10659 10660 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10661 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10662 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10663 // this but there's not much we can do. 10664 String errorMessage = "Instruction set mismatch, " 10665 + ((requirer == null) ? "[caller]" : requirer) 10666 + " requires " + requiredInstructionSet + " whereas " + ps 10667 + " requires " + instructionSet; 10668 Slog.w(TAG, errorMessage); 10669 } 10670 10671 if (requiredInstructionSet == null) { 10672 requiredInstructionSet = instructionSet; 10673 requirer = ps; 10674 } 10675 } 10676 } 10677 10678 if (requiredInstructionSet != null) { 10679 String adjustedAbi; 10680 if (requirer != null) { 10681 // requirer != null implies that either scannedPackage was null or that scannedPackage 10682 // did not require an ABI, in which case we have to adjust scannedPackage to match 10683 // the ABI of the set (which is the same as requirer's ABI) 10684 adjustedAbi = requirer.primaryCpuAbiString; 10685 if (scannedPackage != null) { 10686 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10687 } 10688 } else { 10689 // requirer == null implies that we're updating all ABIs in the set to 10690 // match scannedPackage. 10691 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10692 } 10693 10694 for (PackageSetting ps : packagesForUser) { 10695 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10696 if (ps.primaryCpuAbiString != null) { 10697 continue; 10698 } 10699 10700 ps.primaryCpuAbiString = adjustedAbi; 10701 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10702 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10703 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10704 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10705 + " (requirer=" 10706 + (requirer != null ? requirer.pkg : "null") 10707 + ", scannedPackage=" 10708 + (scannedPackage != null ? scannedPackage : "null") 10709 + ")"); 10710 try { 10711 mInstaller.rmdex(ps.codePathString, 10712 getDexCodeInstructionSet(getPreferredInstructionSet())); 10713 } catch (InstallerException ignored) { 10714 } 10715 } 10716 } 10717 } 10718 } 10719 } 10720 10721 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10722 synchronized (mPackages) { 10723 mResolverReplaced = true; 10724 // Set up information for custom user intent resolution activity. 10725 mResolveActivity.applicationInfo = pkg.applicationInfo; 10726 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10727 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10728 mResolveActivity.processName = pkg.applicationInfo.packageName; 10729 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10730 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10731 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10732 mResolveActivity.theme = 0; 10733 mResolveActivity.exported = true; 10734 mResolveActivity.enabled = true; 10735 mResolveInfo.activityInfo = mResolveActivity; 10736 mResolveInfo.priority = 0; 10737 mResolveInfo.preferredOrder = 0; 10738 mResolveInfo.match = 0; 10739 mResolveComponentName = mCustomResolverComponentName; 10740 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10741 mResolveComponentName); 10742 } 10743 } 10744 10745 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10746 if (installerActivity == null) { 10747 if (DEBUG_EPHEMERAL) { 10748 Slog.d(TAG, "Clear ephemeral installer activity"); 10749 } 10750 mInstantAppInstallerActivity = null; 10751 return; 10752 } 10753 10754 if (DEBUG_EPHEMERAL) { 10755 Slog.d(TAG, "Set ephemeral installer activity: " 10756 + installerActivity.getComponentName()); 10757 } 10758 // Set up information for ephemeral installer activity 10759 mInstantAppInstallerActivity = installerActivity; 10760 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10761 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10762 mInstantAppInstallerActivity.exported = true; 10763 mInstantAppInstallerActivity.enabled = true; 10764 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10765 mInstantAppInstallerInfo.priority = 0; 10766 mInstantAppInstallerInfo.preferredOrder = 1; 10767 mInstantAppInstallerInfo.isDefault = true; 10768 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10769 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10770 } 10771 10772 private static String calculateBundledApkRoot(final String codePathString) { 10773 final File codePath = new File(codePathString); 10774 final File codeRoot; 10775 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10776 codeRoot = Environment.getRootDirectory(); 10777 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10778 codeRoot = Environment.getOemDirectory(); 10779 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10780 codeRoot = Environment.getVendorDirectory(); 10781 } else { 10782 // Unrecognized code path; take its top real segment as the apk root: 10783 // e.g. /something/app/blah.apk => /something 10784 try { 10785 File f = codePath.getCanonicalFile(); 10786 File parent = f.getParentFile(); // non-null because codePath is a file 10787 File tmp; 10788 while ((tmp = parent.getParentFile()) != null) { 10789 f = parent; 10790 parent = tmp; 10791 } 10792 codeRoot = f; 10793 Slog.w(TAG, "Unrecognized code path " 10794 + codePath + " - using " + codeRoot); 10795 } catch (IOException e) { 10796 // Can't canonicalize the code path -- shenanigans? 10797 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10798 return Environment.getRootDirectory().getPath(); 10799 } 10800 } 10801 return codeRoot.getPath(); 10802 } 10803 10804 /** 10805 * Derive and set the location of native libraries for the given package, 10806 * which varies depending on where and how the package was installed. 10807 */ 10808 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10809 final ApplicationInfo info = pkg.applicationInfo; 10810 final String codePath = pkg.codePath; 10811 final File codeFile = new File(codePath); 10812 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10813 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10814 10815 info.nativeLibraryRootDir = null; 10816 info.nativeLibraryRootRequiresIsa = false; 10817 info.nativeLibraryDir = null; 10818 info.secondaryNativeLibraryDir = null; 10819 10820 if (isApkFile(codeFile)) { 10821 // Monolithic install 10822 if (bundledApp) { 10823 // If "/system/lib64/apkname" exists, assume that is the per-package 10824 // native library directory to use; otherwise use "/system/lib/apkname". 10825 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10826 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10827 getPrimaryInstructionSet(info)); 10828 10829 // This is a bundled system app so choose the path based on the ABI. 10830 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10831 // is just the default path. 10832 final String apkName = deriveCodePathName(codePath); 10833 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10834 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10835 apkName).getAbsolutePath(); 10836 10837 if (info.secondaryCpuAbi != null) { 10838 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10839 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10840 secondaryLibDir, apkName).getAbsolutePath(); 10841 } 10842 } else if (asecApp) { 10843 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10844 .getAbsolutePath(); 10845 } else { 10846 final String apkName = deriveCodePathName(codePath); 10847 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10848 .getAbsolutePath(); 10849 } 10850 10851 info.nativeLibraryRootRequiresIsa = false; 10852 info.nativeLibraryDir = info.nativeLibraryRootDir; 10853 } else { 10854 // Cluster install 10855 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10856 info.nativeLibraryRootRequiresIsa = true; 10857 10858 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10859 getPrimaryInstructionSet(info)).getAbsolutePath(); 10860 10861 if (info.secondaryCpuAbi != null) { 10862 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10863 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10864 } 10865 } 10866 } 10867 10868 /** 10869 * Calculate the abis and roots for a bundled app. These can uniquely 10870 * be determined from the contents of the system partition, i.e whether 10871 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10872 * of this information, and instead assume that the system was built 10873 * sensibly. 10874 */ 10875 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10876 PackageSetting pkgSetting) { 10877 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10878 10879 // If "/system/lib64/apkname" exists, assume that is the per-package 10880 // native library directory to use; otherwise use "/system/lib/apkname". 10881 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10882 setBundledAppAbi(pkg, apkRoot, apkName); 10883 // pkgSetting might be null during rescan following uninstall of updates 10884 // to a bundled app, so accommodate that possibility. The settings in 10885 // that case will be established later from the parsed package. 10886 // 10887 // If the settings aren't null, sync them up with what we've just derived. 10888 // note that apkRoot isn't stored in the package settings. 10889 if (pkgSetting != null) { 10890 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10891 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10892 } 10893 } 10894 10895 /** 10896 * Deduces the ABI of a bundled app and sets the relevant fields on the 10897 * parsed pkg object. 10898 * 10899 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10900 * under which system libraries are installed. 10901 * @param apkName the name of the installed package. 10902 */ 10903 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10904 final File codeFile = new File(pkg.codePath); 10905 10906 final boolean has64BitLibs; 10907 final boolean has32BitLibs; 10908 if (isApkFile(codeFile)) { 10909 // Monolithic install 10910 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10911 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10912 } else { 10913 // Cluster install 10914 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10915 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10916 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10917 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10918 has64BitLibs = (new File(rootDir, isa)).exists(); 10919 } else { 10920 has64BitLibs = false; 10921 } 10922 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10923 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10924 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10925 has32BitLibs = (new File(rootDir, isa)).exists(); 10926 } else { 10927 has32BitLibs = false; 10928 } 10929 } 10930 10931 if (has64BitLibs && !has32BitLibs) { 10932 // The package has 64 bit libs, but not 32 bit libs. Its primary 10933 // ABI should be 64 bit. We can safely assume here that the bundled 10934 // native libraries correspond to the most preferred ABI in the list. 10935 10936 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10937 pkg.applicationInfo.secondaryCpuAbi = null; 10938 } else if (has32BitLibs && !has64BitLibs) { 10939 // The package has 32 bit libs but not 64 bit libs. Its primary 10940 // ABI should be 32 bit. 10941 10942 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10943 pkg.applicationInfo.secondaryCpuAbi = null; 10944 } else if (has32BitLibs && has64BitLibs) { 10945 // The application has both 64 and 32 bit bundled libraries. We check 10946 // here that the app declares multiArch support, and warn if it doesn't. 10947 // 10948 // We will be lenient here and record both ABIs. The primary will be the 10949 // ABI that's higher on the list, i.e, a device that's configured to prefer 10950 // 64 bit apps will see a 64 bit primary ABI, 10951 10952 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10953 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10954 } 10955 10956 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10958 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10959 } else { 10960 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10961 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10962 } 10963 } else { 10964 pkg.applicationInfo.primaryCpuAbi = null; 10965 pkg.applicationInfo.secondaryCpuAbi = null; 10966 } 10967 } 10968 10969 private void killApplication(String pkgName, int appId, String reason) { 10970 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10971 } 10972 10973 private void killApplication(String pkgName, int appId, int userId, String reason) { 10974 // Request the ActivityManager to kill the process(only for existing packages) 10975 // so that we do not end up in a confused state while the user is still using the older 10976 // version of the application while the new one gets installed. 10977 final long token = Binder.clearCallingIdentity(); 10978 try { 10979 IActivityManager am = ActivityManager.getService(); 10980 if (am != null) { 10981 try { 10982 am.killApplication(pkgName, appId, userId, reason); 10983 } catch (RemoteException e) { 10984 } 10985 } 10986 } finally { 10987 Binder.restoreCallingIdentity(token); 10988 } 10989 } 10990 10991 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10992 // Remove the parent package setting 10993 PackageSetting ps = (PackageSetting) pkg.mExtras; 10994 if (ps != null) { 10995 removePackageLI(ps, chatty); 10996 } 10997 // Remove the child package setting 10998 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10999 for (int i = 0; i < childCount; i++) { 11000 PackageParser.Package childPkg = pkg.childPackages.get(i); 11001 ps = (PackageSetting) childPkg.mExtras; 11002 if (ps != null) { 11003 removePackageLI(ps, chatty); 11004 } 11005 } 11006 } 11007 11008 void removePackageLI(PackageSetting ps, boolean chatty) { 11009 if (DEBUG_INSTALL) { 11010 if (chatty) 11011 Log.d(TAG, "Removing package " + ps.name); 11012 } 11013 11014 // writer 11015 synchronized (mPackages) { 11016 mPackages.remove(ps.name); 11017 final PackageParser.Package pkg = ps.pkg; 11018 if (pkg != null) { 11019 cleanPackageDataStructuresLILPw(pkg, chatty); 11020 } 11021 } 11022 } 11023 11024 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11025 if (DEBUG_INSTALL) { 11026 if (chatty) 11027 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11028 } 11029 11030 // writer 11031 synchronized (mPackages) { 11032 // Remove the parent package 11033 mPackages.remove(pkg.applicationInfo.packageName); 11034 cleanPackageDataStructuresLILPw(pkg, chatty); 11035 11036 // Remove the child packages 11037 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11038 for (int i = 0; i < childCount; i++) { 11039 PackageParser.Package childPkg = pkg.childPackages.get(i); 11040 mPackages.remove(childPkg.applicationInfo.packageName); 11041 cleanPackageDataStructuresLILPw(childPkg, chatty); 11042 } 11043 } 11044 } 11045 11046 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11047 int N = pkg.providers.size(); 11048 StringBuilder r = null; 11049 int i; 11050 for (i=0; i<N; i++) { 11051 PackageParser.Provider p = pkg.providers.get(i); 11052 mProviders.removeProvider(p); 11053 if (p.info.authority == null) { 11054 11055 /* There was another ContentProvider with this authority when 11056 * this app was installed so this authority is null, 11057 * Ignore it as we don't have to unregister the provider. 11058 */ 11059 continue; 11060 } 11061 String names[] = p.info.authority.split(";"); 11062 for (int j = 0; j < names.length; j++) { 11063 if (mProvidersByAuthority.get(names[j]) == p) { 11064 mProvidersByAuthority.remove(names[j]); 11065 if (DEBUG_REMOVE) { 11066 if (chatty) 11067 Log.d(TAG, "Unregistered content provider: " + names[j] 11068 + ", className = " + p.info.name + ", isSyncable = " 11069 + p.info.isSyncable); 11070 } 11071 } 11072 } 11073 if (DEBUG_REMOVE && chatty) { 11074 if (r == null) { 11075 r = new StringBuilder(256); 11076 } else { 11077 r.append(' '); 11078 } 11079 r.append(p.info.name); 11080 } 11081 } 11082 if (r != null) { 11083 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11084 } 11085 11086 N = pkg.services.size(); 11087 r = null; 11088 for (i=0; i<N; i++) { 11089 PackageParser.Service s = pkg.services.get(i); 11090 mServices.removeService(s); 11091 if (chatty) { 11092 if (r == null) { 11093 r = new StringBuilder(256); 11094 } else { 11095 r.append(' '); 11096 } 11097 r.append(s.info.name); 11098 } 11099 } 11100 if (r != null) { 11101 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11102 } 11103 11104 N = pkg.receivers.size(); 11105 r = null; 11106 for (i=0; i<N; i++) { 11107 PackageParser.Activity a = pkg.receivers.get(i); 11108 mReceivers.removeActivity(a, "receiver"); 11109 if (DEBUG_REMOVE && chatty) { 11110 if (r == null) { 11111 r = new StringBuilder(256); 11112 } else { 11113 r.append(' '); 11114 } 11115 r.append(a.info.name); 11116 } 11117 } 11118 if (r != null) { 11119 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11120 } 11121 11122 N = pkg.activities.size(); 11123 r = null; 11124 for (i=0; i<N; i++) { 11125 PackageParser.Activity a = pkg.activities.get(i); 11126 mActivities.removeActivity(a, "activity"); 11127 if (DEBUG_REMOVE && chatty) { 11128 if (r == null) { 11129 r = new StringBuilder(256); 11130 } else { 11131 r.append(' '); 11132 } 11133 r.append(a.info.name); 11134 } 11135 } 11136 if (r != null) { 11137 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11138 } 11139 11140 N = pkg.permissions.size(); 11141 r = null; 11142 for (i=0; i<N; i++) { 11143 PackageParser.Permission p = pkg.permissions.get(i); 11144 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11145 if (bp == null) { 11146 bp = mSettings.mPermissionTrees.get(p.info.name); 11147 } 11148 if (bp != null && bp.perm == p) { 11149 bp.perm = null; 11150 if (DEBUG_REMOVE && chatty) { 11151 if (r == null) { 11152 r = new StringBuilder(256); 11153 } else { 11154 r.append(' '); 11155 } 11156 r.append(p.info.name); 11157 } 11158 } 11159 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11160 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11161 if (appOpPkgs != null) { 11162 appOpPkgs.remove(pkg.packageName); 11163 } 11164 } 11165 } 11166 if (r != null) { 11167 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11168 } 11169 11170 N = pkg.requestedPermissions.size(); 11171 r = null; 11172 for (i=0; i<N; i++) { 11173 String perm = pkg.requestedPermissions.get(i); 11174 BasePermission bp = mSettings.mPermissions.get(perm); 11175 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11176 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11177 if (appOpPkgs != null) { 11178 appOpPkgs.remove(pkg.packageName); 11179 if (appOpPkgs.isEmpty()) { 11180 mAppOpPermissionPackages.remove(perm); 11181 } 11182 } 11183 } 11184 } 11185 if (r != null) { 11186 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11187 } 11188 11189 N = pkg.instrumentation.size(); 11190 r = null; 11191 for (i=0; i<N; i++) { 11192 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11193 mInstrumentation.remove(a.getComponentName()); 11194 if (DEBUG_REMOVE && chatty) { 11195 if (r == null) { 11196 r = new StringBuilder(256); 11197 } else { 11198 r.append(' '); 11199 } 11200 r.append(a.info.name); 11201 } 11202 } 11203 if (r != null) { 11204 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11205 } 11206 11207 r = null; 11208 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11209 // Only system apps can hold shared libraries. 11210 if (pkg.libraryNames != null) { 11211 for (i = 0; i < pkg.libraryNames.size(); i++) { 11212 String name = pkg.libraryNames.get(i); 11213 if (removeSharedLibraryLPw(name, 0)) { 11214 if (DEBUG_REMOVE && chatty) { 11215 if (r == null) { 11216 r = new StringBuilder(256); 11217 } else { 11218 r.append(' '); 11219 } 11220 r.append(name); 11221 } 11222 } 11223 } 11224 } 11225 } 11226 11227 r = null; 11228 11229 // Any package can hold static shared libraries. 11230 if (pkg.staticSharedLibName != null) { 11231 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11232 if (DEBUG_REMOVE && chatty) { 11233 if (r == null) { 11234 r = new StringBuilder(256); 11235 } else { 11236 r.append(' '); 11237 } 11238 r.append(pkg.staticSharedLibName); 11239 } 11240 } 11241 } 11242 11243 if (r != null) { 11244 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11245 } 11246 } 11247 11248 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11249 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11250 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11251 return true; 11252 } 11253 } 11254 return false; 11255 } 11256 11257 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11258 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11259 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11260 11261 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11262 // Update the parent permissions 11263 updatePermissionsLPw(pkg.packageName, pkg, flags); 11264 // Update the child permissions 11265 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11266 for (int i = 0; i < childCount; i++) { 11267 PackageParser.Package childPkg = pkg.childPackages.get(i); 11268 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11269 } 11270 } 11271 11272 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11273 int flags) { 11274 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11275 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11276 } 11277 11278 private void updatePermissionsLPw(String changingPkg, 11279 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11280 // Make sure there are no dangling permission trees. 11281 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11282 while (it.hasNext()) { 11283 final BasePermission bp = it.next(); 11284 if (bp.packageSetting == null) { 11285 // We may not yet have parsed the package, so just see if 11286 // we still know about its settings. 11287 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11288 } 11289 if (bp.packageSetting == null) { 11290 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11291 + " from package " + bp.sourcePackage); 11292 it.remove(); 11293 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11294 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11295 Slog.i(TAG, "Removing old permission tree: " + bp.name 11296 + " from package " + bp.sourcePackage); 11297 flags |= UPDATE_PERMISSIONS_ALL; 11298 it.remove(); 11299 } 11300 } 11301 } 11302 11303 // Make sure all dynamic permissions have been assigned to a package, 11304 // and make sure there are no dangling permissions. 11305 it = mSettings.mPermissions.values().iterator(); 11306 while (it.hasNext()) { 11307 final BasePermission bp = it.next(); 11308 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11309 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11310 + bp.name + " pkg=" + bp.sourcePackage 11311 + " info=" + bp.pendingInfo); 11312 if (bp.packageSetting == null && bp.pendingInfo != null) { 11313 final BasePermission tree = findPermissionTreeLP(bp.name); 11314 if (tree != null && tree.perm != null) { 11315 bp.packageSetting = tree.packageSetting; 11316 bp.perm = new PackageParser.Permission(tree.perm.owner, 11317 new PermissionInfo(bp.pendingInfo)); 11318 bp.perm.info.packageName = tree.perm.info.packageName; 11319 bp.perm.info.name = bp.name; 11320 bp.uid = tree.uid; 11321 } 11322 } 11323 } 11324 if (bp.packageSetting == null) { 11325 // We may not yet have parsed the package, so just see if 11326 // we still know about its settings. 11327 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11328 } 11329 if (bp.packageSetting == null) { 11330 Slog.w(TAG, "Removing dangling permission: " + bp.name 11331 + " from package " + bp.sourcePackage); 11332 it.remove(); 11333 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11334 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11335 Slog.i(TAG, "Removing old permission: " + bp.name 11336 + " from package " + bp.sourcePackage); 11337 flags |= UPDATE_PERMISSIONS_ALL; 11338 it.remove(); 11339 } 11340 } 11341 } 11342 11343 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11344 // Now update the permissions for all packages, in particular 11345 // replace the granted permissions of the system packages. 11346 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11347 for (PackageParser.Package pkg : mPackages.values()) { 11348 if (pkg != pkgInfo) { 11349 // Only replace for packages on requested volume 11350 final String volumeUuid = getVolumeUuidForPackage(pkg); 11351 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11352 && Objects.equals(replaceVolumeUuid, volumeUuid); 11353 grantPermissionsLPw(pkg, replace, changingPkg); 11354 } 11355 } 11356 } 11357 11358 if (pkgInfo != null) { 11359 // Only replace for packages on requested volume 11360 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11361 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11362 && Objects.equals(replaceVolumeUuid, volumeUuid); 11363 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11364 } 11365 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11366 } 11367 11368 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11369 String packageOfInterest) { 11370 // IMPORTANT: There are two types of permissions: install and runtime. 11371 // Install time permissions are granted when the app is installed to 11372 // all device users and users added in the future. Runtime permissions 11373 // are granted at runtime explicitly to specific users. Normal and signature 11374 // protected permissions are install time permissions. Dangerous permissions 11375 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11376 // otherwise they are runtime permissions. This function does not manage 11377 // runtime permissions except for the case an app targeting Lollipop MR1 11378 // being upgraded to target a newer SDK, in which case dangerous permissions 11379 // are transformed from install time to runtime ones. 11380 11381 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11382 if (ps == null) { 11383 return; 11384 } 11385 11386 PermissionsState permissionsState = ps.getPermissionsState(); 11387 PermissionsState origPermissions = permissionsState; 11388 11389 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11390 11391 boolean runtimePermissionsRevoked = false; 11392 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11393 11394 boolean changedInstallPermission = false; 11395 11396 if (replace) { 11397 ps.installPermissionsFixed = false; 11398 if (!ps.isSharedUser()) { 11399 origPermissions = new PermissionsState(permissionsState); 11400 permissionsState.reset(); 11401 } else { 11402 // We need to know only about runtime permission changes since the 11403 // calling code always writes the install permissions state but 11404 // the runtime ones are written only if changed. The only cases of 11405 // changed runtime permissions here are promotion of an install to 11406 // runtime and revocation of a runtime from a shared user. 11407 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11408 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11409 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11410 runtimePermissionsRevoked = true; 11411 } 11412 } 11413 } 11414 11415 permissionsState.setGlobalGids(mGlobalGids); 11416 11417 final int N = pkg.requestedPermissions.size(); 11418 for (int i=0; i<N; i++) { 11419 final String name = pkg.requestedPermissions.get(i); 11420 final BasePermission bp = mSettings.mPermissions.get(name); 11421 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11422 >= Build.VERSION_CODES.M; 11423 11424 if (DEBUG_INSTALL) { 11425 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11426 } 11427 11428 if (bp == null || bp.packageSetting == null) { 11429 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11430 Slog.w(TAG, "Unknown permission " + name 11431 + " in package " + pkg.packageName); 11432 } 11433 continue; 11434 } 11435 11436 11437 // Limit ephemeral apps to ephemeral allowed permissions. 11438 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11439 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11440 + pkg.packageName); 11441 continue; 11442 } 11443 11444 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 11445 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 11446 + pkg.packageName); 11447 continue; 11448 } 11449 11450 final String perm = bp.name; 11451 boolean allowedSig = false; 11452 int grant = GRANT_DENIED; 11453 11454 // Keep track of app op permissions. 11455 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11456 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11457 if (pkgs == null) { 11458 pkgs = new ArraySet<>(); 11459 mAppOpPermissionPackages.put(bp.name, pkgs); 11460 } 11461 pkgs.add(pkg.packageName); 11462 } 11463 11464 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11465 switch (level) { 11466 case PermissionInfo.PROTECTION_NORMAL: { 11467 // For all apps normal permissions are install time ones. 11468 grant = GRANT_INSTALL; 11469 } break; 11470 11471 case PermissionInfo.PROTECTION_DANGEROUS: { 11472 // If a permission review is required for legacy apps we represent 11473 // their permissions as always granted runtime ones since we need 11474 // to keep the review required permission flag per user while an 11475 // install permission's state is shared across all users. 11476 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11477 // For legacy apps dangerous permissions are install time ones. 11478 grant = GRANT_INSTALL; 11479 } else if (origPermissions.hasInstallPermission(bp.name)) { 11480 // For legacy apps that became modern, install becomes runtime. 11481 grant = GRANT_UPGRADE; 11482 } else if (mPromoteSystemApps 11483 && isSystemApp(ps) 11484 && mExistingSystemPackages.contains(ps.name)) { 11485 // For legacy system apps, install becomes runtime. 11486 // We cannot check hasInstallPermission() for system apps since those 11487 // permissions were granted implicitly and not persisted pre-M. 11488 grant = GRANT_UPGRADE; 11489 } else { 11490 // For modern apps keep runtime permissions unchanged. 11491 grant = GRANT_RUNTIME; 11492 } 11493 } break; 11494 11495 case PermissionInfo.PROTECTION_SIGNATURE: { 11496 // For all apps signature permissions are install time ones. 11497 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11498 if (allowedSig) { 11499 grant = GRANT_INSTALL; 11500 } 11501 } break; 11502 } 11503 11504 if (DEBUG_INSTALL) { 11505 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11506 } 11507 11508 if (grant != GRANT_DENIED) { 11509 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11510 // If this is an existing, non-system package, then 11511 // we can't add any new permissions to it. 11512 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11513 // Except... if this is a permission that was added 11514 // to the platform (note: need to only do this when 11515 // updating the platform). 11516 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11517 grant = GRANT_DENIED; 11518 } 11519 } 11520 } 11521 11522 switch (grant) { 11523 case GRANT_INSTALL: { 11524 // Revoke this as runtime permission to handle the case of 11525 // a runtime permission being downgraded to an install one. 11526 // Also in permission review mode we keep dangerous permissions 11527 // for legacy apps 11528 for (int userId : UserManagerService.getInstance().getUserIds()) { 11529 if (origPermissions.getRuntimePermissionState( 11530 bp.name, userId) != null) { 11531 // Revoke the runtime permission and clear the flags. 11532 origPermissions.revokeRuntimePermission(bp, userId); 11533 origPermissions.updatePermissionFlags(bp, userId, 11534 PackageManager.MASK_PERMISSION_FLAGS, 0); 11535 // If we revoked a permission permission, we have to write. 11536 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11537 changedRuntimePermissionUserIds, userId); 11538 } 11539 } 11540 // Grant an install permission. 11541 if (permissionsState.grantInstallPermission(bp) != 11542 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11543 changedInstallPermission = true; 11544 } 11545 } break; 11546 11547 case GRANT_RUNTIME: { 11548 // Grant previously granted runtime permissions. 11549 for (int userId : UserManagerService.getInstance().getUserIds()) { 11550 PermissionState permissionState = origPermissions 11551 .getRuntimePermissionState(bp.name, userId); 11552 int flags = permissionState != null 11553 ? permissionState.getFlags() : 0; 11554 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11555 // Don't propagate the permission in a permission review mode if 11556 // the former was revoked, i.e. marked to not propagate on upgrade. 11557 // Note that in a permission review mode install permissions are 11558 // represented as constantly granted runtime ones since we need to 11559 // keep a per user state associated with the permission. Also the 11560 // revoke on upgrade flag is no longer applicable and is reset. 11561 final boolean revokeOnUpgrade = (flags & PackageManager 11562 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11563 if (revokeOnUpgrade) { 11564 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11565 // Since we changed the flags, we have to write. 11566 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11567 changedRuntimePermissionUserIds, userId); 11568 } 11569 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11570 if (permissionsState.grantRuntimePermission(bp, userId) == 11571 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11572 // If we cannot put the permission as it was, 11573 // we have to write. 11574 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11575 changedRuntimePermissionUserIds, userId); 11576 } 11577 } 11578 11579 // If the app supports runtime permissions no need for a review. 11580 if (mPermissionReviewRequired 11581 && appSupportsRuntimePermissions 11582 && (flags & PackageManager 11583 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11584 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11585 // Since we changed the flags, we have to write. 11586 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11587 changedRuntimePermissionUserIds, userId); 11588 } 11589 } else if (mPermissionReviewRequired 11590 && !appSupportsRuntimePermissions) { 11591 // For legacy apps that need a permission review, every new 11592 // runtime permission is granted but it is pending a review. 11593 // We also need to review only platform defined runtime 11594 // permissions as these are the only ones the platform knows 11595 // how to disable the API to simulate revocation as legacy 11596 // apps don't expect to run with revoked permissions. 11597 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11598 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11599 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11600 // We changed the flags, hence have to write. 11601 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11602 changedRuntimePermissionUserIds, userId); 11603 } 11604 } 11605 if (permissionsState.grantRuntimePermission(bp, userId) 11606 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11607 // We changed the permission, hence have to write. 11608 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11609 changedRuntimePermissionUserIds, userId); 11610 } 11611 } 11612 // Propagate the permission flags. 11613 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11614 } 11615 } break; 11616 11617 case GRANT_UPGRADE: { 11618 // Grant runtime permissions for a previously held install permission. 11619 PermissionState permissionState = origPermissions 11620 .getInstallPermissionState(bp.name); 11621 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11622 11623 if (origPermissions.revokeInstallPermission(bp) 11624 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11625 // We will be transferring the permission flags, so clear them. 11626 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11627 PackageManager.MASK_PERMISSION_FLAGS, 0); 11628 changedInstallPermission = true; 11629 } 11630 11631 // If the permission is not to be promoted to runtime we ignore it and 11632 // also its other flags as they are not applicable to install permissions. 11633 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11634 for (int userId : currentUserIds) { 11635 if (permissionsState.grantRuntimePermission(bp, userId) != 11636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11637 // Transfer the permission flags. 11638 permissionsState.updatePermissionFlags(bp, userId, 11639 flags, flags); 11640 // If we granted the permission, we have to write. 11641 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11642 changedRuntimePermissionUserIds, userId); 11643 } 11644 } 11645 } 11646 } break; 11647 11648 default: { 11649 if (packageOfInterest == null 11650 || packageOfInterest.equals(pkg.packageName)) { 11651 Slog.w(TAG, "Not granting permission " + perm 11652 + " to package " + pkg.packageName 11653 + " because it was previously installed without"); 11654 } 11655 } break; 11656 } 11657 } else { 11658 if (permissionsState.revokeInstallPermission(bp) != 11659 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11660 // Also drop the permission flags. 11661 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11662 PackageManager.MASK_PERMISSION_FLAGS, 0); 11663 changedInstallPermission = true; 11664 Slog.i(TAG, "Un-granting permission " + perm 11665 + " from package " + pkg.packageName 11666 + " (protectionLevel=" + bp.protectionLevel 11667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11668 + ")"); 11669 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11670 // Don't print warning for app op permissions, since it is fine for them 11671 // not to be granted, there is a UI for the user to decide. 11672 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11673 Slog.w(TAG, "Not granting permission " + perm 11674 + " to package " + pkg.packageName 11675 + " (protectionLevel=" + bp.protectionLevel 11676 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11677 + ")"); 11678 } 11679 } 11680 } 11681 } 11682 11683 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11684 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11685 // This is the first that we have heard about this package, so the 11686 // permissions we have now selected are fixed until explicitly 11687 // changed. 11688 ps.installPermissionsFixed = true; 11689 } 11690 11691 // Persist the runtime permissions state for users with changes. If permissions 11692 // were revoked because no app in the shared user declares them we have to 11693 // write synchronously to avoid losing runtime permissions state. 11694 for (int userId : changedRuntimePermissionUserIds) { 11695 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11696 } 11697 } 11698 11699 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11700 boolean allowed = false; 11701 final int NP = PackageParser.NEW_PERMISSIONS.length; 11702 for (int ip=0; ip<NP; ip++) { 11703 final PackageParser.NewPermissionInfo npi 11704 = PackageParser.NEW_PERMISSIONS[ip]; 11705 if (npi.name.equals(perm) 11706 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11707 allowed = true; 11708 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11709 + pkg.packageName); 11710 break; 11711 } 11712 } 11713 return allowed; 11714 } 11715 11716 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11717 BasePermission bp, PermissionsState origPermissions) { 11718 boolean privilegedPermission = (bp.protectionLevel 11719 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11720 boolean privappPermissionsDisable = 11721 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11722 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11723 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11724 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11725 && !platformPackage && platformPermission) { 11726 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11727 .getPrivAppPermissions(pkg.packageName); 11728 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11729 if (!whitelisted) { 11730 Slog.w(TAG, "Privileged permission " + perm + " for package " 11731 + pkg.packageName + " - not in privapp-permissions whitelist"); 11732 // Only report violations for apps on system image 11733 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11734 if (mPrivappPermissionsViolations == null) { 11735 mPrivappPermissionsViolations = new ArraySet<>(); 11736 } 11737 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11738 } 11739 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11740 return false; 11741 } 11742 } 11743 } 11744 boolean allowed = (compareSignatures( 11745 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11746 == PackageManager.SIGNATURE_MATCH) 11747 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11748 == PackageManager.SIGNATURE_MATCH); 11749 if (!allowed && privilegedPermission) { 11750 if (isSystemApp(pkg)) { 11751 // For updated system applications, a system permission 11752 // is granted only if it had been defined by the original application. 11753 if (pkg.isUpdatedSystemApp()) { 11754 final PackageSetting sysPs = mSettings 11755 .getDisabledSystemPkgLPr(pkg.packageName); 11756 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11757 // If the original was granted this permission, we take 11758 // that grant decision as read and propagate it to the 11759 // update. 11760 if (sysPs.isPrivileged()) { 11761 allowed = true; 11762 } 11763 } else { 11764 // The system apk may have been updated with an older 11765 // version of the one on the data partition, but which 11766 // granted a new system permission that it didn't have 11767 // before. In this case we do want to allow the app to 11768 // now get the new permission if the ancestral apk is 11769 // privileged to get it. 11770 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11771 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11772 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11773 allowed = true; 11774 break; 11775 } 11776 } 11777 } 11778 // Also if a privileged parent package on the system image or any of 11779 // its children requested a privileged permission, the updated child 11780 // packages can also get the permission. 11781 if (pkg.parentPackage != null) { 11782 final PackageSetting disabledSysParentPs = mSettings 11783 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11784 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11785 && disabledSysParentPs.isPrivileged()) { 11786 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11787 allowed = true; 11788 } else if (disabledSysParentPs.pkg.childPackages != null) { 11789 final int count = disabledSysParentPs.pkg.childPackages.size(); 11790 for (int i = 0; i < count; i++) { 11791 PackageParser.Package disabledSysChildPkg = 11792 disabledSysParentPs.pkg.childPackages.get(i); 11793 if (isPackageRequestingPermission(disabledSysChildPkg, 11794 perm)) { 11795 allowed = true; 11796 break; 11797 } 11798 } 11799 } 11800 } 11801 } 11802 } 11803 } else { 11804 allowed = isPrivilegedApp(pkg); 11805 } 11806 } 11807 } 11808 if (!allowed) { 11809 if (!allowed && (bp.protectionLevel 11810 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11811 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11812 // If this was a previously normal/dangerous permission that got moved 11813 // to a system permission as part of the runtime permission redesign, then 11814 // we still want to blindly grant it to old apps. 11815 allowed = true; 11816 } 11817 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11818 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11819 // If this permission is to be granted to the system installer and 11820 // this app is an installer, then it gets the permission. 11821 allowed = true; 11822 } 11823 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11824 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11825 // If this permission is to be granted to the system verifier and 11826 // this app is a verifier, then it gets the permission. 11827 allowed = true; 11828 } 11829 if (!allowed && (bp.protectionLevel 11830 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11831 && isSystemApp(pkg)) { 11832 // Any pre-installed system app is allowed to get this permission. 11833 allowed = true; 11834 } 11835 if (!allowed && (bp.protectionLevel 11836 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11837 // For development permissions, a development permission 11838 // is granted only if it was already granted. 11839 allowed = origPermissions.hasInstallPermission(perm); 11840 } 11841 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11842 && pkg.packageName.equals(mSetupWizardPackage)) { 11843 // If this permission is to be granted to the system setup wizard and 11844 // this app is a setup wizard, then it gets the permission. 11845 allowed = true; 11846 } 11847 } 11848 return allowed; 11849 } 11850 11851 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11852 final int permCount = pkg.requestedPermissions.size(); 11853 for (int j = 0; j < permCount; j++) { 11854 String requestedPermission = pkg.requestedPermissions.get(j); 11855 if (permission.equals(requestedPermission)) { 11856 return true; 11857 } 11858 } 11859 return false; 11860 } 11861 11862 final class ActivityIntentResolver 11863 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11864 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11865 boolean defaultOnly, int userId) { 11866 if (!sUserManager.exists(userId)) return null; 11867 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11868 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11869 } 11870 11871 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11872 int userId) { 11873 if (!sUserManager.exists(userId)) return null; 11874 mFlags = flags; 11875 return super.queryIntent(intent, resolvedType, 11876 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11877 userId); 11878 } 11879 11880 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11881 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11882 if (!sUserManager.exists(userId)) return null; 11883 if (packageActivities == null) { 11884 return null; 11885 } 11886 mFlags = flags; 11887 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11888 final int N = packageActivities.size(); 11889 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11890 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11891 11892 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11893 for (int i = 0; i < N; ++i) { 11894 intentFilters = packageActivities.get(i).intents; 11895 if (intentFilters != null && intentFilters.size() > 0) { 11896 PackageParser.ActivityIntentInfo[] array = 11897 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11898 intentFilters.toArray(array); 11899 listCut.add(array); 11900 } 11901 } 11902 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11903 } 11904 11905 /** 11906 * Finds a privileged activity that matches the specified activity names. 11907 */ 11908 private PackageParser.Activity findMatchingActivity( 11909 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11910 for (PackageParser.Activity sysActivity : activityList) { 11911 if (sysActivity.info.name.equals(activityInfo.name)) { 11912 return sysActivity; 11913 } 11914 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11915 return sysActivity; 11916 } 11917 if (sysActivity.info.targetActivity != null) { 11918 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11919 return sysActivity; 11920 } 11921 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11922 return sysActivity; 11923 } 11924 } 11925 } 11926 return null; 11927 } 11928 11929 public class IterGenerator<E> { 11930 public Iterator<E> generate(ActivityIntentInfo info) { 11931 return null; 11932 } 11933 } 11934 11935 public class ActionIterGenerator extends IterGenerator<String> { 11936 @Override 11937 public Iterator<String> generate(ActivityIntentInfo info) { 11938 return info.actionsIterator(); 11939 } 11940 } 11941 11942 public class CategoriesIterGenerator extends IterGenerator<String> { 11943 @Override 11944 public Iterator<String> generate(ActivityIntentInfo info) { 11945 return info.categoriesIterator(); 11946 } 11947 } 11948 11949 public class SchemesIterGenerator extends IterGenerator<String> { 11950 @Override 11951 public Iterator<String> generate(ActivityIntentInfo info) { 11952 return info.schemesIterator(); 11953 } 11954 } 11955 11956 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11957 @Override 11958 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11959 return info.authoritiesIterator(); 11960 } 11961 } 11962 11963 /** 11964 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11965 * MODIFIED. Do not pass in a list that should not be changed. 11966 */ 11967 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11968 IterGenerator<T> generator, Iterator<T> searchIterator) { 11969 // loop through the set of actions; every one must be found in the intent filter 11970 while (searchIterator.hasNext()) { 11971 // we must have at least one filter in the list to consider a match 11972 if (intentList.size() == 0) { 11973 break; 11974 } 11975 11976 final T searchAction = searchIterator.next(); 11977 11978 // loop through the set of intent filters 11979 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11980 while (intentIter.hasNext()) { 11981 final ActivityIntentInfo intentInfo = intentIter.next(); 11982 boolean selectionFound = false; 11983 11984 // loop through the intent filter's selection criteria; at least one 11985 // of them must match the searched criteria 11986 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11987 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11988 final T intentSelection = intentSelectionIter.next(); 11989 if (intentSelection != null && intentSelection.equals(searchAction)) { 11990 selectionFound = true; 11991 break; 11992 } 11993 } 11994 11995 // the selection criteria wasn't found in this filter's set; this filter 11996 // is not a potential match 11997 if (!selectionFound) { 11998 intentIter.remove(); 11999 } 12000 } 12001 } 12002 } 12003 12004 private boolean isProtectedAction(ActivityIntentInfo filter) { 12005 final Iterator<String> actionsIter = filter.actionsIterator(); 12006 while (actionsIter != null && actionsIter.hasNext()) { 12007 final String filterAction = actionsIter.next(); 12008 if (PROTECTED_ACTIONS.contains(filterAction)) { 12009 return true; 12010 } 12011 } 12012 return false; 12013 } 12014 12015 /** 12016 * Adjusts the priority of the given intent filter according to policy. 12017 * <p> 12018 * <ul> 12019 * <li>The priority for non privileged applications is capped to '0'</li> 12020 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12021 * <li>The priority for unbundled updates to privileged applications is capped to the 12022 * priority defined on the system partition</li> 12023 * </ul> 12024 * <p> 12025 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12026 * allowed to obtain any priority on any action. 12027 */ 12028 private void adjustPriority( 12029 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12030 // nothing to do; priority is fine as-is 12031 if (intent.getPriority() <= 0) { 12032 return; 12033 } 12034 12035 final ActivityInfo activityInfo = intent.activity.info; 12036 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12037 12038 final boolean privilegedApp = 12039 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12040 if (!privilegedApp) { 12041 // non-privileged applications can never define a priority >0 12042 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12043 + " package: " + applicationInfo.packageName 12044 + " activity: " + intent.activity.className 12045 + " origPrio: " + intent.getPriority()); 12046 intent.setPriority(0); 12047 return; 12048 } 12049 12050 if (systemActivities == null) { 12051 // the system package is not disabled; we're parsing the system partition 12052 if (isProtectedAction(intent)) { 12053 if (mDeferProtectedFilters) { 12054 // We can't deal with these just yet. No component should ever obtain a 12055 // >0 priority for a protected actions, with ONE exception -- the setup 12056 // wizard. The setup wizard, however, cannot be known until we're able to 12057 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12058 // until all intent filters have been processed. Chicken, meet egg. 12059 // Let the filter temporarily have a high priority and rectify the 12060 // priorities after all system packages have been scanned. 12061 mProtectedFilters.add(intent); 12062 if (DEBUG_FILTERS) { 12063 Slog.i(TAG, "Protected action; save for later;" 12064 + " package: " + applicationInfo.packageName 12065 + " activity: " + intent.activity.className 12066 + " origPrio: " + intent.getPriority()); 12067 } 12068 return; 12069 } else { 12070 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12071 Slog.i(TAG, "No setup wizard;" 12072 + " All protected intents capped to priority 0"); 12073 } 12074 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12075 if (DEBUG_FILTERS) { 12076 Slog.i(TAG, "Found setup wizard;" 12077 + " allow priority " + intent.getPriority() + ";" 12078 + " package: " + intent.activity.info.packageName 12079 + " activity: " + intent.activity.className 12080 + " priority: " + intent.getPriority()); 12081 } 12082 // setup wizard gets whatever it wants 12083 return; 12084 } 12085 Slog.w(TAG, "Protected action; cap priority to 0;" 12086 + " package: " + intent.activity.info.packageName 12087 + " activity: " + intent.activity.className 12088 + " origPrio: " + intent.getPriority()); 12089 intent.setPriority(0); 12090 return; 12091 } 12092 } 12093 // privileged apps on the system image get whatever priority they request 12094 return; 12095 } 12096 12097 // privileged app unbundled update ... try to find the same activity 12098 final PackageParser.Activity foundActivity = 12099 findMatchingActivity(systemActivities, activityInfo); 12100 if (foundActivity == null) { 12101 // this is a new activity; it cannot obtain >0 priority 12102 if (DEBUG_FILTERS) { 12103 Slog.i(TAG, "New activity; cap priority to 0;" 12104 + " package: " + applicationInfo.packageName 12105 + " activity: " + intent.activity.className 12106 + " origPrio: " + intent.getPriority()); 12107 } 12108 intent.setPriority(0); 12109 return; 12110 } 12111 12112 // found activity, now check for filter equivalence 12113 12114 // a shallow copy is enough; we modify the list, not its contents 12115 final List<ActivityIntentInfo> intentListCopy = 12116 new ArrayList<>(foundActivity.intents); 12117 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12118 12119 // find matching action subsets 12120 final Iterator<String> actionsIterator = intent.actionsIterator(); 12121 if (actionsIterator != null) { 12122 getIntentListSubset( 12123 intentListCopy, new ActionIterGenerator(), actionsIterator); 12124 if (intentListCopy.size() == 0) { 12125 // no more intents to match; we're not equivalent 12126 if (DEBUG_FILTERS) { 12127 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12128 + " package: " + applicationInfo.packageName 12129 + " activity: " + intent.activity.className 12130 + " origPrio: " + intent.getPriority()); 12131 } 12132 intent.setPriority(0); 12133 return; 12134 } 12135 } 12136 12137 // find matching category subsets 12138 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12139 if (categoriesIterator != null) { 12140 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12141 categoriesIterator); 12142 if (intentListCopy.size() == 0) { 12143 // no more intents to match; we're not equivalent 12144 if (DEBUG_FILTERS) { 12145 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12146 + " package: " + applicationInfo.packageName 12147 + " activity: " + intent.activity.className 12148 + " origPrio: " + intent.getPriority()); 12149 } 12150 intent.setPriority(0); 12151 return; 12152 } 12153 } 12154 12155 // find matching schemes subsets 12156 final Iterator<String> schemesIterator = intent.schemesIterator(); 12157 if (schemesIterator != null) { 12158 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12159 schemesIterator); 12160 if (intentListCopy.size() == 0) { 12161 // no more intents to match; we're not equivalent 12162 if (DEBUG_FILTERS) { 12163 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12164 + " package: " + applicationInfo.packageName 12165 + " activity: " + intent.activity.className 12166 + " origPrio: " + intent.getPriority()); 12167 } 12168 intent.setPriority(0); 12169 return; 12170 } 12171 } 12172 12173 // find matching authorities subsets 12174 final Iterator<IntentFilter.AuthorityEntry> 12175 authoritiesIterator = intent.authoritiesIterator(); 12176 if (authoritiesIterator != null) { 12177 getIntentListSubset(intentListCopy, 12178 new AuthoritiesIterGenerator(), 12179 authoritiesIterator); 12180 if (intentListCopy.size() == 0) { 12181 // no more intents to match; we're not equivalent 12182 if (DEBUG_FILTERS) { 12183 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12184 + " package: " + applicationInfo.packageName 12185 + " activity: " + intent.activity.className 12186 + " origPrio: " + intent.getPriority()); 12187 } 12188 intent.setPriority(0); 12189 return; 12190 } 12191 } 12192 12193 // we found matching filter(s); app gets the max priority of all intents 12194 int cappedPriority = 0; 12195 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12196 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12197 } 12198 if (intent.getPriority() > cappedPriority) { 12199 if (DEBUG_FILTERS) { 12200 Slog.i(TAG, "Found matching filter(s);" 12201 + " cap priority to " + cappedPriority + ";" 12202 + " package: " + applicationInfo.packageName 12203 + " activity: " + intent.activity.className 12204 + " origPrio: " + intent.getPriority()); 12205 } 12206 intent.setPriority(cappedPriority); 12207 return; 12208 } 12209 // all this for nothing; the requested priority was <= what was on the system 12210 } 12211 12212 public final void addActivity(PackageParser.Activity a, String type) { 12213 mActivities.put(a.getComponentName(), a); 12214 if (DEBUG_SHOW_INFO) 12215 Log.v( 12216 TAG, " " + type + " " + 12217 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12218 if (DEBUG_SHOW_INFO) 12219 Log.v(TAG, " Class=" + a.info.name); 12220 final int NI = a.intents.size(); 12221 for (int j=0; j<NI; j++) { 12222 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12223 if ("activity".equals(type)) { 12224 final PackageSetting ps = 12225 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12226 final List<PackageParser.Activity> systemActivities = 12227 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12228 adjustPriority(systemActivities, intent); 12229 } 12230 if (DEBUG_SHOW_INFO) { 12231 Log.v(TAG, " IntentFilter:"); 12232 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12233 } 12234 if (!intent.debugCheck()) { 12235 Log.w(TAG, "==> For Activity " + a.info.name); 12236 } 12237 addFilter(intent); 12238 } 12239 } 12240 12241 public final void removeActivity(PackageParser.Activity a, String type) { 12242 mActivities.remove(a.getComponentName()); 12243 if (DEBUG_SHOW_INFO) { 12244 Log.v(TAG, " " + type + " " 12245 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12246 : a.info.name) + ":"); 12247 Log.v(TAG, " Class=" + a.info.name); 12248 } 12249 final int NI = a.intents.size(); 12250 for (int j=0; j<NI; j++) { 12251 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12252 if (DEBUG_SHOW_INFO) { 12253 Log.v(TAG, " IntentFilter:"); 12254 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12255 } 12256 removeFilter(intent); 12257 } 12258 } 12259 12260 @Override 12261 protected boolean allowFilterResult( 12262 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12263 ActivityInfo filterAi = filter.activity.info; 12264 for (int i=dest.size()-1; i>=0; i--) { 12265 ActivityInfo destAi = dest.get(i).activityInfo; 12266 if (destAi.name == filterAi.name 12267 && destAi.packageName == filterAi.packageName) { 12268 return false; 12269 } 12270 } 12271 return true; 12272 } 12273 12274 @Override 12275 protected ActivityIntentInfo[] newArray(int size) { 12276 return new ActivityIntentInfo[size]; 12277 } 12278 12279 @Override 12280 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12281 if (!sUserManager.exists(userId)) return true; 12282 PackageParser.Package p = filter.activity.owner; 12283 if (p != null) { 12284 PackageSetting ps = (PackageSetting)p.mExtras; 12285 if (ps != null) { 12286 // System apps are never considered stopped for purposes of 12287 // filtering, because there may be no way for the user to 12288 // actually re-launch them. 12289 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12290 && ps.getStopped(userId); 12291 } 12292 } 12293 return false; 12294 } 12295 12296 @Override 12297 protected boolean isPackageForFilter(String packageName, 12298 PackageParser.ActivityIntentInfo info) { 12299 return packageName.equals(info.activity.owner.packageName); 12300 } 12301 12302 @Override 12303 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12304 int match, int userId) { 12305 if (!sUserManager.exists(userId)) return null; 12306 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12307 return null; 12308 } 12309 final PackageParser.Activity activity = info.activity; 12310 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12311 if (ps == null) { 12312 return null; 12313 } 12314 final PackageUserState userState = ps.readUserState(userId); 12315 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12316 userState, userId); 12317 if (ai == null) { 12318 return null; 12319 } 12320 final boolean matchVisibleToInstantApp = 12321 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12322 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12323 // throw out filters that aren't visible to ephemeral apps 12324 if (matchVisibleToInstantApp 12325 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12326 return null; 12327 } 12328 // throw out ephemeral filters if we're not explicitly requesting them 12329 if (!isInstantApp && userState.instantApp) { 12330 return null; 12331 } 12332 // throw out instant app filters if updates are available; will trigger 12333 // instant app resolution 12334 if (userState.instantApp && ps.isUpdateAvailable()) { 12335 return null; 12336 } 12337 final ResolveInfo res = new ResolveInfo(); 12338 res.activityInfo = ai; 12339 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12340 res.filter = info; 12341 } 12342 if (info != null) { 12343 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12344 } 12345 res.priority = info.getPriority(); 12346 res.preferredOrder = activity.owner.mPreferredOrder; 12347 //System.out.println("Result: " + res.activityInfo.className + 12348 // " = " + res.priority); 12349 res.match = match; 12350 res.isDefault = info.hasDefault; 12351 res.labelRes = info.labelRes; 12352 res.nonLocalizedLabel = info.nonLocalizedLabel; 12353 if (userNeedsBadging(userId)) { 12354 res.noResourceId = true; 12355 } else { 12356 res.icon = info.icon; 12357 } 12358 res.iconResourceId = info.icon; 12359 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12360 res.instantAppAvailable = userState.instantApp; 12361 return res; 12362 } 12363 12364 @Override 12365 protected void sortResults(List<ResolveInfo> results) { 12366 Collections.sort(results, mResolvePrioritySorter); 12367 } 12368 12369 @Override 12370 protected void dumpFilter(PrintWriter out, String prefix, 12371 PackageParser.ActivityIntentInfo filter) { 12372 out.print(prefix); out.print( 12373 Integer.toHexString(System.identityHashCode(filter.activity))); 12374 out.print(' '); 12375 filter.activity.printComponentShortName(out); 12376 out.print(" filter "); 12377 out.println(Integer.toHexString(System.identityHashCode(filter))); 12378 } 12379 12380 @Override 12381 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12382 return filter.activity; 12383 } 12384 12385 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12386 PackageParser.Activity activity = (PackageParser.Activity)label; 12387 out.print(prefix); out.print( 12388 Integer.toHexString(System.identityHashCode(activity))); 12389 out.print(' '); 12390 activity.printComponentShortName(out); 12391 if (count > 1) { 12392 out.print(" ("); out.print(count); out.print(" filters)"); 12393 } 12394 out.println(); 12395 } 12396 12397 // Keys are String (activity class name), values are Activity. 12398 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12399 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12400 private int mFlags; 12401 } 12402 12403 private final class ServiceIntentResolver 12404 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12405 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12406 boolean defaultOnly, int userId) { 12407 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12408 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12409 } 12410 12411 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12412 int userId) { 12413 if (!sUserManager.exists(userId)) return null; 12414 mFlags = flags; 12415 return super.queryIntent(intent, resolvedType, 12416 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12417 userId); 12418 } 12419 12420 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12421 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12422 if (!sUserManager.exists(userId)) return null; 12423 if (packageServices == null) { 12424 return null; 12425 } 12426 mFlags = flags; 12427 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12428 final int N = packageServices.size(); 12429 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12430 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12431 12432 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12433 for (int i = 0; i < N; ++i) { 12434 intentFilters = packageServices.get(i).intents; 12435 if (intentFilters != null && intentFilters.size() > 0) { 12436 PackageParser.ServiceIntentInfo[] array = 12437 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12438 intentFilters.toArray(array); 12439 listCut.add(array); 12440 } 12441 } 12442 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12443 } 12444 12445 public final void addService(PackageParser.Service s) { 12446 mServices.put(s.getComponentName(), s); 12447 if (DEBUG_SHOW_INFO) { 12448 Log.v(TAG, " " 12449 + (s.info.nonLocalizedLabel != null 12450 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12451 Log.v(TAG, " Class=" + s.info.name); 12452 } 12453 final int NI = s.intents.size(); 12454 int j; 12455 for (j=0; j<NI; j++) { 12456 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12457 if (DEBUG_SHOW_INFO) { 12458 Log.v(TAG, " IntentFilter:"); 12459 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12460 } 12461 if (!intent.debugCheck()) { 12462 Log.w(TAG, "==> For Service " + s.info.name); 12463 } 12464 addFilter(intent); 12465 } 12466 } 12467 12468 public final void removeService(PackageParser.Service s) { 12469 mServices.remove(s.getComponentName()); 12470 if (DEBUG_SHOW_INFO) { 12471 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12472 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12473 Log.v(TAG, " Class=" + s.info.name); 12474 } 12475 final int NI = s.intents.size(); 12476 int j; 12477 for (j=0; j<NI; j++) { 12478 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12479 if (DEBUG_SHOW_INFO) { 12480 Log.v(TAG, " IntentFilter:"); 12481 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12482 } 12483 removeFilter(intent); 12484 } 12485 } 12486 12487 @Override 12488 protected boolean allowFilterResult( 12489 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12490 ServiceInfo filterSi = filter.service.info; 12491 for (int i=dest.size()-1; i>=0; i--) { 12492 ServiceInfo destAi = dest.get(i).serviceInfo; 12493 if (destAi.name == filterSi.name 12494 && destAi.packageName == filterSi.packageName) { 12495 return false; 12496 } 12497 } 12498 return true; 12499 } 12500 12501 @Override 12502 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12503 return new PackageParser.ServiceIntentInfo[size]; 12504 } 12505 12506 @Override 12507 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12508 if (!sUserManager.exists(userId)) return true; 12509 PackageParser.Package p = filter.service.owner; 12510 if (p != null) { 12511 PackageSetting ps = (PackageSetting)p.mExtras; 12512 if (ps != null) { 12513 // System apps are never considered stopped for purposes of 12514 // filtering, because there may be no way for the user to 12515 // actually re-launch them. 12516 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12517 && ps.getStopped(userId); 12518 } 12519 } 12520 return false; 12521 } 12522 12523 @Override 12524 protected boolean isPackageForFilter(String packageName, 12525 PackageParser.ServiceIntentInfo info) { 12526 return packageName.equals(info.service.owner.packageName); 12527 } 12528 12529 @Override 12530 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12531 int match, int userId) { 12532 if (!sUserManager.exists(userId)) return null; 12533 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12534 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12535 return null; 12536 } 12537 final PackageParser.Service service = info.service; 12538 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12539 if (ps == null) { 12540 return null; 12541 } 12542 final PackageUserState userState = ps.readUserState(userId); 12543 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12544 userState, userId); 12545 if (si == null) { 12546 return null; 12547 } 12548 final boolean matchVisibleToInstantApp = 12549 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12550 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12551 // throw out filters that aren't visible to ephemeral apps 12552 if (matchVisibleToInstantApp 12553 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12554 return null; 12555 } 12556 // throw out ephemeral filters if we're not explicitly requesting them 12557 if (!isInstantApp && userState.instantApp) { 12558 return null; 12559 } 12560 // throw out instant app filters if updates are available; will trigger 12561 // instant app resolution 12562 if (userState.instantApp && ps.isUpdateAvailable()) { 12563 return null; 12564 } 12565 final ResolveInfo res = new ResolveInfo(); 12566 res.serviceInfo = si; 12567 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12568 res.filter = filter; 12569 } 12570 res.priority = info.getPriority(); 12571 res.preferredOrder = service.owner.mPreferredOrder; 12572 res.match = match; 12573 res.isDefault = info.hasDefault; 12574 res.labelRes = info.labelRes; 12575 res.nonLocalizedLabel = info.nonLocalizedLabel; 12576 res.icon = info.icon; 12577 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12578 return res; 12579 } 12580 12581 @Override 12582 protected void sortResults(List<ResolveInfo> results) { 12583 Collections.sort(results, mResolvePrioritySorter); 12584 } 12585 12586 @Override 12587 protected void dumpFilter(PrintWriter out, String prefix, 12588 PackageParser.ServiceIntentInfo filter) { 12589 out.print(prefix); out.print( 12590 Integer.toHexString(System.identityHashCode(filter.service))); 12591 out.print(' '); 12592 filter.service.printComponentShortName(out); 12593 out.print(" filter "); 12594 out.println(Integer.toHexString(System.identityHashCode(filter))); 12595 } 12596 12597 @Override 12598 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12599 return filter.service; 12600 } 12601 12602 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12603 PackageParser.Service service = (PackageParser.Service)label; 12604 out.print(prefix); out.print( 12605 Integer.toHexString(System.identityHashCode(service))); 12606 out.print(' '); 12607 service.printComponentShortName(out); 12608 if (count > 1) { 12609 out.print(" ("); out.print(count); out.print(" filters)"); 12610 } 12611 out.println(); 12612 } 12613 12614// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12615// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12616// final List<ResolveInfo> retList = Lists.newArrayList(); 12617// while (i.hasNext()) { 12618// final ResolveInfo resolveInfo = (ResolveInfo) i; 12619// if (isEnabledLP(resolveInfo.serviceInfo)) { 12620// retList.add(resolveInfo); 12621// } 12622// } 12623// return retList; 12624// } 12625 12626 // Keys are String (activity class name), values are Activity. 12627 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12628 = new ArrayMap<ComponentName, PackageParser.Service>(); 12629 private int mFlags; 12630 } 12631 12632 private final class ProviderIntentResolver 12633 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12634 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12635 boolean defaultOnly, int userId) { 12636 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12637 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12638 } 12639 12640 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12641 int userId) { 12642 if (!sUserManager.exists(userId)) 12643 return null; 12644 mFlags = flags; 12645 return super.queryIntent(intent, resolvedType, 12646 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12647 userId); 12648 } 12649 12650 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12651 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12652 if (!sUserManager.exists(userId)) 12653 return null; 12654 if (packageProviders == null) { 12655 return null; 12656 } 12657 mFlags = flags; 12658 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12659 final int N = packageProviders.size(); 12660 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12661 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12662 12663 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12664 for (int i = 0; i < N; ++i) { 12665 intentFilters = packageProviders.get(i).intents; 12666 if (intentFilters != null && intentFilters.size() > 0) { 12667 PackageParser.ProviderIntentInfo[] array = 12668 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12669 intentFilters.toArray(array); 12670 listCut.add(array); 12671 } 12672 } 12673 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12674 } 12675 12676 public final void addProvider(PackageParser.Provider p) { 12677 if (mProviders.containsKey(p.getComponentName())) { 12678 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12679 return; 12680 } 12681 12682 mProviders.put(p.getComponentName(), p); 12683 if (DEBUG_SHOW_INFO) { 12684 Log.v(TAG, " " 12685 + (p.info.nonLocalizedLabel != null 12686 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12687 Log.v(TAG, " Class=" + p.info.name); 12688 } 12689 final int NI = p.intents.size(); 12690 int j; 12691 for (j = 0; j < NI; j++) { 12692 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12693 if (DEBUG_SHOW_INFO) { 12694 Log.v(TAG, " IntentFilter:"); 12695 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12696 } 12697 if (!intent.debugCheck()) { 12698 Log.w(TAG, "==> For Provider " + p.info.name); 12699 } 12700 addFilter(intent); 12701 } 12702 } 12703 12704 public final void removeProvider(PackageParser.Provider p) { 12705 mProviders.remove(p.getComponentName()); 12706 if (DEBUG_SHOW_INFO) { 12707 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12708 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12709 Log.v(TAG, " Class=" + p.info.name); 12710 } 12711 final int NI = p.intents.size(); 12712 int j; 12713 for (j = 0; j < NI; j++) { 12714 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12715 if (DEBUG_SHOW_INFO) { 12716 Log.v(TAG, " IntentFilter:"); 12717 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12718 } 12719 removeFilter(intent); 12720 } 12721 } 12722 12723 @Override 12724 protected boolean allowFilterResult( 12725 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12726 ProviderInfo filterPi = filter.provider.info; 12727 for (int i = dest.size() - 1; i >= 0; i--) { 12728 ProviderInfo destPi = dest.get(i).providerInfo; 12729 if (destPi.name == filterPi.name 12730 && destPi.packageName == filterPi.packageName) { 12731 return false; 12732 } 12733 } 12734 return true; 12735 } 12736 12737 @Override 12738 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12739 return new PackageParser.ProviderIntentInfo[size]; 12740 } 12741 12742 @Override 12743 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12744 if (!sUserManager.exists(userId)) 12745 return true; 12746 PackageParser.Package p = filter.provider.owner; 12747 if (p != null) { 12748 PackageSetting ps = (PackageSetting) p.mExtras; 12749 if (ps != null) { 12750 // System apps are never considered stopped for purposes of 12751 // filtering, because there may be no way for the user to 12752 // actually re-launch them. 12753 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12754 && ps.getStopped(userId); 12755 } 12756 } 12757 return false; 12758 } 12759 12760 @Override 12761 protected boolean isPackageForFilter(String packageName, 12762 PackageParser.ProviderIntentInfo info) { 12763 return packageName.equals(info.provider.owner.packageName); 12764 } 12765 12766 @Override 12767 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12768 int match, int userId) { 12769 if (!sUserManager.exists(userId)) 12770 return null; 12771 final PackageParser.ProviderIntentInfo info = filter; 12772 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12773 return null; 12774 } 12775 final PackageParser.Provider provider = info.provider; 12776 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12777 if (ps == null) { 12778 return null; 12779 } 12780 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12781 ps.readUserState(userId), userId); 12782 if (pi == null) { 12783 return null; 12784 } 12785 final ResolveInfo res = new ResolveInfo(); 12786 res.providerInfo = pi; 12787 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12788 res.filter = filter; 12789 } 12790 res.priority = info.getPriority(); 12791 res.preferredOrder = provider.owner.mPreferredOrder; 12792 res.match = match; 12793 res.isDefault = info.hasDefault; 12794 res.labelRes = info.labelRes; 12795 res.nonLocalizedLabel = info.nonLocalizedLabel; 12796 res.icon = info.icon; 12797 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12798 return res; 12799 } 12800 12801 @Override 12802 protected void sortResults(List<ResolveInfo> results) { 12803 Collections.sort(results, mResolvePrioritySorter); 12804 } 12805 12806 @Override 12807 protected void dumpFilter(PrintWriter out, String prefix, 12808 PackageParser.ProviderIntentInfo filter) { 12809 out.print(prefix); 12810 out.print( 12811 Integer.toHexString(System.identityHashCode(filter.provider))); 12812 out.print(' '); 12813 filter.provider.printComponentShortName(out); 12814 out.print(" filter "); 12815 out.println(Integer.toHexString(System.identityHashCode(filter))); 12816 } 12817 12818 @Override 12819 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12820 return filter.provider; 12821 } 12822 12823 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12824 PackageParser.Provider provider = (PackageParser.Provider)label; 12825 out.print(prefix); out.print( 12826 Integer.toHexString(System.identityHashCode(provider))); 12827 out.print(' '); 12828 provider.printComponentShortName(out); 12829 if (count > 1) { 12830 out.print(" ("); out.print(count); out.print(" filters)"); 12831 } 12832 out.println(); 12833 } 12834 12835 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12836 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12837 private int mFlags; 12838 } 12839 12840 static final class EphemeralIntentResolver 12841 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12842 /** 12843 * The result that has the highest defined order. Ordering applies on a 12844 * per-package basis. Mapping is from package name to Pair of order and 12845 * EphemeralResolveInfo. 12846 * <p> 12847 * NOTE: This is implemented as a field variable for convenience and efficiency. 12848 * By having a field variable, we're able to track filter ordering as soon as 12849 * a non-zero order is defined. Otherwise, multiple loops across the result set 12850 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12851 * this needs to be contained entirely within {@link #filterResults}. 12852 */ 12853 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12854 12855 @Override 12856 protected AuxiliaryResolveInfo[] newArray(int size) { 12857 return new AuxiliaryResolveInfo[size]; 12858 } 12859 12860 @Override 12861 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12862 return true; 12863 } 12864 12865 @Override 12866 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12867 int userId) { 12868 if (!sUserManager.exists(userId)) { 12869 return null; 12870 } 12871 final String packageName = responseObj.resolveInfo.getPackageName(); 12872 final Integer order = responseObj.getOrder(); 12873 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12874 mOrderResult.get(packageName); 12875 // ordering is enabled and this item's order isn't high enough 12876 if (lastOrderResult != null && lastOrderResult.first >= order) { 12877 return null; 12878 } 12879 final InstantAppResolveInfo res = responseObj.resolveInfo; 12880 if (order > 0) { 12881 // non-zero order, enable ordering 12882 mOrderResult.put(packageName, new Pair<>(order, res)); 12883 } 12884 return responseObj; 12885 } 12886 12887 @Override 12888 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12889 // only do work if ordering is enabled [most of the time it won't be] 12890 if (mOrderResult.size() == 0) { 12891 return; 12892 } 12893 int resultSize = results.size(); 12894 for (int i = 0; i < resultSize; i++) { 12895 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12896 final String packageName = info.getPackageName(); 12897 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12898 if (savedInfo == null) { 12899 // package doesn't having ordering 12900 continue; 12901 } 12902 if (savedInfo.second == info) { 12903 // circled back to the highest ordered item; remove from order list 12904 mOrderResult.remove(savedInfo); 12905 if (mOrderResult.size() == 0) { 12906 // no more ordered items 12907 break; 12908 } 12909 continue; 12910 } 12911 // item has a worse order, remove it from the result list 12912 results.remove(i); 12913 resultSize--; 12914 i--; 12915 } 12916 } 12917 } 12918 12919 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12920 new Comparator<ResolveInfo>() { 12921 public int compare(ResolveInfo r1, ResolveInfo r2) { 12922 int v1 = r1.priority; 12923 int v2 = r2.priority; 12924 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12925 if (v1 != v2) { 12926 return (v1 > v2) ? -1 : 1; 12927 } 12928 v1 = r1.preferredOrder; 12929 v2 = r2.preferredOrder; 12930 if (v1 != v2) { 12931 return (v1 > v2) ? -1 : 1; 12932 } 12933 if (r1.isDefault != r2.isDefault) { 12934 return r1.isDefault ? -1 : 1; 12935 } 12936 v1 = r1.match; 12937 v2 = r2.match; 12938 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12939 if (v1 != v2) { 12940 return (v1 > v2) ? -1 : 1; 12941 } 12942 if (r1.system != r2.system) { 12943 return r1.system ? -1 : 1; 12944 } 12945 if (r1.activityInfo != null) { 12946 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12947 } 12948 if (r1.serviceInfo != null) { 12949 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12950 } 12951 if (r1.providerInfo != null) { 12952 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12953 } 12954 return 0; 12955 } 12956 }; 12957 12958 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12959 new Comparator<ProviderInfo>() { 12960 public int compare(ProviderInfo p1, ProviderInfo p2) { 12961 final int v1 = p1.initOrder; 12962 final int v2 = p2.initOrder; 12963 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12964 } 12965 }; 12966 12967 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12968 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12969 final int[] userIds) { 12970 mHandler.post(new Runnable() { 12971 @Override 12972 public void run() { 12973 try { 12974 final IActivityManager am = ActivityManager.getService(); 12975 if (am == null) return; 12976 final int[] resolvedUserIds; 12977 if (userIds == null) { 12978 resolvedUserIds = am.getRunningUserIds(); 12979 } else { 12980 resolvedUserIds = userIds; 12981 } 12982 for (int id : resolvedUserIds) { 12983 final Intent intent = new Intent(action, 12984 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12985 if (extras != null) { 12986 intent.putExtras(extras); 12987 } 12988 if (targetPkg != null) { 12989 intent.setPackage(targetPkg); 12990 } 12991 // Modify the UID when posting to other users 12992 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12993 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12994 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12995 intent.putExtra(Intent.EXTRA_UID, uid); 12996 } 12997 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12998 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12999 if (DEBUG_BROADCASTS) { 13000 RuntimeException here = new RuntimeException("here"); 13001 here.fillInStackTrace(); 13002 Slog.d(TAG, "Sending to user " + id + ": " 13003 + intent.toShortString(false, true, false, false) 13004 + " " + intent.getExtras(), here); 13005 } 13006 am.broadcastIntent(null, intent, null, finishedReceiver, 13007 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13008 null, finishedReceiver != null, false, id); 13009 } 13010 } catch (RemoteException ex) { 13011 } 13012 } 13013 }); 13014 } 13015 13016 /** 13017 * Check if the external storage media is available. This is true if there 13018 * is a mounted external storage medium or if the external storage is 13019 * emulated. 13020 */ 13021 private boolean isExternalMediaAvailable() { 13022 return mMediaMounted || Environment.isExternalStorageEmulated(); 13023 } 13024 13025 @Override 13026 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13027 // writer 13028 synchronized (mPackages) { 13029 if (!isExternalMediaAvailable()) { 13030 // If the external storage is no longer mounted at this point, 13031 // the caller may not have been able to delete all of this 13032 // packages files and can not delete any more. Bail. 13033 return null; 13034 } 13035 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13036 if (lastPackage != null) { 13037 pkgs.remove(lastPackage); 13038 } 13039 if (pkgs.size() > 0) { 13040 return pkgs.get(0); 13041 } 13042 } 13043 return null; 13044 } 13045 13046 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13047 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13048 userId, andCode ? 1 : 0, packageName); 13049 if (mSystemReady) { 13050 msg.sendToTarget(); 13051 } else { 13052 if (mPostSystemReadyMessages == null) { 13053 mPostSystemReadyMessages = new ArrayList<>(); 13054 } 13055 mPostSystemReadyMessages.add(msg); 13056 } 13057 } 13058 13059 void startCleaningPackages() { 13060 // reader 13061 if (!isExternalMediaAvailable()) { 13062 return; 13063 } 13064 synchronized (mPackages) { 13065 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13066 return; 13067 } 13068 } 13069 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13070 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13071 IActivityManager am = ActivityManager.getService(); 13072 if (am != null) { 13073 int dcsUid = -1; 13074 synchronized (mPackages) { 13075 if (!mDefaultContainerWhitelisted) { 13076 mDefaultContainerWhitelisted = true; 13077 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13078 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13079 } 13080 } 13081 try { 13082 if (dcsUid > 0) { 13083 am.backgroundWhitelistUid(dcsUid); 13084 } 13085 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13086 UserHandle.USER_SYSTEM); 13087 } catch (RemoteException e) { 13088 } 13089 } 13090 } 13091 13092 @Override 13093 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13094 int installFlags, String installerPackageName, int userId) { 13095 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13096 13097 final int callingUid = Binder.getCallingUid(); 13098 enforceCrossUserPermission(callingUid, userId, 13099 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13100 13101 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13102 try { 13103 if (observer != null) { 13104 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13105 } 13106 } catch (RemoteException re) { 13107 } 13108 return; 13109 } 13110 13111 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13112 installFlags |= PackageManager.INSTALL_FROM_ADB; 13113 13114 } else { 13115 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13116 // about installerPackageName. 13117 13118 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13119 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13120 } 13121 13122 UserHandle user; 13123 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13124 user = UserHandle.ALL; 13125 } else { 13126 user = new UserHandle(userId); 13127 } 13128 13129 // Only system components can circumvent runtime permissions when installing. 13130 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13131 && mContext.checkCallingOrSelfPermission(Manifest.permission 13132 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13133 throw new SecurityException("You need the " 13134 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13135 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13136 } 13137 13138 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13139 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13140 throw new IllegalArgumentException( 13141 "New installs into ASEC containers no longer supported"); 13142 } 13143 13144 final File originFile = new File(originPath); 13145 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13146 13147 final Message msg = mHandler.obtainMessage(INIT_COPY); 13148 final VerificationInfo verificationInfo = new VerificationInfo( 13149 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13150 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13151 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13152 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13153 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13154 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13155 msg.obj = params; 13156 13157 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13158 System.identityHashCode(msg.obj)); 13159 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13160 System.identityHashCode(msg.obj)); 13161 13162 mHandler.sendMessage(msg); 13163 } 13164 13165 13166 /** 13167 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13168 * it is acting on behalf on an enterprise or the user). 13169 * 13170 * Note that the ordering of the conditionals in this method is important. The checks we perform 13171 * are as follows, in this order: 13172 * 13173 * 1) If the install is being performed by a system app, we can trust the app to have set the 13174 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13175 * what it is. 13176 * 2) If the install is being performed by a device or profile owner app, the install reason 13177 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13178 * set the install reason correctly. If the app targets an older SDK version where install 13179 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13180 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13181 * 3) In all other cases, the install is being performed by a regular app that is neither part 13182 * of the system nor a device or profile owner. We have no reason to believe that this app is 13183 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13184 * set to enterprise policy and if so, change it to unknown instead. 13185 */ 13186 private int fixUpInstallReason(String installerPackageName, int installerUid, 13187 int installReason) { 13188 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13189 == PERMISSION_GRANTED) { 13190 // If the install is being performed by a system app, we trust that app to have set the 13191 // install reason correctly. 13192 return installReason; 13193 } 13194 13195 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13196 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13197 if (dpm != null) { 13198 ComponentName owner = null; 13199 try { 13200 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13201 if (owner == null) { 13202 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13203 } 13204 } catch (RemoteException e) { 13205 } 13206 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13207 // If the install is being performed by a device or profile owner, the install 13208 // reason should be enterprise policy. 13209 return PackageManager.INSTALL_REASON_POLICY; 13210 } 13211 } 13212 13213 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13214 // If the install is being performed by a regular app (i.e. neither system app nor 13215 // device or profile owner), we have no reason to believe that the app is acting on 13216 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13217 // change it to unknown instead. 13218 return PackageManager.INSTALL_REASON_UNKNOWN; 13219 } 13220 13221 // If the install is being performed by a regular app and the install reason was set to any 13222 // value but enterprise policy, leave the install reason unchanged. 13223 return installReason; 13224 } 13225 13226 void installStage(String packageName, File stagedDir, String stagedCid, 13227 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13228 String installerPackageName, int installerUid, UserHandle user, 13229 Certificate[][] certificates) { 13230 if (DEBUG_EPHEMERAL) { 13231 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13232 Slog.d(TAG, "Ephemeral install of " + packageName); 13233 } 13234 } 13235 final VerificationInfo verificationInfo = new VerificationInfo( 13236 sessionParams.originatingUri, sessionParams.referrerUri, 13237 sessionParams.originatingUid, installerUid); 13238 13239 final OriginInfo origin; 13240 if (stagedDir != null) { 13241 origin = OriginInfo.fromStagedFile(stagedDir); 13242 } else { 13243 origin = OriginInfo.fromStagedContainer(stagedCid); 13244 } 13245 13246 final Message msg = mHandler.obtainMessage(INIT_COPY); 13247 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13248 sessionParams.installReason); 13249 final InstallParams params = new InstallParams(origin, null, observer, 13250 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13251 verificationInfo, user, sessionParams.abiOverride, 13252 sessionParams.grantedRuntimePermissions, certificates, installReason); 13253 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13254 msg.obj = params; 13255 13256 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13257 System.identityHashCode(msg.obj)); 13258 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13259 System.identityHashCode(msg.obj)); 13260 13261 mHandler.sendMessage(msg); 13262 } 13263 13264 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13265 int userId) { 13266 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13267 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13268 } 13269 13270 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13271 int appId, int... userIds) { 13272 if (ArrayUtils.isEmpty(userIds)) { 13273 return; 13274 } 13275 Bundle extras = new Bundle(1); 13276 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13277 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13278 13279 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13280 packageName, extras, 0, null, null, userIds); 13281 if (isSystem) { 13282 mHandler.post(() -> { 13283 for (int userId : userIds) { 13284 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13285 } 13286 } 13287 ); 13288 } 13289 } 13290 13291 /** 13292 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13293 * automatically without needing an explicit launch. 13294 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13295 */ 13296 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13297 // If user is not running, the app didn't miss any broadcast 13298 if (!mUserManagerInternal.isUserRunning(userId)) { 13299 return; 13300 } 13301 final IActivityManager am = ActivityManager.getService(); 13302 try { 13303 // Deliver LOCKED_BOOT_COMPLETED first 13304 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13305 .setPackage(packageName); 13306 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13307 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13308 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13309 13310 // Deliver BOOT_COMPLETED only if user is unlocked 13311 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13312 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13313 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13314 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13315 } 13316 } catch (RemoteException e) { 13317 throw e.rethrowFromSystemServer(); 13318 } 13319 } 13320 13321 @Override 13322 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13323 int userId) { 13324 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13325 PackageSetting pkgSetting; 13326 final int uid = Binder.getCallingUid(); 13327 enforceCrossUserPermission(uid, userId, 13328 true /* requireFullPermission */, true /* checkShell */, 13329 "setApplicationHiddenSetting for user " + userId); 13330 13331 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13332 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13333 return false; 13334 } 13335 13336 long callingId = Binder.clearCallingIdentity(); 13337 try { 13338 boolean sendAdded = false; 13339 boolean sendRemoved = false; 13340 // writer 13341 synchronized (mPackages) { 13342 pkgSetting = mSettings.mPackages.get(packageName); 13343 if (pkgSetting == null) { 13344 return false; 13345 } 13346 // Do not allow "android" is being disabled 13347 if ("android".equals(packageName)) { 13348 Slog.w(TAG, "Cannot hide package: android"); 13349 return false; 13350 } 13351 // Cannot hide static shared libs as they are considered 13352 // a part of the using app (emulating static linking). Also 13353 // static libs are installed always on internal storage. 13354 PackageParser.Package pkg = mPackages.get(packageName); 13355 if (pkg != null && pkg.staticSharedLibName != null) { 13356 Slog.w(TAG, "Cannot hide package: " + packageName 13357 + " providing static shared library: " 13358 + pkg.staticSharedLibName); 13359 return false; 13360 } 13361 // Only allow protected packages to hide themselves. 13362 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13363 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13364 Slog.w(TAG, "Not hiding protected package: " + packageName); 13365 return false; 13366 } 13367 13368 if (pkgSetting.getHidden(userId) != hidden) { 13369 pkgSetting.setHidden(hidden, userId); 13370 mSettings.writePackageRestrictionsLPr(userId); 13371 if (hidden) { 13372 sendRemoved = true; 13373 } else { 13374 sendAdded = true; 13375 } 13376 } 13377 } 13378 if (sendAdded) { 13379 sendPackageAddedForUser(packageName, pkgSetting, userId); 13380 return true; 13381 } 13382 if (sendRemoved) { 13383 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13384 "hiding pkg"); 13385 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13386 return true; 13387 } 13388 } finally { 13389 Binder.restoreCallingIdentity(callingId); 13390 } 13391 return false; 13392 } 13393 13394 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13395 int userId) { 13396 final PackageRemovedInfo info = new PackageRemovedInfo(); 13397 info.removedPackage = packageName; 13398 info.removedUsers = new int[] {userId}; 13399 info.broadcastUsers = new int[] {userId}; 13400 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13401 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13402 } 13403 13404 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13405 if (pkgList.length > 0) { 13406 Bundle extras = new Bundle(1); 13407 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13408 13409 sendPackageBroadcast( 13410 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13411 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13412 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13413 new int[] {userId}); 13414 } 13415 } 13416 13417 /** 13418 * Returns true if application is not found or there was an error. Otherwise it returns 13419 * the hidden state of the package for the given user. 13420 */ 13421 @Override 13422 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13423 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13424 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13425 true /* requireFullPermission */, false /* checkShell */, 13426 "getApplicationHidden for user " + userId); 13427 PackageSetting pkgSetting; 13428 long callingId = Binder.clearCallingIdentity(); 13429 try { 13430 // writer 13431 synchronized (mPackages) { 13432 pkgSetting = mSettings.mPackages.get(packageName); 13433 if (pkgSetting == null) { 13434 return true; 13435 } 13436 return pkgSetting.getHidden(userId); 13437 } 13438 } finally { 13439 Binder.restoreCallingIdentity(callingId); 13440 } 13441 } 13442 13443 /** 13444 * @hide 13445 */ 13446 @Override 13447 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13448 int installReason) { 13449 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13450 null); 13451 PackageSetting pkgSetting; 13452 final int uid = Binder.getCallingUid(); 13453 enforceCrossUserPermission(uid, userId, 13454 true /* requireFullPermission */, true /* checkShell */, 13455 "installExistingPackage for user " + userId); 13456 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13457 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13458 } 13459 13460 long callingId = Binder.clearCallingIdentity(); 13461 try { 13462 boolean installed = false; 13463 final boolean instantApp = 13464 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13465 final boolean fullApp = 13466 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13467 13468 // writer 13469 synchronized (mPackages) { 13470 pkgSetting = mSettings.mPackages.get(packageName); 13471 if (pkgSetting == null) { 13472 return PackageManager.INSTALL_FAILED_INVALID_URI; 13473 } 13474 if (!pkgSetting.getInstalled(userId)) { 13475 pkgSetting.setInstalled(true, userId); 13476 pkgSetting.setHidden(false, userId); 13477 pkgSetting.setInstallReason(installReason, userId); 13478 mSettings.writePackageRestrictionsLPr(userId); 13479 mSettings.writeKernelMappingLPr(pkgSetting); 13480 installed = true; 13481 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13482 // upgrade app from instant to full; we don't allow app downgrade 13483 installed = true; 13484 } 13485 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13486 } 13487 13488 if (installed) { 13489 if (pkgSetting.pkg != null) { 13490 synchronized (mInstallLock) { 13491 // We don't need to freeze for a brand new install 13492 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13493 } 13494 } 13495 sendPackageAddedForUser(packageName, pkgSetting, userId); 13496 synchronized (mPackages) { 13497 updateSequenceNumberLP(packageName, new int[]{ userId }); 13498 } 13499 } 13500 } finally { 13501 Binder.restoreCallingIdentity(callingId); 13502 } 13503 13504 return PackageManager.INSTALL_SUCCEEDED; 13505 } 13506 13507 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13508 boolean instantApp, boolean fullApp) { 13509 // no state specified; do nothing 13510 if (!instantApp && !fullApp) { 13511 return; 13512 } 13513 if (userId != UserHandle.USER_ALL) { 13514 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13515 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13516 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13517 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13518 } 13519 } else { 13520 for (int currentUserId : sUserManager.getUserIds()) { 13521 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13522 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13523 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13524 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13525 } 13526 } 13527 } 13528 } 13529 13530 boolean isUserRestricted(int userId, String restrictionKey) { 13531 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13532 if (restrictions.getBoolean(restrictionKey, false)) { 13533 Log.w(TAG, "User is restricted: " + restrictionKey); 13534 return true; 13535 } 13536 return false; 13537 } 13538 13539 @Override 13540 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13541 int userId) { 13542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13543 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13544 true /* requireFullPermission */, true /* checkShell */, 13545 "setPackagesSuspended for user " + userId); 13546 13547 if (ArrayUtils.isEmpty(packageNames)) { 13548 return packageNames; 13549 } 13550 13551 // List of package names for whom the suspended state has changed. 13552 List<String> changedPackages = new ArrayList<>(packageNames.length); 13553 // List of package names for whom the suspended state is not set as requested in this 13554 // method. 13555 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13556 long callingId = Binder.clearCallingIdentity(); 13557 try { 13558 for (int i = 0; i < packageNames.length; i++) { 13559 String packageName = packageNames[i]; 13560 boolean changed = false; 13561 final int appId; 13562 synchronized (mPackages) { 13563 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13564 if (pkgSetting == null) { 13565 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13566 + "\". Skipping suspending/un-suspending."); 13567 unactionedPackages.add(packageName); 13568 continue; 13569 } 13570 appId = pkgSetting.appId; 13571 if (pkgSetting.getSuspended(userId) != suspended) { 13572 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13573 unactionedPackages.add(packageName); 13574 continue; 13575 } 13576 pkgSetting.setSuspended(suspended, userId); 13577 mSettings.writePackageRestrictionsLPr(userId); 13578 changed = true; 13579 changedPackages.add(packageName); 13580 } 13581 } 13582 13583 if (changed && suspended) { 13584 killApplication(packageName, UserHandle.getUid(userId, appId), 13585 "suspending package"); 13586 } 13587 } 13588 } finally { 13589 Binder.restoreCallingIdentity(callingId); 13590 } 13591 13592 if (!changedPackages.isEmpty()) { 13593 sendPackagesSuspendedForUser(changedPackages.toArray( 13594 new String[changedPackages.size()]), userId, suspended); 13595 } 13596 13597 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13598 } 13599 13600 @Override 13601 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13602 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13603 true /* requireFullPermission */, false /* checkShell */, 13604 "isPackageSuspendedForUser for user " + userId); 13605 synchronized (mPackages) { 13606 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13607 if (pkgSetting == null) { 13608 throw new IllegalArgumentException("Unknown target package: " + packageName); 13609 } 13610 return pkgSetting.getSuspended(userId); 13611 } 13612 } 13613 13614 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13615 if (isPackageDeviceAdmin(packageName, userId)) { 13616 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13617 + "\": has an active device admin"); 13618 return false; 13619 } 13620 13621 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13622 if (packageName.equals(activeLauncherPackageName)) { 13623 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13624 + "\": contains the active launcher"); 13625 return false; 13626 } 13627 13628 if (packageName.equals(mRequiredInstallerPackage)) { 13629 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13630 + "\": required for package installation"); 13631 return false; 13632 } 13633 13634 if (packageName.equals(mRequiredUninstallerPackage)) { 13635 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13636 + "\": required for package uninstallation"); 13637 return false; 13638 } 13639 13640 if (packageName.equals(mRequiredVerifierPackage)) { 13641 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13642 + "\": required for package verification"); 13643 return false; 13644 } 13645 13646 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13647 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13648 + "\": is the default dialer"); 13649 return false; 13650 } 13651 13652 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13653 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13654 + "\": protected package"); 13655 return false; 13656 } 13657 13658 // Cannot suspend static shared libs as they are considered 13659 // a part of the using app (emulating static linking). Also 13660 // static libs are installed always on internal storage. 13661 PackageParser.Package pkg = mPackages.get(packageName); 13662 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13663 Slog.w(TAG, "Cannot suspend package: " + packageName 13664 + " providing static shared library: " 13665 + pkg.staticSharedLibName); 13666 return false; 13667 } 13668 13669 return true; 13670 } 13671 13672 private String getActiveLauncherPackageName(int userId) { 13673 Intent intent = new Intent(Intent.ACTION_MAIN); 13674 intent.addCategory(Intent.CATEGORY_HOME); 13675 ResolveInfo resolveInfo = resolveIntent( 13676 intent, 13677 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13678 PackageManager.MATCH_DEFAULT_ONLY, 13679 userId); 13680 13681 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13682 } 13683 13684 private String getDefaultDialerPackageName(int userId) { 13685 synchronized (mPackages) { 13686 return mSettings.getDefaultDialerPackageNameLPw(userId); 13687 } 13688 } 13689 13690 @Override 13691 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13692 mContext.enforceCallingOrSelfPermission( 13693 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13694 "Only package verification agents can verify applications"); 13695 13696 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13697 final PackageVerificationResponse response = new PackageVerificationResponse( 13698 verificationCode, Binder.getCallingUid()); 13699 msg.arg1 = id; 13700 msg.obj = response; 13701 mHandler.sendMessage(msg); 13702 } 13703 13704 @Override 13705 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13706 long millisecondsToDelay) { 13707 mContext.enforceCallingOrSelfPermission( 13708 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13709 "Only package verification agents can extend verification timeouts"); 13710 13711 final PackageVerificationState state = mPendingVerification.get(id); 13712 final PackageVerificationResponse response = new PackageVerificationResponse( 13713 verificationCodeAtTimeout, Binder.getCallingUid()); 13714 13715 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13716 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13717 } 13718 if (millisecondsToDelay < 0) { 13719 millisecondsToDelay = 0; 13720 } 13721 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13722 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13723 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13724 } 13725 13726 if ((state != null) && !state.timeoutExtended()) { 13727 state.extendTimeout(); 13728 13729 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13730 msg.arg1 = id; 13731 msg.obj = response; 13732 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13733 } 13734 } 13735 13736 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13737 int verificationCode, UserHandle user) { 13738 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13739 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13740 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13741 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13742 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13743 13744 mContext.sendBroadcastAsUser(intent, user, 13745 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13746 } 13747 13748 private ComponentName matchComponentForVerifier(String packageName, 13749 List<ResolveInfo> receivers) { 13750 ActivityInfo targetReceiver = null; 13751 13752 final int NR = receivers.size(); 13753 for (int i = 0; i < NR; i++) { 13754 final ResolveInfo info = receivers.get(i); 13755 if (info.activityInfo == null) { 13756 continue; 13757 } 13758 13759 if (packageName.equals(info.activityInfo.packageName)) { 13760 targetReceiver = info.activityInfo; 13761 break; 13762 } 13763 } 13764 13765 if (targetReceiver == null) { 13766 return null; 13767 } 13768 13769 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13770 } 13771 13772 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13773 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13774 if (pkgInfo.verifiers.length == 0) { 13775 return null; 13776 } 13777 13778 final int N = pkgInfo.verifiers.length; 13779 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13780 for (int i = 0; i < N; i++) { 13781 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13782 13783 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13784 receivers); 13785 if (comp == null) { 13786 continue; 13787 } 13788 13789 final int verifierUid = getUidForVerifier(verifierInfo); 13790 if (verifierUid == -1) { 13791 continue; 13792 } 13793 13794 if (DEBUG_VERIFY) { 13795 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13796 + " with the correct signature"); 13797 } 13798 sufficientVerifiers.add(comp); 13799 verificationState.addSufficientVerifier(verifierUid); 13800 } 13801 13802 return sufficientVerifiers; 13803 } 13804 13805 private int getUidForVerifier(VerifierInfo verifierInfo) { 13806 synchronized (mPackages) { 13807 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13808 if (pkg == null) { 13809 return -1; 13810 } else if (pkg.mSignatures.length != 1) { 13811 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13812 + " has more than one signature; ignoring"); 13813 return -1; 13814 } 13815 13816 /* 13817 * If the public key of the package's signature does not match 13818 * our expected public key, then this is a different package and 13819 * we should skip. 13820 */ 13821 13822 final byte[] expectedPublicKey; 13823 try { 13824 final Signature verifierSig = pkg.mSignatures[0]; 13825 final PublicKey publicKey = verifierSig.getPublicKey(); 13826 expectedPublicKey = publicKey.getEncoded(); 13827 } catch (CertificateException e) { 13828 return -1; 13829 } 13830 13831 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13832 13833 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13834 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13835 + " does not have the expected public key; ignoring"); 13836 return -1; 13837 } 13838 13839 return pkg.applicationInfo.uid; 13840 } 13841 } 13842 13843 @Override 13844 public void finishPackageInstall(int token, boolean didLaunch) { 13845 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13846 13847 if (DEBUG_INSTALL) { 13848 Slog.v(TAG, "BM finishing package install for " + token); 13849 } 13850 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13851 13852 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13853 mHandler.sendMessage(msg); 13854 } 13855 13856 /** 13857 * Get the verification agent timeout. 13858 * 13859 * @return verification timeout in milliseconds 13860 */ 13861 private long getVerificationTimeout() { 13862 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13863 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13864 DEFAULT_VERIFICATION_TIMEOUT); 13865 } 13866 13867 /** 13868 * Get the default verification agent response code. 13869 * 13870 * @return default verification response code 13871 */ 13872 private int getDefaultVerificationResponse() { 13873 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13874 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13875 DEFAULT_VERIFICATION_RESPONSE); 13876 } 13877 13878 /** 13879 * Check whether or not package verification has been enabled. 13880 * 13881 * @return true if verification should be performed 13882 */ 13883 private boolean isVerificationEnabled(int userId, int installFlags) { 13884 if (!DEFAULT_VERIFY_ENABLE) { 13885 return false; 13886 } 13887 13888 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13889 13890 // Check if installing from ADB 13891 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13892 // Do not run verification in a test harness environment 13893 if (ActivityManager.isRunningInTestHarness()) { 13894 return false; 13895 } 13896 if (ensureVerifyAppsEnabled) { 13897 return true; 13898 } 13899 // Check if the developer does not want package verification for ADB installs 13900 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13901 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13902 return false; 13903 } 13904 } 13905 13906 if (ensureVerifyAppsEnabled) { 13907 return true; 13908 } 13909 13910 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13911 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13912 } 13913 13914 @Override 13915 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13916 throws RemoteException { 13917 mContext.enforceCallingOrSelfPermission( 13918 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13919 "Only intentfilter verification agents can verify applications"); 13920 13921 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13922 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13923 Binder.getCallingUid(), verificationCode, failedDomains); 13924 msg.arg1 = id; 13925 msg.obj = response; 13926 mHandler.sendMessage(msg); 13927 } 13928 13929 @Override 13930 public int getIntentVerificationStatus(String packageName, int userId) { 13931 synchronized (mPackages) { 13932 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13933 } 13934 } 13935 13936 @Override 13937 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13938 mContext.enforceCallingOrSelfPermission( 13939 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13940 13941 boolean result = false; 13942 synchronized (mPackages) { 13943 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13944 } 13945 if (result) { 13946 scheduleWritePackageRestrictionsLocked(userId); 13947 } 13948 return result; 13949 } 13950 13951 @Override 13952 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13953 String packageName) { 13954 synchronized (mPackages) { 13955 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13956 } 13957 } 13958 13959 @Override 13960 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13961 if (TextUtils.isEmpty(packageName)) { 13962 return ParceledListSlice.emptyList(); 13963 } 13964 synchronized (mPackages) { 13965 PackageParser.Package pkg = mPackages.get(packageName); 13966 if (pkg == null || pkg.activities == null) { 13967 return ParceledListSlice.emptyList(); 13968 } 13969 final int count = pkg.activities.size(); 13970 ArrayList<IntentFilter> result = new ArrayList<>(); 13971 for (int n=0; n<count; n++) { 13972 PackageParser.Activity activity = pkg.activities.get(n); 13973 if (activity.intents != null && activity.intents.size() > 0) { 13974 result.addAll(activity.intents); 13975 } 13976 } 13977 return new ParceledListSlice<>(result); 13978 } 13979 } 13980 13981 @Override 13982 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13983 mContext.enforceCallingOrSelfPermission( 13984 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13985 13986 synchronized (mPackages) { 13987 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13988 if (packageName != null) { 13989 result |= updateIntentVerificationStatus(packageName, 13990 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13991 userId); 13992 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13993 packageName, userId); 13994 } 13995 return result; 13996 } 13997 } 13998 13999 @Override 14000 public String getDefaultBrowserPackageName(int userId) { 14001 synchronized (mPackages) { 14002 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14003 } 14004 } 14005 14006 /** 14007 * Get the "allow unknown sources" setting. 14008 * 14009 * @return the current "allow unknown sources" setting 14010 */ 14011 private int getUnknownSourcesSettings() { 14012 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14013 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14014 -1); 14015 } 14016 14017 @Override 14018 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14019 final int uid = Binder.getCallingUid(); 14020 // writer 14021 synchronized (mPackages) { 14022 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14023 if (targetPackageSetting == null) { 14024 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14025 } 14026 14027 PackageSetting installerPackageSetting; 14028 if (installerPackageName != null) { 14029 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14030 if (installerPackageSetting == null) { 14031 throw new IllegalArgumentException("Unknown installer package: " 14032 + installerPackageName); 14033 } 14034 } else { 14035 installerPackageSetting = null; 14036 } 14037 14038 Signature[] callerSignature; 14039 Object obj = mSettings.getUserIdLPr(uid); 14040 if (obj != null) { 14041 if (obj instanceof SharedUserSetting) { 14042 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14043 } else if (obj instanceof PackageSetting) { 14044 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14045 } else { 14046 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14047 } 14048 } else { 14049 throw new SecurityException("Unknown calling UID: " + uid); 14050 } 14051 14052 // Verify: can't set installerPackageName to a package that is 14053 // not signed with the same cert as the caller. 14054 if (installerPackageSetting != null) { 14055 if (compareSignatures(callerSignature, 14056 installerPackageSetting.signatures.mSignatures) 14057 != PackageManager.SIGNATURE_MATCH) { 14058 throw new SecurityException( 14059 "Caller does not have same cert as new installer package " 14060 + installerPackageName); 14061 } 14062 } 14063 14064 // Verify: if target already has an installer package, it must 14065 // be signed with the same cert as the caller. 14066 if (targetPackageSetting.installerPackageName != null) { 14067 PackageSetting setting = mSettings.mPackages.get( 14068 targetPackageSetting.installerPackageName); 14069 // If the currently set package isn't valid, then it's always 14070 // okay to change it. 14071 if (setting != null) { 14072 if (compareSignatures(callerSignature, 14073 setting.signatures.mSignatures) 14074 != PackageManager.SIGNATURE_MATCH) { 14075 throw new SecurityException( 14076 "Caller does not have same cert as old installer package " 14077 + targetPackageSetting.installerPackageName); 14078 } 14079 } 14080 } 14081 14082 // Okay! 14083 targetPackageSetting.installerPackageName = installerPackageName; 14084 if (installerPackageName != null) { 14085 mSettings.mInstallerPackages.add(installerPackageName); 14086 } 14087 scheduleWriteSettingsLocked(); 14088 } 14089 } 14090 14091 @Override 14092 public void setApplicationCategoryHint(String packageName, int categoryHint, 14093 String callerPackageName) { 14094 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14095 callerPackageName); 14096 synchronized (mPackages) { 14097 PackageSetting ps = mSettings.mPackages.get(packageName); 14098 if (ps == null) { 14099 throw new IllegalArgumentException("Unknown target package " + packageName); 14100 } 14101 14102 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14103 throw new IllegalArgumentException("Calling package " + callerPackageName 14104 + " is not installer for " + packageName); 14105 } 14106 14107 if (ps.categoryHint != categoryHint) { 14108 ps.categoryHint = categoryHint; 14109 scheduleWriteSettingsLocked(); 14110 } 14111 } 14112 } 14113 14114 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14115 // Queue up an async operation since the package installation may take a little while. 14116 mHandler.post(new Runnable() { 14117 public void run() { 14118 mHandler.removeCallbacks(this); 14119 // Result object to be returned 14120 PackageInstalledInfo res = new PackageInstalledInfo(); 14121 res.setReturnCode(currentStatus); 14122 res.uid = -1; 14123 res.pkg = null; 14124 res.removedInfo = null; 14125 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14126 args.doPreInstall(res.returnCode); 14127 synchronized (mInstallLock) { 14128 installPackageTracedLI(args, res); 14129 } 14130 args.doPostInstall(res.returnCode, res.uid); 14131 } 14132 14133 // A restore should be performed at this point if (a) the install 14134 // succeeded, (b) the operation is not an update, and (c) the new 14135 // package has not opted out of backup participation. 14136 final boolean update = res.removedInfo != null 14137 && res.removedInfo.removedPackage != null; 14138 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14139 boolean doRestore = !update 14140 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14141 14142 // Set up the post-install work request bookkeeping. This will be used 14143 // and cleaned up by the post-install event handling regardless of whether 14144 // there's a restore pass performed. Token values are >= 1. 14145 int token; 14146 if (mNextInstallToken < 0) mNextInstallToken = 1; 14147 token = mNextInstallToken++; 14148 14149 PostInstallData data = new PostInstallData(args, res); 14150 mRunningInstalls.put(token, data); 14151 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14152 14153 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14154 // Pass responsibility to the Backup Manager. It will perform a 14155 // restore if appropriate, then pass responsibility back to the 14156 // Package Manager to run the post-install observer callbacks 14157 // and broadcasts. 14158 IBackupManager bm = IBackupManager.Stub.asInterface( 14159 ServiceManager.getService(Context.BACKUP_SERVICE)); 14160 if (bm != null) { 14161 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14162 + " to BM for possible restore"); 14163 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14164 try { 14165 // TODO: http://b/22388012 14166 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14167 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14168 } else { 14169 doRestore = false; 14170 } 14171 } catch (RemoteException e) { 14172 // can't happen; the backup manager is local 14173 } catch (Exception e) { 14174 Slog.e(TAG, "Exception trying to enqueue restore", e); 14175 doRestore = false; 14176 } 14177 } else { 14178 Slog.e(TAG, "Backup Manager not found!"); 14179 doRestore = false; 14180 } 14181 } 14182 14183 if (!doRestore) { 14184 // No restore possible, or the Backup Manager was mysteriously not 14185 // available -- just fire the post-install work request directly. 14186 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14187 14188 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14189 14190 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14191 mHandler.sendMessage(msg); 14192 } 14193 } 14194 }); 14195 } 14196 14197 /** 14198 * Callback from PackageSettings whenever an app is first transitioned out of the 14199 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14200 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14201 * here whether the app is the target of an ongoing install, and only send the 14202 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14203 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14204 * handling. 14205 */ 14206 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14207 // Serialize this with the rest of the install-process message chain. In the 14208 // restore-at-install case, this Runnable will necessarily run before the 14209 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14210 // are coherent. In the non-restore case, the app has already completed install 14211 // and been launched through some other means, so it is not in a problematic 14212 // state for observers to see the FIRST_LAUNCH signal. 14213 mHandler.post(new Runnable() { 14214 @Override 14215 public void run() { 14216 for (int i = 0; i < mRunningInstalls.size(); i++) { 14217 final PostInstallData data = mRunningInstalls.valueAt(i); 14218 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14219 continue; 14220 } 14221 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14222 // right package; but is it for the right user? 14223 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14224 if (userId == data.res.newUsers[uIndex]) { 14225 if (DEBUG_BACKUP) { 14226 Slog.i(TAG, "Package " + pkgName 14227 + " being restored so deferring FIRST_LAUNCH"); 14228 } 14229 return; 14230 } 14231 } 14232 } 14233 } 14234 // didn't find it, so not being restored 14235 if (DEBUG_BACKUP) { 14236 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14237 } 14238 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14239 } 14240 }); 14241 } 14242 14243 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14244 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14245 installerPkg, null, userIds); 14246 } 14247 14248 private abstract class HandlerParams { 14249 private static final int MAX_RETRIES = 4; 14250 14251 /** 14252 * Number of times startCopy() has been attempted and had a non-fatal 14253 * error. 14254 */ 14255 private int mRetries = 0; 14256 14257 /** User handle for the user requesting the information or installation. */ 14258 private final UserHandle mUser; 14259 String traceMethod; 14260 int traceCookie; 14261 14262 HandlerParams(UserHandle user) { 14263 mUser = user; 14264 } 14265 14266 UserHandle getUser() { 14267 return mUser; 14268 } 14269 14270 HandlerParams setTraceMethod(String traceMethod) { 14271 this.traceMethod = traceMethod; 14272 return this; 14273 } 14274 14275 HandlerParams setTraceCookie(int traceCookie) { 14276 this.traceCookie = traceCookie; 14277 return this; 14278 } 14279 14280 final boolean startCopy() { 14281 boolean res; 14282 try { 14283 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14284 14285 if (++mRetries > MAX_RETRIES) { 14286 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14287 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14288 handleServiceError(); 14289 return false; 14290 } else { 14291 handleStartCopy(); 14292 res = true; 14293 } 14294 } catch (RemoteException e) { 14295 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14296 mHandler.sendEmptyMessage(MCS_RECONNECT); 14297 res = false; 14298 } 14299 handleReturnCode(); 14300 return res; 14301 } 14302 14303 final void serviceError() { 14304 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14305 handleServiceError(); 14306 handleReturnCode(); 14307 } 14308 14309 abstract void handleStartCopy() throws RemoteException; 14310 abstract void handleServiceError(); 14311 abstract void handleReturnCode(); 14312 } 14313 14314 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14315 for (File path : paths) { 14316 try { 14317 mcs.clearDirectory(path.getAbsolutePath()); 14318 } catch (RemoteException e) { 14319 } 14320 } 14321 } 14322 14323 static class OriginInfo { 14324 /** 14325 * Location where install is coming from, before it has been 14326 * copied/renamed into place. This could be a single monolithic APK 14327 * file, or a cluster directory. This location may be untrusted. 14328 */ 14329 final File file; 14330 final String cid; 14331 14332 /** 14333 * Flag indicating that {@link #file} or {@link #cid} has already been 14334 * staged, meaning downstream users don't need to defensively copy the 14335 * contents. 14336 */ 14337 final boolean staged; 14338 14339 /** 14340 * Flag indicating that {@link #file} or {@link #cid} is an already 14341 * installed app that is being moved. 14342 */ 14343 final boolean existing; 14344 14345 final String resolvedPath; 14346 final File resolvedFile; 14347 14348 static OriginInfo fromNothing() { 14349 return new OriginInfo(null, null, false, false); 14350 } 14351 14352 static OriginInfo fromUntrustedFile(File file) { 14353 return new OriginInfo(file, null, false, false); 14354 } 14355 14356 static OriginInfo fromExistingFile(File file) { 14357 return new OriginInfo(file, null, false, true); 14358 } 14359 14360 static OriginInfo fromStagedFile(File file) { 14361 return new OriginInfo(file, null, true, false); 14362 } 14363 14364 static OriginInfo fromStagedContainer(String cid) { 14365 return new OriginInfo(null, cid, true, false); 14366 } 14367 14368 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14369 this.file = file; 14370 this.cid = cid; 14371 this.staged = staged; 14372 this.existing = existing; 14373 14374 if (cid != null) { 14375 resolvedPath = PackageHelper.getSdDir(cid); 14376 resolvedFile = new File(resolvedPath); 14377 } else if (file != null) { 14378 resolvedPath = file.getAbsolutePath(); 14379 resolvedFile = file; 14380 } else { 14381 resolvedPath = null; 14382 resolvedFile = null; 14383 } 14384 } 14385 } 14386 14387 static class MoveInfo { 14388 final int moveId; 14389 final String fromUuid; 14390 final String toUuid; 14391 final String packageName; 14392 final String dataAppName; 14393 final int appId; 14394 final String seinfo; 14395 final int targetSdkVersion; 14396 14397 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14398 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14399 this.moveId = moveId; 14400 this.fromUuid = fromUuid; 14401 this.toUuid = toUuid; 14402 this.packageName = packageName; 14403 this.dataAppName = dataAppName; 14404 this.appId = appId; 14405 this.seinfo = seinfo; 14406 this.targetSdkVersion = targetSdkVersion; 14407 } 14408 } 14409 14410 static class VerificationInfo { 14411 /** A constant used to indicate that a uid value is not present. */ 14412 public static final int NO_UID = -1; 14413 14414 /** URI referencing where the package was downloaded from. */ 14415 final Uri originatingUri; 14416 14417 /** HTTP referrer URI associated with the originatingURI. */ 14418 final Uri referrer; 14419 14420 /** UID of the application that the install request originated from. */ 14421 final int originatingUid; 14422 14423 /** UID of application requesting the install */ 14424 final int installerUid; 14425 14426 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14427 this.originatingUri = originatingUri; 14428 this.referrer = referrer; 14429 this.originatingUid = originatingUid; 14430 this.installerUid = installerUid; 14431 } 14432 } 14433 14434 class InstallParams extends HandlerParams { 14435 final OriginInfo origin; 14436 final MoveInfo move; 14437 final IPackageInstallObserver2 observer; 14438 int installFlags; 14439 final String installerPackageName; 14440 final String volumeUuid; 14441 private InstallArgs mArgs; 14442 private int mRet; 14443 final String packageAbiOverride; 14444 final String[] grantedRuntimePermissions; 14445 final VerificationInfo verificationInfo; 14446 final Certificate[][] certificates; 14447 final int installReason; 14448 14449 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14450 int installFlags, String installerPackageName, String volumeUuid, 14451 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14452 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14453 super(user); 14454 this.origin = origin; 14455 this.move = move; 14456 this.observer = observer; 14457 this.installFlags = installFlags; 14458 this.installerPackageName = installerPackageName; 14459 this.volumeUuid = volumeUuid; 14460 this.verificationInfo = verificationInfo; 14461 this.packageAbiOverride = packageAbiOverride; 14462 this.grantedRuntimePermissions = grantedPermissions; 14463 this.certificates = certificates; 14464 this.installReason = installReason; 14465 } 14466 14467 @Override 14468 public String toString() { 14469 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14470 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14471 } 14472 14473 private int installLocationPolicy(PackageInfoLite pkgLite) { 14474 String packageName = pkgLite.packageName; 14475 int installLocation = pkgLite.installLocation; 14476 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14477 // reader 14478 synchronized (mPackages) { 14479 // Currently installed package which the new package is attempting to replace or 14480 // null if no such package is installed. 14481 PackageParser.Package installedPkg = mPackages.get(packageName); 14482 // Package which currently owns the data which the new package will own if installed. 14483 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14484 // will be null whereas dataOwnerPkg will contain information about the package 14485 // which was uninstalled while keeping its data. 14486 PackageParser.Package dataOwnerPkg = installedPkg; 14487 if (dataOwnerPkg == null) { 14488 PackageSetting ps = mSettings.mPackages.get(packageName); 14489 if (ps != null) { 14490 dataOwnerPkg = ps.pkg; 14491 } 14492 } 14493 14494 if (dataOwnerPkg != null) { 14495 // If installed, the package will get access to data left on the device by its 14496 // predecessor. As a security measure, this is permited only if this is not a 14497 // version downgrade or if the predecessor package is marked as debuggable and 14498 // a downgrade is explicitly requested. 14499 // 14500 // On debuggable platform builds, downgrades are permitted even for 14501 // non-debuggable packages to make testing easier. Debuggable platform builds do 14502 // not offer security guarantees and thus it's OK to disable some security 14503 // mechanisms to make debugging/testing easier on those builds. However, even on 14504 // debuggable builds downgrades of packages are permitted only if requested via 14505 // installFlags. This is because we aim to keep the behavior of debuggable 14506 // platform builds as close as possible to the behavior of non-debuggable 14507 // platform builds. 14508 final boolean downgradeRequested = 14509 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14510 final boolean packageDebuggable = 14511 (dataOwnerPkg.applicationInfo.flags 14512 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14513 final boolean downgradePermitted = 14514 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14515 if (!downgradePermitted) { 14516 try { 14517 checkDowngrade(dataOwnerPkg, pkgLite); 14518 } catch (PackageManagerException e) { 14519 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14520 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14521 } 14522 } 14523 } 14524 14525 if (installedPkg != null) { 14526 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14527 // Check for updated system application. 14528 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14529 if (onSd) { 14530 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14531 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14532 } 14533 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14534 } else { 14535 if (onSd) { 14536 // Install flag overrides everything. 14537 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14538 } 14539 // If current upgrade specifies particular preference 14540 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14541 // Application explicitly specified internal. 14542 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14543 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14544 // App explictly prefers external. Let policy decide 14545 } else { 14546 // Prefer previous location 14547 if (isExternal(installedPkg)) { 14548 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14549 } 14550 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14551 } 14552 } 14553 } else { 14554 // Invalid install. Return error code 14555 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14556 } 14557 } 14558 } 14559 // All the special cases have been taken care of. 14560 // Return result based on recommended install location. 14561 if (onSd) { 14562 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14563 } 14564 return pkgLite.recommendedInstallLocation; 14565 } 14566 14567 /* 14568 * Invoke remote method to get package information and install 14569 * location values. Override install location based on default 14570 * policy if needed and then create install arguments based 14571 * on the install location. 14572 */ 14573 public void handleStartCopy() throws RemoteException { 14574 int ret = PackageManager.INSTALL_SUCCEEDED; 14575 14576 // If we're already staged, we've firmly committed to an install location 14577 if (origin.staged) { 14578 if (origin.file != null) { 14579 installFlags |= PackageManager.INSTALL_INTERNAL; 14580 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14581 } else if (origin.cid != null) { 14582 installFlags |= PackageManager.INSTALL_EXTERNAL; 14583 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14584 } else { 14585 throw new IllegalStateException("Invalid stage location"); 14586 } 14587 } 14588 14589 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14590 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14591 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14592 PackageInfoLite pkgLite = null; 14593 14594 if (onInt && onSd) { 14595 // Check if both bits are set. 14596 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14597 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14598 } else if (onSd && ephemeral) { 14599 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14600 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14601 } else { 14602 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14603 packageAbiOverride); 14604 14605 if (DEBUG_EPHEMERAL && ephemeral) { 14606 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14607 } 14608 14609 /* 14610 * If we have too little free space, try to free cache 14611 * before giving up. 14612 */ 14613 if (!origin.staged && pkgLite.recommendedInstallLocation 14614 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14615 // TODO: focus freeing disk space on the target device 14616 final StorageManager storage = StorageManager.from(mContext); 14617 final long lowThreshold = storage.getStorageLowBytes( 14618 Environment.getDataDirectory()); 14619 14620 final long sizeBytes = mContainerService.calculateInstalledSize( 14621 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14622 14623 try { 14624 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14625 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14626 installFlags, packageAbiOverride); 14627 } catch (InstallerException e) { 14628 Slog.w(TAG, "Failed to free cache", e); 14629 } 14630 14631 /* 14632 * The cache free must have deleted the file we 14633 * downloaded to install. 14634 * 14635 * TODO: fix the "freeCache" call to not delete 14636 * the file we care about. 14637 */ 14638 if (pkgLite.recommendedInstallLocation 14639 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14640 pkgLite.recommendedInstallLocation 14641 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14642 } 14643 } 14644 } 14645 14646 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14647 int loc = pkgLite.recommendedInstallLocation; 14648 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14649 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14650 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14651 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14652 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14653 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14654 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14655 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14656 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14657 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14658 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14659 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14660 } else { 14661 // Override with defaults if needed. 14662 loc = installLocationPolicy(pkgLite); 14663 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14664 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14665 } else if (!onSd && !onInt) { 14666 // Override install location with flags 14667 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14668 // Set the flag to install on external media. 14669 installFlags |= PackageManager.INSTALL_EXTERNAL; 14670 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14671 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14672 if (DEBUG_EPHEMERAL) { 14673 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14674 } 14675 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14676 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14677 |PackageManager.INSTALL_INTERNAL); 14678 } else { 14679 // Make sure the flag for installing on external 14680 // media is unset 14681 installFlags |= PackageManager.INSTALL_INTERNAL; 14682 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14683 } 14684 } 14685 } 14686 } 14687 14688 final InstallArgs args = createInstallArgs(this); 14689 mArgs = args; 14690 14691 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14692 // TODO: http://b/22976637 14693 // Apps installed for "all" users use the device owner to verify the app 14694 UserHandle verifierUser = getUser(); 14695 if (verifierUser == UserHandle.ALL) { 14696 verifierUser = UserHandle.SYSTEM; 14697 } 14698 14699 /* 14700 * Determine if we have any installed package verifiers. If we 14701 * do, then we'll defer to them to verify the packages. 14702 */ 14703 final int requiredUid = mRequiredVerifierPackage == null ? -1 14704 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14705 verifierUser.getIdentifier()); 14706 if (!origin.existing && requiredUid != -1 14707 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14708 final Intent verification = new Intent( 14709 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14710 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14711 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14712 PACKAGE_MIME_TYPE); 14713 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14714 14715 // Query all live verifiers based on current user state 14716 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14717 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14718 14719 if (DEBUG_VERIFY) { 14720 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14721 + verification.toString() + " with " + pkgLite.verifiers.length 14722 + " optional verifiers"); 14723 } 14724 14725 final int verificationId = mPendingVerificationToken++; 14726 14727 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14728 14729 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14730 installerPackageName); 14731 14732 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14733 installFlags); 14734 14735 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14736 pkgLite.packageName); 14737 14738 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14739 pkgLite.versionCode); 14740 14741 if (verificationInfo != null) { 14742 if (verificationInfo.originatingUri != null) { 14743 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14744 verificationInfo.originatingUri); 14745 } 14746 if (verificationInfo.referrer != null) { 14747 verification.putExtra(Intent.EXTRA_REFERRER, 14748 verificationInfo.referrer); 14749 } 14750 if (verificationInfo.originatingUid >= 0) { 14751 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14752 verificationInfo.originatingUid); 14753 } 14754 if (verificationInfo.installerUid >= 0) { 14755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14756 verificationInfo.installerUid); 14757 } 14758 } 14759 14760 final PackageVerificationState verificationState = new PackageVerificationState( 14761 requiredUid, args); 14762 14763 mPendingVerification.append(verificationId, verificationState); 14764 14765 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14766 receivers, verificationState); 14767 14768 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14769 final long idleDuration = getVerificationTimeout(); 14770 14771 /* 14772 * If any sufficient verifiers were listed in the package 14773 * manifest, attempt to ask them. 14774 */ 14775 if (sufficientVerifiers != null) { 14776 final int N = sufficientVerifiers.size(); 14777 if (N == 0) { 14778 Slog.i(TAG, "Additional verifiers required, but none installed."); 14779 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14780 } else { 14781 for (int i = 0; i < N; i++) { 14782 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14783 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14784 verifierComponent.getPackageName(), idleDuration, 14785 verifierUser.getIdentifier(), false, "package verifier"); 14786 14787 final Intent sufficientIntent = new Intent(verification); 14788 sufficientIntent.setComponent(verifierComponent); 14789 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14790 } 14791 } 14792 } 14793 14794 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14795 mRequiredVerifierPackage, receivers); 14796 if (ret == PackageManager.INSTALL_SUCCEEDED 14797 && mRequiredVerifierPackage != null) { 14798 Trace.asyncTraceBegin( 14799 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14800 /* 14801 * Send the intent to the required verification agent, 14802 * but only start the verification timeout after the 14803 * target BroadcastReceivers have run. 14804 */ 14805 verification.setComponent(requiredVerifierComponent); 14806 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14807 mRequiredVerifierPackage, idleDuration, 14808 verifierUser.getIdentifier(), false, "package verifier"); 14809 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14810 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14811 new BroadcastReceiver() { 14812 @Override 14813 public void onReceive(Context context, Intent intent) { 14814 final Message msg = mHandler 14815 .obtainMessage(CHECK_PENDING_VERIFICATION); 14816 msg.arg1 = verificationId; 14817 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14818 } 14819 }, null, 0, null, null); 14820 14821 /* 14822 * We don't want the copy to proceed until verification 14823 * succeeds, so null out this field. 14824 */ 14825 mArgs = null; 14826 } 14827 } else { 14828 /* 14829 * No package verification is enabled, so immediately start 14830 * the remote call to initiate copy using temporary file. 14831 */ 14832 ret = args.copyApk(mContainerService, true); 14833 } 14834 } 14835 14836 mRet = ret; 14837 } 14838 14839 @Override 14840 void handleReturnCode() { 14841 // If mArgs is null, then MCS couldn't be reached. When it 14842 // reconnects, it will try again to install. At that point, this 14843 // will succeed. 14844 if (mArgs != null) { 14845 processPendingInstall(mArgs, mRet); 14846 } 14847 } 14848 14849 @Override 14850 void handleServiceError() { 14851 mArgs = createInstallArgs(this); 14852 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14853 } 14854 14855 public boolean isForwardLocked() { 14856 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14857 } 14858 } 14859 14860 /** 14861 * Used during creation of InstallArgs 14862 * 14863 * @param installFlags package installation flags 14864 * @return true if should be installed on external storage 14865 */ 14866 private static boolean installOnExternalAsec(int installFlags) { 14867 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14868 return false; 14869 } 14870 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14871 return true; 14872 } 14873 return false; 14874 } 14875 14876 /** 14877 * Used during creation of InstallArgs 14878 * 14879 * @param installFlags package installation flags 14880 * @return true if should be installed as forward locked 14881 */ 14882 private static boolean installForwardLocked(int installFlags) { 14883 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14884 } 14885 14886 private InstallArgs createInstallArgs(InstallParams params) { 14887 if (params.move != null) { 14888 return new MoveInstallArgs(params); 14889 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14890 return new AsecInstallArgs(params); 14891 } else { 14892 return new FileInstallArgs(params); 14893 } 14894 } 14895 14896 /** 14897 * Create args that describe an existing installed package. Typically used 14898 * when cleaning up old installs, or used as a move source. 14899 */ 14900 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14901 String resourcePath, String[] instructionSets) { 14902 final boolean isInAsec; 14903 if (installOnExternalAsec(installFlags)) { 14904 /* Apps on SD card are always in ASEC containers. */ 14905 isInAsec = true; 14906 } else if (installForwardLocked(installFlags) 14907 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14908 /* 14909 * Forward-locked apps are only in ASEC containers if they're the 14910 * new style 14911 */ 14912 isInAsec = true; 14913 } else { 14914 isInAsec = false; 14915 } 14916 14917 if (isInAsec) { 14918 return new AsecInstallArgs(codePath, instructionSets, 14919 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14920 } else { 14921 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14922 } 14923 } 14924 14925 static abstract class InstallArgs { 14926 /** @see InstallParams#origin */ 14927 final OriginInfo origin; 14928 /** @see InstallParams#move */ 14929 final MoveInfo move; 14930 14931 final IPackageInstallObserver2 observer; 14932 // Always refers to PackageManager flags only 14933 final int installFlags; 14934 final String installerPackageName; 14935 final String volumeUuid; 14936 final UserHandle user; 14937 final String abiOverride; 14938 final String[] installGrantPermissions; 14939 /** If non-null, drop an async trace when the install completes */ 14940 final String traceMethod; 14941 final int traceCookie; 14942 final Certificate[][] certificates; 14943 final int installReason; 14944 14945 // The list of instruction sets supported by this app. This is currently 14946 // only used during the rmdex() phase to clean up resources. We can get rid of this 14947 // if we move dex files under the common app path. 14948 /* nullable */ String[] instructionSets; 14949 14950 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14951 int installFlags, String installerPackageName, String volumeUuid, 14952 UserHandle user, String[] instructionSets, 14953 String abiOverride, String[] installGrantPermissions, 14954 String traceMethod, int traceCookie, Certificate[][] certificates, 14955 int installReason) { 14956 this.origin = origin; 14957 this.move = move; 14958 this.installFlags = installFlags; 14959 this.observer = observer; 14960 this.installerPackageName = installerPackageName; 14961 this.volumeUuid = volumeUuid; 14962 this.user = user; 14963 this.instructionSets = instructionSets; 14964 this.abiOverride = abiOverride; 14965 this.installGrantPermissions = installGrantPermissions; 14966 this.traceMethod = traceMethod; 14967 this.traceCookie = traceCookie; 14968 this.certificates = certificates; 14969 this.installReason = installReason; 14970 } 14971 14972 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14973 abstract int doPreInstall(int status); 14974 14975 /** 14976 * Rename package into final resting place. All paths on the given 14977 * scanned package should be updated to reflect the rename. 14978 */ 14979 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14980 abstract int doPostInstall(int status, int uid); 14981 14982 /** @see PackageSettingBase#codePathString */ 14983 abstract String getCodePath(); 14984 /** @see PackageSettingBase#resourcePathString */ 14985 abstract String getResourcePath(); 14986 14987 // Need installer lock especially for dex file removal. 14988 abstract void cleanUpResourcesLI(); 14989 abstract boolean doPostDeleteLI(boolean delete); 14990 14991 /** 14992 * Called before the source arguments are copied. This is used mostly 14993 * for MoveParams when it needs to read the source file to put it in the 14994 * destination. 14995 */ 14996 int doPreCopy() { 14997 return PackageManager.INSTALL_SUCCEEDED; 14998 } 14999 15000 /** 15001 * Called after the source arguments are copied. This is used mostly for 15002 * MoveParams when it needs to read the source file to put it in the 15003 * destination. 15004 */ 15005 int doPostCopy(int uid) { 15006 return PackageManager.INSTALL_SUCCEEDED; 15007 } 15008 15009 protected boolean isFwdLocked() { 15010 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15011 } 15012 15013 protected boolean isExternalAsec() { 15014 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15015 } 15016 15017 protected boolean isEphemeral() { 15018 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15019 } 15020 15021 UserHandle getUser() { 15022 return user; 15023 } 15024 } 15025 15026 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15027 if (!allCodePaths.isEmpty()) { 15028 if (instructionSets == null) { 15029 throw new IllegalStateException("instructionSet == null"); 15030 } 15031 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15032 for (String codePath : allCodePaths) { 15033 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15034 try { 15035 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15036 } catch (InstallerException ignored) { 15037 } 15038 } 15039 } 15040 } 15041 } 15042 15043 /** 15044 * Logic to handle installation of non-ASEC applications, including copying 15045 * and renaming logic. 15046 */ 15047 class FileInstallArgs extends InstallArgs { 15048 private File codeFile; 15049 private File resourceFile; 15050 15051 // Example topology: 15052 // /data/app/com.example/base.apk 15053 // /data/app/com.example/split_foo.apk 15054 // /data/app/com.example/lib/arm/libfoo.so 15055 // /data/app/com.example/lib/arm64/libfoo.so 15056 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15057 15058 /** New install */ 15059 FileInstallArgs(InstallParams params) { 15060 super(params.origin, params.move, params.observer, params.installFlags, 15061 params.installerPackageName, params.volumeUuid, 15062 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15063 params.grantedRuntimePermissions, 15064 params.traceMethod, params.traceCookie, params.certificates, 15065 params.installReason); 15066 if (isFwdLocked()) { 15067 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15068 } 15069 } 15070 15071 /** Existing install */ 15072 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15073 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15074 null, null, null, 0, null /*certificates*/, 15075 PackageManager.INSTALL_REASON_UNKNOWN); 15076 this.codeFile = (codePath != null) ? new File(codePath) : null; 15077 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15078 } 15079 15080 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15081 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15082 try { 15083 return doCopyApk(imcs, temp); 15084 } finally { 15085 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15086 } 15087 } 15088 15089 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15090 if (origin.staged) { 15091 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15092 codeFile = origin.file; 15093 resourceFile = origin.file; 15094 return PackageManager.INSTALL_SUCCEEDED; 15095 } 15096 15097 try { 15098 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15099 final File tempDir = 15100 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15101 codeFile = tempDir; 15102 resourceFile = tempDir; 15103 } catch (IOException e) { 15104 Slog.w(TAG, "Failed to create copy file: " + e); 15105 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15106 } 15107 15108 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15109 @Override 15110 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15111 if (!FileUtils.isValidExtFilename(name)) { 15112 throw new IllegalArgumentException("Invalid filename: " + name); 15113 } 15114 try { 15115 final File file = new File(codeFile, name); 15116 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15117 O_RDWR | O_CREAT, 0644); 15118 Os.chmod(file.getAbsolutePath(), 0644); 15119 return new ParcelFileDescriptor(fd); 15120 } catch (ErrnoException e) { 15121 throw new RemoteException("Failed to open: " + e.getMessage()); 15122 } 15123 } 15124 }; 15125 15126 int ret = PackageManager.INSTALL_SUCCEEDED; 15127 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15128 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15129 Slog.e(TAG, "Failed to copy package"); 15130 return ret; 15131 } 15132 15133 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15134 NativeLibraryHelper.Handle handle = null; 15135 try { 15136 handle = NativeLibraryHelper.Handle.create(codeFile); 15137 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15138 abiOverride); 15139 } catch (IOException e) { 15140 Slog.e(TAG, "Copying native libraries failed", e); 15141 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15142 } finally { 15143 IoUtils.closeQuietly(handle); 15144 } 15145 15146 return ret; 15147 } 15148 15149 int doPreInstall(int status) { 15150 if (status != PackageManager.INSTALL_SUCCEEDED) { 15151 cleanUp(); 15152 } 15153 return status; 15154 } 15155 15156 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15157 if (status != PackageManager.INSTALL_SUCCEEDED) { 15158 cleanUp(); 15159 return false; 15160 } 15161 15162 final File targetDir = codeFile.getParentFile(); 15163 final File beforeCodeFile = codeFile; 15164 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15165 15166 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15167 try { 15168 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15169 } catch (ErrnoException e) { 15170 Slog.w(TAG, "Failed to rename", e); 15171 return false; 15172 } 15173 15174 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15175 Slog.w(TAG, "Failed to restorecon"); 15176 return false; 15177 } 15178 15179 // Reflect the rename internally 15180 codeFile = afterCodeFile; 15181 resourceFile = afterCodeFile; 15182 15183 // Reflect the rename in scanned details 15184 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15185 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15186 afterCodeFile, pkg.baseCodePath)); 15187 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15188 afterCodeFile, pkg.splitCodePaths)); 15189 15190 // Reflect the rename in app info 15191 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15192 pkg.setApplicationInfoCodePath(pkg.codePath); 15193 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15194 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15195 pkg.setApplicationInfoResourcePath(pkg.codePath); 15196 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15197 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15198 15199 return true; 15200 } 15201 15202 int doPostInstall(int status, int uid) { 15203 if (status != PackageManager.INSTALL_SUCCEEDED) { 15204 cleanUp(); 15205 } 15206 return status; 15207 } 15208 15209 @Override 15210 String getCodePath() { 15211 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15212 } 15213 15214 @Override 15215 String getResourcePath() { 15216 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15217 } 15218 15219 private boolean cleanUp() { 15220 if (codeFile == null || !codeFile.exists()) { 15221 return false; 15222 } 15223 15224 removeCodePathLI(codeFile); 15225 15226 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15227 resourceFile.delete(); 15228 } 15229 15230 return true; 15231 } 15232 15233 void cleanUpResourcesLI() { 15234 // Try enumerating all code paths before deleting 15235 List<String> allCodePaths = Collections.EMPTY_LIST; 15236 if (codeFile != null && codeFile.exists()) { 15237 try { 15238 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15239 allCodePaths = pkg.getAllCodePaths(); 15240 } catch (PackageParserException e) { 15241 // Ignored; we tried our best 15242 } 15243 } 15244 15245 cleanUp(); 15246 removeDexFiles(allCodePaths, instructionSets); 15247 } 15248 15249 boolean doPostDeleteLI(boolean delete) { 15250 // XXX err, shouldn't we respect the delete flag? 15251 cleanUpResourcesLI(); 15252 return true; 15253 } 15254 } 15255 15256 private boolean isAsecExternal(String cid) { 15257 final String asecPath = PackageHelper.getSdFilesystem(cid); 15258 return !asecPath.startsWith(mAsecInternalPath); 15259 } 15260 15261 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15262 PackageManagerException { 15263 if (copyRet < 0) { 15264 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15265 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15266 throw new PackageManagerException(copyRet, message); 15267 } 15268 } 15269 } 15270 15271 /** 15272 * Extract the StorageManagerService "container ID" from the full code path of an 15273 * .apk. 15274 */ 15275 static String cidFromCodePath(String fullCodePath) { 15276 int eidx = fullCodePath.lastIndexOf("/"); 15277 String subStr1 = fullCodePath.substring(0, eidx); 15278 int sidx = subStr1.lastIndexOf("/"); 15279 return subStr1.substring(sidx+1, eidx); 15280 } 15281 15282 /** 15283 * Logic to handle installation of ASEC applications, including copying and 15284 * renaming logic. 15285 */ 15286 class AsecInstallArgs extends InstallArgs { 15287 static final String RES_FILE_NAME = "pkg.apk"; 15288 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15289 15290 String cid; 15291 String packagePath; 15292 String resourcePath; 15293 15294 /** New install */ 15295 AsecInstallArgs(InstallParams params) { 15296 super(params.origin, params.move, params.observer, params.installFlags, 15297 params.installerPackageName, params.volumeUuid, 15298 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15299 params.grantedRuntimePermissions, 15300 params.traceMethod, params.traceCookie, params.certificates, 15301 params.installReason); 15302 } 15303 15304 /** Existing install */ 15305 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15306 boolean isExternal, boolean isForwardLocked) { 15307 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15308 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15309 instructionSets, null, null, null, 0, null /*certificates*/, 15310 PackageManager.INSTALL_REASON_UNKNOWN); 15311 // Hackily pretend we're still looking at a full code path 15312 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15313 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15314 } 15315 15316 // Extract cid from fullCodePath 15317 int eidx = fullCodePath.lastIndexOf("/"); 15318 String subStr1 = fullCodePath.substring(0, eidx); 15319 int sidx = subStr1.lastIndexOf("/"); 15320 cid = subStr1.substring(sidx+1, eidx); 15321 setMountPath(subStr1); 15322 } 15323 15324 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15325 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15326 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15327 instructionSets, null, null, null, 0, null /*certificates*/, 15328 PackageManager.INSTALL_REASON_UNKNOWN); 15329 this.cid = cid; 15330 setMountPath(PackageHelper.getSdDir(cid)); 15331 } 15332 15333 void createCopyFile() { 15334 cid = mInstallerService.allocateExternalStageCidLegacy(); 15335 } 15336 15337 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15338 if (origin.staged && origin.cid != null) { 15339 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15340 cid = origin.cid; 15341 setMountPath(PackageHelper.getSdDir(cid)); 15342 return PackageManager.INSTALL_SUCCEEDED; 15343 } 15344 15345 if (temp) { 15346 createCopyFile(); 15347 } else { 15348 /* 15349 * Pre-emptively destroy the container since it's destroyed if 15350 * copying fails due to it existing anyway. 15351 */ 15352 PackageHelper.destroySdDir(cid); 15353 } 15354 15355 final String newMountPath = imcs.copyPackageToContainer( 15356 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15357 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15358 15359 if (newMountPath != null) { 15360 setMountPath(newMountPath); 15361 return PackageManager.INSTALL_SUCCEEDED; 15362 } else { 15363 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15364 } 15365 } 15366 15367 @Override 15368 String getCodePath() { 15369 return packagePath; 15370 } 15371 15372 @Override 15373 String getResourcePath() { 15374 return resourcePath; 15375 } 15376 15377 int doPreInstall(int status) { 15378 if (status != PackageManager.INSTALL_SUCCEEDED) { 15379 // Destroy container 15380 PackageHelper.destroySdDir(cid); 15381 } else { 15382 boolean mounted = PackageHelper.isContainerMounted(cid); 15383 if (!mounted) { 15384 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15385 Process.SYSTEM_UID); 15386 if (newMountPath != null) { 15387 setMountPath(newMountPath); 15388 } else { 15389 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15390 } 15391 } 15392 } 15393 return status; 15394 } 15395 15396 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15397 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15398 String newMountPath = null; 15399 if (PackageHelper.isContainerMounted(cid)) { 15400 // Unmount the container 15401 if (!PackageHelper.unMountSdDir(cid)) { 15402 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15403 return false; 15404 } 15405 } 15406 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15407 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15408 " which might be stale. Will try to clean up."); 15409 // Clean up the stale container and proceed to recreate. 15410 if (!PackageHelper.destroySdDir(newCacheId)) { 15411 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15412 return false; 15413 } 15414 // Successfully cleaned up stale container. Try to rename again. 15415 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15416 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15417 + " inspite of cleaning it up."); 15418 return false; 15419 } 15420 } 15421 if (!PackageHelper.isContainerMounted(newCacheId)) { 15422 Slog.w(TAG, "Mounting container " + newCacheId); 15423 newMountPath = PackageHelper.mountSdDir(newCacheId, 15424 getEncryptKey(), Process.SYSTEM_UID); 15425 } else { 15426 newMountPath = PackageHelper.getSdDir(newCacheId); 15427 } 15428 if (newMountPath == null) { 15429 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15430 return false; 15431 } 15432 Log.i(TAG, "Succesfully renamed " + cid + 15433 " to " + newCacheId + 15434 " at new path: " + newMountPath); 15435 cid = newCacheId; 15436 15437 final File beforeCodeFile = new File(packagePath); 15438 setMountPath(newMountPath); 15439 final File afterCodeFile = new File(packagePath); 15440 15441 // Reflect the rename in scanned details 15442 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15443 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15444 afterCodeFile, pkg.baseCodePath)); 15445 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15446 afterCodeFile, pkg.splitCodePaths)); 15447 15448 // Reflect the rename in app info 15449 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15450 pkg.setApplicationInfoCodePath(pkg.codePath); 15451 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15452 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15453 pkg.setApplicationInfoResourcePath(pkg.codePath); 15454 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15455 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15456 15457 return true; 15458 } 15459 15460 private void setMountPath(String mountPath) { 15461 final File mountFile = new File(mountPath); 15462 15463 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15464 if (monolithicFile.exists()) { 15465 packagePath = monolithicFile.getAbsolutePath(); 15466 if (isFwdLocked()) { 15467 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15468 } else { 15469 resourcePath = packagePath; 15470 } 15471 } else { 15472 packagePath = mountFile.getAbsolutePath(); 15473 resourcePath = packagePath; 15474 } 15475 } 15476 15477 int doPostInstall(int status, int uid) { 15478 if (status != PackageManager.INSTALL_SUCCEEDED) { 15479 cleanUp(); 15480 } else { 15481 final int groupOwner; 15482 final String protectedFile; 15483 if (isFwdLocked()) { 15484 groupOwner = UserHandle.getSharedAppGid(uid); 15485 protectedFile = RES_FILE_NAME; 15486 } else { 15487 groupOwner = -1; 15488 protectedFile = null; 15489 } 15490 15491 if (uid < Process.FIRST_APPLICATION_UID 15492 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15493 Slog.e(TAG, "Failed to finalize " + cid); 15494 PackageHelper.destroySdDir(cid); 15495 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15496 } 15497 15498 boolean mounted = PackageHelper.isContainerMounted(cid); 15499 if (!mounted) { 15500 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15501 } 15502 } 15503 return status; 15504 } 15505 15506 private void cleanUp() { 15507 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15508 15509 // Destroy secure container 15510 PackageHelper.destroySdDir(cid); 15511 } 15512 15513 private List<String> getAllCodePaths() { 15514 final File codeFile = new File(getCodePath()); 15515 if (codeFile != null && codeFile.exists()) { 15516 try { 15517 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15518 return pkg.getAllCodePaths(); 15519 } catch (PackageParserException e) { 15520 // Ignored; we tried our best 15521 } 15522 } 15523 return Collections.EMPTY_LIST; 15524 } 15525 15526 void cleanUpResourcesLI() { 15527 // Enumerate all code paths before deleting 15528 cleanUpResourcesLI(getAllCodePaths()); 15529 } 15530 15531 private void cleanUpResourcesLI(List<String> allCodePaths) { 15532 cleanUp(); 15533 removeDexFiles(allCodePaths, instructionSets); 15534 } 15535 15536 String getPackageName() { 15537 return getAsecPackageName(cid); 15538 } 15539 15540 boolean doPostDeleteLI(boolean delete) { 15541 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15542 final List<String> allCodePaths = getAllCodePaths(); 15543 boolean mounted = PackageHelper.isContainerMounted(cid); 15544 if (mounted) { 15545 // Unmount first 15546 if (PackageHelper.unMountSdDir(cid)) { 15547 mounted = false; 15548 } 15549 } 15550 if (!mounted && delete) { 15551 cleanUpResourcesLI(allCodePaths); 15552 } 15553 return !mounted; 15554 } 15555 15556 @Override 15557 int doPreCopy() { 15558 if (isFwdLocked()) { 15559 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15560 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15561 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15562 } 15563 } 15564 15565 return PackageManager.INSTALL_SUCCEEDED; 15566 } 15567 15568 @Override 15569 int doPostCopy(int uid) { 15570 if (isFwdLocked()) { 15571 if (uid < Process.FIRST_APPLICATION_UID 15572 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15573 RES_FILE_NAME)) { 15574 Slog.e(TAG, "Failed to finalize " + cid); 15575 PackageHelper.destroySdDir(cid); 15576 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15577 } 15578 } 15579 15580 return PackageManager.INSTALL_SUCCEEDED; 15581 } 15582 } 15583 15584 /** 15585 * Logic to handle movement of existing installed applications. 15586 */ 15587 class MoveInstallArgs extends InstallArgs { 15588 private File codeFile; 15589 private File resourceFile; 15590 15591 /** New install */ 15592 MoveInstallArgs(InstallParams params) { 15593 super(params.origin, params.move, params.observer, params.installFlags, 15594 params.installerPackageName, params.volumeUuid, 15595 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15596 params.grantedRuntimePermissions, 15597 params.traceMethod, params.traceCookie, params.certificates, 15598 params.installReason); 15599 } 15600 15601 int copyApk(IMediaContainerService imcs, boolean temp) { 15602 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15603 + move.fromUuid + " to " + move.toUuid); 15604 synchronized (mInstaller) { 15605 try { 15606 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15607 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15608 } catch (InstallerException e) { 15609 Slog.w(TAG, "Failed to move app", e); 15610 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15611 } 15612 } 15613 15614 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15615 resourceFile = codeFile; 15616 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15617 15618 return PackageManager.INSTALL_SUCCEEDED; 15619 } 15620 15621 int doPreInstall(int status) { 15622 if (status != PackageManager.INSTALL_SUCCEEDED) { 15623 cleanUp(move.toUuid); 15624 } 15625 return status; 15626 } 15627 15628 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15629 if (status != PackageManager.INSTALL_SUCCEEDED) { 15630 cleanUp(move.toUuid); 15631 return false; 15632 } 15633 15634 // Reflect the move in app info 15635 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15636 pkg.setApplicationInfoCodePath(pkg.codePath); 15637 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15638 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15639 pkg.setApplicationInfoResourcePath(pkg.codePath); 15640 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15641 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15642 15643 return true; 15644 } 15645 15646 int doPostInstall(int status, int uid) { 15647 if (status == PackageManager.INSTALL_SUCCEEDED) { 15648 cleanUp(move.fromUuid); 15649 } else { 15650 cleanUp(move.toUuid); 15651 } 15652 return status; 15653 } 15654 15655 @Override 15656 String getCodePath() { 15657 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15658 } 15659 15660 @Override 15661 String getResourcePath() { 15662 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15663 } 15664 15665 private boolean cleanUp(String volumeUuid) { 15666 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15667 move.dataAppName); 15668 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15669 final int[] userIds = sUserManager.getUserIds(); 15670 synchronized (mInstallLock) { 15671 // Clean up both app data and code 15672 // All package moves are frozen until finished 15673 for (int userId : userIds) { 15674 try { 15675 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15676 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15677 } catch (InstallerException e) { 15678 Slog.w(TAG, String.valueOf(e)); 15679 } 15680 } 15681 removeCodePathLI(codeFile); 15682 } 15683 return true; 15684 } 15685 15686 void cleanUpResourcesLI() { 15687 throw new UnsupportedOperationException(); 15688 } 15689 15690 boolean doPostDeleteLI(boolean delete) { 15691 throw new UnsupportedOperationException(); 15692 } 15693 } 15694 15695 static String getAsecPackageName(String packageCid) { 15696 int idx = packageCid.lastIndexOf("-"); 15697 if (idx == -1) { 15698 return packageCid; 15699 } 15700 return packageCid.substring(0, idx); 15701 } 15702 15703 // Utility method used to create code paths based on package name and available index. 15704 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15705 String idxStr = ""; 15706 int idx = 1; 15707 // Fall back to default value of idx=1 if prefix is not 15708 // part of oldCodePath 15709 if (oldCodePath != null) { 15710 String subStr = oldCodePath; 15711 // Drop the suffix right away 15712 if (suffix != null && subStr.endsWith(suffix)) { 15713 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15714 } 15715 // If oldCodePath already contains prefix find out the 15716 // ending index to either increment or decrement. 15717 int sidx = subStr.lastIndexOf(prefix); 15718 if (sidx != -1) { 15719 subStr = subStr.substring(sidx + prefix.length()); 15720 if (subStr != null) { 15721 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15722 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15723 } 15724 try { 15725 idx = Integer.parseInt(subStr); 15726 if (idx <= 1) { 15727 idx++; 15728 } else { 15729 idx--; 15730 } 15731 } catch(NumberFormatException e) { 15732 } 15733 } 15734 } 15735 } 15736 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15737 return prefix + idxStr; 15738 } 15739 15740 private File getNextCodePath(File targetDir, String packageName) { 15741 File result; 15742 SecureRandom random = new SecureRandom(); 15743 byte[] bytes = new byte[16]; 15744 do { 15745 random.nextBytes(bytes); 15746 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15747 result = new File(targetDir, packageName + "-" + suffix); 15748 } while (result.exists()); 15749 return result; 15750 } 15751 15752 // Utility method that returns the relative package path with respect 15753 // to the installation directory. Like say for /data/data/com.test-1.apk 15754 // string com.test-1 is returned. 15755 static String deriveCodePathName(String codePath) { 15756 if (codePath == null) { 15757 return null; 15758 } 15759 final File codeFile = new File(codePath); 15760 final String name = codeFile.getName(); 15761 if (codeFile.isDirectory()) { 15762 return name; 15763 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15764 final int lastDot = name.lastIndexOf('.'); 15765 return name.substring(0, lastDot); 15766 } else { 15767 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15768 return null; 15769 } 15770 } 15771 15772 static class PackageInstalledInfo { 15773 String name; 15774 int uid; 15775 // The set of users that originally had this package installed. 15776 int[] origUsers; 15777 // The set of users that now have this package installed. 15778 int[] newUsers; 15779 PackageParser.Package pkg; 15780 int returnCode; 15781 String returnMsg; 15782 PackageRemovedInfo removedInfo; 15783 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15784 15785 public void setError(int code, String msg) { 15786 setReturnCode(code); 15787 setReturnMessage(msg); 15788 Slog.w(TAG, msg); 15789 } 15790 15791 public void setError(String msg, PackageParserException e) { 15792 setReturnCode(e.error); 15793 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15794 Slog.w(TAG, msg, e); 15795 } 15796 15797 public void setError(String msg, PackageManagerException e) { 15798 returnCode = e.error; 15799 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15800 Slog.w(TAG, msg, e); 15801 } 15802 15803 public void setReturnCode(int returnCode) { 15804 this.returnCode = returnCode; 15805 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15806 for (int i = 0; i < childCount; i++) { 15807 addedChildPackages.valueAt(i).returnCode = returnCode; 15808 } 15809 } 15810 15811 private void setReturnMessage(String returnMsg) { 15812 this.returnMsg = returnMsg; 15813 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15814 for (int i = 0; i < childCount; i++) { 15815 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15816 } 15817 } 15818 15819 // In some error cases we want to convey more info back to the observer 15820 String origPackage; 15821 String origPermission; 15822 } 15823 15824 /* 15825 * Install a non-existing package. 15826 */ 15827 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15828 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15829 PackageInstalledInfo res, int installReason) { 15830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15831 15832 // Remember this for later, in case we need to rollback this install 15833 String pkgName = pkg.packageName; 15834 15835 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15836 15837 synchronized(mPackages) { 15838 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15839 if (renamedPackage != null) { 15840 // A package with the same name is already installed, though 15841 // it has been renamed to an older name. The package we 15842 // are trying to install should be installed as an update to 15843 // the existing one, but that has not been requested, so bail. 15844 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15845 + " without first uninstalling package running as " 15846 + renamedPackage); 15847 return; 15848 } 15849 if (mPackages.containsKey(pkgName)) { 15850 // Don't allow installation over an existing package with the same name. 15851 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15852 + " without first uninstalling."); 15853 return; 15854 } 15855 } 15856 15857 try { 15858 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15859 System.currentTimeMillis(), user); 15860 15861 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15862 15863 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15864 prepareAppDataAfterInstallLIF(newPackage); 15865 15866 } else { 15867 // Remove package from internal structures, but keep around any 15868 // data that might have already existed 15869 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15870 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15871 } 15872 } catch (PackageManagerException e) { 15873 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15874 } 15875 15876 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15877 } 15878 15879 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15880 // Can't rotate keys during boot or if sharedUser. 15881 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15882 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15883 return false; 15884 } 15885 // app is using upgradeKeySets; make sure all are valid 15886 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15887 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15888 for (int i = 0; i < upgradeKeySets.length; i++) { 15889 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15890 Slog.wtf(TAG, "Package " 15891 + (oldPs.name != null ? oldPs.name : "<null>") 15892 + " contains upgrade-key-set reference to unknown key-set: " 15893 + upgradeKeySets[i] 15894 + " reverting to signatures check."); 15895 return false; 15896 } 15897 } 15898 return true; 15899 } 15900 15901 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15902 // Upgrade keysets are being used. Determine if new package has a superset of the 15903 // required keys. 15904 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15905 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15906 for (int i = 0; i < upgradeKeySets.length; i++) { 15907 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15908 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15909 return true; 15910 } 15911 } 15912 return false; 15913 } 15914 15915 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15916 try (DigestInputStream digestStream = 15917 new DigestInputStream(new FileInputStream(file), digest)) { 15918 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15919 } 15920 } 15921 15922 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15923 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15924 int installReason) { 15925 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15926 15927 final PackageParser.Package oldPackage; 15928 final String pkgName = pkg.packageName; 15929 final int[] allUsers; 15930 final int[] installedUsers; 15931 15932 synchronized(mPackages) { 15933 oldPackage = mPackages.get(pkgName); 15934 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15935 15936 // don't allow upgrade to target a release SDK from a pre-release SDK 15937 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15938 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15939 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15940 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15941 if (oldTargetsPreRelease 15942 && !newTargetsPreRelease 15943 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15944 Slog.w(TAG, "Can't install package targeting released sdk"); 15945 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15946 return; 15947 } 15948 15949 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15950 15951 // verify signatures are valid 15952 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15953 if (!checkUpgradeKeySetLP(ps, pkg)) { 15954 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15955 "New package not signed by keys specified by upgrade-keysets: " 15956 + pkgName); 15957 return; 15958 } 15959 } else { 15960 // default to original signature matching 15961 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15962 != PackageManager.SIGNATURE_MATCH) { 15963 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15964 "New package has a different signature: " + pkgName); 15965 return; 15966 } 15967 } 15968 15969 // don't allow a system upgrade unless the upgrade hash matches 15970 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15971 byte[] digestBytes = null; 15972 try { 15973 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15974 updateDigest(digest, new File(pkg.baseCodePath)); 15975 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15976 for (String path : pkg.splitCodePaths) { 15977 updateDigest(digest, new File(path)); 15978 } 15979 } 15980 digestBytes = digest.digest(); 15981 } catch (NoSuchAlgorithmException | IOException e) { 15982 res.setError(INSTALL_FAILED_INVALID_APK, 15983 "Could not compute hash: " + pkgName); 15984 return; 15985 } 15986 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15987 res.setError(INSTALL_FAILED_INVALID_APK, 15988 "New package fails restrict-update check: " + pkgName); 15989 return; 15990 } 15991 // retain upgrade restriction 15992 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15993 } 15994 15995 // Check for shared user id changes 15996 String invalidPackageName = 15997 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15998 if (invalidPackageName != null) { 15999 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16000 "Package " + invalidPackageName + " tried to change user " 16001 + oldPackage.mSharedUserId); 16002 return; 16003 } 16004 16005 // In case of rollback, remember per-user/profile install state 16006 allUsers = sUserManager.getUserIds(); 16007 installedUsers = ps.queryInstalledUsers(allUsers, true); 16008 16009 // don't allow an upgrade from full to ephemeral 16010 if (isInstantApp) { 16011 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16012 for (int currentUser : allUsers) { 16013 if (!ps.getInstantApp(currentUser)) { 16014 // can't downgrade from full to instant 16015 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16016 + " for user: " + currentUser); 16017 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16018 return; 16019 } 16020 } 16021 } else if (!ps.getInstantApp(user.getIdentifier())) { 16022 // can't downgrade from full to instant 16023 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16024 + " for user: " + user.getIdentifier()); 16025 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16026 return; 16027 } 16028 } 16029 } 16030 16031 // Update what is removed 16032 res.removedInfo = new PackageRemovedInfo(); 16033 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16034 res.removedInfo.removedPackage = oldPackage.packageName; 16035 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16036 res.removedInfo.isUpdate = true; 16037 res.removedInfo.origUsers = installedUsers; 16038 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16039 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16040 for (int i = 0; i < installedUsers.length; i++) { 16041 final int userId = installedUsers[i]; 16042 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16043 } 16044 16045 final int childCount = (oldPackage.childPackages != null) 16046 ? oldPackage.childPackages.size() : 0; 16047 for (int i = 0; i < childCount; i++) { 16048 boolean childPackageUpdated = false; 16049 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16050 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16051 if (res.addedChildPackages != null) { 16052 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16053 if (childRes != null) { 16054 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16055 childRes.removedInfo.removedPackage = childPkg.packageName; 16056 childRes.removedInfo.isUpdate = true; 16057 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16058 childPackageUpdated = true; 16059 } 16060 } 16061 if (!childPackageUpdated) { 16062 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16063 childRemovedRes.removedPackage = childPkg.packageName; 16064 childRemovedRes.isUpdate = false; 16065 childRemovedRes.dataRemoved = true; 16066 synchronized (mPackages) { 16067 if (childPs != null) { 16068 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16069 } 16070 } 16071 if (res.removedInfo.removedChildPackages == null) { 16072 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16073 } 16074 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16075 } 16076 } 16077 16078 boolean sysPkg = (isSystemApp(oldPackage)); 16079 if (sysPkg) { 16080 // Set the system/privileged flags as needed 16081 final boolean privileged = 16082 (oldPackage.applicationInfo.privateFlags 16083 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16084 final int systemPolicyFlags = policyFlags 16085 | PackageParser.PARSE_IS_SYSTEM 16086 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16087 16088 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16089 user, allUsers, installerPackageName, res, installReason); 16090 } else { 16091 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16092 user, allUsers, installerPackageName, res, installReason); 16093 } 16094 } 16095 16096 public List<String> getPreviousCodePaths(String packageName) { 16097 final PackageSetting ps = mSettings.mPackages.get(packageName); 16098 final List<String> result = new ArrayList<String>(); 16099 if (ps != null && ps.oldCodePaths != null) { 16100 result.addAll(ps.oldCodePaths); 16101 } 16102 return result; 16103 } 16104 16105 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16106 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16107 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16108 int installReason) { 16109 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16110 + deletedPackage); 16111 16112 String pkgName = deletedPackage.packageName; 16113 boolean deletedPkg = true; 16114 boolean addedPkg = false; 16115 boolean updatedSettings = false; 16116 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16117 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16118 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16119 16120 final long origUpdateTime = (pkg.mExtras != null) 16121 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16122 16123 // First delete the existing package while retaining the data directory 16124 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16125 res.removedInfo, true, pkg)) { 16126 // If the existing package wasn't successfully deleted 16127 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16128 deletedPkg = false; 16129 } else { 16130 // Successfully deleted the old package; proceed with replace. 16131 16132 // If deleted package lived in a container, give users a chance to 16133 // relinquish resources before killing. 16134 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16135 if (DEBUG_INSTALL) { 16136 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16137 } 16138 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16139 final ArrayList<String> pkgList = new ArrayList<String>(1); 16140 pkgList.add(deletedPackage.applicationInfo.packageName); 16141 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16142 } 16143 16144 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16145 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16146 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16147 16148 try { 16149 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16150 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16151 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16152 installReason); 16153 16154 // Update the in-memory copy of the previous code paths. 16155 PackageSetting ps = mSettings.mPackages.get(pkgName); 16156 if (!killApp) { 16157 if (ps.oldCodePaths == null) { 16158 ps.oldCodePaths = new ArraySet<>(); 16159 } 16160 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16161 if (deletedPackage.splitCodePaths != null) { 16162 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16163 } 16164 } else { 16165 ps.oldCodePaths = null; 16166 } 16167 if (ps.childPackageNames != null) { 16168 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16169 final String childPkgName = ps.childPackageNames.get(i); 16170 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16171 childPs.oldCodePaths = ps.oldCodePaths; 16172 } 16173 } 16174 // set instant app status, but, only if it's explicitly specified 16175 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16176 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16177 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16178 prepareAppDataAfterInstallLIF(newPackage); 16179 addedPkg = true; 16180 mDexManager.notifyPackageUpdated(newPackage.packageName, 16181 newPackage.baseCodePath, newPackage.splitCodePaths); 16182 } catch (PackageManagerException e) { 16183 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16184 } 16185 } 16186 16187 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16188 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16189 16190 // Revert all internal state mutations and added folders for the failed install 16191 if (addedPkg) { 16192 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16193 res.removedInfo, true, null); 16194 } 16195 16196 // Restore the old package 16197 if (deletedPkg) { 16198 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16199 File restoreFile = new File(deletedPackage.codePath); 16200 // Parse old package 16201 boolean oldExternal = isExternal(deletedPackage); 16202 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16203 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16204 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16205 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16206 try { 16207 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16208 null); 16209 } catch (PackageManagerException e) { 16210 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16211 + e.getMessage()); 16212 return; 16213 } 16214 16215 synchronized (mPackages) { 16216 // Ensure the installer package name up to date 16217 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16218 16219 // Update permissions for restored package 16220 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16221 16222 mSettings.writeLPr(); 16223 } 16224 16225 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16226 } 16227 } else { 16228 synchronized (mPackages) { 16229 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16230 if (ps != null) { 16231 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16232 if (res.removedInfo.removedChildPackages != null) { 16233 final int childCount = res.removedInfo.removedChildPackages.size(); 16234 // Iterate in reverse as we may modify the collection 16235 for (int i = childCount - 1; i >= 0; i--) { 16236 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16237 if (res.addedChildPackages.containsKey(childPackageName)) { 16238 res.removedInfo.removedChildPackages.removeAt(i); 16239 } else { 16240 PackageRemovedInfo childInfo = res.removedInfo 16241 .removedChildPackages.valueAt(i); 16242 childInfo.removedForAllUsers = mPackages.get( 16243 childInfo.removedPackage) == null; 16244 } 16245 } 16246 } 16247 } 16248 } 16249 } 16250 } 16251 16252 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16253 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16254 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16255 int installReason) { 16256 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16257 + ", old=" + deletedPackage); 16258 16259 final boolean disabledSystem; 16260 16261 // Remove existing system package 16262 removePackageLI(deletedPackage, true); 16263 16264 synchronized (mPackages) { 16265 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16266 } 16267 if (!disabledSystem) { 16268 // We didn't need to disable the .apk as a current system package, 16269 // which means we are replacing another update that is already 16270 // installed. We need to make sure to delete the older one's .apk. 16271 res.removedInfo.args = createInstallArgsForExisting(0, 16272 deletedPackage.applicationInfo.getCodePath(), 16273 deletedPackage.applicationInfo.getResourcePath(), 16274 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16275 } else { 16276 res.removedInfo.args = null; 16277 } 16278 16279 // Successfully disabled the old package. Now proceed with re-installation 16280 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16281 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16282 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16283 16284 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16285 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16286 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16287 16288 PackageParser.Package newPackage = null; 16289 try { 16290 // Add the package to the internal data structures 16291 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16292 16293 // Set the update and install times 16294 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16295 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16296 System.currentTimeMillis()); 16297 16298 // Update the package dynamic state if succeeded 16299 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16300 // Now that the install succeeded make sure we remove data 16301 // directories for any child package the update removed. 16302 final int deletedChildCount = (deletedPackage.childPackages != null) 16303 ? deletedPackage.childPackages.size() : 0; 16304 final int newChildCount = (newPackage.childPackages != null) 16305 ? newPackage.childPackages.size() : 0; 16306 for (int i = 0; i < deletedChildCount; i++) { 16307 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16308 boolean childPackageDeleted = true; 16309 for (int j = 0; j < newChildCount; j++) { 16310 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16311 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16312 childPackageDeleted = false; 16313 break; 16314 } 16315 } 16316 if (childPackageDeleted) { 16317 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16318 deletedChildPkg.packageName); 16319 if (ps != null && res.removedInfo.removedChildPackages != null) { 16320 PackageRemovedInfo removedChildRes = res.removedInfo 16321 .removedChildPackages.get(deletedChildPkg.packageName); 16322 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16323 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16324 } 16325 } 16326 } 16327 16328 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16329 installReason); 16330 prepareAppDataAfterInstallLIF(newPackage); 16331 16332 mDexManager.notifyPackageUpdated(newPackage.packageName, 16333 newPackage.baseCodePath, newPackage.splitCodePaths); 16334 } 16335 } catch (PackageManagerException e) { 16336 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16337 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16338 } 16339 16340 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16341 // Re installation failed. Restore old information 16342 // Remove new pkg information 16343 if (newPackage != null) { 16344 removeInstalledPackageLI(newPackage, true); 16345 } 16346 // Add back the old system package 16347 try { 16348 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16349 } catch (PackageManagerException e) { 16350 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16351 } 16352 16353 synchronized (mPackages) { 16354 if (disabledSystem) { 16355 enableSystemPackageLPw(deletedPackage); 16356 } 16357 16358 // Ensure the installer package name up to date 16359 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16360 16361 // Update permissions for restored package 16362 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16363 16364 mSettings.writeLPr(); 16365 } 16366 16367 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16368 + " after failed upgrade"); 16369 } 16370 } 16371 16372 /** 16373 * Checks whether the parent or any of the child packages have a change shared 16374 * user. For a package to be a valid update the shred users of the parent and 16375 * the children should match. We may later support changing child shared users. 16376 * @param oldPkg The updated package. 16377 * @param newPkg The update package. 16378 * @return The shared user that change between the versions. 16379 */ 16380 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16381 PackageParser.Package newPkg) { 16382 // Check parent shared user 16383 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16384 return newPkg.packageName; 16385 } 16386 // Check child shared users 16387 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16388 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16389 for (int i = 0; i < newChildCount; i++) { 16390 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16391 // If this child was present, did it have the same shared user? 16392 for (int j = 0; j < oldChildCount; j++) { 16393 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16394 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16395 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16396 return newChildPkg.packageName; 16397 } 16398 } 16399 } 16400 return null; 16401 } 16402 16403 private void removeNativeBinariesLI(PackageSetting ps) { 16404 // Remove the lib path for the parent package 16405 if (ps != null) { 16406 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16407 // Remove the lib path for the child packages 16408 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16409 for (int i = 0; i < childCount; i++) { 16410 PackageSetting childPs = null; 16411 synchronized (mPackages) { 16412 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16413 } 16414 if (childPs != null) { 16415 NativeLibraryHelper.removeNativeBinariesLI(childPs 16416 .legacyNativeLibraryPathString); 16417 } 16418 } 16419 } 16420 } 16421 16422 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16423 // Enable the parent package 16424 mSettings.enableSystemPackageLPw(pkg.packageName); 16425 // Enable the child packages 16426 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16427 for (int i = 0; i < childCount; i++) { 16428 PackageParser.Package childPkg = pkg.childPackages.get(i); 16429 mSettings.enableSystemPackageLPw(childPkg.packageName); 16430 } 16431 } 16432 16433 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16434 PackageParser.Package newPkg) { 16435 // Disable the parent package (parent always replaced) 16436 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16437 // Disable the child packages 16438 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16439 for (int i = 0; i < childCount; i++) { 16440 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16441 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16442 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16443 } 16444 return disabled; 16445 } 16446 16447 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16448 String installerPackageName) { 16449 // Enable the parent package 16450 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16451 // Enable the child packages 16452 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16453 for (int i = 0; i < childCount; i++) { 16454 PackageParser.Package childPkg = pkg.childPackages.get(i); 16455 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16456 } 16457 } 16458 16459 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16460 // Collect all used permissions in the UID 16461 ArraySet<String> usedPermissions = new ArraySet<>(); 16462 final int packageCount = su.packages.size(); 16463 for (int i = 0; i < packageCount; i++) { 16464 PackageSetting ps = su.packages.valueAt(i); 16465 if (ps.pkg == null) { 16466 continue; 16467 } 16468 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16469 for (int j = 0; j < requestedPermCount; j++) { 16470 String permission = ps.pkg.requestedPermissions.get(j); 16471 BasePermission bp = mSettings.mPermissions.get(permission); 16472 if (bp != null) { 16473 usedPermissions.add(permission); 16474 } 16475 } 16476 } 16477 16478 PermissionsState permissionsState = su.getPermissionsState(); 16479 // Prune install permissions 16480 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16481 final int installPermCount = installPermStates.size(); 16482 for (int i = installPermCount - 1; i >= 0; i--) { 16483 PermissionState permissionState = installPermStates.get(i); 16484 if (!usedPermissions.contains(permissionState.getName())) { 16485 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16486 if (bp != null) { 16487 permissionsState.revokeInstallPermission(bp); 16488 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16489 PackageManager.MASK_PERMISSION_FLAGS, 0); 16490 } 16491 } 16492 } 16493 16494 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16495 16496 // Prune runtime permissions 16497 for (int userId : allUserIds) { 16498 List<PermissionState> runtimePermStates = permissionsState 16499 .getRuntimePermissionStates(userId); 16500 final int runtimePermCount = runtimePermStates.size(); 16501 for (int i = runtimePermCount - 1; i >= 0; i--) { 16502 PermissionState permissionState = runtimePermStates.get(i); 16503 if (!usedPermissions.contains(permissionState.getName())) { 16504 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16505 if (bp != null) { 16506 permissionsState.revokeRuntimePermission(bp, userId); 16507 permissionsState.updatePermissionFlags(bp, userId, 16508 PackageManager.MASK_PERMISSION_FLAGS, 0); 16509 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16510 runtimePermissionChangedUserIds, userId); 16511 } 16512 } 16513 } 16514 } 16515 16516 return runtimePermissionChangedUserIds; 16517 } 16518 16519 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16520 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16521 // Update the parent package setting 16522 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16523 res, user, installReason); 16524 // Update the child packages setting 16525 final int childCount = (newPackage.childPackages != null) 16526 ? newPackage.childPackages.size() : 0; 16527 for (int i = 0; i < childCount; i++) { 16528 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16529 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16530 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16531 childRes.origUsers, childRes, user, installReason); 16532 } 16533 } 16534 16535 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16536 String installerPackageName, int[] allUsers, int[] installedForUsers, 16537 PackageInstalledInfo res, UserHandle user, int installReason) { 16538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16539 16540 String pkgName = newPackage.packageName; 16541 synchronized (mPackages) { 16542 //write settings. the installStatus will be incomplete at this stage. 16543 //note that the new package setting would have already been 16544 //added to mPackages. It hasn't been persisted yet. 16545 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16546 // TODO: Remove this write? It's also written at the end of this method 16547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16548 mSettings.writeLPr(); 16549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16550 } 16551 16552 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16553 synchronized (mPackages) { 16554 updatePermissionsLPw(newPackage.packageName, newPackage, 16555 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16556 ? UPDATE_PERMISSIONS_ALL : 0)); 16557 // For system-bundled packages, we assume that installing an upgraded version 16558 // of the package implies that the user actually wants to run that new code, 16559 // so we enable the package. 16560 PackageSetting ps = mSettings.mPackages.get(pkgName); 16561 final int userId = user.getIdentifier(); 16562 if (ps != null) { 16563 if (isSystemApp(newPackage)) { 16564 if (DEBUG_INSTALL) { 16565 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16566 } 16567 // Enable system package for requested users 16568 if (res.origUsers != null) { 16569 for (int origUserId : res.origUsers) { 16570 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16571 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16572 origUserId, installerPackageName); 16573 } 16574 } 16575 } 16576 // Also convey the prior install/uninstall state 16577 if (allUsers != null && installedForUsers != null) { 16578 for (int currentUserId : allUsers) { 16579 final boolean installed = ArrayUtils.contains( 16580 installedForUsers, currentUserId); 16581 if (DEBUG_INSTALL) { 16582 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16583 } 16584 ps.setInstalled(installed, currentUserId); 16585 } 16586 // these install state changes will be persisted in the 16587 // upcoming call to mSettings.writeLPr(). 16588 } 16589 } 16590 // It's implied that when a user requests installation, they want the app to be 16591 // installed and enabled. 16592 if (userId != UserHandle.USER_ALL) { 16593 ps.setInstalled(true, userId); 16594 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16595 } 16596 16597 // When replacing an existing package, preserve the original install reason for all 16598 // users that had the package installed before. 16599 final Set<Integer> previousUserIds = new ArraySet<>(); 16600 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16601 final int installReasonCount = res.removedInfo.installReasons.size(); 16602 for (int i = 0; i < installReasonCount; i++) { 16603 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16604 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16605 ps.setInstallReason(previousInstallReason, previousUserId); 16606 previousUserIds.add(previousUserId); 16607 } 16608 } 16609 16610 // Set install reason for users that are having the package newly installed. 16611 if (userId == UserHandle.USER_ALL) { 16612 for (int currentUserId : sUserManager.getUserIds()) { 16613 if (!previousUserIds.contains(currentUserId)) { 16614 ps.setInstallReason(installReason, currentUserId); 16615 } 16616 } 16617 } else if (!previousUserIds.contains(userId)) { 16618 ps.setInstallReason(installReason, userId); 16619 } 16620 mSettings.writeKernelMappingLPr(ps); 16621 } 16622 res.name = pkgName; 16623 res.uid = newPackage.applicationInfo.uid; 16624 res.pkg = newPackage; 16625 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16626 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16627 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16628 //to update install status 16629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16630 mSettings.writeLPr(); 16631 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16632 } 16633 16634 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16635 } 16636 16637 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16638 try { 16639 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16640 installPackageLI(args, res); 16641 } finally { 16642 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16643 } 16644 } 16645 16646 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16647 final int installFlags = args.installFlags; 16648 final String installerPackageName = args.installerPackageName; 16649 final String volumeUuid = args.volumeUuid; 16650 final File tmpPackageFile = new File(args.getCodePath()); 16651 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16652 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16653 || (args.volumeUuid != null)); 16654 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16655 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16656 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16657 boolean replace = false; 16658 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16659 if (args.move != null) { 16660 // moving a complete application; perform an initial scan on the new install location 16661 scanFlags |= SCAN_INITIAL; 16662 } 16663 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16664 scanFlags |= SCAN_DONT_KILL_APP; 16665 } 16666 if (instantApp) { 16667 scanFlags |= SCAN_AS_INSTANT_APP; 16668 } 16669 if (fullApp) { 16670 scanFlags |= SCAN_AS_FULL_APP; 16671 } 16672 16673 // Result object to be returned 16674 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16675 16676 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16677 16678 // Sanity check 16679 if (instantApp && (forwardLocked || onExternal)) { 16680 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16681 + " external=" + onExternal); 16682 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16683 return; 16684 } 16685 16686 // Retrieve PackageSettings and parse package 16687 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16688 | PackageParser.PARSE_ENFORCE_CODE 16689 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16690 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16691 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16692 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16693 PackageParser pp = new PackageParser(); 16694 pp.setSeparateProcesses(mSeparateProcesses); 16695 pp.setDisplayMetrics(mMetrics); 16696 pp.setCallback(mPackageParserCallback); 16697 16698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16699 final PackageParser.Package pkg; 16700 try { 16701 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16702 } catch (PackageParserException e) { 16703 res.setError("Failed parse during installPackageLI", e); 16704 return; 16705 } finally { 16706 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16707 } 16708 16709 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16710 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16711 Slog.w(TAG, "Instant app package " + pkg.packageName 16712 + " does not target O, this will be a fatal error."); 16713 // STOPSHIP: Make this a fatal error 16714 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16715 } 16716 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16717 Slog.w(TAG, "Instant app package " + pkg.packageName 16718 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16719 // STOPSHIP: Make this a fatal error 16720 pkg.applicationInfo.targetSandboxVersion = 2; 16721 } 16722 16723 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16724 // Static shared libraries have synthetic package names 16725 renameStaticSharedLibraryPackage(pkg); 16726 16727 // No static shared libs on external storage 16728 if (onExternal) { 16729 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16730 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16731 "Packages declaring static-shared libs cannot be updated"); 16732 return; 16733 } 16734 } 16735 16736 // If we are installing a clustered package add results for the children 16737 if (pkg.childPackages != null) { 16738 synchronized (mPackages) { 16739 final int childCount = pkg.childPackages.size(); 16740 for (int i = 0; i < childCount; i++) { 16741 PackageParser.Package childPkg = pkg.childPackages.get(i); 16742 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16743 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16744 childRes.pkg = childPkg; 16745 childRes.name = childPkg.packageName; 16746 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16747 if (childPs != null) { 16748 childRes.origUsers = childPs.queryInstalledUsers( 16749 sUserManager.getUserIds(), true); 16750 } 16751 if ((mPackages.containsKey(childPkg.packageName))) { 16752 childRes.removedInfo = new PackageRemovedInfo(); 16753 childRes.removedInfo.removedPackage = childPkg.packageName; 16754 } 16755 if (res.addedChildPackages == null) { 16756 res.addedChildPackages = new ArrayMap<>(); 16757 } 16758 res.addedChildPackages.put(childPkg.packageName, childRes); 16759 } 16760 } 16761 } 16762 16763 // If package doesn't declare API override, mark that we have an install 16764 // time CPU ABI override. 16765 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16766 pkg.cpuAbiOverride = args.abiOverride; 16767 } 16768 16769 String pkgName = res.name = pkg.packageName; 16770 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16771 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16772 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16773 return; 16774 } 16775 } 16776 16777 try { 16778 // either use what we've been given or parse directly from the APK 16779 if (args.certificates != null) { 16780 try { 16781 PackageParser.populateCertificates(pkg, args.certificates); 16782 } catch (PackageParserException e) { 16783 // there was something wrong with the certificates we were given; 16784 // try to pull them from the APK 16785 PackageParser.collectCertificates(pkg, parseFlags); 16786 } 16787 } else { 16788 PackageParser.collectCertificates(pkg, parseFlags); 16789 } 16790 } catch (PackageParserException e) { 16791 res.setError("Failed collect during installPackageLI", e); 16792 return; 16793 } 16794 16795 // Get rid of all references to package scan path via parser. 16796 pp = null; 16797 String oldCodePath = null; 16798 boolean systemApp = false; 16799 synchronized (mPackages) { 16800 // Check if installing already existing package 16801 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16802 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16803 if (pkg.mOriginalPackages != null 16804 && pkg.mOriginalPackages.contains(oldName) 16805 && mPackages.containsKey(oldName)) { 16806 // This package is derived from an original package, 16807 // and this device has been updating from that original 16808 // name. We must continue using the original name, so 16809 // rename the new package here. 16810 pkg.setPackageName(oldName); 16811 pkgName = pkg.packageName; 16812 replace = true; 16813 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16814 + oldName + " pkgName=" + pkgName); 16815 } else if (mPackages.containsKey(pkgName)) { 16816 // This package, under its official name, already exists 16817 // on the device; we should replace it. 16818 replace = true; 16819 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16820 } 16821 16822 // Child packages are installed through the parent package 16823 if (pkg.parentPackage != null) { 16824 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16825 "Package " + pkg.packageName + " is child of package " 16826 + pkg.parentPackage.parentPackage + ". Child packages " 16827 + "can be updated only through the parent package."); 16828 return; 16829 } 16830 16831 if (replace) { 16832 // Prevent apps opting out from runtime permissions 16833 PackageParser.Package oldPackage = mPackages.get(pkgName); 16834 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16835 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16836 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16837 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16838 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16839 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16840 + " doesn't support runtime permissions but the old" 16841 + " target SDK " + oldTargetSdk + " does."); 16842 return; 16843 } 16844 // Prevent apps from downgrading their targetSandbox. 16845 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16846 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16847 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16848 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16849 "Package " + pkg.packageName + " new target sandbox " 16850 + newTargetSandbox + " is incompatible with the previous value of" 16851 + oldTargetSandbox + "."); 16852 return; 16853 } 16854 16855 // Prevent installing of child packages 16856 if (oldPackage.parentPackage != null) { 16857 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16858 "Package " + pkg.packageName + " is child of package " 16859 + oldPackage.parentPackage + ". Child packages " 16860 + "can be updated only through the parent package."); 16861 return; 16862 } 16863 } 16864 } 16865 16866 PackageSetting ps = mSettings.mPackages.get(pkgName); 16867 if (ps != null) { 16868 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16869 16870 // Static shared libs have same package with different versions where 16871 // we internally use a synthetic package name to allow multiple versions 16872 // of the same package, therefore we need to compare signatures against 16873 // the package setting for the latest library version. 16874 PackageSetting signatureCheckPs = ps; 16875 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16876 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16877 if (libraryEntry != null) { 16878 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16879 } 16880 } 16881 16882 // Quick sanity check that we're signed correctly if updating; 16883 // we'll check this again later when scanning, but we want to 16884 // bail early here before tripping over redefined permissions. 16885 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16886 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16887 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16888 + pkg.packageName + " upgrade keys do not match the " 16889 + "previously installed version"); 16890 return; 16891 } 16892 } else { 16893 try { 16894 verifySignaturesLP(signatureCheckPs, pkg); 16895 } catch (PackageManagerException e) { 16896 res.setError(e.error, e.getMessage()); 16897 return; 16898 } 16899 } 16900 16901 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16902 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16903 systemApp = (ps.pkg.applicationInfo.flags & 16904 ApplicationInfo.FLAG_SYSTEM) != 0; 16905 } 16906 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16907 } 16908 16909 int N = pkg.permissions.size(); 16910 for (int i = N-1; i >= 0; i--) { 16911 PackageParser.Permission perm = pkg.permissions.get(i); 16912 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16913 16914 // Don't allow anyone but the platform to define ephemeral permissions. 16915 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16916 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16917 Slog.w(TAG, "Package " + pkg.packageName 16918 + " attempting to delcare ephemeral permission " 16919 + perm.info.name + "; Removing ephemeral."); 16920 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16921 } 16922 // Check whether the newly-scanned package wants to define an already-defined perm 16923 if (bp != null) { 16924 // If the defining package is signed with our cert, it's okay. This 16925 // also includes the "updating the same package" case, of course. 16926 // "updating same package" could also involve key-rotation. 16927 final boolean sigsOk; 16928 if (bp.sourcePackage.equals(pkg.packageName) 16929 && (bp.packageSetting instanceof PackageSetting) 16930 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16931 scanFlags))) { 16932 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16933 } else { 16934 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16935 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16936 } 16937 if (!sigsOk) { 16938 // If the owning package is the system itself, we log but allow 16939 // install to proceed; we fail the install on all other permission 16940 // redefinitions. 16941 if (!bp.sourcePackage.equals("android")) { 16942 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16943 + pkg.packageName + " attempting to redeclare permission " 16944 + perm.info.name + " already owned by " + bp.sourcePackage); 16945 res.origPermission = perm.info.name; 16946 res.origPackage = bp.sourcePackage; 16947 return; 16948 } else { 16949 Slog.w(TAG, "Package " + pkg.packageName 16950 + " attempting to redeclare system permission " 16951 + perm.info.name + "; ignoring new declaration"); 16952 pkg.permissions.remove(i); 16953 } 16954 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16955 // Prevent apps to change protection level to dangerous from any other 16956 // type as this would allow a privilege escalation where an app adds a 16957 // normal/signature permission in other app's group and later redefines 16958 // it as dangerous leading to the group auto-grant. 16959 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16960 == PermissionInfo.PROTECTION_DANGEROUS) { 16961 if (bp != null && !bp.isRuntime()) { 16962 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16963 + "non-runtime permission " + perm.info.name 16964 + " to runtime; keeping old protection level"); 16965 perm.info.protectionLevel = bp.protectionLevel; 16966 } 16967 } 16968 } 16969 } 16970 } 16971 } 16972 16973 if (systemApp) { 16974 if (onExternal) { 16975 // Abort update; system app can't be replaced with app on sdcard 16976 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16977 "Cannot install updates to system apps on sdcard"); 16978 return; 16979 } else if (instantApp) { 16980 // Abort update; system app can't be replaced with an instant app 16981 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16982 "Cannot update a system app with an instant app"); 16983 return; 16984 } 16985 } 16986 16987 if (args.move != null) { 16988 // We did an in-place move, so dex is ready to roll 16989 scanFlags |= SCAN_NO_DEX; 16990 scanFlags |= SCAN_MOVE; 16991 16992 synchronized (mPackages) { 16993 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16994 if (ps == null) { 16995 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16996 "Missing settings for moved package " + pkgName); 16997 } 16998 16999 // We moved the entire application as-is, so bring over the 17000 // previously derived ABI information. 17001 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17002 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17003 } 17004 17005 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17006 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17007 scanFlags |= SCAN_NO_DEX; 17008 17009 try { 17010 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17011 args.abiOverride : pkg.cpuAbiOverride); 17012 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17013 true /*extractLibs*/, mAppLib32InstallDir); 17014 } catch (PackageManagerException pme) { 17015 Slog.e(TAG, "Error deriving application ABI", pme); 17016 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17017 return; 17018 } 17019 17020 // Shared libraries for the package need to be updated. 17021 synchronized (mPackages) { 17022 try { 17023 updateSharedLibrariesLPr(pkg, null); 17024 } catch (PackageManagerException e) { 17025 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17026 } 17027 } 17028 17029 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17030 // Do not run PackageDexOptimizer through the local performDexOpt 17031 // method because `pkg` may not be in `mPackages` yet. 17032 // 17033 // Also, don't fail application installs if the dexopt step fails. 17034 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17035 null /* instructionSets */, false /* checkProfiles */, 17036 getCompilerFilterForReason(REASON_INSTALL), 17037 getOrCreateCompilerPackageStats(pkg), 17038 mDexManager.isUsedByOtherApps(pkg.packageName)); 17039 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17040 17041 // Notify BackgroundDexOptService that the package has been changed. 17042 // If this is an update of a package which used to fail to compile, 17043 // BDOS will remove it from its blacklist. 17044 // TODO: Layering violation 17045 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17046 } 17047 17048 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17049 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17050 return; 17051 } 17052 17053 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17054 17055 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17056 "installPackageLI")) { 17057 if (replace) { 17058 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17059 // Static libs have a synthetic package name containing the version 17060 // and cannot be updated as an update would get a new package name, 17061 // unless this is the exact same version code which is useful for 17062 // development. 17063 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17064 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17065 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17066 + "static-shared libs cannot be updated"); 17067 return; 17068 } 17069 } 17070 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17071 installerPackageName, res, args.installReason); 17072 } else { 17073 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17074 args.user, installerPackageName, volumeUuid, res, args.installReason); 17075 } 17076 } 17077 17078 synchronized (mPackages) { 17079 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17080 if (ps != null) { 17081 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17082 ps.setUpdateAvailable(false /*updateAvailable*/); 17083 } 17084 17085 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17086 for (int i = 0; i < childCount; i++) { 17087 PackageParser.Package childPkg = pkg.childPackages.get(i); 17088 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17089 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17090 if (childPs != null) { 17091 childRes.newUsers = childPs.queryInstalledUsers( 17092 sUserManager.getUserIds(), true); 17093 } 17094 } 17095 17096 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17097 updateSequenceNumberLP(pkgName, res.newUsers); 17098 updateInstantAppInstallerLocked(pkgName); 17099 } 17100 } 17101 } 17102 17103 private void startIntentFilterVerifications(int userId, boolean replacing, 17104 PackageParser.Package pkg) { 17105 if (mIntentFilterVerifierComponent == null) { 17106 Slog.w(TAG, "No IntentFilter verification will not be done as " 17107 + "there is no IntentFilterVerifier available!"); 17108 return; 17109 } 17110 17111 final int verifierUid = getPackageUid( 17112 mIntentFilterVerifierComponent.getPackageName(), 17113 MATCH_DEBUG_TRIAGED_MISSING, 17114 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17115 17116 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17117 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17118 mHandler.sendMessage(msg); 17119 17120 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17121 for (int i = 0; i < childCount; i++) { 17122 PackageParser.Package childPkg = pkg.childPackages.get(i); 17123 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17124 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17125 mHandler.sendMessage(msg); 17126 } 17127 } 17128 17129 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17130 PackageParser.Package pkg) { 17131 int size = pkg.activities.size(); 17132 if (size == 0) { 17133 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17134 "No activity, so no need to verify any IntentFilter!"); 17135 return; 17136 } 17137 17138 final boolean hasDomainURLs = hasDomainURLs(pkg); 17139 if (!hasDomainURLs) { 17140 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17141 "No domain URLs, so no need to verify any IntentFilter!"); 17142 return; 17143 } 17144 17145 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17146 + " if any IntentFilter from the " + size 17147 + " Activities needs verification ..."); 17148 17149 int count = 0; 17150 final String packageName = pkg.packageName; 17151 17152 synchronized (mPackages) { 17153 // If this is a new install and we see that we've already run verification for this 17154 // package, we have nothing to do: it means the state was restored from backup. 17155 if (!replacing) { 17156 IntentFilterVerificationInfo ivi = 17157 mSettings.getIntentFilterVerificationLPr(packageName); 17158 if (ivi != null) { 17159 if (DEBUG_DOMAIN_VERIFICATION) { 17160 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17161 + ivi.getStatusString()); 17162 } 17163 return; 17164 } 17165 } 17166 17167 // If any filters need to be verified, then all need to be. 17168 boolean needToVerify = false; 17169 for (PackageParser.Activity a : pkg.activities) { 17170 for (ActivityIntentInfo filter : a.intents) { 17171 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17172 if (DEBUG_DOMAIN_VERIFICATION) { 17173 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17174 } 17175 needToVerify = true; 17176 break; 17177 } 17178 } 17179 } 17180 17181 if (needToVerify) { 17182 final int verificationId = mIntentFilterVerificationToken++; 17183 for (PackageParser.Activity a : pkg.activities) { 17184 for (ActivityIntentInfo filter : a.intents) { 17185 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17186 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17187 "Verification needed for IntentFilter:" + filter.toString()); 17188 mIntentFilterVerifier.addOneIntentFilterVerification( 17189 verifierUid, userId, verificationId, filter, packageName); 17190 count++; 17191 } 17192 } 17193 } 17194 } 17195 } 17196 17197 if (count > 0) { 17198 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17199 + " IntentFilter verification" + (count > 1 ? "s" : "") 17200 + " for userId:" + userId); 17201 mIntentFilterVerifier.startVerifications(userId); 17202 } else { 17203 if (DEBUG_DOMAIN_VERIFICATION) { 17204 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17205 } 17206 } 17207 } 17208 17209 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17210 final ComponentName cn = filter.activity.getComponentName(); 17211 final String packageName = cn.getPackageName(); 17212 17213 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17214 packageName); 17215 if (ivi == null) { 17216 return true; 17217 } 17218 int status = ivi.getStatus(); 17219 switch (status) { 17220 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17221 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17222 return true; 17223 17224 default: 17225 // Nothing to do 17226 return false; 17227 } 17228 } 17229 17230 private static boolean isMultiArch(ApplicationInfo info) { 17231 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17232 } 17233 17234 private static boolean isExternal(PackageParser.Package pkg) { 17235 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17236 } 17237 17238 private static boolean isExternal(PackageSetting ps) { 17239 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17240 } 17241 17242 private static boolean isSystemApp(PackageParser.Package pkg) { 17243 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17244 } 17245 17246 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17247 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17248 } 17249 17250 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17251 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17252 } 17253 17254 private static boolean isSystemApp(PackageSetting ps) { 17255 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17256 } 17257 17258 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17259 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17260 } 17261 17262 private int packageFlagsToInstallFlags(PackageSetting ps) { 17263 int installFlags = 0; 17264 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17265 // This existing package was an external ASEC install when we have 17266 // the external flag without a UUID 17267 installFlags |= PackageManager.INSTALL_EXTERNAL; 17268 } 17269 if (ps.isForwardLocked()) { 17270 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17271 } 17272 return installFlags; 17273 } 17274 17275 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17276 if (isExternal(pkg)) { 17277 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17278 return StorageManager.UUID_PRIMARY_PHYSICAL; 17279 } else { 17280 return pkg.volumeUuid; 17281 } 17282 } else { 17283 return StorageManager.UUID_PRIVATE_INTERNAL; 17284 } 17285 } 17286 17287 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17288 if (isExternal(pkg)) { 17289 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17290 return mSettings.getExternalVersion(); 17291 } else { 17292 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17293 } 17294 } else { 17295 return mSettings.getInternalVersion(); 17296 } 17297 } 17298 17299 private void deleteTempPackageFiles() { 17300 final FilenameFilter filter = new FilenameFilter() { 17301 public boolean accept(File dir, String name) { 17302 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17303 } 17304 }; 17305 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17306 file.delete(); 17307 } 17308 } 17309 17310 @Override 17311 public void deletePackageAsUser(String packageName, int versionCode, 17312 IPackageDeleteObserver observer, int userId, int flags) { 17313 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17314 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17315 } 17316 17317 @Override 17318 public void deletePackageVersioned(VersionedPackage versionedPackage, 17319 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17320 mContext.enforceCallingOrSelfPermission( 17321 android.Manifest.permission.DELETE_PACKAGES, null); 17322 Preconditions.checkNotNull(versionedPackage); 17323 Preconditions.checkNotNull(observer); 17324 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17325 PackageManager.VERSION_CODE_HIGHEST, 17326 Integer.MAX_VALUE, "versionCode must be >= -1"); 17327 17328 final String packageName = versionedPackage.getPackageName(); 17329 // TODO: We will change version code to long, so in the new API it is long 17330 final int versionCode = (int) versionedPackage.getVersionCode(); 17331 final String internalPackageName; 17332 synchronized (mPackages) { 17333 // Normalize package name to handle renamed packages and static libs 17334 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17335 // TODO: We will change version code to long, so in the new API it is long 17336 (int) versionedPackage.getVersionCode()); 17337 } 17338 17339 final int uid = Binder.getCallingUid(); 17340 if (!isOrphaned(internalPackageName) 17341 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17342 try { 17343 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17344 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17345 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17346 observer.onUserActionRequired(intent); 17347 } catch (RemoteException re) { 17348 } 17349 return; 17350 } 17351 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17352 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17353 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17354 mContext.enforceCallingOrSelfPermission( 17355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17356 "deletePackage for user " + userId); 17357 } 17358 17359 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17360 try { 17361 observer.onPackageDeleted(packageName, 17362 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17363 } catch (RemoteException re) { 17364 } 17365 return; 17366 } 17367 17368 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17369 try { 17370 observer.onPackageDeleted(packageName, 17371 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17372 } catch (RemoteException re) { 17373 } 17374 return; 17375 } 17376 17377 if (DEBUG_REMOVE) { 17378 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17379 + " deleteAllUsers: " + deleteAllUsers + " version=" 17380 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17381 ? "VERSION_CODE_HIGHEST" : versionCode)); 17382 } 17383 // Queue up an async operation since the package deletion may take a little while. 17384 mHandler.post(new Runnable() { 17385 public void run() { 17386 mHandler.removeCallbacks(this); 17387 int returnCode; 17388 if (!deleteAllUsers) { 17389 returnCode = deletePackageX(internalPackageName, versionCode, 17390 userId, deleteFlags); 17391 } else { 17392 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17393 internalPackageName, users); 17394 // If nobody is blocking uninstall, proceed with delete for all users 17395 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17396 returnCode = deletePackageX(internalPackageName, versionCode, 17397 userId, deleteFlags); 17398 } else { 17399 // Otherwise uninstall individually for users with blockUninstalls=false 17400 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17401 for (int userId : users) { 17402 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17403 returnCode = deletePackageX(internalPackageName, versionCode, 17404 userId, userFlags); 17405 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17406 Slog.w(TAG, "Package delete failed for user " + userId 17407 + ", returnCode " + returnCode); 17408 } 17409 } 17410 } 17411 // The app has only been marked uninstalled for certain users. 17412 // We still need to report that delete was blocked 17413 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17414 } 17415 } 17416 try { 17417 observer.onPackageDeleted(packageName, returnCode, null); 17418 } catch (RemoteException e) { 17419 Log.i(TAG, "Observer no longer exists."); 17420 } //end catch 17421 } //end run 17422 }); 17423 } 17424 17425 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17426 if (pkg.staticSharedLibName != null) { 17427 return pkg.manifestPackageName; 17428 } 17429 return pkg.packageName; 17430 } 17431 17432 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17433 // Handle renamed packages 17434 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17435 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17436 17437 // Is this a static library? 17438 SparseArray<SharedLibraryEntry> versionedLib = 17439 mStaticLibsByDeclaringPackage.get(packageName); 17440 if (versionedLib == null || versionedLib.size() <= 0) { 17441 return packageName; 17442 } 17443 17444 // Figure out which lib versions the caller can see 17445 SparseIntArray versionsCallerCanSee = null; 17446 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17447 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17448 && callingAppId != Process.ROOT_UID) { 17449 versionsCallerCanSee = new SparseIntArray(); 17450 String libName = versionedLib.valueAt(0).info.getName(); 17451 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17452 if (uidPackages != null) { 17453 for (String uidPackage : uidPackages) { 17454 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17455 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17456 if (libIdx >= 0) { 17457 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17458 versionsCallerCanSee.append(libVersion, libVersion); 17459 } 17460 } 17461 } 17462 } 17463 17464 // Caller can see nothing - done 17465 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17466 return packageName; 17467 } 17468 17469 // Find the version the caller can see and the app version code 17470 SharedLibraryEntry highestVersion = null; 17471 final int versionCount = versionedLib.size(); 17472 for (int i = 0; i < versionCount; i++) { 17473 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17474 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17475 libEntry.info.getVersion()) < 0) { 17476 continue; 17477 } 17478 // TODO: We will change version code to long, so in the new API it is long 17479 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17480 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17481 if (libVersionCode == versionCode) { 17482 return libEntry.apk; 17483 } 17484 } else if (highestVersion == null) { 17485 highestVersion = libEntry; 17486 } else if (libVersionCode > highestVersion.info 17487 .getDeclaringPackage().getVersionCode()) { 17488 highestVersion = libEntry; 17489 } 17490 } 17491 17492 if (highestVersion != null) { 17493 return highestVersion.apk; 17494 } 17495 17496 return packageName; 17497 } 17498 17499 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17500 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17501 || callingUid == Process.SYSTEM_UID) { 17502 return true; 17503 } 17504 final int callingUserId = UserHandle.getUserId(callingUid); 17505 // If the caller installed the pkgName, then allow it to silently uninstall. 17506 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17507 return true; 17508 } 17509 17510 // Allow package verifier to silently uninstall. 17511 if (mRequiredVerifierPackage != null && 17512 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17513 return true; 17514 } 17515 17516 // Allow package uninstaller to silently uninstall. 17517 if (mRequiredUninstallerPackage != null && 17518 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17519 return true; 17520 } 17521 17522 // Allow storage manager to silently uninstall. 17523 if (mStorageManagerPackage != null && 17524 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17525 return true; 17526 } 17527 return false; 17528 } 17529 17530 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17531 int[] result = EMPTY_INT_ARRAY; 17532 for (int userId : userIds) { 17533 if (getBlockUninstallForUser(packageName, userId)) { 17534 result = ArrayUtils.appendInt(result, userId); 17535 } 17536 } 17537 return result; 17538 } 17539 17540 @Override 17541 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17542 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17543 } 17544 17545 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17546 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17547 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17548 try { 17549 if (dpm != null) { 17550 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17551 /* callingUserOnly =*/ false); 17552 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17553 : deviceOwnerComponentName.getPackageName(); 17554 // Does the package contains the device owner? 17555 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17556 // this check is probably not needed, since DO should be registered as a device 17557 // admin on some user too. (Original bug for this: b/17657954) 17558 if (packageName.equals(deviceOwnerPackageName)) { 17559 return true; 17560 } 17561 // Does it contain a device admin for any user? 17562 int[] users; 17563 if (userId == UserHandle.USER_ALL) { 17564 users = sUserManager.getUserIds(); 17565 } else { 17566 users = new int[]{userId}; 17567 } 17568 for (int i = 0; i < users.length; ++i) { 17569 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17570 return true; 17571 } 17572 } 17573 } 17574 } catch (RemoteException e) { 17575 } 17576 return false; 17577 } 17578 17579 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17580 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17581 } 17582 17583 /** 17584 * This method is an internal method that could be get invoked either 17585 * to delete an installed package or to clean up a failed installation. 17586 * After deleting an installed package, a broadcast is sent to notify any 17587 * listeners that the package has been removed. For cleaning up a failed 17588 * installation, the broadcast is not necessary since the package's 17589 * installation wouldn't have sent the initial broadcast either 17590 * The key steps in deleting a package are 17591 * deleting the package information in internal structures like mPackages, 17592 * deleting the packages base directories through installd 17593 * updating mSettings to reflect current status 17594 * persisting settings for later use 17595 * sending a broadcast if necessary 17596 */ 17597 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17598 final PackageRemovedInfo info = new PackageRemovedInfo(); 17599 final boolean res; 17600 17601 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17602 ? UserHandle.USER_ALL : userId; 17603 17604 if (isPackageDeviceAdmin(packageName, removeUser)) { 17605 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17606 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17607 } 17608 17609 PackageSetting uninstalledPs = null; 17610 PackageParser.Package pkg = null; 17611 17612 // for the uninstall-updates case and restricted profiles, remember the per- 17613 // user handle installed state 17614 int[] allUsers; 17615 synchronized (mPackages) { 17616 uninstalledPs = mSettings.mPackages.get(packageName); 17617 if (uninstalledPs == null) { 17618 Slog.w(TAG, "Not removing non-existent package " + packageName); 17619 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17620 } 17621 17622 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17623 && uninstalledPs.versionCode != versionCode) { 17624 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17625 + uninstalledPs.versionCode + " != " + versionCode); 17626 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17627 } 17628 17629 // Static shared libs can be declared by any package, so let us not 17630 // allow removing a package if it provides a lib others depend on. 17631 pkg = mPackages.get(packageName); 17632 if (pkg != null && pkg.staticSharedLibName != null) { 17633 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17634 pkg.staticSharedLibVersion); 17635 if (libEntry != null) { 17636 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17637 libEntry.info, 0, userId); 17638 if (!ArrayUtils.isEmpty(libClientPackages)) { 17639 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17640 + " hosting lib " + libEntry.info.getName() + " version " 17641 + libEntry.info.getVersion() + " used by " + libClientPackages); 17642 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17643 } 17644 } 17645 } 17646 17647 allUsers = sUserManager.getUserIds(); 17648 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17649 } 17650 17651 final int freezeUser; 17652 if (isUpdatedSystemApp(uninstalledPs) 17653 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17654 // We're downgrading a system app, which will apply to all users, so 17655 // freeze them all during the downgrade 17656 freezeUser = UserHandle.USER_ALL; 17657 } else { 17658 freezeUser = removeUser; 17659 } 17660 17661 synchronized (mInstallLock) { 17662 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17663 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17664 deleteFlags, "deletePackageX")) { 17665 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17666 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17667 } 17668 synchronized (mPackages) { 17669 if (res) { 17670 if (pkg != null) { 17671 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17672 } 17673 updateSequenceNumberLP(packageName, info.removedUsers); 17674 updateInstantAppInstallerLocked(packageName); 17675 } 17676 } 17677 } 17678 17679 if (res) { 17680 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17681 info.sendPackageRemovedBroadcasts(killApp); 17682 info.sendSystemPackageUpdatedBroadcasts(); 17683 info.sendSystemPackageAppearedBroadcasts(); 17684 } 17685 // Force a gc here. 17686 Runtime.getRuntime().gc(); 17687 // Delete the resources here after sending the broadcast to let 17688 // other processes clean up before deleting resources. 17689 if (info.args != null) { 17690 synchronized (mInstallLock) { 17691 info.args.doPostDeleteLI(true); 17692 } 17693 } 17694 17695 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17696 } 17697 17698 class PackageRemovedInfo { 17699 String removedPackage; 17700 int uid = -1; 17701 int removedAppId = -1; 17702 int[] origUsers; 17703 int[] removedUsers = null; 17704 int[] broadcastUsers = null; 17705 SparseArray<Integer> installReasons; 17706 boolean isRemovedPackageSystemUpdate = false; 17707 boolean isUpdate; 17708 boolean dataRemoved; 17709 boolean removedForAllUsers; 17710 boolean isStaticSharedLib; 17711 // Clean up resources deleted packages. 17712 InstallArgs args = null; 17713 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17714 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17715 17716 void sendPackageRemovedBroadcasts(boolean killApp) { 17717 sendPackageRemovedBroadcastInternal(killApp); 17718 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17719 for (int i = 0; i < childCount; i++) { 17720 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17721 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17722 } 17723 } 17724 17725 void sendSystemPackageUpdatedBroadcasts() { 17726 if (isRemovedPackageSystemUpdate) { 17727 sendSystemPackageUpdatedBroadcastsInternal(); 17728 final int childCount = (removedChildPackages != null) 17729 ? removedChildPackages.size() : 0; 17730 for (int i = 0; i < childCount; i++) { 17731 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17732 if (childInfo.isRemovedPackageSystemUpdate) { 17733 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17734 } 17735 } 17736 } 17737 } 17738 17739 void sendSystemPackageAppearedBroadcasts() { 17740 final int packageCount = (appearedChildPackages != null) 17741 ? appearedChildPackages.size() : 0; 17742 for (int i = 0; i < packageCount; i++) { 17743 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17744 sendPackageAddedForNewUsers(installedInfo.name, true, 17745 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17746 } 17747 } 17748 17749 private void sendSystemPackageUpdatedBroadcastsInternal() { 17750 Bundle extras = new Bundle(2); 17751 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17752 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17753 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17754 extras, 0, null, null, null); 17755 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17756 extras, 0, null, null, null); 17757 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17758 null, 0, removedPackage, null, null); 17759 } 17760 17761 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17762 // Don't send static shared library removal broadcasts as these 17763 // libs are visible only the the apps that depend on them an one 17764 // cannot remove the library if it has a dependency. 17765 if (isStaticSharedLib) { 17766 return; 17767 } 17768 Bundle extras = new Bundle(2); 17769 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17770 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17771 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17772 if (isUpdate || isRemovedPackageSystemUpdate) { 17773 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17774 } 17775 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17776 if (removedPackage != null) { 17777 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17778 extras, 0, null, null, broadcastUsers); 17779 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17780 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17781 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17782 null, null, broadcastUsers); 17783 } 17784 } 17785 if (removedAppId >= 0) { 17786 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17787 broadcastUsers); 17788 } 17789 } 17790 } 17791 17792 /* 17793 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17794 * flag is not set, the data directory is removed as well. 17795 * make sure this flag is set for partially installed apps. If not its meaningless to 17796 * delete a partially installed application. 17797 */ 17798 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17799 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17800 String packageName = ps.name; 17801 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17802 // Retrieve object to delete permissions for shared user later on 17803 final PackageParser.Package deletedPkg; 17804 final PackageSetting deletedPs; 17805 // reader 17806 synchronized (mPackages) { 17807 deletedPkg = mPackages.get(packageName); 17808 deletedPs = mSettings.mPackages.get(packageName); 17809 if (outInfo != null) { 17810 outInfo.removedPackage = packageName; 17811 outInfo.isStaticSharedLib = deletedPkg != null 17812 && deletedPkg.staticSharedLibName != null; 17813 outInfo.removedUsers = deletedPs != null 17814 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17815 : null; 17816 if (outInfo.removedUsers == null) { 17817 outInfo.broadcastUsers = null; 17818 } else { 17819 outInfo.broadcastUsers = EMPTY_INT_ARRAY; 17820 int[] allUsers = outInfo.removedUsers; 17821 for (int i = allUsers.length - 1; i >= 0; --i) { 17822 final int userId = allUsers[i]; 17823 if (deletedPs.getInstantApp(userId)) { 17824 continue; 17825 } 17826 outInfo.broadcastUsers = 17827 ArrayUtils.appendInt(outInfo.broadcastUsers, userId); 17828 } 17829 } 17830 } 17831 } 17832 17833 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17834 17835 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17836 final PackageParser.Package resolvedPkg; 17837 if (deletedPkg != null) { 17838 resolvedPkg = deletedPkg; 17839 } else { 17840 // We don't have a parsed package when it lives on an ejected 17841 // adopted storage device, so fake something together 17842 resolvedPkg = new PackageParser.Package(ps.name); 17843 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17844 } 17845 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17846 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17847 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17848 if (outInfo != null) { 17849 outInfo.dataRemoved = true; 17850 } 17851 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17852 } 17853 17854 int removedAppId = -1; 17855 17856 // writer 17857 synchronized (mPackages) { 17858 boolean installedStateChanged = false; 17859 if (deletedPs != null) { 17860 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17861 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17862 clearDefaultBrowserIfNeeded(packageName); 17863 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17864 removedAppId = mSettings.removePackageLPw(packageName); 17865 if (outInfo != null) { 17866 outInfo.removedAppId = removedAppId; 17867 } 17868 updatePermissionsLPw(deletedPs.name, null, 0); 17869 if (deletedPs.sharedUser != null) { 17870 // Remove permissions associated with package. Since runtime 17871 // permissions are per user we have to kill the removed package 17872 // or packages running under the shared user of the removed 17873 // package if revoking the permissions requested only by the removed 17874 // package is successful and this causes a change in gids. 17875 for (int userId : UserManagerService.getInstance().getUserIds()) { 17876 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17877 userId); 17878 if (userIdToKill == UserHandle.USER_ALL 17879 || userIdToKill >= UserHandle.USER_SYSTEM) { 17880 // If gids changed for this user, kill all affected packages. 17881 mHandler.post(new Runnable() { 17882 @Override 17883 public void run() { 17884 // This has to happen with no lock held. 17885 killApplication(deletedPs.name, deletedPs.appId, 17886 KILL_APP_REASON_GIDS_CHANGED); 17887 } 17888 }); 17889 break; 17890 } 17891 } 17892 } 17893 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17894 } 17895 // make sure to preserve per-user disabled state if this removal was just 17896 // a downgrade of a system app to the factory package 17897 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17898 if (DEBUG_REMOVE) { 17899 Slog.d(TAG, "Propagating install state across downgrade"); 17900 } 17901 for (int userId : allUserHandles) { 17902 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17903 if (DEBUG_REMOVE) { 17904 Slog.d(TAG, " user " + userId + " => " + installed); 17905 } 17906 if (installed != ps.getInstalled(userId)) { 17907 installedStateChanged = true; 17908 } 17909 ps.setInstalled(installed, userId); 17910 } 17911 } 17912 } 17913 // can downgrade to reader 17914 if (writeSettings) { 17915 // Save settings now 17916 mSettings.writeLPr(); 17917 } 17918 if (installedStateChanged) { 17919 mSettings.writeKernelMappingLPr(ps); 17920 } 17921 } 17922 if (removedAppId != -1) { 17923 // A user ID was deleted here. Go through all users and remove it 17924 // from KeyStore. 17925 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17926 } 17927 } 17928 17929 static boolean locationIsPrivileged(File path) { 17930 try { 17931 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17932 .getCanonicalPath(); 17933 return path.getCanonicalPath().startsWith(privilegedAppDir); 17934 } catch (IOException e) { 17935 Slog.e(TAG, "Unable to access code path " + path); 17936 } 17937 return false; 17938 } 17939 17940 /* 17941 * Tries to delete system package. 17942 */ 17943 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17944 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17945 boolean writeSettings) { 17946 if (deletedPs.parentPackageName != null) { 17947 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17948 return false; 17949 } 17950 17951 final boolean applyUserRestrictions 17952 = (allUserHandles != null) && (outInfo.origUsers != null); 17953 final PackageSetting disabledPs; 17954 // Confirm if the system package has been updated 17955 // An updated system app can be deleted. This will also have to restore 17956 // the system pkg from system partition 17957 // reader 17958 synchronized (mPackages) { 17959 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17960 } 17961 17962 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17963 + " disabledPs=" + disabledPs); 17964 17965 if (disabledPs == null) { 17966 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17967 return false; 17968 } else if (DEBUG_REMOVE) { 17969 Slog.d(TAG, "Deleting system pkg from data partition"); 17970 } 17971 17972 if (DEBUG_REMOVE) { 17973 if (applyUserRestrictions) { 17974 Slog.d(TAG, "Remembering install states:"); 17975 for (int userId : allUserHandles) { 17976 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17977 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17978 } 17979 } 17980 } 17981 17982 // Delete the updated package 17983 outInfo.isRemovedPackageSystemUpdate = true; 17984 if (outInfo.removedChildPackages != null) { 17985 final int childCount = (deletedPs.childPackageNames != null) 17986 ? deletedPs.childPackageNames.size() : 0; 17987 for (int i = 0; i < childCount; i++) { 17988 String childPackageName = deletedPs.childPackageNames.get(i); 17989 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17990 .contains(childPackageName)) { 17991 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17992 childPackageName); 17993 if (childInfo != null) { 17994 childInfo.isRemovedPackageSystemUpdate = true; 17995 } 17996 } 17997 } 17998 } 17999 18000 if (disabledPs.versionCode < deletedPs.versionCode) { 18001 // Delete data for downgrades 18002 flags &= ~PackageManager.DELETE_KEEP_DATA; 18003 } else { 18004 // Preserve data by setting flag 18005 flags |= PackageManager.DELETE_KEEP_DATA; 18006 } 18007 18008 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18009 outInfo, writeSettings, disabledPs.pkg); 18010 if (!ret) { 18011 return false; 18012 } 18013 18014 // writer 18015 synchronized (mPackages) { 18016 // Reinstate the old system package 18017 enableSystemPackageLPw(disabledPs.pkg); 18018 // Remove any native libraries from the upgraded package. 18019 removeNativeBinariesLI(deletedPs); 18020 } 18021 18022 // Install the system package 18023 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18024 int parseFlags = mDefParseFlags 18025 | PackageParser.PARSE_MUST_BE_APK 18026 | PackageParser.PARSE_IS_SYSTEM 18027 | PackageParser.PARSE_IS_SYSTEM_DIR; 18028 if (locationIsPrivileged(disabledPs.codePath)) { 18029 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18030 } 18031 18032 final PackageParser.Package newPkg; 18033 try { 18034 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18035 0 /* currentTime */, null); 18036 } catch (PackageManagerException e) { 18037 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18038 + e.getMessage()); 18039 return false; 18040 } 18041 18042 try { 18043 // update shared libraries for the newly re-installed system package 18044 updateSharedLibrariesLPr(newPkg, null); 18045 } catch (PackageManagerException e) { 18046 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18047 } 18048 18049 prepareAppDataAfterInstallLIF(newPkg); 18050 18051 // writer 18052 synchronized (mPackages) { 18053 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18054 18055 // Propagate the permissions state as we do not want to drop on the floor 18056 // runtime permissions. The update permissions method below will take 18057 // care of removing obsolete permissions and grant install permissions. 18058 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18059 updatePermissionsLPw(newPkg.packageName, newPkg, 18060 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18061 18062 if (applyUserRestrictions) { 18063 boolean installedStateChanged = false; 18064 if (DEBUG_REMOVE) { 18065 Slog.d(TAG, "Propagating install state across reinstall"); 18066 } 18067 for (int userId : allUserHandles) { 18068 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18069 if (DEBUG_REMOVE) { 18070 Slog.d(TAG, " user " + userId + " => " + installed); 18071 } 18072 if (installed != ps.getInstalled(userId)) { 18073 installedStateChanged = true; 18074 } 18075 ps.setInstalled(installed, userId); 18076 18077 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18078 } 18079 // Regardless of writeSettings we need to ensure that this restriction 18080 // state propagation is persisted 18081 mSettings.writeAllUsersPackageRestrictionsLPr(); 18082 if (installedStateChanged) { 18083 mSettings.writeKernelMappingLPr(ps); 18084 } 18085 } 18086 // can downgrade to reader here 18087 if (writeSettings) { 18088 mSettings.writeLPr(); 18089 } 18090 } 18091 return true; 18092 } 18093 18094 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18095 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18096 PackageRemovedInfo outInfo, boolean writeSettings, 18097 PackageParser.Package replacingPackage) { 18098 synchronized (mPackages) { 18099 if (outInfo != null) { 18100 outInfo.uid = ps.appId; 18101 } 18102 18103 if (outInfo != null && outInfo.removedChildPackages != null) { 18104 final int childCount = (ps.childPackageNames != null) 18105 ? ps.childPackageNames.size() : 0; 18106 for (int i = 0; i < childCount; i++) { 18107 String childPackageName = ps.childPackageNames.get(i); 18108 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18109 if (childPs == null) { 18110 return false; 18111 } 18112 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18113 childPackageName); 18114 if (childInfo != null) { 18115 childInfo.uid = childPs.appId; 18116 } 18117 } 18118 } 18119 } 18120 18121 // Delete package data from internal structures and also remove data if flag is set 18122 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18123 18124 // Delete the child packages data 18125 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18126 for (int i = 0; i < childCount; i++) { 18127 PackageSetting childPs; 18128 synchronized (mPackages) { 18129 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18130 } 18131 if (childPs != null) { 18132 PackageRemovedInfo childOutInfo = (outInfo != null 18133 && outInfo.removedChildPackages != null) 18134 ? outInfo.removedChildPackages.get(childPs.name) : null; 18135 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18136 && (replacingPackage != null 18137 && !replacingPackage.hasChildPackage(childPs.name)) 18138 ? flags & ~DELETE_KEEP_DATA : flags; 18139 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18140 deleteFlags, writeSettings); 18141 } 18142 } 18143 18144 // Delete application code and resources only for parent packages 18145 if (ps.parentPackageName == null) { 18146 if (deleteCodeAndResources && (outInfo != null)) { 18147 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18148 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18149 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18150 } 18151 } 18152 18153 return true; 18154 } 18155 18156 @Override 18157 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18158 int userId) { 18159 mContext.enforceCallingOrSelfPermission( 18160 android.Manifest.permission.DELETE_PACKAGES, null); 18161 synchronized (mPackages) { 18162 PackageSetting ps = mSettings.mPackages.get(packageName); 18163 if (ps == null) { 18164 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18165 return false; 18166 } 18167 // Cannot block uninstall of static shared libs as they are 18168 // considered a part of the using app (emulating static linking). 18169 // Also static libs are installed always on internal storage. 18170 PackageParser.Package pkg = mPackages.get(packageName); 18171 if (pkg != null && pkg.staticSharedLibName != null) { 18172 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18173 + " providing static shared library: " + pkg.staticSharedLibName); 18174 return false; 18175 } 18176 if (!ps.getInstalled(userId)) { 18177 // Can't block uninstall for an app that is not installed or enabled. 18178 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18179 return false; 18180 } 18181 ps.setBlockUninstall(blockUninstall, userId); 18182 mSettings.writePackageRestrictionsLPr(userId); 18183 } 18184 return true; 18185 } 18186 18187 @Override 18188 public boolean getBlockUninstallForUser(String packageName, int userId) { 18189 synchronized (mPackages) { 18190 PackageSetting ps = mSettings.mPackages.get(packageName); 18191 if (ps == null) { 18192 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18193 return false; 18194 } 18195 return ps.getBlockUninstall(userId); 18196 } 18197 } 18198 18199 @Override 18200 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18201 int callingUid = Binder.getCallingUid(); 18202 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18203 throw new SecurityException( 18204 "setRequiredForSystemUser can only be run by the system or root"); 18205 } 18206 synchronized (mPackages) { 18207 PackageSetting ps = mSettings.mPackages.get(packageName); 18208 if (ps == null) { 18209 Log.w(TAG, "Package doesn't exist: " + packageName); 18210 return false; 18211 } 18212 if (systemUserApp) { 18213 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18214 } else { 18215 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18216 } 18217 mSettings.writeLPr(); 18218 } 18219 return true; 18220 } 18221 18222 /* 18223 * This method handles package deletion in general 18224 */ 18225 private boolean deletePackageLIF(String packageName, UserHandle user, 18226 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18227 PackageRemovedInfo outInfo, boolean writeSettings, 18228 PackageParser.Package replacingPackage) { 18229 if (packageName == null) { 18230 Slog.w(TAG, "Attempt to delete null packageName."); 18231 return false; 18232 } 18233 18234 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18235 18236 PackageSetting ps; 18237 synchronized (mPackages) { 18238 ps = mSettings.mPackages.get(packageName); 18239 if (ps == null) { 18240 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18241 return false; 18242 } 18243 18244 if (ps.parentPackageName != null && (!isSystemApp(ps) 18245 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18246 if (DEBUG_REMOVE) { 18247 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18248 + ((user == null) ? UserHandle.USER_ALL : user)); 18249 } 18250 final int removedUserId = (user != null) ? user.getIdentifier() 18251 : UserHandle.USER_ALL; 18252 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18253 return false; 18254 } 18255 markPackageUninstalledForUserLPw(ps, user); 18256 scheduleWritePackageRestrictionsLocked(user); 18257 return true; 18258 } 18259 } 18260 18261 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18262 && user.getIdentifier() != UserHandle.USER_ALL)) { 18263 // The caller is asking that the package only be deleted for a single 18264 // user. To do this, we just mark its uninstalled state and delete 18265 // its data. If this is a system app, we only allow this to happen if 18266 // they have set the special DELETE_SYSTEM_APP which requests different 18267 // semantics than normal for uninstalling system apps. 18268 markPackageUninstalledForUserLPw(ps, user); 18269 18270 if (!isSystemApp(ps)) { 18271 // Do not uninstall the APK if an app should be cached 18272 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18273 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18274 // Other user still have this package installed, so all 18275 // we need to do is clear this user's data and save that 18276 // it is uninstalled. 18277 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18278 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18279 return false; 18280 } 18281 scheduleWritePackageRestrictionsLocked(user); 18282 return true; 18283 } else { 18284 // We need to set it back to 'installed' so the uninstall 18285 // broadcasts will be sent correctly. 18286 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18287 ps.setInstalled(true, user.getIdentifier()); 18288 mSettings.writeKernelMappingLPr(ps); 18289 } 18290 } else { 18291 // This is a system app, so we assume that the 18292 // other users still have this package installed, so all 18293 // we need to do is clear this user's data and save that 18294 // it is uninstalled. 18295 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18296 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18297 return false; 18298 } 18299 scheduleWritePackageRestrictionsLocked(user); 18300 return true; 18301 } 18302 } 18303 18304 // If we are deleting a composite package for all users, keep track 18305 // of result for each child. 18306 if (ps.childPackageNames != null && outInfo != null) { 18307 synchronized (mPackages) { 18308 final int childCount = ps.childPackageNames.size(); 18309 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18310 for (int i = 0; i < childCount; i++) { 18311 String childPackageName = ps.childPackageNames.get(i); 18312 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18313 childInfo.removedPackage = childPackageName; 18314 outInfo.removedChildPackages.put(childPackageName, childInfo); 18315 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18316 if (childPs != null) { 18317 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18318 } 18319 } 18320 } 18321 } 18322 18323 boolean ret = false; 18324 if (isSystemApp(ps)) { 18325 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18326 // When an updated system application is deleted we delete the existing resources 18327 // as well and fall back to existing code in system partition 18328 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18329 } else { 18330 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18331 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18332 outInfo, writeSettings, replacingPackage); 18333 } 18334 18335 // Take a note whether we deleted the package for all users 18336 if (outInfo != null) { 18337 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18338 if (outInfo.removedChildPackages != null) { 18339 synchronized (mPackages) { 18340 final int childCount = outInfo.removedChildPackages.size(); 18341 for (int i = 0; i < childCount; i++) { 18342 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18343 if (childInfo != null) { 18344 childInfo.removedForAllUsers = mPackages.get( 18345 childInfo.removedPackage) == null; 18346 } 18347 } 18348 } 18349 } 18350 // If we uninstalled an update to a system app there may be some 18351 // child packages that appeared as they are declared in the system 18352 // app but were not declared in the update. 18353 if (isSystemApp(ps)) { 18354 synchronized (mPackages) { 18355 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18356 final int childCount = (updatedPs.childPackageNames != null) 18357 ? updatedPs.childPackageNames.size() : 0; 18358 for (int i = 0; i < childCount; i++) { 18359 String childPackageName = updatedPs.childPackageNames.get(i); 18360 if (outInfo.removedChildPackages == null 18361 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18362 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18363 if (childPs == null) { 18364 continue; 18365 } 18366 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18367 installRes.name = childPackageName; 18368 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18369 installRes.pkg = mPackages.get(childPackageName); 18370 installRes.uid = childPs.pkg.applicationInfo.uid; 18371 if (outInfo.appearedChildPackages == null) { 18372 outInfo.appearedChildPackages = new ArrayMap<>(); 18373 } 18374 outInfo.appearedChildPackages.put(childPackageName, installRes); 18375 } 18376 } 18377 } 18378 } 18379 } 18380 18381 return ret; 18382 } 18383 18384 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18385 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18386 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18387 for (int nextUserId : userIds) { 18388 if (DEBUG_REMOVE) { 18389 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18390 } 18391 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18392 false /*installed*/, 18393 true /*stopped*/, 18394 true /*notLaunched*/, 18395 false /*hidden*/, 18396 false /*suspended*/, 18397 false /*instantApp*/, 18398 null /*lastDisableAppCaller*/, 18399 null /*enabledComponents*/, 18400 null /*disabledComponents*/, 18401 false /*blockUninstall*/, 18402 ps.readUserState(nextUserId).domainVerificationStatus, 18403 0, PackageManager.INSTALL_REASON_UNKNOWN); 18404 } 18405 mSettings.writeKernelMappingLPr(ps); 18406 } 18407 18408 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18409 PackageRemovedInfo outInfo) { 18410 final PackageParser.Package pkg; 18411 synchronized (mPackages) { 18412 pkg = mPackages.get(ps.name); 18413 } 18414 18415 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18416 : new int[] {userId}; 18417 for (int nextUserId : userIds) { 18418 if (DEBUG_REMOVE) { 18419 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18420 + nextUserId); 18421 } 18422 18423 destroyAppDataLIF(pkg, userId, 18424 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18425 destroyAppProfilesLIF(pkg, userId); 18426 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18427 schedulePackageCleaning(ps.name, nextUserId, false); 18428 synchronized (mPackages) { 18429 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18430 scheduleWritePackageRestrictionsLocked(nextUserId); 18431 } 18432 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18433 } 18434 } 18435 18436 if (outInfo != null) { 18437 outInfo.removedPackage = ps.name; 18438 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18439 outInfo.removedAppId = ps.appId; 18440 outInfo.removedUsers = userIds; 18441 outInfo.broadcastUsers = userIds; 18442 } 18443 18444 return true; 18445 } 18446 18447 private final class ClearStorageConnection implements ServiceConnection { 18448 IMediaContainerService mContainerService; 18449 18450 @Override 18451 public void onServiceConnected(ComponentName name, IBinder service) { 18452 synchronized (this) { 18453 mContainerService = IMediaContainerService.Stub 18454 .asInterface(Binder.allowBlocking(service)); 18455 notifyAll(); 18456 } 18457 } 18458 18459 @Override 18460 public void onServiceDisconnected(ComponentName name) { 18461 } 18462 } 18463 18464 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18465 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18466 18467 final boolean mounted; 18468 if (Environment.isExternalStorageEmulated()) { 18469 mounted = true; 18470 } else { 18471 final String status = Environment.getExternalStorageState(); 18472 18473 mounted = status.equals(Environment.MEDIA_MOUNTED) 18474 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18475 } 18476 18477 if (!mounted) { 18478 return; 18479 } 18480 18481 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18482 int[] users; 18483 if (userId == UserHandle.USER_ALL) { 18484 users = sUserManager.getUserIds(); 18485 } else { 18486 users = new int[] { userId }; 18487 } 18488 final ClearStorageConnection conn = new ClearStorageConnection(); 18489 if (mContext.bindServiceAsUser( 18490 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18491 try { 18492 for (int curUser : users) { 18493 long timeout = SystemClock.uptimeMillis() + 5000; 18494 synchronized (conn) { 18495 long now; 18496 while (conn.mContainerService == null && 18497 (now = SystemClock.uptimeMillis()) < timeout) { 18498 try { 18499 conn.wait(timeout - now); 18500 } catch (InterruptedException e) { 18501 } 18502 } 18503 } 18504 if (conn.mContainerService == null) { 18505 return; 18506 } 18507 18508 final UserEnvironment userEnv = new UserEnvironment(curUser); 18509 clearDirectory(conn.mContainerService, 18510 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18511 if (allData) { 18512 clearDirectory(conn.mContainerService, 18513 userEnv.buildExternalStorageAppDataDirs(packageName)); 18514 clearDirectory(conn.mContainerService, 18515 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18516 } 18517 } 18518 } finally { 18519 mContext.unbindService(conn); 18520 } 18521 } 18522 } 18523 18524 @Override 18525 public void clearApplicationProfileData(String packageName) { 18526 enforceSystemOrRoot("Only the system can clear all profile data"); 18527 18528 final PackageParser.Package pkg; 18529 synchronized (mPackages) { 18530 pkg = mPackages.get(packageName); 18531 } 18532 18533 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18534 synchronized (mInstallLock) { 18535 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18536 } 18537 } 18538 } 18539 18540 @Override 18541 public void clearApplicationUserData(final String packageName, 18542 final IPackageDataObserver observer, final int userId) { 18543 mContext.enforceCallingOrSelfPermission( 18544 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18545 18546 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18547 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18548 18549 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18550 throw new SecurityException("Cannot clear data for a protected package: " 18551 + packageName); 18552 } 18553 // Queue up an async operation since the package deletion may take a little while. 18554 mHandler.post(new Runnable() { 18555 public void run() { 18556 mHandler.removeCallbacks(this); 18557 final boolean succeeded; 18558 try (PackageFreezer freezer = freezePackage(packageName, 18559 "clearApplicationUserData")) { 18560 synchronized (mInstallLock) { 18561 succeeded = clearApplicationUserDataLIF(packageName, userId); 18562 } 18563 clearExternalStorageDataSync(packageName, userId, true); 18564 synchronized (mPackages) { 18565 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18566 packageName, userId); 18567 } 18568 } 18569 if (succeeded) { 18570 // invoke DeviceStorageMonitor's update method to clear any notifications 18571 DeviceStorageMonitorInternal dsm = LocalServices 18572 .getService(DeviceStorageMonitorInternal.class); 18573 if (dsm != null) { 18574 dsm.checkMemory(); 18575 } 18576 } 18577 if(observer != null) { 18578 try { 18579 observer.onRemoveCompleted(packageName, succeeded); 18580 } catch (RemoteException e) { 18581 Log.i(TAG, "Observer no longer exists."); 18582 } 18583 } //end if observer 18584 } //end run 18585 }); 18586 } 18587 18588 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18589 if (packageName == null) { 18590 Slog.w(TAG, "Attempt to delete null packageName."); 18591 return false; 18592 } 18593 18594 // Try finding details about the requested package 18595 PackageParser.Package pkg; 18596 synchronized (mPackages) { 18597 pkg = mPackages.get(packageName); 18598 if (pkg == null) { 18599 final PackageSetting ps = mSettings.mPackages.get(packageName); 18600 if (ps != null) { 18601 pkg = ps.pkg; 18602 } 18603 } 18604 18605 if (pkg == null) { 18606 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18607 return false; 18608 } 18609 18610 PackageSetting ps = (PackageSetting) pkg.mExtras; 18611 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18612 } 18613 18614 clearAppDataLIF(pkg, userId, 18615 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18616 18617 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18618 removeKeystoreDataIfNeeded(userId, appId); 18619 18620 UserManagerInternal umInternal = getUserManagerInternal(); 18621 final int flags; 18622 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18623 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18624 } else if (umInternal.isUserRunning(userId)) { 18625 flags = StorageManager.FLAG_STORAGE_DE; 18626 } else { 18627 flags = 0; 18628 } 18629 prepareAppDataContentsLIF(pkg, userId, flags); 18630 18631 return true; 18632 } 18633 18634 /** 18635 * Reverts user permission state changes (permissions and flags) in 18636 * all packages for a given user. 18637 * 18638 * @param userId The device user for which to do a reset. 18639 */ 18640 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18641 final int packageCount = mPackages.size(); 18642 for (int i = 0; i < packageCount; i++) { 18643 PackageParser.Package pkg = mPackages.valueAt(i); 18644 PackageSetting ps = (PackageSetting) pkg.mExtras; 18645 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18646 } 18647 } 18648 18649 private void resetNetworkPolicies(int userId) { 18650 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18651 } 18652 18653 /** 18654 * Reverts user permission state changes (permissions and flags). 18655 * 18656 * @param ps The package for which to reset. 18657 * @param userId The device user for which to do a reset. 18658 */ 18659 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18660 final PackageSetting ps, final int userId) { 18661 if (ps.pkg == null) { 18662 return; 18663 } 18664 18665 // These are flags that can change base on user actions. 18666 final int userSettableMask = FLAG_PERMISSION_USER_SET 18667 | FLAG_PERMISSION_USER_FIXED 18668 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18669 | FLAG_PERMISSION_REVIEW_REQUIRED; 18670 18671 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18672 | FLAG_PERMISSION_POLICY_FIXED; 18673 18674 boolean writeInstallPermissions = false; 18675 boolean writeRuntimePermissions = false; 18676 18677 final int permissionCount = ps.pkg.requestedPermissions.size(); 18678 for (int i = 0; i < permissionCount; i++) { 18679 String permission = ps.pkg.requestedPermissions.get(i); 18680 18681 BasePermission bp = mSettings.mPermissions.get(permission); 18682 if (bp == null) { 18683 continue; 18684 } 18685 18686 // If shared user we just reset the state to which only this app contributed. 18687 if (ps.sharedUser != null) { 18688 boolean used = false; 18689 final int packageCount = ps.sharedUser.packages.size(); 18690 for (int j = 0; j < packageCount; j++) { 18691 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18692 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18693 && pkg.pkg.requestedPermissions.contains(permission)) { 18694 used = true; 18695 break; 18696 } 18697 } 18698 if (used) { 18699 continue; 18700 } 18701 } 18702 18703 PermissionsState permissionsState = ps.getPermissionsState(); 18704 18705 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18706 18707 // Always clear the user settable flags. 18708 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18709 bp.name) != null; 18710 // If permission review is enabled and this is a legacy app, mark the 18711 // permission as requiring a review as this is the initial state. 18712 int flags = 0; 18713 if (mPermissionReviewRequired 18714 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18715 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18716 } 18717 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18718 if (hasInstallState) { 18719 writeInstallPermissions = true; 18720 } else { 18721 writeRuntimePermissions = true; 18722 } 18723 } 18724 18725 // Below is only runtime permission handling. 18726 if (!bp.isRuntime()) { 18727 continue; 18728 } 18729 18730 // Never clobber system or policy. 18731 if ((oldFlags & policyOrSystemFlags) != 0) { 18732 continue; 18733 } 18734 18735 // If this permission was granted by default, make sure it is. 18736 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18737 if (permissionsState.grantRuntimePermission(bp, userId) 18738 != PERMISSION_OPERATION_FAILURE) { 18739 writeRuntimePermissions = true; 18740 } 18741 // If permission review is enabled the permissions for a legacy apps 18742 // are represented as constantly granted runtime ones, so don't revoke. 18743 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18744 // Otherwise, reset the permission. 18745 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18746 switch (revokeResult) { 18747 case PERMISSION_OPERATION_SUCCESS: 18748 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18749 writeRuntimePermissions = true; 18750 final int appId = ps.appId; 18751 mHandler.post(new Runnable() { 18752 @Override 18753 public void run() { 18754 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18755 } 18756 }); 18757 } break; 18758 } 18759 } 18760 } 18761 18762 // Synchronously write as we are taking permissions away. 18763 if (writeRuntimePermissions) { 18764 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18765 } 18766 18767 // Synchronously write as we are taking permissions away. 18768 if (writeInstallPermissions) { 18769 mSettings.writeLPr(); 18770 } 18771 } 18772 18773 /** 18774 * Remove entries from the keystore daemon. Will only remove it if the 18775 * {@code appId} is valid. 18776 */ 18777 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18778 if (appId < 0) { 18779 return; 18780 } 18781 18782 final KeyStore keyStore = KeyStore.getInstance(); 18783 if (keyStore != null) { 18784 if (userId == UserHandle.USER_ALL) { 18785 for (final int individual : sUserManager.getUserIds()) { 18786 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18787 } 18788 } else { 18789 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18790 } 18791 } else { 18792 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18793 } 18794 } 18795 18796 @Override 18797 public void deleteApplicationCacheFiles(final String packageName, 18798 final IPackageDataObserver observer) { 18799 final int userId = UserHandle.getCallingUserId(); 18800 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18801 } 18802 18803 @Override 18804 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18805 final IPackageDataObserver observer) { 18806 mContext.enforceCallingOrSelfPermission( 18807 android.Manifest.permission.DELETE_CACHE_FILES, null); 18808 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18809 /* requireFullPermission= */ true, /* checkShell= */ false, 18810 "delete application cache files"); 18811 18812 final PackageParser.Package pkg; 18813 synchronized (mPackages) { 18814 pkg = mPackages.get(packageName); 18815 } 18816 18817 // Queue up an async operation since the package deletion may take a little while. 18818 mHandler.post(new Runnable() { 18819 public void run() { 18820 synchronized (mInstallLock) { 18821 final int flags = StorageManager.FLAG_STORAGE_DE 18822 | StorageManager.FLAG_STORAGE_CE; 18823 // We're only clearing cache files, so we don't care if the 18824 // app is unfrozen and still able to run 18825 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18826 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18827 } 18828 clearExternalStorageDataSync(packageName, userId, false); 18829 if (observer != null) { 18830 try { 18831 observer.onRemoveCompleted(packageName, true); 18832 } catch (RemoteException e) { 18833 Log.i(TAG, "Observer no longer exists."); 18834 } 18835 } 18836 } 18837 }); 18838 } 18839 18840 @Override 18841 public void getPackageSizeInfo(final String packageName, int userHandle, 18842 final IPackageStatsObserver observer) { 18843 throw new UnsupportedOperationException( 18844 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18845 } 18846 18847 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18848 final PackageSetting ps; 18849 synchronized (mPackages) { 18850 ps = mSettings.mPackages.get(packageName); 18851 if (ps == null) { 18852 Slog.w(TAG, "Failed to find settings for " + packageName); 18853 return false; 18854 } 18855 } 18856 18857 final String[] packageNames = { packageName }; 18858 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18859 final String[] codePaths = { ps.codePathString }; 18860 18861 try { 18862 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18863 ps.appId, ceDataInodes, codePaths, stats); 18864 18865 // For now, ignore code size of packages on system partition 18866 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18867 stats.codeSize = 0; 18868 } 18869 18870 // External clients expect these to be tracked separately 18871 stats.dataSize -= stats.cacheSize; 18872 18873 } catch (InstallerException e) { 18874 Slog.w(TAG, String.valueOf(e)); 18875 return false; 18876 } 18877 18878 return true; 18879 } 18880 18881 private int getUidTargetSdkVersionLockedLPr(int uid) { 18882 Object obj = mSettings.getUserIdLPr(uid); 18883 if (obj instanceof SharedUserSetting) { 18884 final SharedUserSetting sus = (SharedUserSetting) obj; 18885 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18886 final Iterator<PackageSetting> it = sus.packages.iterator(); 18887 while (it.hasNext()) { 18888 final PackageSetting ps = it.next(); 18889 if (ps.pkg != null) { 18890 int v = ps.pkg.applicationInfo.targetSdkVersion; 18891 if (v < vers) vers = v; 18892 } 18893 } 18894 return vers; 18895 } else if (obj instanceof PackageSetting) { 18896 final PackageSetting ps = (PackageSetting) obj; 18897 if (ps.pkg != null) { 18898 return ps.pkg.applicationInfo.targetSdkVersion; 18899 } 18900 } 18901 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18902 } 18903 18904 @Override 18905 public void addPreferredActivity(IntentFilter filter, int match, 18906 ComponentName[] set, ComponentName activity, int userId) { 18907 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18908 "Adding preferred"); 18909 } 18910 18911 private void addPreferredActivityInternal(IntentFilter filter, int match, 18912 ComponentName[] set, ComponentName activity, boolean always, int userId, 18913 String opname) { 18914 // writer 18915 int callingUid = Binder.getCallingUid(); 18916 enforceCrossUserPermission(callingUid, userId, 18917 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18918 if (filter.countActions() == 0) { 18919 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18920 return; 18921 } 18922 synchronized (mPackages) { 18923 if (mContext.checkCallingOrSelfPermission( 18924 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18925 != PackageManager.PERMISSION_GRANTED) { 18926 if (getUidTargetSdkVersionLockedLPr(callingUid) 18927 < Build.VERSION_CODES.FROYO) { 18928 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18929 + callingUid); 18930 return; 18931 } 18932 mContext.enforceCallingOrSelfPermission( 18933 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18934 } 18935 18936 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18937 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18938 + userId + ":"); 18939 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18940 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18941 scheduleWritePackageRestrictionsLocked(userId); 18942 postPreferredActivityChangedBroadcast(userId); 18943 } 18944 } 18945 18946 private void postPreferredActivityChangedBroadcast(int userId) { 18947 mHandler.post(() -> { 18948 final IActivityManager am = ActivityManager.getService(); 18949 if (am == null) { 18950 return; 18951 } 18952 18953 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18954 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18955 try { 18956 am.broadcastIntent(null, intent, null, null, 18957 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18958 null, false, false, userId); 18959 } catch (RemoteException e) { 18960 } 18961 }); 18962 } 18963 18964 @Override 18965 public void replacePreferredActivity(IntentFilter filter, int match, 18966 ComponentName[] set, ComponentName activity, int userId) { 18967 if (filter.countActions() != 1) { 18968 throw new IllegalArgumentException( 18969 "replacePreferredActivity expects filter to have only 1 action."); 18970 } 18971 if (filter.countDataAuthorities() != 0 18972 || filter.countDataPaths() != 0 18973 || filter.countDataSchemes() > 1 18974 || filter.countDataTypes() != 0) { 18975 throw new IllegalArgumentException( 18976 "replacePreferredActivity expects filter to have no data authorities, " + 18977 "paths, or types; and at most one scheme."); 18978 } 18979 18980 final int callingUid = Binder.getCallingUid(); 18981 enforceCrossUserPermission(callingUid, userId, 18982 true /* requireFullPermission */, false /* checkShell */, 18983 "replace preferred activity"); 18984 synchronized (mPackages) { 18985 if (mContext.checkCallingOrSelfPermission( 18986 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18987 != PackageManager.PERMISSION_GRANTED) { 18988 if (getUidTargetSdkVersionLockedLPr(callingUid) 18989 < Build.VERSION_CODES.FROYO) { 18990 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18991 + Binder.getCallingUid()); 18992 return; 18993 } 18994 mContext.enforceCallingOrSelfPermission( 18995 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18996 } 18997 18998 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18999 if (pir != null) { 19000 // Get all of the existing entries that exactly match this filter. 19001 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19002 if (existing != null && existing.size() == 1) { 19003 PreferredActivity cur = existing.get(0); 19004 if (DEBUG_PREFERRED) { 19005 Slog.i(TAG, "Checking replace of preferred:"); 19006 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19007 if (!cur.mPref.mAlways) { 19008 Slog.i(TAG, " -- CUR; not mAlways!"); 19009 } else { 19010 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19011 Slog.i(TAG, " -- CUR: mSet=" 19012 + Arrays.toString(cur.mPref.mSetComponents)); 19013 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19014 Slog.i(TAG, " -- NEW: mMatch=" 19015 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19016 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19017 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19018 } 19019 } 19020 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19021 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19022 && cur.mPref.sameSet(set)) { 19023 // Setting the preferred activity to what it happens to be already 19024 if (DEBUG_PREFERRED) { 19025 Slog.i(TAG, "Replacing with same preferred activity " 19026 + cur.mPref.mShortComponent + " for user " 19027 + userId + ":"); 19028 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19029 } 19030 return; 19031 } 19032 } 19033 19034 if (existing != null) { 19035 if (DEBUG_PREFERRED) { 19036 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19037 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19038 } 19039 for (int i = 0; i < existing.size(); i++) { 19040 PreferredActivity pa = existing.get(i); 19041 if (DEBUG_PREFERRED) { 19042 Slog.i(TAG, "Removing existing preferred activity " 19043 + pa.mPref.mComponent + ":"); 19044 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19045 } 19046 pir.removeFilter(pa); 19047 } 19048 } 19049 } 19050 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19051 "Replacing preferred"); 19052 } 19053 } 19054 19055 @Override 19056 public void clearPackagePreferredActivities(String packageName) { 19057 final int uid = Binder.getCallingUid(); 19058 // writer 19059 synchronized (mPackages) { 19060 PackageParser.Package pkg = mPackages.get(packageName); 19061 if (pkg == null || pkg.applicationInfo.uid != uid) { 19062 if (mContext.checkCallingOrSelfPermission( 19063 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19064 != PackageManager.PERMISSION_GRANTED) { 19065 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19066 < Build.VERSION_CODES.FROYO) { 19067 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19068 + Binder.getCallingUid()); 19069 return; 19070 } 19071 mContext.enforceCallingOrSelfPermission( 19072 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19073 } 19074 } 19075 19076 int user = UserHandle.getCallingUserId(); 19077 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19078 scheduleWritePackageRestrictionsLocked(user); 19079 } 19080 } 19081 } 19082 19083 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19084 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19085 ArrayList<PreferredActivity> removed = null; 19086 boolean changed = false; 19087 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19088 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19089 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19090 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19091 continue; 19092 } 19093 Iterator<PreferredActivity> it = pir.filterIterator(); 19094 while (it.hasNext()) { 19095 PreferredActivity pa = it.next(); 19096 // Mark entry for removal only if it matches the package name 19097 // and the entry is of type "always". 19098 if (packageName == null || 19099 (pa.mPref.mComponent.getPackageName().equals(packageName) 19100 && pa.mPref.mAlways)) { 19101 if (removed == null) { 19102 removed = new ArrayList<PreferredActivity>(); 19103 } 19104 removed.add(pa); 19105 } 19106 } 19107 if (removed != null) { 19108 for (int j=0; j<removed.size(); j++) { 19109 PreferredActivity pa = removed.get(j); 19110 pir.removeFilter(pa); 19111 } 19112 changed = true; 19113 } 19114 } 19115 if (changed) { 19116 postPreferredActivityChangedBroadcast(userId); 19117 } 19118 return changed; 19119 } 19120 19121 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19122 private void clearIntentFilterVerificationsLPw(int userId) { 19123 final int packageCount = mPackages.size(); 19124 for (int i = 0; i < packageCount; i++) { 19125 PackageParser.Package pkg = mPackages.valueAt(i); 19126 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19127 } 19128 } 19129 19130 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19131 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19132 if (userId == UserHandle.USER_ALL) { 19133 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19134 sUserManager.getUserIds())) { 19135 for (int oneUserId : sUserManager.getUserIds()) { 19136 scheduleWritePackageRestrictionsLocked(oneUserId); 19137 } 19138 } 19139 } else { 19140 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19141 scheduleWritePackageRestrictionsLocked(userId); 19142 } 19143 } 19144 } 19145 19146 void clearDefaultBrowserIfNeeded(String packageName) { 19147 for (int oneUserId : sUserManager.getUserIds()) { 19148 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19149 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19150 if (packageName.equals(defaultBrowserPackageName)) { 19151 setDefaultBrowserPackageName(null, oneUserId); 19152 } 19153 } 19154 } 19155 19156 @Override 19157 public void resetApplicationPreferences(int userId) { 19158 mContext.enforceCallingOrSelfPermission( 19159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19160 final long identity = Binder.clearCallingIdentity(); 19161 // writer 19162 try { 19163 synchronized (mPackages) { 19164 clearPackagePreferredActivitiesLPw(null, userId); 19165 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19166 // TODO: We have to reset the default SMS and Phone. This requires 19167 // significant refactoring to keep all default apps in the package 19168 // manager (cleaner but more work) or have the services provide 19169 // callbacks to the package manager to request a default app reset. 19170 applyFactoryDefaultBrowserLPw(userId); 19171 clearIntentFilterVerificationsLPw(userId); 19172 primeDomainVerificationsLPw(userId); 19173 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19174 scheduleWritePackageRestrictionsLocked(userId); 19175 } 19176 resetNetworkPolicies(userId); 19177 } finally { 19178 Binder.restoreCallingIdentity(identity); 19179 } 19180 } 19181 19182 @Override 19183 public int getPreferredActivities(List<IntentFilter> outFilters, 19184 List<ComponentName> outActivities, String packageName) { 19185 19186 int num = 0; 19187 final int userId = UserHandle.getCallingUserId(); 19188 // reader 19189 synchronized (mPackages) { 19190 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19191 if (pir != null) { 19192 final Iterator<PreferredActivity> it = pir.filterIterator(); 19193 while (it.hasNext()) { 19194 final PreferredActivity pa = it.next(); 19195 if (packageName == null 19196 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19197 && pa.mPref.mAlways)) { 19198 if (outFilters != null) { 19199 outFilters.add(new IntentFilter(pa)); 19200 } 19201 if (outActivities != null) { 19202 outActivities.add(pa.mPref.mComponent); 19203 } 19204 } 19205 } 19206 } 19207 } 19208 19209 return num; 19210 } 19211 19212 @Override 19213 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19214 int userId) { 19215 int callingUid = Binder.getCallingUid(); 19216 if (callingUid != Process.SYSTEM_UID) { 19217 throw new SecurityException( 19218 "addPersistentPreferredActivity can only be run by the system"); 19219 } 19220 if (filter.countActions() == 0) { 19221 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19222 return; 19223 } 19224 synchronized (mPackages) { 19225 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19226 ":"); 19227 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19228 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19229 new PersistentPreferredActivity(filter, activity)); 19230 scheduleWritePackageRestrictionsLocked(userId); 19231 postPreferredActivityChangedBroadcast(userId); 19232 } 19233 } 19234 19235 @Override 19236 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19237 int callingUid = Binder.getCallingUid(); 19238 if (callingUid != Process.SYSTEM_UID) { 19239 throw new SecurityException( 19240 "clearPackagePersistentPreferredActivities can only be run by the system"); 19241 } 19242 ArrayList<PersistentPreferredActivity> removed = null; 19243 boolean changed = false; 19244 synchronized (mPackages) { 19245 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19246 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19247 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19248 .valueAt(i); 19249 if (userId != thisUserId) { 19250 continue; 19251 } 19252 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19253 while (it.hasNext()) { 19254 PersistentPreferredActivity ppa = it.next(); 19255 // Mark entry for removal only if it matches the package name. 19256 if (ppa.mComponent.getPackageName().equals(packageName)) { 19257 if (removed == null) { 19258 removed = new ArrayList<PersistentPreferredActivity>(); 19259 } 19260 removed.add(ppa); 19261 } 19262 } 19263 if (removed != null) { 19264 for (int j=0; j<removed.size(); j++) { 19265 PersistentPreferredActivity ppa = removed.get(j); 19266 ppir.removeFilter(ppa); 19267 } 19268 changed = true; 19269 } 19270 } 19271 19272 if (changed) { 19273 scheduleWritePackageRestrictionsLocked(userId); 19274 postPreferredActivityChangedBroadcast(userId); 19275 } 19276 } 19277 } 19278 19279 /** 19280 * Common machinery for picking apart a restored XML blob and passing 19281 * it to a caller-supplied functor to be applied to the running system. 19282 */ 19283 private void restoreFromXml(XmlPullParser parser, int userId, 19284 String expectedStartTag, BlobXmlRestorer functor) 19285 throws IOException, XmlPullParserException { 19286 int type; 19287 while ((type = parser.next()) != XmlPullParser.START_TAG 19288 && type != XmlPullParser.END_DOCUMENT) { 19289 } 19290 if (type != XmlPullParser.START_TAG) { 19291 // oops didn't find a start tag?! 19292 if (DEBUG_BACKUP) { 19293 Slog.e(TAG, "Didn't find start tag during restore"); 19294 } 19295 return; 19296 } 19297Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19298 // this is supposed to be TAG_PREFERRED_BACKUP 19299 if (!expectedStartTag.equals(parser.getName())) { 19300 if (DEBUG_BACKUP) { 19301 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19302 } 19303 return; 19304 } 19305 19306 // skip interfering stuff, then we're aligned with the backing implementation 19307 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19308Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19309 functor.apply(parser, userId); 19310 } 19311 19312 private interface BlobXmlRestorer { 19313 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19314 } 19315 19316 /** 19317 * Non-Binder method, support for the backup/restore mechanism: write the 19318 * full set of preferred activities in its canonical XML format. Returns the 19319 * XML output as a byte array, or null if there is none. 19320 */ 19321 @Override 19322 public byte[] getPreferredActivityBackup(int userId) { 19323 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19324 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19325 } 19326 19327 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19328 try { 19329 final XmlSerializer serializer = new FastXmlSerializer(); 19330 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19331 serializer.startDocument(null, true); 19332 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19333 19334 synchronized (mPackages) { 19335 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19336 } 19337 19338 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19339 serializer.endDocument(); 19340 serializer.flush(); 19341 } catch (Exception e) { 19342 if (DEBUG_BACKUP) { 19343 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19344 } 19345 return null; 19346 } 19347 19348 return dataStream.toByteArray(); 19349 } 19350 19351 @Override 19352 public void restorePreferredActivities(byte[] backup, int userId) { 19353 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19354 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19355 } 19356 19357 try { 19358 final XmlPullParser parser = Xml.newPullParser(); 19359 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19360 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19361 new BlobXmlRestorer() { 19362 @Override 19363 public void apply(XmlPullParser parser, int userId) 19364 throws XmlPullParserException, IOException { 19365 synchronized (mPackages) { 19366 mSettings.readPreferredActivitiesLPw(parser, userId); 19367 } 19368 } 19369 } ); 19370 } catch (Exception e) { 19371 if (DEBUG_BACKUP) { 19372 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19373 } 19374 } 19375 } 19376 19377 /** 19378 * Non-Binder method, support for the backup/restore mechanism: write the 19379 * default browser (etc) settings in its canonical XML format. Returns the default 19380 * browser XML representation as a byte array, or null if there is none. 19381 */ 19382 @Override 19383 public byte[] getDefaultAppsBackup(int userId) { 19384 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19385 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19386 } 19387 19388 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19389 try { 19390 final XmlSerializer serializer = new FastXmlSerializer(); 19391 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19392 serializer.startDocument(null, true); 19393 serializer.startTag(null, TAG_DEFAULT_APPS); 19394 19395 synchronized (mPackages) { 19396 mSettings.writeDefaultAppsLPr(serializer, userId); 19397 } 19398 19399 serializer.endTag(null, TAG_DEFAULT_APPS); 19400 serializer.endDocument(); 19401 serializer.flush(); 19402 } catch (Exception e) { 19403 if (DEBUG_BACKUP) { 19404 Slog.e(TAG, "Unable to write default apps for backup", e); 19405 } 19406 return null; 19407 } 19408 19409 return dataStream.toByteArray(); 19410 } 19411 19412 @Override 19413 public void restoreDefaultApps(byte[] backup, int userId) { 19414 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19415 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19416 } 19417 19418 try { 19419 final XmlPullParser parser = Xml.newPullParser(); 19420 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19421 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19422 new BlobXmlRestorer() { 19423 @Override 19424 public void apply(XmlPullParser parser, int userId) 19425 throws XmlPullParserException, IOException { 19426 synchronized (mPackages) { 19427 mSettings.readDefaultAppsLPw(parser, userId); 19428 } 19429 } 19430 } ); 19431 } catch (Exception e) { 19432 if (DEBUG_BACKUP) { 19433 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19434 } 19435 } 19436 } 19437 19438 @Override 19439 public byte[] getIntentFilterVerificationBackup(int userId) { 19440 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19441 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19442 } 19443 19444 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19445 try { 19446 final XmlSerializer serializer = new FastXmlSerializer(); 19447 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19448 serializer.startDocument(null, true); 19449 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19450 19451 synchronized (mPackages) { 19452 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19453 } 19454 19455 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19456 serializer.endDocument(); 19457 serializer.flush(); 19458 } catch (Exception e) { 19459 if (DEBUG_BACKUP) { 19460 Slog.e(TAG, "Unable to write default apps for backup", e); 19461 } 19462 return null; 19463 } 19464 19465 return dataStream.toByteArray(); 19466 } 19467 19468 @Override 19469 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19470 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19471 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19472 } 19473 19474 try { 19475 final XmlPullParser parser = Xml.newPullParser(); 19476 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19477 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19478 new BlobXmlRestorer() { 19479 @Override 19480 public void apply(XmlPullParser parser, int userId) 19481 throws XmlPullParserException, IOException { 19482 synchronized (mPackages) { 19483 mSettings.readAllDomainVerificationsLPr(parser, userId); 19484 mSettings.writeLPr(); 19485 } 19486 } 19487 } ); 19488 } catch (Exception e) { 19489 if (DEBUG_BACKUP) { 19490 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19491 } 19492 } 19493 } 19494 19495 @Override 19496 public byte[] getPermissionGrantBackup(int userId) { 19497 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19498 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19499 } 19500 19501 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19502 try { 19503 final XmlSerializer serializer = new FastXmlSerializer(); 19504 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19505 serializer.startDocument(null, true); 19506 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19507 19508 synchronized (mPackages) { 19509 serializeRuntimePermissionGrantsLPr(serializer, userId); 19510 } 19511 19512 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19513 serializer.endDocument(); 19514 serializer.flush(); 19515 } catch (Exception e) { 19516 if (DEBUG_BACKUP) { 19517 Slog.e(TAG, "Unable to write default apps for backup", e); 19518 } 19519 return null; 19520 } 19521 19522 return dataStream.toByteArray(); 19523 } 19524 19525 @Override 19526 public void restorePermissionGrants(byte[] backup, int userId) { 19527 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19528 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19529 } 19530 19531 try { 19532 final XmlPullParser parser = Xml.newPullParser(); 19533 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19534 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19535 new BlobXmlRestorer() { 19536 @Override 19537 public void apply(XmlPullParser parser, int userId) 19538 throws XmlPullParserException, IOException { 19539 synchronized (mPackages) { 19540 processRestoredPermissionGrantsLPr(parser, userId); 19541 } 19542 } 19543 } ); 19544 } catch (Exception e) { 19545 if (DEBUG_BACKUP) { 19546 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19547 } 19548 } 19549 } 19550 19551 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19552 throws IOException { 19553 serializer.startTag(null, TAG_ALL_GRANTS); 19554 19555 final int N = mSettings.mPackages.size(); 19556 for (int i = 0; i < N; i++) { 19557 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19558 boolean pkgGrantsKnown = false; 19559 19560 PermissionsState packagePerms = ps.getPermissionsState(); 19561 19562 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19563 final int grantFlags = state.getFlags(); 19564 // only look at grants that are not system/policy fixed 19565 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19566 final boolean isGranted = state.isGranted(); 19567 // And only back up the user-twiddled state bits 19568 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19569 final String packageName = mSettings.mPackages.keyAt(i); 19570 if (!pkgGrantsKnown) { 19571 serializer.startTag(null, TAG_GRANT); 19572 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19573 pkgGrantsKnown = true; 19574 } 19575 19576 final boolean userSet = 19577 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19578 final boolean userFixed = 19579 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19580 final boolean revoke = 19581 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19582 19583 serializer.startTag(null, TAG_PERMISSION); 19584 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19585 if (isGranted) { 19586 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19587 } 19588 if (userSet) { 19589 serializer.attribute(null, ATTR_USER_SET, "true"); 19590 } 19591 if (userFixed) { 19592 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19593 } 19594 if (revoke) { 19595 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19596 } 19597 serializer.endTag(null, TAG_PERMISSION); 19598 } 19599 } 19600 } 19601 19602 if (pkgGrantsKnown) { 19603 serializer.endTag(null, TAG_GRANT); 19604 } 19605 } 19606 19607 serializer.endTag(null, TAG_ALL_GRANTS); 19608 } 19609 19610 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19611 throws XmlPullParserException, IOException { 19612 String pkgName = null; 19613 int outerDepth = parser.getDepth(); 19614 int type; 19615 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19616 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19617 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19618 continue; 19619 } 19620 19621 final String tagName = parser.getName(); 19622 if (tagName.equals(TAG_GRANT)) { 19623 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19624 if (DEBUG_BACKUP) { 19625 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19626 } 19627 } else if (tagName.equals(TAG_PERMISSION)) { 19628 19629 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19630 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19631 19632 int newFlagSet = 0; 19633 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19634 newFlagSet |= FLAG_PERMISSION_USER_SET; 19635 } 19636 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19637 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19638 } 19639 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19640 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19641 } 19642 if (DEBUG_BACKUP) { 19643 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19644 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19645 } 19646 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19647 if (ps != null) { 19648 // Already installed so we apply the grant immediately 19649 if (DEBUG_BACKUP) { 19650 Slog.v(TAG, " + already installed; applying"); 19651 } 19652 PermissionsState perms = ps.getPermissionsState(); 19653 BasePermission bp = mSettings.mPermissions.get(permName); 19654 if (bp != null) { 19655 if (isGranted) { 19656 perms.grantRuntimePermission(bp, userId); 19657 } 19658 if (newFlagSet != 0) { 19659 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19660 } 19661 } 19662 } else { 19663 // Need to wait for post-restore install to apply the grant 19664 if (DEBUG_BACKUP) { 19665 Slog.v(TAG, " - not yet installed; saving for later"); 19666 } 19667 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19668 isGranted, newFlagSet, userId); 19669 } 19670 } else { 19671 PackageManagerService.reportSettingsProblem(Log.WARN, 19672 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19673 XmlUtils.skipCurrentTag(parser); 19674 } 19675 } 19676 19677 scheduleWriteSettingsLocked(); 19678 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19679 } 19680 19681 @Override 19682 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19683 int sourceUserId, int targetUserId, int flags) { 19684 mContext.enforceCallingOrSelfPermission( 19685 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19686 int callingUid = Binder.getCallingUid(); 19687 enforceOwnerRights(ownerPackage, callingUid); 19688 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19689 if (intentFilter.countActions() == 0) { 19690 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19691 return; 19692 } 19693 synchronized (mPackages) { 19694 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19695 ownerPackage, targetUserId, flags); 19696 CrossProfileIntentResolver resolver = 19697 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19698 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19699 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19700 if (existing != null) { 19701 int size = existing.size(); 19702 for (int i = 0; i < size; i++) { 19703 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19704 return; 19705 } 19706 } 19707 } 19708 resolver.addFilter(newFilter); 19709 scheduleWritePackageRestrictionsLocked(sourceUserId); 19710 } 19711 } 19712 19713 @Override 19714 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19715 mContext.enforceCallingOrSelfPermission( 19716 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19717 int callingUid = Binder.getCallingUid(); 19718 enforceOwnerRights(ownerPackage, callingUid); 19719 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19720 synchronized (mPackages) { 19721 CrossProfileIntentResolver resolver = 19722 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19723 ArraySet<CrossProfileIntentFilter> set = 19724 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19725 for (CrossProfileIntentFilter filter : set) { 19726 if (filter.getOwnerPackage().equals(ownerPackage)) { 19727 resolver.removeFilter(filter); 19728 } 19729 } 19730 scheduleWritePackageRestrictionsLocked(sourceUserId); 19731 } 19732 } 19733 19734 // Enforcing that callingUid is owning pkg on userId 19735 private void enforceOwnerRights(String pkg, int callingUid) { 19736 // The system owns everything. 19737 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19738 return; 19739 } 19740 int callingUserId = UserHandle.getUserId(callingUid); 19741 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19742 if (pi == null) { 19743 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19744 + callingUserId); 19745 } 19746 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19747 throw new SecurityException("Calling uid " + callingUid 19748 + " does not own package " + pkg); 19749 } 19750 } 19751 19752 @Override 19753 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19754 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19755 } 19756 19757 /** 19758 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19759 * then reports the most likely home activity or null if there are more than one. 19760 */ 19761 public ComponentName getDefaultHomeActivity(int userId) { 19762 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19763 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19764 if (cn != null) { 19765 return cn; 19766 } 19767 19768 // Find the launcher with the highest priority and return that component if there are no 19769 // other home activity with the same priority. 19770 int lastPriority = Integer.MIN_VALUE; 19771 ComponentName lastComponent = null; 19772 final int size = allHomeCandidates.size(); 19773 for (int i = 0; i < size; i++) { 19774 final ResolveInfo ri = allHomeCandidates.get(i); 19775 if (ri.priority > lastPriority) { 19776 lastComponent = ri.activityInfo.getComponentName(); 19777 lastPriority = ri.priority; 19778 } else if (ri.priority == lastPriority) { 19779 // Two components found with same priority. 19780 lastComponent = null; 19781 } 19782 } 19783 return lastComponent; 19784 } 19785 19786 private Intent getHomeIntent() { 19787 Intent intent = new Intent(Intent.ACTION_MAIN); 19788 intent.addCategory(Intent.CATEGORY_HOME); 19789 intent.addCategory(Intent.CATEGORY_DEFAULT); 19790 return intent; 19791 } 19792 19793 private IntentFilter getHomeFilter() { 19794 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19795 filter.addCategory(Intent.CATEGORY_HOME); 19796 filter.addCategory(Intent.CATEGORY_DEFAULT); 19797 return filter; 19798 } 19799 19800 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19801 int userId) { 19802 Intent intent = getHomeIntent(); 19803 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19804 PackageManager.GET_META_DATA, userId); 19805 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19806 true, false, false, userId); 19807 19808 allHomeCandidates.clear(); 19809 if (list != null) { 19810 for (ResolveInfo ri : list) { 19811 allHomeCandidates.add(ri); 19812 } 19813 } 19814 return (preferred == null || preferred.activityInfo == null) 19815 ? null 19816 : new ComponentName(preferred.activityInfo.packageName, 19817 preferred.activityInfo.name); 19818 } 19819 19820 @Override 19821 public void setHomeActivity(ComponentName comp, int userId) { 19822 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19823 getHomeActivitiesAsUser(homeActivities, userId); 19824 19825 boolean found = false; 19826 19827 final int size = homeActivities.size(); 19828 final ComponentName[] set = new ComponentName[size]; 19829 for (int i = 0; i < size; i++) { 19830 final ResolveInfo candidate = homeActivities.get(i); 19831 final ActivityInfo info = candidate.activityInfo; 19832 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19833 set[i] = activityName; 19834 if (!found && activityName.equals(comp)) { 19835 found = true; 19836 } 19837 } 19838 if (!found) { 19839 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19840 + userId); 19841 } 19842 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19843 set, comp, userId); 19844 } 19845 19846 private @Nullable String getSetupWizardPackageName() { 19847 final Intent intent = new Intent(Intent.ACTION_MAIN); 19848 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19849 19850 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19851 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19852 | MATCH_DISABLED_COMPONENTS, 19853 UserHandle.myUserId()); 19854 if (matches.size() == 1) { 19855 return matches.get(0).getComponentInfo().packageName; 19856 } else { 19857 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19858 + ": matches=" + matches); 19859 return null; 19860 } 19861 } 19862 19863 private @Nullable String getStorageManagerPackageName() { 19864 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19865 19866 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19867 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19868 | MATCH_DISABLED_COMPONENTS, 19869 UserHandle.myUserId()); 19870 if (matches.size() == 1) { 19871 return matches.get(0).getComponentInfo().packageName; 19872 } else { 19873 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19874 + matches.size() + ": matches=" + matches); 19875 return null; 19876 } 19877 } 19878 19879 @Override 19880 public void setApplicationEnabledSetting(String appPackageName, 19881 int newState, int flags, int userId, String callingPackage) { 19882 if (!sUserManager.exists(userId)) return; 19883 if (callingPackage == null) { 19884 callingPackage = Integer.toString(Binder.getCallingUid()); 19885 } 19886 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19887 } 19888 19889 @Override 19890 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19891 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19892 synchronized (mPackages) { 19893 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19894 if (pkgSetting != null) { 19895 pkgSetting.setUpdateAvailable(updateAvailable); 19896 } 19897 } 19898 } 19899 19900 @Override 19901 public void setComponentEnabledSetting(ComponentName componentName, 19902 int newState, int flags, int userId) { 19903 if (!sUserManager.exists(userId)) return; 19904 setEnabledSetting(componentName.getPackageName(), 19905 componentName.getClassName(), newState, flags, userId, null); 19906 } 19907 19908 private void setEnabledSetting(final String packageName, String className, int newState, 19909 final int flags, int userId, String callingPackage) { 19910 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19911 || newState == COMPONENT_ENABLED_STATE_ENABLED 19912 || newState == COMPONENT_ENABLED_STATE_DISABLED 19913 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19914 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19915 throw new IllegalArgumentException("Invalid new component state: " 19916 + newState); 19917 } 19918 PackageSetting pkgSetting; 19919 final int uid = Binder.getCallingUid(); 19920 final int permission; 19921 if (uid == Process.SYSTEM_UID) { 19922 permission = PackageManager.PERMISSION_GRANTED; 19923 } else { 19924 permission = mContext.checkCallingOrSelfPermission( 19925 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19926 } 19927 enforceCrossUserPermission(uid, userId, 19928 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19929 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19930 boolean sendNow = false; 19931 boolean isApp = (className == null); 19932 String componentName = isApp ? packageName : className; 19933 int packageUid = -1; 19934 ArrayList<String> components; 19935 19936 // writer 19937 synchronized (mPackages) { 19938 pkgSetting = mSettings.mPackages.get(packageName); 19939 if (pkgSetting == null) { 19940 if (className == null) { 19941 throw new IllegalArgumentException("Unknown package: " + packageName); 19942 } 19943 throw new IllegalArgumentException( 19944 "Unknown component: " + packageName + "/" + className); 19945 } 19946 } 19947 19948 // Limit who can change which apps 19949 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19950 // Don't allow apps that don't have permission to modify other apps 19951 if (!allowedByPermission) { 19952 throw new SecurityException( 19953 "Permission Denial: attempt to change component state from pid=" 19954 + Binder.getCallingPid() 19955 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19956 } 19957 // Don't allow changing protected packages. 19958 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19959 throw new SecurityException("Cannot disable a protected package: " + packageName); 19960 } 19961 } 19962 19963 synchronized (mPackages) { 19964 if (uid == Process.SHELL_UID 19965 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19966 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19967 // unless it is a test package. 19968 int oldState = pkgSetting.getEnabled(userId); 19969 if (className == null 19970 && 19971 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19972 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19973 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19974 && 19975 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19976 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19977 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19978 // ok 19979 } else { 19980 throw new SecurityException( 19981 "Shell cannot change component state for " + packageName + "/" 19982 + className + " to " + newState); 19983 } 19984 } 19985 if (className == null) { 19986 // We're dealing with an application/package level state change 19987 if (pkgSetting.getEnabled(userId) == newState) { 19988 // Nothing to do 19989 return; 19990 } 19991 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19992 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19993 // Don't care about who enables an app. 19994 callingPackage = null; 19995 } 19996 pkgSetting.setEnabled(newState, userId, callingPackage); 19997 // pkgSetting.pkg.mSetEnabled = newState; 19998 } else { 19999 // We're dealing with a component level state change 20000 // First, verify that this is a valid class name. 20001 PackageParser.Package pkg = pkgSetting.pkg; 20002 if (pkg == null || !pkg.hasComponentClassName(className)) { 20003 if (pkg != null && 20004 pkg.applicationInfo.targetSdkVersion >= 20005 Build.VERSION_CODES.JELLY_BEAN) { 20006 throw new IllegalArgumentException("Component class " + className 20007 + " does not exist in " + packageName); 20008 } else { 20009 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20010 + className + " does not exist in " + packageName); 20011 } 20012 } 20013 switch (newState) { 20014 case COMPONENT_ENABLED_STATE_ENABLED: 20015 if (!pkgSetting.enableComponentLPw(className, userId)) { 20016 return; 20017 } 20018 break; 20019 case COMPONENT_ENABLED_STATE_DISABLED: 20020 if (!pkgSetting.disableComponentLPw(className, userId)) { 20021 return; 20022 } 20023 break; 20024 case COMPONENT_ENABLED_STATE_DEFAULT: 20025 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20026 return; 20027 } 20028 break; 20029 default: 20030 Slog.e(TAG, "Invalid new component state: " + newState); 20031 return; 20032 } 20033 } 20034 scheduleWritePackageRestrictionsLocked(userId); 20035 updateSequenceNumberLP(packageName, new int[] { userId }); 20036 final long callingId = Binder.clearCallingIdentity(); 20037 try { 20038 updateInstantAppInstallerLocked(packageName); 20039 } finally { 20040 Binder.restoreCallingIdentity(callingId); 20041 } 20042 components = mPendingBroadcasts.get(userId, packageName); 20043 final boolean newPackage = components == null; 20044 if (newPackage) { 20045 components = new ArrayList<String>(); 20046 } 20047 if (!components.contains(componentName)) { 20048 components.add(componentName); 20049 } 20050 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20051 sendNow = true; 20052 // Purge entry from pending broadcast list if another one exists already 20053 // since we are sending one right away. 20054 mPendingBroadcasts.remove(userId, packageName); 20055 } else { 20056 if (newPackage) { 20057 mPendingBroadcasts.put(userId, packageName, components); 20058 } 20059 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20060 // Schedule a message 20061 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20062 } 20063 } 20064 } 20065 20066 long callingId = Binder.clearCallingIdentity(); 20067 try { 20068 if (sendNow) { 20069 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20070 sendPackageChangedBroadcast(packageName, 20071 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20072 } 20073 } finally { 20074 Binder.restoreCallingIdentity(callingId); 20075 } 20076 } 20077 20078 @Override 20079 public void flushPackageRestrictionsAsUser(int userId) { 20080 if (!sUserManager.exists(userId)) { 20081 return; 20082 } 20083 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20084 false /* checkShell */, "flushPackageRestrictions"); 20085 synchronized (mPackages) { 20086 mSettings.writePackageRestrictionsLPr(userId); 20087 mDirtyUsers.remove(userId); 20088 if (mDirtyUsers.isEmpty()) { 20089 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20090 } 20091 } 20092 } 20093 20094 private void sendPackageChangedBroadcast(String packageName, 20095 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20096 if (DEBUG_INSTALL) 20097 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20098 + componentNames); 20099 Bundle extras = new Bundle(4); 20100 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20101 String nameList[] = new String[componentNames.size()]; 20102 componentNames.toArray(nameList); 20103 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20104 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20105 extras.putInt(Intent.EXTRA_UID, packageUid); 20106 // If this is not reporting a change of the overall package, then only send it 20107 // to registered receivers. We don't want to launch a swath of apps for every 20108 // little component state change. 20109 final int flags = !componentNames.contains(packageName) 20110 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20111 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20112 new int[] {UserHandle.getUserId(packageUid)}); 20113 } 20114 20115 @Override 20116 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20117 if (!sUserManager.exists(userId)) return; 20118 final int uid = Binder.getCallingUid(); 20119 final int permission = mContext.checkCallingOrSelfPermission( 20120 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20121 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20122 enforceCrossUserPermission(uid, userId, 20123 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20124 // writer 20125 synchronized (mPackages) { 20126 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20127 allowedByPermission, uid, userId)) { 20128 scheduleWritePackageRestrictionsLocked(userId); 20129 } 20130 } 20131 } 20132 20133 @Override 20134 public String getInstallerPackageName(String packageName) { 20135 // reader 20136 synchronized (mPackages) { 20137 return mSettings.getInstallerPackageNameLPr(packageName); 20138 } 20139 } 20140 20141 public boolean isOrphaned(String packageName) { 20142 // reader 20143 synchronized (mPackages) { 20144 return mSettings.isOrphaned(packageName); 20145 } 20146 } 20147 20148 @Override 20149 public int getApplicationEnabledSetting(String packageName, int userId) { 20150 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20151 int uid = Binder.getCallingUid(); 20152 enforceCrossUserPermission(uid, userId, 20153 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20154 // reader 20155 synchronized (mPackages) { 20156 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20157 } 20158 } 20159 20160 @Override 20161 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20162 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20163 int uid = Binder.getCallingUid(); 20164 enforceCrossUserPermission(uid, userId, 20165 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20166 // reader 20167 synchronized (mPackages) { 20168 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20169 } 20170 } 20171 20172 @Override 20173 public void enterSafeMode() { 20174 enforceSystemOrRoot("Only the system can request entering safe mode"); 20175 20176 if (!mSystemReady) { 20177 mSafeMode = true; 20178 } 20179 } 20180 20181 @Override 20182 public void systemReady() { 20183 mSystemReady = true; 20184 20185 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20186 // disabled after already being started. 20187 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20188 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20189 20190 // Read the compatibilty setting when the system is ready. 20191 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20192 mContext.getContentResolver(), 20193 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20194 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20195 if (DEBUG_SETTINGS) { 20196 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20197 } 20198 20199 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20200 20201 synchronized (mPackages) { 20202 // Verify that all of the preferred activity components actually 20203 // exist. It is possible for applications to be updated and at 20204 // that point remove a previously declared activity component that 20205 // had been set as a preferred activity. We try to clean this up 20206 // the next time we encounter that preferred activity, but it is 20207 // possible for the user flow to never be able to return to that 20208 // situation so here we do a sanity check to make sure we haven't 20209 // left any junk around. 20210 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20211 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20212 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20213 removed.clear(); 20214 for (PreferredActivity pa : pir.filterSet()) { 20215 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20216 removed.add(pa); 20217 } 20218 } 20219 if (removed.size() > 0) { 20220 for (int r=0; r<removed.size(); r++) { 20221 PreferredActivity pa = removed.get(r); 20222 Slog.w(TAG, "Removing dangling preferred activity: " 20223 + pa.mPref.mComponent); 20224 pir.removeFilter(pa); 20225 } 20226 mSettings.writePackageRestrictionsLPr( 20227 mSettings.mPreferredActivities.keyAt(i)); 20228 } 20229 } 20230 20231 for (int userId : UserManagerService.getInstance().getUserIds()) { 20232 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20233 grantPermissionsUserIds = ArrayUtils.appendInt( 20234 grantPermissionsUserIds, userId); 20235 } 20236 } 20237 } 20238 sUserManager.systemReady(); 20239 20240 // If we upgraded grant all default permissions before kicking off. 20241 for (int userId : grantPermissionsUserIds) { 20242 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20243 } 20244 20245 // If we did not grant default permissions, we preload from this the 20246 // default permission exceptions lazily to ensure we don't hit the 20247 // disk on a new user creation. 20248 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20249 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20250 } 20251 20252 // Kick off any messages waiting for system ready 20253 if (mPostSystemReadyMessages != null) { 20254 for (Message msg : mPostSystemReadyMessages) { 20255 msg.sendToTarget(); 20256 } 20257 mPostSystemReadyMessages = null; 20258 } 20259 20260 // Watch for external volumes that come and go over time 20261 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20262 storage.registerListener(mStorageListener); 20263 20264 mInstallerService.systemReady(); 20265 mPackageDexOptimizer.systemReady(); 20266 20267 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20268 StorageManagerInternal.class); 20269 StorageManagerInternal.addExternalStoragePolicy( 20270 new StorageManagerInternal.ExternalStorageMountPolicy() { 20271 @Override 20272 public int getMountMode(int uid, String packageName) { 20273 if (Process.isIsolated(uid)) { 20274 return Zygote.MOUNT_EXTERNAL_NONE; 20275 } 20276 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20277 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20278 } 20279 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20280 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20281 } 20282 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20283 return Zygote.MOUNT_EXTERNAL_READ; 20284 } 20285 return Zygote.MOUNT_EXTERNAL_WRITE; 20286 } 20287 20288 @Override 20289 public boolean hasExternalStorage(int uid, String packageName) { 20290 return true; 20291 } 20292 }); 20293 20294 // Now that we're mostly running, clean up stale users and apps 20295 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20296 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20297 20298 if (mPrivappPermissionsViolations != null) { 20299 Slog.wtf(TAG,"Signature|privileged permissions not in " 20300 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20301 mPrivappPermissionsViolations = null; 20302 } 20303 } 20304 20305 public void waitForAppDataPrepared() { 20306 if (mPrepareAppDataFuture == null) { 20307 return; 20308 } 20309 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20310 mPrepareAppDataFuture = null; 20311 } 20312 20313 @Override 20314 public boolean isSafeMode() { 20315 return mSafeMode; 20316 } 20317 20318 @Override 20319 public boolean hasSystemUidErrors() { 20320 return mHasSystemUidErrors; 20321 } 20322 20323 static String arrayToString(int[] array) { 20324 StringBuffer buf = new StringBuffer(128); 20325 buf.append('['); 20326 if (array != null) { 20327 for (int i=0; i<array.length; i++) { 20328 if (i > 0) buf.append(", "); 20329 buf.append(array[i]); 20330 } 20331 } 20332 buf.append(']'); 20333 return buf.toString(); 20334 } 20335 20336 static class DumpState { 20337 public static final int DUMP_LIBS = 1 << 0; 20338 public static final int DUMP_FEATURES = 1 << 1; 20339 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20340 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20341 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20342 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20343 public static final int DUMP_PERMISSIONS = 1 << 6; 20344 public static final int DUMP_PACKAGES = 1 << 7; 20345 public static final int DUMP_SHARED_USERS = 1 << 8; 20346 public static final int DUMP_MESSAGES = 1 << 9; 20347 public static final int DUMP_PROVIDERS = 1 << 10; 20348 public static final int DUMP_VERIFIERS = 1 << 11; 20349 public static final int DUMP_PREFERRED = 1 << 12; 20350 public static final int DUMP_PREFERRED_XML = 1 << 13; 20351 public static final int DUMP_KEYSETS = 1 << 14; 20352 public static final int DUMP_VERSION = 1 << 15; 20353 public static final int DUMP_INSTALLS = 1 << 16; 20354 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20355 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20356 public static final int DUMP_FROZEN = 1 << 19; 20357 public static final int DUMP_DEXOPT = 1 << 20; 20358 public static final int DUMP_COMPILER_STATS = 1 << 21; 20359 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20360 20361 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20362 20363 private int mTypes; 20364 20365 private int mOptions; 20366 20367 private boolean mTitlePrinted; 20368 20369 private SharedUserSetting mSharedUser; 20370 20371 public boolean isDumping(int type) { 20372 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20373 return true; 20374 } 20375 20376 return (mTypes & type) != 0; 20377 } 20378 20379 public void setDump(int type) { 20380 mTypes |= type; 20381 } 20382 20383 public boolean isOptionEnabled(int option) { 20384 return (mOptions & option) != 0; 20385 } 20386 20387 public void setOptionEnabled(int option) { 20388 mOptions |= option; 20389 } 20390 20391 public boolean onTitlePrinted() { 20392 final boolean printed = mTitlePrinted; 20393 mTitlePrinted = true; 20394 return printed; 20395 } 20396 20397 public boolean getTitlePrinted() { 20398 return mTitlePrinted; 20399 } 20400 20401 public void setTitlePrinted(boolean enabled) { 20402 mTitlePrinted = enabled; 20403 } 20404 20405 public SharedUserSetting getSharedUser() { 20406 return mSharedUser; 20407 } 20408 20409 public void setSharedUser(SharedUserSetting user) { 20410 mSharedUser = user; 20411 } 20412 } 20413 20414 @Override 20415 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20416 FileDescriptor err, String[] args, ShellCallback callback, 20417 ResultReceiver resultReceiver) { 20418 (new PackageManagerShellCommand(this)).exec( 20419 this, in, out, err, args, callback, resultReceiver); 20420 } 20421 20422 @Override 20423 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20424 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20425 20426 DumpState dumpState = new DumpState(); 20427 boolean fullPreferred = false; 20428 boolean checkin = false; 20429 20430 String packageName = null; 20431 ArraySet<String> permissionNames = null; 20432 20433 int opti = 0; 20434 while (opti < args.length) { 20435 String opt = args[opti]; 20436 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20437 break; 20438 } 20439 opti++; 20440 20441 if ("-a".equals(opt)) { 20442 // Right now we only know how to print all. 20443 } else if ("-h".equals(opt)) { 20444 pw.println("Package manager dump options:"); 20445 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20446 pw.println(" --checkin: dump for a checkin"); 20447 pw.println(" -f: print details of intent filters"); 20448 pw.println(" -h: print this help"); 20449 pw.println(" cmd may be one of:"); 20450 pw.println(" l[ibraries]: list known shared libraries"); 20451 pw.println(" f[eatures]: list device features"); 20452 pw.println(" k[eysets]: print known keysets"); 20453 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20454 pw.println(" perm[issions]: dump permissions"); 20455 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20456 pw.println(" pref[erred]: print preferred package settings"); 20457 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20458 pw.println(" prov[iders]: dump content providers"); 20459 pw.println(" p[ackages]: dump installed packages"); 20460 pw.println(" s[hared-users]: dump shared user IDs"); 20461 pw.println(" m[essages]: print collected runtime messages"); 20462 pw.println(" v[erifiers]: print package verifier info"); 20463 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20464 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20465 pw.println(" version: print database version info"); 20466 pw.println(" write: write current settings now"); 20467 pw.println(" installs: details about install sessions"); 20468 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20469 pw.println(" dexopt: dump dexopt state"); 20470 pw.println(" compiler-stats: dump compiler statistics"); 20471 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20472 pw.println(" <package.name>: info about given package"); 20473 return; 20474 } else if ("--checkin".equals(opt)) { 20475 checkin = true; 20476 } else if ("-f".equals(opt)) { 20477 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20478 } else if ("--proto".equals(opt)) { 20479 dumpProto(fd); 20480 return; 20481 } else { 20482 pw.println("Unknown argument: " + opt + "; use -h for help"); 20483 } 20484 } 20485 20486 // Is the caller requesting to dump a particular piece of data? 20487 if (opti < args.length) { 20488 String cmd = args[opti]; 20489 opti++; 20490 // Is this a package name? 20491 if ("android".equals(cmd) || cmd.contains(".")) { 20492 packageName = cmd; 20493 // When dumping a single package, we always dump all of its 20494 // filter information since the amount of data will be reasonable. 20495 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20496 } else if ("check-permission".equals(cmd)) { 20497 if (opti >= args.length) { 20498 pw.println("Error: check-permission missing permission argument"); 20499 return; 20500 } 20501 String perm = args[opti]; 20502 opti++; 20503 if (opti >= args.length) { 20504 pw.println("Error: check-permission missing package argument"); 20505 return; 20506 } 20507 20508 String pkg = args[opti]; 20509 opti++; 20510 int user = UserHandle.getUserId(Binder.getCallingUid()); 20511 if (opti < args.length) { 20512 try { 20513 user = Integer.parseInt(args[opti]); 20514 } catch (NumberFormatException e) { 20515 pw.println("Error: check-permission user argument is not a number: " 20516 + args[opti]); 20517 return; 20518 } 20519 } 20520 20521 // Normalize package name to handle renamed packages and static libs 20522 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20523 20524 pw.println(checkPermission(perm, pkg, user)); 20525 return; 20526 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20527 dumpState.setDump(DumpState.DUMP_LIBS); 20528 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20529 dumpState.setDump(DumpState.DUMP_FEATURES); 20530 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20531 if (opti >= args.length) { 20532 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20533 | DumpState.DUMP_SERVICE_RESOLVERS 20534 | DumpState.DUMP_RECEIVER_RESOLVERS 20535 | DumpState.DUMP_CONTENT_RESOLVERS); 20536 } else { 20537 while (opti < args.length) { 20538 String name = args[opti]; 20539 if ("a".equals(name) || "activity".equals(name)) { 20540 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20541 } else if ("s".equals(name) || "service".equals(name)) { 20542 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20543 } else if ("r".equals(name) || "receiver".equals(name)) { 20544 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20545 } else if ("c".equals(name) || "content".equals(name)) { 20546 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20547 } else { 20548 pw.println("Error: unknown resolver table type: " + name); 20549 return; 20550 } 20551 opti++; 20552 } 20553 } 20554 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20555 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20556 } else if ("permission".equals(cmd)) { 20557 if (opti >= args.length) { 20558 pw.println("Error: permission requires permission name"); 20559 return; 20560 } 20561 permissionNames = new ArraySet<>(); 20562 while (opti < args.length) { 20563 permissionNames.add(args[opti]); 20564 opti++; 20565 } 20566 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20567 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20568 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20569 dumpState.setDump(DumpState.DUMP_PREFERRED); 20570 } else if ("preferred-xml".equals(cmd)) { 20571 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20572 if (opti < args.length && "--full".equals(args[opti])) { 20573 fullPreferred = true; 20574 opti++; 20575 } 20576 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20577 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20578 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20579 dumpState.setDump(DumpState.DUMP_PACKAGES); 20580 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20581 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20582 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20583 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20584 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20585 dumpState.setDump(DumpState.DUMP_MESSAGES); 20586 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20587 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20588 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20589 || "intent-filter-verifiers".equals(cmd)) { 20590 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20591 } else if ("version".equals(cmd)) { 20592 dumpState.setDump(DumpState.DUMP_VERSION); 20593 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20594 dumpState.setDump(DumpState.DUMP_KEYSETS); 20595 } else if ("installs".equals(cmd)) { 20596 dumpState.setDump(DumpState.DUMP_INSTALLS); 20597 } else if ("frozen".equals(cmd)) { 20598 dumpState.setDump(DumpState.DUMP_FROZEN); 20599 } else if ("dexopt".equals(cmd)) { 20600 dumpState.setDump(DumpState.DUMP_DEXOPT); 20601 } else if ("compiler-stats".equals(cmd)) { 20602 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20603 } else if ("enabled-overlays".equals(cmd)) { 20604 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20605 } else if ("write".equals(cmd)) { 20606 synchronized (mPackages) { 20607 mSettings.writeLPr(); 20608 pw.println("Settings written."); 20609 return; 20610 } 20611 } 20612 } 20613 20614 if (checkin) { 20615 pw.println("vers,1"); 20616 } 20617 20618 // reader 20619 synchronized (mPackages) { 20620 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20621 if (!checkin) { 20622 if (dumpState.onTitlePrinted()) 20623 pw.println(); 20624 pw.println("Database versions:"); 20625 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20626 } 20627 } 20628 20629 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20630 if (!checkin) { 20631 if (dumpState.onTitlePrinted()) 20632 pw.println(); 20633 pw.println("Verifiers:"); 20634 pw.print(" Required: "); 20635 pw.print(mRequiredVerifierPackage); 20636 pw.print(" (uid="); 20637 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20638 UserHandle.USER_SYSTEM)); 20639 pw.println(")"); 20640 } else if (mRequiredVerifierPackage != null) { 20641 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20642 pw.print(","); 20643 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20644 UserHandle.USER_SYSTEM)); 20645 } 20646 } 20647 20648 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20649 packageName == null) { 20650 if (mIntentFilterVerifierComponent != null) { 20651 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20652 if (!checkin) { 20653 if (dumpState.onTitlePrinted()) 20654 pw.println(); 20655 pw.println("Intent Filter Verifier:"); 20656 pw.print(" Using: "); 20657 pw.print(verifierPackageName); 20658 pw.print(" (uid="); 20659 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20660 UserHandle.USER_SYSTEM)); 20661 pw.println(")"); 20662 } else if (verifierPackageName != null) { 20663 pw.print("ifv,"); pw.print(verifierPackageName); 20664 pw.print(","); 20665 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20666 UserHandle.USER_SYSTEM)); 20667 } 20668 } else { 20669 pw.println(); 20670 pw.println("No Intent Filter Verifier available!"); 20671 } 20672 } 20673 20674 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20675 boolean printedHeader = false; 20676 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20677 while (it.hasNext()) { 20678 String libName = it.next(); 20679 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20680 if (versionedLib == null) { 20681 continue; 20682 } 20683 final int versionCount = versionedLib.size(); 20684 for (int i = 0; i < versionCount; i++) { 20685 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20686 if (!checkin) { 20687 if (!printedHeader) { 20688 if (dumpState.onTitlePrinted()) 20689 pw.println(); 20690 pw.println("Libraries:"); 20691 printedHeader = true; 20692 } 20693 pw.print(" "); 20694 } else { 20695 pw.print("lib,"); 20696 } 20697 pw.print(libEntry.info.getName()); 20698 if (libEntry.info.isStatic()) { 20699 pw.print(" version=" + libEntry.info.getVersion()); 20700 } 20701 if (!checkin) { 20702 pw.print(" -> "); 20703 } 20704 if (libEntry.path != null) { 20705 pw.print(" (jar) "); 20706 pw.print(libEntry.path); 20707 } else { 20708 pw.print(" (apk) "); 20709 pw.print(libEntry.apk); 20710 } 20711 pw.println(); 20712 } 20713 } 20714 } 20715 20716 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20717 if (dumpState.onTitlePrinted()) 20718 pw.println(); 20719 if (!checkin) { 20720 pw.println("Features:"); 20721 } 20722 20723 synchronized (mAvailableFeatures) { 20724 for (FeatureInfo feat : mAvailableFeatures.values()) { 20725 if (checkin) { 20726 pw.print("feat,"); 20727 pw.print(feat.name); 20728 pw.print(","); 20729 pw.println(feat.version); 20730 } else { 20731 pw.print(" "); 20732 pw.print(feat.name); 20733 if (feat.version > 0) { 20734 pw.print(" version="); 20735 pw.print(feat.version); 20736 } 20737 pw.println(); 20738 } 20739 } 20740 } 20741 } 20742 20743 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20744 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20745 : "Activity Resolver Table:", " ", packageName, 20746 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20747 dumpState.setTitlePrinted(true); 20748 } 20749 } 20750 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20751 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20752 : "Receiver Resolver Table:", " ", packageName, 20753 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20754 dumpState.setTitlePrinted(true); 20755 } 20756 } 20757 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20758 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20759 : "Service Resolver Table:", " ", packageName, 20760 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20761 dumpState.setTitlePrinted(true); 20762 } 20763 } 20764 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20765 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20766 : "Provider Resolver Table:", " ", packageName, 20767 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20768 dumpState.setTitlePrinted(true); 20769 } 20770 } 20771 20772 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20773 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20774 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20775 int user = mSettings.mPreferredActivities.keyAt(i); 20776 if (pir.dump(pw, 20777 dumpState.getTitlePrinted() 20778 ? "\nPreferred Activities User " + user + ":" 20779 : "Preferred Activities User " + user + ":", " ", 20780 packageName, true, false)) { 20781 dumpState.setTitlePrinted(true); 20782 } 20783 } 20784 } 20785 20786 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20787 pw.flush(); 20788 FileOutputStream fout = new FileOutputStream(fd); 20789 BufferedOutputStream str = new BufferedOutputStream(fout); 20790 XmlSerializer serializer = new FastXmlSerializer(); 20791 try { 20792 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20793 serializer.startDocument(null, true); 20794 serializer.setFeature( 20795 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20796 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20797 serializer.endDocument(); 20798 serializer.flush(); 20799 } catch (IllegalArgumentException e) { 20800 pw.println("Failed writing: " + e); 20801 } catch (IllegalStateException e) { 20802 pw.println("Failed writing: " + e); 20803 } catch (IOException e) { 20804 pw.println("Failed writing: " + e); 20805 } 20806 } 20807 20808 if (!checkin 20809 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20810 && packageName == null) { 20811 pw.println(); 20812 int count = mSettings.mPackages.size(); 20813 if (count == 0) { 20814 pw.println("No applications!"); 20815 pw.println(); 20816 } else { 20817 final String prefix = " "; 20818 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20819 if (allPackageSettings.size() == 0) { 20820 pw.println("No domain preferred apps!"); 20821 pw.println(); 20822 } else { 20823 pw.println("App verification status:"); 20824 pw.println(); 20825 count = 0; 20826 for (PackageSetting ps : allPackageSettings) { 20827 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20828 if (ivi == null || ivi.getPackageName() == null) continue; 20829 pw.println(prefix + "Package: " + ivi.getPackageName()); 20830 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20831 pw.println(prefix + "Status: " + ivi.getStatusString()); 20832 pw.println(); 20833 count++; 20834 } 20835 if (count == 0) { 20836 pw.println(prefix + "No app verification established."); 20837 pw.println(); 20838 } 20839 for (int userId : sUserManager.getUserIds()) { 20840 pw.println("App linkages for user " + userId + ":"); 20841 pw.println(); 20842 count = 0; 20843 for (PackageSetting ps : allPackageSettings) { 20844 final long status = ps.getDomainVerificationStatusForUser(userId); 20845 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20846 && !DEBUG_DOMAIN_VERIFICATION) { 20847 continue; 20848 } 20849 pw.println(prefix + "Package: " + ps.name); 20850 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20851 String statusStr = IntentFilterVerificationInfo. 20852 getStatusStringFromValue(status); 20853 pw.println(prefix + "Status: " + statusStr); 20854 pw.println(); 20855 count++; 20856 } 20857 if (count == 0) { 20858 pw.println(prefix + "No configured app linkages."); 20859 pw.println(); 20860 } 20861 } 20862 } 20863 } 20864 } 20865 20866 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20867 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20868 if (packageName == null && permissionNames == null) { 20869 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20870 if (iperm == 0) { 20871 if (dumpState.onTitlePrinted()) 20872 pw.println(); 20873 pw.println("AppOp Permissions:"); 20874 } 20875 pw.print(" AppOp Permission "); 20876 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20877 pw.println(":"); 20878 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20879 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20880 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20881 } 20882 } 20883 } 20884 } 20885 20886 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20887 boolean printedSomething = false; 20888 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20889 if (packageName != null && !packageName.equals(p.info.packageName)) { 20890 continue; 20891 } 20892 if (!printedSomething) { 20893 if (dumpState.onTitlePrinted()) 20894 pw.println(); 20895 pw.println("Registered ContentProviders:"); 20896 printedSomething = true; 20897 } 20898 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20899 pw.print(" "); pw.println(p.toString()); 20900 } 20901 printedSomething = false; 20902 for (Map.Entry<String, PackageParser.Provider> entry : 20903 mProvidersByAuthority.entrySet()) { 20904 PackageParser.Provider p = entry.getValue(); 20905 if (packageName != null && !packageName.equals(p.info.packageName)) { 20906 continue; 20907 } 20908 if (!printedSomething) { 20909 if (dumpState.onTitlePrinted()) 20910 pw.println(); 20911 pw.println("ContentProvider Authorities:"); 20912 printedSomething = true; 20913 } 20914 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20915 pw.print(" "); pw.println(p.toString()); 20916 if (p.info != null && p.info.applicationInfo != null) { 20917 final String appInfo = p.info.applicationInfo.toString(); 20918 pw.print(" applicationInfo="); pw.println(appInfo); 20919 } 20920 } 20921 } 20922 20923 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20924 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20925 } 20926 20927 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20928 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20929 } 20930 20931 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20932 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20933 } 20934 20935 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20936 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20937 } 20938 20939 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20940 // XXX should handle packageName != null by dumping only install data that 20941 // the given package is involved with. 20942 if (dumpState.onTitlePrinted()) pw.println(); 20943 20944 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20945 ipw.println(); 20946 ipw.println("Frozen packages:"); 20947 ipw.increaseIndent(); 20948 if (mFrozenPackages.size() == 0) { 20949 ipw.println("(none)"); 20950 } else { 20951 for (int i = 0; i < mFrozenPackages.size(); i++) { 20952 ipw.println(mFrozenPackages.valueAt(i)); 20953 } 20954 } 20955 ipw.decreaseIndent(); 20956 } 20957 20958 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20959 if (dumpState.onTitlePrinted()) pw.println(); 20960 dumpDexoptStateLPr(pw, packageName); 20961 } 20962 20963 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20964 if (dumpState.onTitlePrinted()) pw.println(); 20965 dumpCompilerStatsLPr(pw, packageName); 20966 } 20967 20968 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20969 if (dumpState.onTitlePrinted()) pw.println(); 20970 dumpEnabledOverlaysLPr(pw); 20971 } 20972 20973 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20974 if (dumpState.onTitlePrinted()) pw.println(); 20975 mSettings.dumpReadMessagesLPr(pw, dumpState); 20976 20977 pw.println(); 20978 pw.println("Package warning messages:"); 20979 BufferedReader in = null; 20980 String line = null; 20981 try { 20982 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20983 while ((line = in.readLine()) != null) { 20984 if (line.contains("ignored: updated version")) continue; 20985 pw.println(line); 20986 } 20987 } catch (IOException ignored) { 20988 } finally { 20989 IoUtils.closeQuietly(in); 20990 } 20991 } 20992 20993 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20994 BufferedReader in = null; 20995 String line = null; 20996 try { 20997 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20998 while ((line = in.readLine()) != null) { 20999 if (line.contains("ignored: updated version")) continue; 21000 pw.print("msg,"); 21001 pw.println(line); 21002 } 21003 } catch (IOException ignored) { 21004 } finally { 21005 IoUtils.closeQuietly(in); 21006 } 21007 } 21008 } 21009 21010 // PackageInstaller should be called outside of mPackages lock 21011 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21012 // XXX should handle packageName != null by dumping only install data that 21013 // the given package is involved with. 21014 if (dumpState.onTitlePrinted()) pw.println(); 21015 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21016 } 21017 } 21018 21019 private void dumpProto(FileDescriptor fd) { 21020 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21021 21022 synchronized (mPackages) { 21023 final long requiredVerifierPackageToken = 21024 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21025 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21026 proto.write( 21027 PackageServiceDumpProto.PackageShortProto.UID, 21028 getPackageUid( 21029 mRequiredVerifierPackage, 21030 MATCH_DEBUG_TRIAGED_MISSING, 21031 UserHandle.USER_SYSTEM)); 21032 proto.end(requiredVerifierPackageToken); 21033 21034 if (mIntentFilterVerifierComponent != null) { 21035 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21036 final long verifierPackageToken = 21037 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21038 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21039 proto.write( 21040 PackageServiceDumpProto.PackageShortProto.UID, 21041 getPackageUid( 21042 verifierPackageName, 21043 MATCH_DEBUG_TRIAGED_MISSING, 21044 UserHandle.USER_SYSTEM)); 21045 proto.end(verifierPackageToken); 21046 } 21047 21048 dumpSharedLibrariesProto(proto); 21049 dumpFeaturesProto(proto); 21050 mSettings.dumpPackagesProto(proto); 21051 mSettings.dumpSharedUsersProto(proto); 21052 dumpMessagesProto(proto); 21053 } 21054 proto.flush(); 21055 } 21056 21057 private void dumpMessagesProto(ProtoOutputStream proto) { 21058 BufferedReader in = null; 21059 String line = null; 21060 try { 21061 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21062 while ((line = in.readLine()) != null) { 21063 if (line.contains("ignored: updated version")) continue; 21064 proto.write(PackageServiceDumpProto.MESSAGES, line); 21065 } 21066 } catch (IOException ignored) { 21067 } finally { 21068 IoUtils.closeQuietly(in); 21069 } 21070 } 21071 21072 private void dumpFeaturesProto(ProtoOutputStream proto) { 21073 synchronized (mAvailableFeatures) { 21074 final int count = mAvailableFeatures.size(); 21075 for (int i = 0; i < count; i++) { 21076 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21077 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21078 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21079 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21080 proto.end(featureToken); 21081 } 21082 } 21083 } 21084 21085 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21086 final int count = mSharedLibraries.size(); 21087 for (int i = 0; i < count; i++) { 21088 final String libName = mSharedLibraries.keyAt(i); 21089 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21090 if (versionedLib == null) { 21091 continue; 21092 } 21093 final int versionCount = versionedLib.size(); 21094 for (int j = 0; j < versionCount; j++) { 21095 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21096 final long sharedLibraryToken = 21097 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21098 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21099 final boolean isJar = (libEntry.path != null); 21100 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21101 if (isJar) { 21102 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21103 } else { 21104 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21105 } 21106 proto.end(sharedLibraryToken); 21107 } 21108 } 21109 } 21110 21111 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21112 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21113 ipw.println(); 21114 ipw.println("Dexopt state:"); 21115 ipw.increaseIndent(); 21116 Collection<PackageParser.Package> packages = null; 21117 if (packageName != null) { 21118 PackageParser.Package targetPackage = mPackages.get(packageName); 21119 if (targetPackage != null) { 21120 packages = Collections.singletonList(targetPackage); 21121 } else { 21122 ipw.println("Unable to find package: " + packageName); 21123 return; 21124 } 21125 } else { 21126 packages = mPackages.values(); 21127 } 21128 21129 for (PackageParser.Package pkg : packages) { 21130 ipw.println("[" + pkg.packageName + "]"); 21131 ipw.increaseIndent(); 21132 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21133 ipw.decreaseIndent(); 21134 } 21135 } 21136 21137 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21138 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21139 ipw.println(); 21140 ipw.println("Compiler stats:"); 21141 ipw.increaseIndent(); 21142 Collection<PackageParser.Package> packages = null; 21143 if (packageName != null) { 21144 PackageParser.Package targetPackage = mPackages.get(packageName); 21145 if (targetPackage != null) { 21146 packages = Collections.singletonList(targetPackage); 21147 } else { 21148 ipw.println("Unable to find package: " + packageName); 21149 return; 21150 } 21151 } else { 21152 packages = mPackages.values(); 21153 } 21154 21155 for (PackageParser.Package pkg : packages) { 21156 ipw.println("[" + pkg.packageName + "]"); 21157 ipw.increaseIndent(); 21158 21159 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21160 if (stats == null) { 21161 ipw.println("(No recorded stats)"); 21162 } else { 21163 stats.dump(ipw); 21164 } 21165 ipw.decreaseIndent(); 21166 } 21167 } 21168 21169 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21170 pw.println("Enabled overlay paths:"); 21171 final int N = mEnabledOverlayPaths.size(); 21172 for (int i = 0; i < N; i++) { 21173 final int userId = mEnabledOverlayPaths.keyAt(i); 21174 pw.println(String.format(" User %d:", userId)); 21175 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21176 mEnabledOverlayPaths.valueAt(i); 21177 final int M = userSpecificOverlays.size(); 21178 for (int j = 0; j < M; j++) { 21179 final String targetPackageName = userSpecificOverlays.keyAt(j); 21180 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21181 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21182 } 21183 } 21184 } 21185 21186 private String dumpDomainString(String packageName) { 21187 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21188 .getList(); 21189 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21190 21191 ArraySet<String> result = new ArraySet<>(); 21192 if (iviList.size() > 0) { 21193 for (IntentFilterVerificationInfo ivi : iviList) { 21194 for (String host : ivi.getDomains()) { 21195 result.add(host); 21196 } 21197 } 21198 } 21199 if (filters != null && filters.size() > 0) { 21200 for (IntentFilter filter : filters) { 21201 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21202 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21203 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21204 result.addAll(filter.getHostsList()); 21205 } 21206 } 21207 } 21208 21209 StringBuilder sb = new StringBuilder(result.size() * 16); 21210 for (String domain : result) { 21211 if (sb.length() > 0) sb.append(" "); 21212 sb.append(domain); 21213 } 21214 return sb.toString(); 21215 } 21216 21217 // ------- apps on sdcard specific code ------- 21218 static final boolean DEBUG_SD_INSTALL = false; 21219 21220 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21221 21222 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21223 21224 private boolean mMediaMounted = false; 21225 21226 static String getEncryptKey() { 21227 try { 21228 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21229 SD_ENCRYPTION_KEYSTORE_NAME); 21230 if (sdEncKey == null) { 21231 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21232 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21233 if (sdEncKey == null) { 21234 Slog.e(TAG, "Failed to create encryption keys"); 21235 return null; 21236 } 21237 } 21238 return sdEncKey; 21239 } catch (NoSuchAlgorithmException nsae) { 21240 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21241 return null; 21242 } catch (IOException ioe) { 21243 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21244 return null; 21245 } 21246 } 21247 21248 /* 21249 * Update media status on PackageManager. 21250 */ 21251 @Override 21252 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21253 int callingUid = Binder.getCallingUid(); 21254 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21255 throw new SecurityException("Media status can only be updated by the system"); 21256 } 21257 // reader; this apparently protects mMediaMounted, but should probably 21258 // be a different lock in that case. 21259 synchronized (mPackages) { 21260 Log.i(TAG, "Updating external media status from " 21261 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21262 + (mediaStatus ? "mounted" : "unmounted")); 21263 if (DEBUG_SD_INSTALL) 21264 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21265 + ", mMediaMounted=" + mMediaMounted); 21266 if (mediaStatus == mMediaMounted) { 21267 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21268 : 0, -1); 21269 mHandler.sendMessage(msg); 21270 return; 21271 } 21272 mMediaMounted = mediaStatus; 21273 } 21274 // Queue up an async operation since the package installation may take a 21275 // little while. 21276 mHandler.post(new Runnable() { 21277 public void run() { 21278 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21279 } 21280 }); 21281 } 21282 21283 /** 21284 * Called by StorageManagerService when the initial ASECs to scan are available. 21285 * Should block until all the ASEC containers are finished being scanned. 21286 */ 21287 public void scanAvailableAsecs() { 21288 updateExternalMediaStatusInner(true, false, false); 21289 } 21290 21291 /* 21292 * Collect information of applications on external media, map them against 21293 * existing containers and update information based on current mount status. 21294 * Please note that we always have to report status if reportStatus has been 21295 * set to true especially when unloading packages. 21296 */ 21297 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21298 boolean externalStorage) { 21299 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21300 int[] uidArr = EmptyArray.INT; 21301 21302 final String[] list = PackageHelper.getSecureContainerList(); 21303 if (ArrayUtils.isEmpty(list)) { 21304 Log.i(TAG, "No secure containers found"); 21305 } else { 21306 // Process list of secure containers and categorize them 21307 // as active or stale based on their package internal state. 21308 21309 // reader 21310 synchronized (mPackages) { 21311 for (String cid : list) { 21312 // Leave stages untouched for now; installer service owns them 21313 if (PackageInstallerService.isStageName(cid)) continue; 21314 21315 if (DEBUG_SD_INSTALL) 21316 Log.i(TAG, "Processing container " + cid); 21317 String pkgName = getAsecPackageName(cid); 21318 if (pkgName == null) { 21319 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21320 continue; 21321 } 21322 if (DEBUG_SD_INSTALL) 21323 Log.i(TAG, "Looking for pkg : " + pkgName); 21324 21325 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21326 if (ps == null) { 21327 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21328 continue; 21329 } 21330 21331 /* 21332 * Skip packages that are not external if we're unmounting 21333 * external storage. 21334 */ 21335 if (externalStorage && !isMounted && !isExternal(ps)) { 21336 continue; 21337 } 21338 21339 final AsecInstallArgs args = new AsecInstallArgs(cid, 21340 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21341 // The package status is changed only if the code path 21342 // matches between settings and the container id. 21343 if (ps.codePathString != null 21344 && ps.codePathString.startsWith(args.getCodePath())) { 21345 if (DEBUG_SD_INSTALL) { 21346 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21347 + " at code path: " + ps.codePathString); 21348 } 21349 21350 // We do have a valid package installed on sdcard 21351 processCids.put(args, ps.codePathString); 21352 final int uid = ps.appId; 21353 if (uid != -1) { 21354 uidArr = ArrayUtils.appendInt(uidArr, uid); 21355 } 21356 } else { 21357 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21358 + ps.codePathString); 21359 } 21360 } 21361 } 21362 21363 Arrays.sort(uidArr); 21364 } 21365 21366 // Process packages with valid entries. 21367 if (isMounted) { 21368 if (DEBUG_SD_INSTALL) 21369 Log.i(TAG, "Loading packages"); 21370 loadMediaPackages(processCids, uidArr, externalStorage); 21371 startCleaningPackages(); 21372 mInstallerService.onSecureContainersAvailable(); 21373 } else { 21374 if (DEBUG_SD_INSTALL) 21375 Log.i(TAG, "Unloading packages"); 21376 unloadMediaPackages(processCids, uidArr, reportStatus); 21377 } 21378 } 21379 21380 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21381 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21382 final int size = infos.size(); 21383 final String[] packageNames = new String[size]; 21384 final int[] packageUids = new int[size]; 21385 for (int i = 0; i < size; i++) { 21386 final ApplicationInfo info = infos.get(i); 21387 packageNames[i] = info.packageName; 21388 packageUids[i] = info.uid; 21389 } 21390 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21391 finishedReceiver); 21392 } 21393 21394 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21395 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21396 sendResourcesChangedBroadcast(mediaStatus, replacing, 21397 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21398 } 21399 21400 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21401 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21402 int size = pkgList.length; 21403 if (size > 0) { 21404 // Send broadcasts here 21405 Bundle extras = new Bundle(); 21406 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21407 if (uidArr != null) { 21408 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21409 } 21410 if (replacing) { 21411 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21412 } 21413 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21414 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21415 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21416 } 21417 } 21418 21419 /* 21420 * Look at potentially valid container ids from processCids If package 21421 * information doesn't match the one on record or package scanning fails, 21422 * the cid is added to list of removeCids. We currently don't delete stale 21423 * containers. 21424 */ 21425 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21426 boolean externalStorage) { 21427 ArrayList<String> pkgList = new ArrayList<String>(); 21428 Set<AsecInstallArgs> keys = processCids.keySet(); 21429 21430 for (AsecInstallArgs args : keys) { 21431 String codePath = processCids.get(args); 21432 if (DEBUG_SD_INSTALL) 21433 Log.i(TAG, "Loading container : " + args.cid); 21434 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21435 try { 21436 // Make sure there are no container errors first. 21437 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21438 Slog.e(TAG, "Failed to mount cid : " + args.cid 21439 + " when installing from sdcard"); 21440 continue; 21441 } 21442 // Check code path here. 21443 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21444 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21445 + " does not match one in settings " + codePath); 21446 continue; 21447 } 21448 // Parse package 21449 int parseFlags = mDefParseFlags; 21450 if (args.isExternalAsec()) { 21451 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21452 } 21453 if (args.isFwdLocked()) { 21454 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21455 } 21456 21457 synchronized (mInstallLock) { 21458 PackageParser.Package pkg = null; 21459 try { 21460 // Sadly we don't know the package name yet to freeze it 21461 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21462 SCAN_IGNORE_FROZEN, 0, null); 21463 } catch (PackageManagerException e) { 21464 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21465 } 21466 // Scan the package 21467 if (pkg != null) { 21468 /* 21469 * TODO why is the lock being held? doPostInstall is 21470 * called in other places without the lock. This needs 21471 * to be straightened out. 21472 */ 21473 // writer 21474 synchronized (mPackages) { 21475 retCode = PackageManager.INSTALL_SUCCEEDED; 21476 pkgList.add(pkg.packageName); 21477 // Post process args 21478 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21479 pkg.applicationInfo.uid); 21480 } 21481 } else { 21482 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21483 } 21484 } 21485 21486 } finally { 21487 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21488 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21489 } 21490 } 21491 } 21492 // writer 21493 synchronized (mPackages) { 21494 // If the platform SDK has changed since the last time we booted, 21495 // we need to re-grant app permission to catch any new ones that 21496 // appear. This is really a hack, and means that apps can in some 21497 // cases get permissions that the user didn't initially explicitly 21498 // allow... it would be nice to have some better way to handle 21499 // this situation. 21500 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21501 : mSettings.getInternalVersion(); 21502 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21503 : StorageManager.UUID_PRIVATE_INTERNAL; 21504 21505 int updateFlags = UPDATE_PERMISSIONS_ALL; 21506 if (ver.sdkVersion != mSdkVersion) { 21507 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21508 + mSdkVersion + "; regranting permissions for external"); 21509 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21510 } 21511 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21512 21513 // Yay, everything is now upgraded 21514 ver.forceCurrent(); 21515 21516 // can downgrade to reader 21517 // Persist settings 21518 mSettings.writeLPr(); 21519 } 21520 // Send a broadcast to let everyone know we are done processing 21521 if (pkgList.size() > 0) { 21522 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21523 } 21524 } 21525 21526 /* 21527 * Utility method to unload a list of specified containers 21528 */ 21529 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21530 // Just unmount all valid containers. 21531 for (AsecInstallArgs arg : cidArgs) { 21532 synchronized (mInstallLock) { 21533 arg.doPostDeleteLI(false); 21534 } 21535 } 21536 } 21537 21538 /* 21539 * Unload packages mounted on external media. This involves deleting package 21540 * data from internal structures, sending broadcasts about disabled packages, 21541 * gc'ing to free up references, unmounting all secure containers 21542 * corresponding to packages on external media, and posting a 21543 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21544 * that we always have to post this message if status has been requested no 21545 * matter what. 21546 */ 21547 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21548 final boolean reportStatus) { 21549 if (DEBUG_SD_INSTALL) 21550 Log.i(TAG, "unloading media packages"); 21551 ArrayList<String> pkgList = new ArrayList<String>(); 21552 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21553 final Set<AsecInstallArgs> keys = processCids.keySet(); 21554 for (AsecInstallArgs args : keys) { 21555 String pkgName = args.getPackageName(); 21556 if (DEBUG_SD_INSTALL) 21557 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21558 // Delete package internally 21559 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21560 synchronized (mInstallLock) { 21561 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21562 final boolean res; 21563 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21564 "unloadMediaPackages")) { 21565 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21566 null); 21567 } 21568 if (res) { 21569 pkgList.add(pkgName); 21570 } else { 21571 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21572 failedList.add(args); 21573 } 21574 } 21575 } 21576 21577 // reader 21578 synchronized (mPackages) { 21579 // We didn't update the settings after removing each package; 21580 // write them now for all packages. 21581 mSettings.writeLPr(); 21582 } 21583 21584 // We have to absolutely send UPDATED_MEDIA_STATUS only 21585 // after confirming that all the receivers processed the ordered 21586 // broadcast when packages get disabled, force a gc to clean things up. 21587 // and unload all the containers. 21588 if (pkgList.size() > 0) { 21589 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21590 new IIntentReceiver.Stub() { 21591 public void performReceive(Intent intent, int resultCode, String data, 21592 Bundle extras, boolean ordered, boolean sticky, 21593 int sendingUser) throws RemoteException { 21594 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21595 reportStatus ? 1 : 0, 1, keys); 21596 mHandler.sendMessage(msg); 21597 } 21598 }); 21599 } else { 21600 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21601 keys); 21602 mHandler.sendMessage(msg); 21603 } 21604 } 21605 21606 private void loadPrivatePackages(final VolumeInfo vol) { 21607 mHandler.post(new Runnable() { 21608 @Override 21609 public void run() { 21610 loadPrivatePackagesInner(vol); 21611 } 21612 }); 21613 } 21614 21615 private void loadPrivatePackagesInner(VolumeInfo vol) { 21616 final String volumeUuid = vol.fsUuid; 21617 if (TextUtils.isEmpty(volumeUuid)) { 21618 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21619 return; 21620 } 21621 21622 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21623 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21624 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21625 21626 final VersionInfo ver; 21627 final List<PackageSetting> packages; 21628 synchronized (mPackages) { 21629 ver = mSettings.findOrCreateVersion(volumeUuid); 21630 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21631 } 21632 21633 for (PackageSetting ps : packages) { 21634 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21635 synchronized (mInstallLock) { 21636 final PackageParser.Package pkg; 21637 try { 21638 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21639 loaded.add(pkg.applicationInfo); 21640 21641 } catch (PackageManagerException e) { 21642 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21643 } 21644 21645 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21646 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21647 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21648 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21649 } 21650 } 21651 } 21652 21653 // Reconcile app data for all started/unlocked users 21654 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21655 final UserManager um = mContext.getSystemService(UserManager.class); 21656 UserManagerInternal umInternal = getUserManagerInternal(); 21657 for (UserInfo user : um.getUsers()) { 21658 final int flags; 21659 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21660 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21661 } else if (umInternal.isUserRunning(user.id)) { 21662 flags = StorageManager.FLAG_STORAGE_DE; 21663 } else { 21664 continue; 21665 } 21666 21667 try { 21668 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21669 synchronized (mInstallLock) { 21670 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21671 } 21672 } catch (IllegalStateException e) { 21673 // Device was probably ejected, and we'll process that event momentarily 21674 Slog.w(TAG, "Failed to prepare storage: " + e); 21675 } 21676 } 21677 21678 synchronized (mPackages) { 21679 int updateFlags = UPDATE_PERMISSIONS_ALL; 21680 if (ver.sdkVersion != mSdkVersion) { 21681 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21682 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21683 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21684 } 21685 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21686 21687 // Yay, everything is now upgraded 21688 ver.forceCurrent(); 21689 21690 mSettings.writeLPr(); 21691 } 21692 21693 for (PackageFreezer freezer : freezers) { 21694 freezer.close(); 21695 } 21696 21697 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21698 sendResourcesChangedBroadcast(true, false, loaded, null); 21699 } 21700 21701 private void unloadPrivatePackages(final VolumeInfo vol) { 21702 mHandler.post(new Runnable() { 21703 @Override 21704 public void run() { 21705 unloadPrivatePackagesInner(vol); 21706 } 21707 }); 21708 } 21709 21710 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21711 final String volumeUuid = vol.fsUuid; 21712 if (TextUtils.isEmpty(volumeUuid)) { 21713 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21714 return; 21715 } 21716 21717 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21718 synchronized (mInstallLock) { 21719 synchronized (mPackages) { 21720 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21721 for (PackageSetting ps : packages) { 21722 if (ps.pkg == null) continue; 21723 21724 final ApplicationInfo info = ps.pkg.applicationInfo; 21725 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21726 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21727 21728 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21729 "unloadPrivatePackagesInner")) { 21730 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21731 false, null)) { 21732 unloaded.add(info); 21733 } else { 21734 Slog.w(TAG, "Failed to unload " + ps.codePath); 21735 } 21736 } 21737 21738 // Try very hard to release any references to this package 21739 // so we don't risk the system server being killed due to 21740 // open FDs 21741 AttributeCache.instance().removePackage(ps.name); 21742 } 21743 21744 mSettings.writeLPr(); 21745 } 21746 } 21747 21748 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21749 sendResourcesChangedBroadcast(false, false, unloaded, null); 21750 21751 // Try very hard to release any references to this path so we don't risk 21752 // the system server being killed due to open FDs 21753 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21754 21755 for (int i = 0; i < 3; i++) { 21756 System.gc(); 21757 System.runFinalization(); 21758 } 21759 } 21760 21761 private void assertPackageKnown(String volumeUuid, String packageName) 21762 throws PackageManagerException { 21763 synchronized (mPackages) { 21764 // Normalize package name to handle renamed packages 21765 packageName = normalizePackageNameLPr(packageName); 21766 21767 final PackageSetting ps = mSettings.mPackages.get(packageName); 21768 if (ps == null) { 21769 throw new PackageManagerException("Package " + packageName + " is unknown"); 21770 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21771 throw new PackageManagerException( 21772 "Package " + packageName + " found on unknown volume " + volumeUuid 21773 + "; expected volume " + ps.volumeUuid); 21774 } 21775 } 21776 } 21777 21778 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21779 throws PackageManagerException { 21780 synchronized (mPackages) { 21781 // Normalize package name to handle renamed packages 21782 packageName = normalizePackageNameLPr(packageName); 21783 21784 final PackageSetting ps = mSettings.mPackages.get(packageName); 21785 if (ps == null) { 21786 throw new PackageManagerException("Package " + packageName + " is unknown"); 21787 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21788 throw new PackageManagerException( 21789 "Package " + packageName + " found on unknown volume " + volumeUuid 21790 + "; expected volume " + ps.volumeUuid); 21791 } else if (!ps.getInstalled(userId)) { 21792 throw new PackageManagerException( 21793 "Package " + packageName + " not installed for user " + userId); 21794 } 21795 } 21796 } 21797 21798 private List<String> collectAbsoluteCodePaths() { 21799 synchronized (mPackages) { 21800 List<String> codePaths = new ArrayList<>(); 21801 final int packageCount = mSettings.mPackages.size(); 21802 for (int i = 0; i < packageCount; i++) { 21803 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21804 codePaths.add(ps.codePath.getAbsolutePath()); 21805 } 21806 return codePaths; 21807 } 21808 } 21809 21810 /** 21811 * Examine all apps present on given mounted volume, and destroy apps that 21812 * aren't expected, either due to uninstallation or reinstallation on 21813 * another volume. 21814 */ 21815 private void reconcileApps(String volumeUuid) { 21816 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21817 List<File> filesToDelete = null; 21818 21819 final File[] files = FileUtils.listFilesOrEmpty( 21820 Environment.getDataAppDirectory(volumeUuid)); 21821 for (File file : files) { 21822 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21823 && !PackageInstallerService.isStageName(file.getName()); 21824 if (!isPackage) { 21825 // Ignore entries which are not packages 21826 continue; 21827 } 21828 21829 String absolutePath = file.getAbsolutePath(); 21830 21831 boolean pathValid = false; 21832 final int absoluteCodePathCount = absoluteCodePaths.size(); 21833 for (int i = 0; i < absoluteCodePathCount; i++) { 21834 String absoluteCodePath = absoluteCodePaths.get(i); 21835 if (absolutePath.startsWith(absoluteCodePath)) { 21836 pathValid = true; 21837 break; 21838 } 21839 } 21840 21841 if (!pathValid) { 21842 if (filesToDelete == null) { 21843 filesToDelete = new ArrayList<>(); 21844 } 21845 filesToDelete.add(file); 21846 } 21847 } 21848 21849 if (filesToDelete != null) { 21850 final int fileToDeleteCount = filesToDelete.size(); 21851 for (int i = 0; i < fileToDeleteCount; i++) { 21852 File fileToDelete = filesToDelete.get(i); 21853 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21854 synchronized (mInstallLock) { 21855 removeCodePathLI(fileToDelete); 21856 } 21857 } 21858 } 21859 } 21860 21861 /** 21862 * Reconcile all app data for the given user. 21863 * <p> 21864 * Verifies that directories exist and that ownership and labeling is 21865 * correct for all installed apps on all mounted volumes. 21866 */ 21867 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21868 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21869 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21870 final String volumeUuid = vol.getFsUuid(); 21871 synchronized (mInstallLock) { 21872 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21873 } 21874 } 21875 } 21876 21877 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21878 boolean migrateAppData) { 21879 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21880 } 21881 21882 /** 21883 * Reconcile all app data on given mounted volume. 21884 * <p> 21885 * Destroys app data that isn't expected, either due to uninstallation or 21886 * reinstallation on another volume. 21887 * <p> 21888 * Verifies that directories exist and that ownership and labeling is 21889 * correct for all installed apps. 21890 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21891 */ 21892 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21893 boolean migrateAppData, boolean onlyCoreApps) { 21894 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21895 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21896 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21897 21898 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21899 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21900 21901 // First look for stale data that doesn't belong, and check if things 21902 // have changed since we did our last restorecon 21903 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21904 if (StorageManager.isFileEncryptedNativeOrEmulated() 21905 && !StorageManager.isUserKeyUnlocked(userId)) { 21906 throw new RuntimeException( 21907 "Yikes, someone asked us to reconcile CE storage while " + userId 21908 + " was still locked; this would have caused massive data loss!"); 21909 } 21910 21911 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21912 for (File file : files) { 21913 final String packageName = file.getName(); 21914 try { 21915 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21916 } catch (PackageManagerException e) { 21917 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21918 try { 21919 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21920 StorageManager.FLAG_STORAGE_CE, 0); 21921 } catch (InstallerException e2) { 21922 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21923 } 21924 } 21925 } 21926 } 21927 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21928 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21929 for (File file : files) { 21930 final String packageName = file.getName(); 21931 try { 21932 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21933 } catch (PackageManagerException e) { 21934 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21935 try { 21936 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21937 StorageManager.FLAG_STORAGE_DE, 0); 21938 } catch (InstallerException e2) { 21939 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21940 } 21941 } 21942 } 21943 } 21944 21945 // Ensure that data directories are ready to roll for all packages 21946 // installed for this volume and user 21947 final List<PackageSetting> packages; 21948 synchronized (mPackages) { 21949 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21950 } 21951 int preparedCount = 0; 21952 for (PackageSetting ps : packages) { 21953 final String packageName = ps.name; 21954 if (ps.pkg == null) { 21955 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21956 // TODO: might be due to legacy ASEC apps; we should circle back 21957 // and reconcile again once they're scanned 21958 continue; 21959 } 21960 // Skip non-core apps if requested 21961 if (onlyCoreApps && !ps.pkg.coreApp) { 21962 result.add(packageName); 21963 continue; 21964 } 21965 21966 if (ps.getInstalled(userId)) { 21967 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21968 preparedCount++; 21969 } 21970 } 21971 21972 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21973 return result; 21974 } 21975 21976 /** 21977 * Prepare app data for the given app just after it was installed or 21978 * upgraded. This method carefully only touches users that it's installed 21979 * for, and it forces a restorecon to handle any seinfo changes. 21980 * <p> 21981 * Verifies that directories exist and that ownership and labeling is 21982 * correct for all installed apps. If there is an ownership mismatch, it 21983 * will try recovering system apps by wiping data; third-party app data is 21984 * left intact. 21985 * <p> 21986 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21987 */ 21988 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21989 final PackageSetting ps; 21990 synchronized (mPackages) { 21991 ps = mSettings.mPackages.get(pkg.packageName); 21992 mSettings.writeKernelMappingLPr(ps); 21993 } 21994 21995 final UserManager um = mContext.getSystemService(UserManager.class); 21996 UserManagerInternal umInternal = getUserManagerInternal(); 21997 for (UserInfo user : um.getUsers()) { 21998 final int flags; 21999 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22000 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22001 } else if (umInternal.isUserRunning(user.id)) { 22002 flags = StorageManager.FLAG_STORAGE_DE; 22003 } else { 22004 continue; 22005 } 22006 22007 if (ps.getInstalled(user.id)) { 22008 // TODO: when user data is locked, mark that we're still dirty 22009 prepareAppDataLIF(pkg, user.id, flags); 22010 } 22011 } 22012 } 22013 22014 /** 22015 * Prepare app data for the given app. 22016 * <p> 22017 * Verifies that directories exist and that ownership and labeling is 22018 * correct for all installed apps. If there is an ownership mismatch, this 22019 * will try recovering system apps by wiping data; third-party app data is 22020 * left intact. 22021 */ 22022 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22023 if (pkg == null) { 22024 Slog.wtf(TAG, "Package was null!", new Throwable()); 22025 return; 22026 } 22027 prepareAppDataLeafLIF(pkg, userId, flags); 22028 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22029 for (int i = 0; i < childCount; i++) { 22030 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22031 } 22032 } 22033 22034 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22035 boolean maybeMigrateAppData) { 22036 prepareAppDataLIF(pkg, userId, flags); 22037 22038 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22039 // We may have just shuffled around app data directories, so 22040 // prepare them one more time 22041 prepareAppDataLIF(pkg, userId, flags); 22042 } 22043 } 22044 22045 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22046 if (DEBUG_APP_DATA) { 22047 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22048 + Integer.toHexString(flags)); 22049 } 22050 22051 final String volumeUuid = pkg.volumeUuid; 22052 final String packageName = pkg.packageName; 22053 final ApplicationInfo app = pkg.applicationInfo; 22054 final int appId = UserHandle.getAppId(app.uid); 22055 22056 Preconditions.checkNotNull(app.seInfo); 22057 22058 long ceDataInode = -1; 22059 try { 22060 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22061 appId, app.seInfo, app.targetSdkVersion); 22062 } catch (InstallerException e) { 22063 if (app.isSystemApp()) { 22064 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22065 + ", but trying to recover: " + e); 22066 destroyAppDataLeafLIF(pkg, userId, flags); 22067 try { 22068 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22069 appId, app.seInfo, app.targetSdkVersion); 22070 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22071 } catch (InstallerException e2) { 22072 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22073 } 22074 } else { 22075 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22076 } 22077 } 22078 22079 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22080 // TODO: mark this structure as dirty so we persist it! 22081 synchronized (mPackages) { 22082 final PackageSetting ps = mSettings.mPackages.get(packageName); 22083 if (ps != null) { 22084 ps.setCeDataInode(ceDataInode, userId); 22085 } 22086 } 22087 } 22088 22089 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22090 } 22091 22092 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22093 if (pkg == null) { 22094 Slog.wtf(TAG, "Package was null!", new Throwable()); 22095 return; 22096 } 22097 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22098 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22099 for (int i = 0; i < childCount; i++) { 22100 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22101 } 22102 } 22103 22104 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22105 final String volumeUuid = pkg.volumeUuid; 22106 final String packageName = pkg.packageName; 22107 final ApplicationInfo app = pkg.applicationInfo; 22108 22109 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22110 // Create a native library symlink only if we have native libraries 22111 // and if the native libraries are 32 bit libraries. We do not provide 22112 // this symlink for 64 bit libraries. 22113 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22114 final String nativeLibPath = app.nativeLibraryDir; 22115 try { 22116 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22117 nativeLibPath, userId); 22118 } catch (InstallerException e) { 22119 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22120 } 22121 } 22122 } 22123 } 22124 22125 /** 22126 * For system apps on non-FBE devices, this method migrates any existing 22127 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22128 * requested by the app. 22129 */ 22130 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22131 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22132 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22133 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22134 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22135 try { 22136 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22137 storageTarget); 22138 } catch (InstallerException e) { 22139 logCriticalInfo(Log.WARN, 22140 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22141 } 22142 return true; 22143 } else { 22144 return false; 22145 } 22146 } 22147 22148 public PackageFreezer freezePackage(String packageName, String killReason) { 22149 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22150 } 22151 22152 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22153 return new PackageFreezer(packageName, userId, killReason); 22154 } 22155 22156 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22157 String killReason) { 22158 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22159 } 22160 22161 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22162 String killReason) { 22163 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22164 return new PackageFreezer(); 22165 } else { 22166 return freezePackage(packageName, userId, killReason); 22167 } 22168 } 22169 22170 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22171 String killReason) { 22172 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22173 } 22174 22175 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22176 String killReason) { 22177 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22178 return new PackageFreezer(); 22179 } else { 22180 return freezePackage(packageName, userId, killReason); 22181 } 22182 } 22183 22184 /** 22185 * Class that freezes and kills the given package upon creation, and 22186 * unfreezes it upon closing. This is typically used when doing surgery on 22187 * app code/data to prevent the app from running while you're working. 22188 */ 22189 private class PackageFreezer implements AutoCloseable { 22190 private final String mPackageName; 22191 private final PackageFreezer[] mChildren; 22192 22193 private final boolean mWeFroze; 22194 22195 private final AtomicBoolean mClosed = new AtomicBoolean(); 22196 private final CloseGuard mCloseGuard = CloseGuard.get(); 22197 22198 /** 22199 * Create and return a stub freezer that doesn't actually do anything, 22200 * typically used when someone requested 22201 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22202 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22203 */ 22204 public PackageFreezer() { 22205 mPackageName = null; 22206 mChildren = null; 22207 mWeFroze = false; 22208 mCloseGuard.open("close"); 22209 } 22210 22211 public PackageFreezer(String packageName, int userId, String killReason) { 22212 synchronized (mPackages) { 22213 mPackageName = packageName; 22214 mWeFroze = mFrozenPackages.add(mPackageName); 22215 22216 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22217 if (ps != null) { 22218 killApplication(ps.name, ps.appId, userId, killReason); 22219 } 22220 22221 final PackageParser.Package p = mPackages.get(packageName); 22222 if (p != null && p.childPackages != null) { 22223 final int N = p.childPackages.size(); 22224 mChildren = new PackageFreezer[N]; 22225 for (int i = 0; i < N; i++) { 22226 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22227 userId, killReason); 22228 } 22229 } else { 22230 mChildren = null; 22231 } 22232 } 22233 mCloseGuard.open("close"); 22234 } 22235 22236 @Override 22237 protected void finalize() throws Throwable { 22238 try { 22239 mCloseGuard.warnIfOpen(); 22240 close(); 22241 } finally { 22242 super.finalize(); 22243 } 22244 } 22245 22246 @Override 22247 public void close() { 22248 mCloseGuard.close(); 22249 if (mClosed.compareAndSet(false, true)) { 22250 synchronized (mPackages) { 22251 if (mWeFroze) { 22252 mFrozenPackages.remove(mPackageName); 22253 } 22254 22255 if (mChildren != null) { 22256 for (PackageFreezer freezer : mChildren) { 22257 freezer.close(); 22258 } 22259 } 22260 } 22261 } 22262 } 22263 } 22264 22265 /** 22266 * Verify that given package is currently frozen. 22267 */ 22268 private void checkPackageFrozen(String packageName) { 22269 synchronized (mPackages) { 22270 if (!mFrozenPackages.contains(packageName)) { 22271 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22272 } 22273 } 22274 } 22275 22276 @Override 22277 public int movePackage(final String packageName, final String volumeUuid) { 22278 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22279 22280 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22281 final int moveId = mNextMoveId.getAndIncrement(); 22282 mHandler.post(new Runnable() { 22283 @Override 22284 public void run() { 22285 try { 22286 movePackageInternal(packageName, volumeUuid, moveId, user); 22287 } catch (PackageManagerException e) { 22288 Slog.w(TAG, "Failed to move " + packageName, e); 22289 mMoveCallbacks.notifyStatusChanged(moveId, 22290 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22291 } 22292 } 22293 }); 22294 return moveId; 22295 } 22296 22297 private void movePackageInternal(final String packageName, final String volumeUuid, 22298 final int moveId, UserHandle user) throws PackageManagerException { 22299 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22300 final PackageManager pm = mContext.getPackageManager(); 22301 22302 final boolean currentAsec; 22303 final String currentVolumeUuid; 22304 final File codeFile; 22305 final String installerPackageName; 22306 final String packageAbiOverride; 22307 final int appId; 22308 final String seinfo; 22309 final String label; 22310 final int targetSdkVersion; 22311 final PackageFreezer freezer; 22312 final int[] installedUserIds; 22313 22314 // reader 22315 synchronized (mPackages) { 22316 final PackageParser.Package pkg = mPackages.get(packageName); 22317 final PackageSetting ps = mSettings.mPackages.get(packageName); 22318 if (pkg == null || ps == null) { 22319 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22320 } 22321 22322 if (pkg.applicationInfo.isSystemApp()) { 22323 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22324 "Cannot move system application"); 22325 } 22326 22327 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22328 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22329 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22330 if (isInternalStorage && !allow3rdPartyOnInternal) { 22331 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22332 "3rd party apps are not allowed on internal storage"); 22333 } 22334 22335 if (pkg.applicationInfo.isExternalAsec()) { 22336 currentAsec = true; 22337 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22338 } else if (pkg.applicationInfo.isForwardLocked()) { 22339 currentAsec = true; 22340 currentVolumeUuid = "forward_locked"; 22341 } else { 22342 currentAsec = false; 22343 currentVolumeUuid = ps.volumeUuid; 22344 22345 final File probe = new File(pkg.codePath); 22346 final File probeOat = new File(probe, "oat"); 22347 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22348 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22349 "Move only supported for modern cluster style installs"); 22350 } 22351 } 22352 22353 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22354 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22355 "Package already moved to " + volumeUuid); 22356 } 22357 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22358 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22359 "Device admin cannot be moved"); 22360 } 22361 22362 if (mFrozenPackages.contains(packageName)) { 22363 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22364 "Failed to move already frozen package"); 22365 } 22366 22367 codeFile = new File(pkg.codePath); 22368 installerPackageName = ps.installerPackageName; 22369 packageAbiOverride = ps.cpuAbiOverrideString; 22370 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22371 seinfo = pkg.applicationInfo.seInfo; 22372 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22373 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22374 freezer = freezePackage(packageName, "movePackageInternal"); 22375 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22376 } 22377 22378 final Bundle extras = new Bundle(); 22379 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22380 extras.putString(Intent.EXTRA_TITLE, label); 22381 mMoveCallbacks.notifyCreated(moveId, extras); 22382 22383 int installFlags; 22384 final boolean moveCompleteApp; 22385 final File measurePath; 22386 22387 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22388 installFlags = INSTALL_INTERNAL; 22389 moveCompleteApp = !currentAsec; 22390 measurePath = Environment.getDataAppDirectory(volumeUuid); 22391 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22392 installFlags = INSTALL_EXTERNAL; 22393 moveCompleteApp = false; 22394 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22395 } else { 22396 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22397 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22398 || !volume.isMountedWritable()) { 22399 freezer.close(); 22400 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22401 "Move location not mounted private volume"); 22402 } 22403 22404 Preconditions.checkState(!currentAsec); 22405 22406 installFlags = INSTALL_INTERNAL; 22407 moveCompleteApp = true; 22408 measurePath = Environment.getDataAppDirectory(volumeUuid); 22409 } 22410 22411 final PackageStats stats = new PackageStats(null, -1); 22412 synchronized (mInstaller) { 22413 for (int userId : installedUserIds) { 22414 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22415 freezer.close(); 22416 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22417 "Failed to measure package size"); 22418 } 22419 } 22420 } 22421 22422 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22423 + stats.dataSize); 22424 22425 final long startFreeBytes = measurePath.getUsableSpace(); 22426 final long sizeBytes; 22427 if (moveCompleteApp) { 22428 sizeBytes = stats.codeSize + stats.dataSize; 22429 } else { 22430 sizeBytes = stats.codeSize; 22431 } 22432 22433 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22434 freezer.close(); 22435 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22436 "Not enough free space to move"); 22437 } 22438 22439 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22440 22441 final CountDownLatch installedLatch = new CountDownLatch(1); 22442 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22443 @Override 22444 public void onUserActionRequired(Intent intent) throws RemoteException { 22445 throw new IllegalStateException(); 22446 } 22447 22448 @Override 22449 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22450 Bundle extras) throws RemoteException { 22451 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22452 + PackageManager.installStatusToString(returnCode, msg)); 22453 22454 installedLatch.countDown(); 22455 freezer.close(); 22456 22457 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22458 switch (status) { 22459 case PackageInstaller.STATUS_SUCCESS: 22460 mMoveCallbacks.notifyStatusChanged(moveId, 22461 PackageManager.MOVE_SUCCEEDED); 22462 break; 22463 case PackageInstaller.STATUS_FAILURE_STORAGE: 22464 mMoveCallbacks.notifyStatusChanged(moveId, 22465 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22466 break; 22467 default: 22468 mMoveCallbacks.notifyStatusChanged(moveId, 22469 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22470 break; 22471 } 22472 } 22473 }; 22474 22475 final MoveInfo move; 22476 if (moveCompleteApp) { 22477 // Kick off a thread to report progress estimates 22478 new Thread() { 22479 @Override 22480 public void run() { 22481 while (true) { 22482 try { 22483 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22484 break; 22485 } 22486 } catch (InterruptedException ignored) { 22487 } 22488 22489 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22490 final int progress = 10 + (int) MathUtils.constrain( 22491 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22492 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22493 } 22494 } 22495 }.start(); 22496 22497 final String dataAppName = codeFile.getName(); 22498 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22499 dataAppName, appId, seinfo, targetSdkVersion); 22500 } else { 22501 move = null; 22502 } 22503 22504 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22505 22506 final Message msg = mHandler.obtainMessage(INIT_COPY); 22507 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22508 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22509 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22510 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22511 PackageManager.INSTALL_REASON_UNKNOWN); 22512 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22513 msg.obj = params; 22514 22515 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22516 System.identityHashCode(msg.obj)); 22517 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22518 System.identityHashCode(msg.obj)); 22519 22520 mHandler.sendMessage(msg); 22521 } 22522 22523 @Override 22524 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22525 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22526 22527 final int realMoveId = mNextMoveId.getAndIncrement(); 22528 final Bundle extras = new Bundle(); 22529 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22530 mMoveCallbacks.notifyCreated(realMoveId, extras); 22531 22532 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22533 @Override 22534 public void onCreated(int moveId, Bundle extras) { 22535 // Ignored 22536 } 22537 22538 @Override 22539 public void onStatusChanged(int moveId, int status, long estMillis) { 22540 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22541 } 22542 }; 22543 22544 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22545 storage.setPrimaryStorageUuid(volumeUuid, callback); 22546 return realMoveId; 22547 } 22548 22549 @Override 22550 public int getMoveStatus(int moveId) { 22551 mContext.enforceCallingOrSelfPermission( 22552 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22553 return mMoveCallbacks.mLastStatus.get(moveId); 22554 } 22555 22556 @Override 22557 public void registerMoveCallback(IPackageMoveObserver callback) { 22558 mContext.enforceCallingOrSelfPermission( 22559 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22560 mMoveCallbacks.register(callback); 22561 } 22562 22563 @Override 22564 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22565 mContext.enforceCallingOrSelfPermission( 22566 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22567 mMoveCallbacks.unregister(callback); 22568 } 22569 22570 @Override 22571 public boolean setInstallLocation(int loc) { 22572 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22573 null); 22574 if (getInstallLocation() == loc) { 22575 return true; 22576 } 22577 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22578 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22579 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22580 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22581 return true; 22582 } 22583 return false; 22584 } 22585 22586 @Override 22587 public int getInstallLocation() { 22588 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22589 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22590 PackageHelper.APP_INSTALL_AUTO); 22591 } 22592 22593 /** Called by UserManagerService */ 22594 void cleanUpUser(UserManagerService userManager, int userHandle) { 22595 synchronized (mPackages) { 22596 mDirtyUsers.remove(userHandle); 22597 mUserNeedsBadging.delete(userHandle); 22598 mSettings.removeUserLPw(userHandle); 22599 mPendingBroadcasts.remove(userHandle); 22600 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22601 removeUnusedPackagesLPw(userManager, userHandle); 22602 } 22603 } 22604 22605 /** 22606 * We're removing userHandle and would like to remove any downloaded packages 22607 * that are no longer in use by any other user. 22608 * @param userHandle the user being removed 22609 */ 22610 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22611 final boolean DEBUG_CLEAN_APKS = false; 22612 int [] users = userManager.getUserIds(); 22613 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22614 while (psit.hasNext()) { 22615 PackageSetting ps = psit.next(); 22616 if (ps.pkg == null) { 22617 continue; 22618 } 22619 final String packageName = ps.pkg.packageName; 22620 // Skip over if system app 22621 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22622 continue; 22623 } 22624 if (DEBUG_CLEAN_APKS) { 22625 Slog.i(TAG, "Checking package " + packageName); 22626 } 22627 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22628 if (keep) { 22629 if (DEBUG_CLEAN_APKS) { 22630 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22631 } 22632 } else { 22633 for (int i = 0; i < users.length; i++) { 22634 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22635 keep = true; 22636 if (DEBUG_CLEAN_APKS) { 22637 Slog.i(TAG, " Keeping package " + packageName + " for user " 22638 + users[i]); 22639 } 22640 break; 22641 } 22642 } 22643 } 22644 if (!keep) { 22645 if (DEBUG_CLEAN_APKS) { 22646 Slog.i(TAG, " Removing package " + packageName); 22647 } 22648 mHandler.post(new Runnable() { 22649 public void run() { 22650 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22651 userHandle, 0); 22652 } //end run 22653 }); 22654 } 22655 } 22656 } 22657 22658 /** Called by UserManagerService */ 22659 void createNewUser(int userId, String[] disallowedPackages) { 22660 synchronized (mInstallLock) { 22661 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22662 } 22663 synchronized (mPackages) { 22664 scheduleWritePackageRestrictionsLocked(userId); 22665 scheduleWritePackageListLocked(userId); 22666 applyFactoryDefaultBrowserLPw(userId); 22667 primeDomainVerificationsLPw(userId); 22668 } 22669 } 22670 22671 void onNewUserCreated(final int userId) { 22672 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22673 // If permission review for legacy apps is required, we represent 22674 // dagerous permissions for such apps as always granted runtime 22675 // permissions to keep per user flag state whether review is needed. 22676 // Hence, if a new user is added we have to propagate dangerous 22677 // permission grants for these legacy apps. 22678 if (mPermissionReviewRequired) { 22679 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22680 | UPDATE_PERMISSIONS_REPLACE_ALL); 22681 } 22682 } 22683 22684 @Override 22685 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22686 mContext.enforceCallingOrSelfPermission( 22687 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22688 "Only package verification agents can read the verifier device identity"); 22689 22690 synchronized (mPackages) { 22691 return mSettings.getVerifierDeviceIdentityLPw(); 22692 } 22693 } 22694 22695 @Override 22696 public void setPermissionEnforced(String permission, boolean enforced) { 22697 // TODO: Now that we no longer change GID for storage, this should to away. 22698 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22699 "setPermissionEnforced"); 22700 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22701 synchronized (mPackages) { 22702 if (mSettings.mReadExternalStorageEnforced == null 22703 || mSettings.mReadExternalStorageEnforced != enforced) { 22704 mSettings.mReadExternalStorageEnforced = enforced; 22705 mSettings.writeLPr(); 22706 } 22707 } 22708 // kill any non-foreground processes so we restart them and 22709 // grant/revoke the GID. 22710 final IActivityManager am = ActivityManager.getService(); 22711 if (am != null) { 22712 final long token = Binder.clearCallingIdentity(); 22713 try { 22714 am.killProcessesBelowForeground("setPermissionEnforcement"); 22715 } catch (RemoteException e) { 22716 } finally { 22717 Binder.restoreCallingIdentity(token); 22718 } 22719 } 22720 } else { 22721 throw new IllegalArgumentException("No selective enforcement for " + permission); 22722 } 22723 } 22724 22725 @Override 22726 @Deprecated 22727 public boolean isPermissionEnforced(String permission) { 22728 return true; 22729 } 22730 22731 @Override 22732 public boolean isStorageLow() { 22733 final long token = Binder.clearCallingIdentity(); 22734 try { 22735 final DeviceStorageMonitorInternal 22736 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22737 if (dsm != null) { 22738 return dsm.isMemoryLow(); 22739 } else { 22740 return false; 22741 } 22742 } finally { 22743 Binder.restoreCallingIdentity(token); 22744 } 22745 } 22746 22747 @Override 22748 public IPackageInstaller getPackageInstaller() { 22749 return mInstallerService; 22750 } 22751 22752 private boolean userNeedsBadging(int userId) { 22753 int index = mUserNeedsBadging.indexOfKey(userId); 22754 if (index < 0) { 22755 final UserInfo userInfo; 22756 final long token = Binder.clearCallingIdentity(); 22757 try { 22758 userInfo = sUserManager.getUserInfo(userId); 22759 } finally { 22760 Binder.restoreCallingIdentity(token); 22761 } 22762 final boolean b; 22763 if (userInfo != null && userInfo.isManagedProfile()) { 22764 b = true; 22765 } else { 22766 b = false; 22767 } 22768 mUserNeedsBadging.put(userId, b); 22769 return b; 22770 } 22771 return mUserNeedsBadging.valueAt(index); 22772 } 22773 22774 @Override 22775 public KeySet getKeySetByAlias(String packageName, String alias) { 22776 if (packageName == null || alias == null) { 22777 return null; 22778 } 22779 synchronized(mPackages) { 22780 final PackageParser.Package pkg = mPackages.get(packageName); 22781 if (pkg == null) { 22782 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22783 throw new IllegalArgumentException("Unknown package: " + packageName); 22784 } 22785 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22786 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22787 } 22788 } 22789 22790 @Override 22791 public KeySet getSigningKeySet(String packageName) { 22792 if (packageName == null) { 22793 return null; 22794 } 22795 synchronized(mPackages) { 22796 final PackageParser.Package pkg = mPackages.get(packageName); 22797 if (pkg == null) { 22798 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22799 throw new IllegalArgumentException("Unknown package: " + packageName); 22800 } 22801 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22802 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22803 throw new SecurityException("May not access signing KeySet of other apps."); 22804 } 22805 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22806 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22807 } 22808 } 22809 22810 @Override 22811 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22812 if (packageName == null || ks == null) { 22813 return false; 22814 } 22815 synchronized(mPackages) { 22816 final PackageParser.Package pkg = mPackages.get(packageName); 22817 if (pkg == null) { 22818 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22819 throw new IllegalArgumentException("Unknown package: " + packageName); 22820 } 22821 IBinder ksh = ks.getToken(); 22822 if (ksh instanceof KeySetHandle) { 22823 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22824 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22825 } 22826 return false; 22827 } 22828 } 22829 22830 @Override 22831 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22832 if (packageName == null || ks == null) { 22833 return false; 22834 } 22835 synchronized(mPackages) { 22836 final PackageParser.Package pkg = mPackages.get(packageName); 22837 if (pkg == null) { 22838 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22839 throw new IllegalArgumentException("Unknown package: " + packageName); 22840 } 22841 IBinder ksh = ks.getToken(); 22842 if (ksh instanceof KeySetHandle) { 22843 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22844 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22845 } 22846 return false; 22847 } 22848 } 22849 22850 private void deletePackageIfUnusedLPr(final String packageName) { 22851 PackageSetting ps = mSettings.mPackages.get(packageName); 22852 if (ps == null) { 22853 return; 22854 } 22855 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22856 // TODO Implement atomic delete if package is unused 22857 // It is currently possible that the package will be deleted even if it is installed 22858 // after this method returns. 22859 mHandler.post(new Runnable() { 22860 public void run() { 22861 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22862 0, PackageManager.DELETE_ALL_USERS); 22863 } 22864 }); 22865 } 22866 } 22867 22868 /** 22869 * Check and throw if the given before/after packages would be considered a 22870 * downgrade. 22871 */ 22872 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22873 throws PackageManagerException { 22874 if (after.versionCode < before.mVersionCode) { 22875 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22876 "Update version code " + after.versionCode + " is older than current " 22877 + before.mVersionCode); 22878 } else if (after.versionCode == before.mVersionCode) { 22879 if (after.baseRevisionCode < before.baseRevisionCode) { 22880 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22881 "Update base revision code " + after.baseRevisionCode 22882 + " is older than current " + before.baseRevisionCode); 22883 } 22884 22885 if (!ArrayUtils.isEmpty(after.splitNames)) { 22886 for (int i = 0; i < after.splitNames.length; i++) { 22887 final String splitName = after.splitNames[i]; 22888 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22889 if (j != -1) { 22890 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22891 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22892 "Update split " + splitName + " revision code " 22893 + after.splitRevisionCodes[i] + " is older than current " 22894 + before.splitRevisionCodes[j]); 22895 } 22896 } 22897 } 22898 } 22899 } 22900 } 22901 22902 private static class MoveCallbacks extends Handler { 22903 private static final int MSG_CREATED = 1; 22904 private static final int MSG_STATUS_CHANGED = 2; 22905 22906 private final RemoteCallbackList<IPackageMoveObserver> 22907 mCallbacks = new RemoteCallbackList<>(); 22908 22909 private final SparseIntArray mLastStatus = new SparseIntArray(); 22910 22911 public MoveCallbacks(Looper looper) { 22912 super(looper); 22913 } 22914 22915 public void register(IPackageMoveObserver callback) { 22916 mCallbacks.register(callback); 22917 } 22918 22919 public void unregister(IPackageMoveObserver callback) { 22920 mCallbacks.unregister(callback); 22921 } 22922 22923 @Override 22924 public void handleMessage(Message msg) { 22925 final SomeArgs args = (SomeArgs) msg.obj; 22926 final int n = mCallbacks.beginBroadcast(); 22927 for (int i = 0; i < n; i++) { 22928 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22929 try { 22930 invokeCallback(callback, msg.what, args); 22931 } catch (RemoteException ignored) { 22932 } 22933 } 22934 mCallbacks.finishBroadcast(); 22935 args.recycle(); 22936 } 22937 22938 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22939 throws RemoteException { 22940 switch (what) { 22941 case MSG_CREATED: { 22942 callback.onCreated(args.argi1, (Bundle) args.arg2); 22943 break; 22944 } 22945 case MSG_STATUS_CHANGED: { 22946 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22947 break; 22948 } 22949 } 22950 } 22951 22952 private void notifyCreated(int moveId, Bundle extras) { 22953 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22954 22955 final SomeArgs args = SomeArgs.obtain(); 22956 args.argi1 = moveId; 22957 args.arg2 = extras; 22958 obtainMessage(MSG_CREATED, args).sendToTarget(); 22959 } 22960 22961 private void notifyStatusChanged(int moveId, int status) { 22962 notifyStatusChanged(moveId, status, -1); 22963 } 22964 22965 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22966 Slog.v(TAG, "Move " + moveId + " status " + status); 22967 22968 final SomeArgs args = SomeArgs.obtain(); 22969 args.argi1 = moveId; 22970 args.argi2 = status; 22971 args.arg3 = estMillis; 22972 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22973 22974 synchronized (mLastStatus) { 22975 mLastStatus.put(moveId, status); 22976 } 22977 } 22978 } 22979 22980 private final static class OnPermissionChangeListeners extends Handler { 22981 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22982 22983 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22984 new RemoteCallbackList<>(); 22985 22986 public OnPermissionChangeListeners(Looper looper) { 22987 super(looper); 22988 } 22989 22990 @Override 22991 public void handleMessage(Message msg) { 22992 switch (msg.what) { 22993 case MSG_ON_PERMISSIONS_CHANGED: { 22994 final int uid = msg.arg1; 22995 handleOnPermissionsChanged(uid); 22996 } break; 22997 } 22998 } 22999 23000 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23001 mPermissionListeners.register(listener); 23002 23003 } 23004 23005 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23006 mPermissionListeners.unregister(listener); 23007 } 23008 23009 public void onPermissionsChanged(int uid) { 23010 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23011 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23012 } 23013 } 23014 23015 private void handleOnPermissionsChanged(int uid) { 23016 final int count = mPermissionListeners.beginBroadcast(); 23017 try { 23018 for (int i = 0; i < count; i++) { 23019 IOnPermissionsChangeListener callback = mPermissionListeners 23020 .getBroadcastItem(i); 23021 try { 23022 callback.onPermissionsChanged(uid); 23023 } catch (RemoteException e) { 23024 Log.e(TAG, "Permission listener is dead", e); 23025 } 23026 } 23027 } finally { 23028 mPermissionListeners.finishBroadcast(); 23029 } 23030 } 23031 } 23032 23033 private class PackageManagerInternalImpl extends PackageManagerInternal { 23034 @Override 23035 public void setLocationPackagesProvider(PackagesProvider provider) { 23036 synchronized (mPackages) { 23037 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23038 } 23039 } 23040 23041 @Override 23042 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23043 synchronized (mPackages) { 23044 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23045 } 23046 } 23047 23048 @Override 23049 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23050 synchronized (mPackages) { 23051 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23052 } 23053 } 23054 23055 @Override 23056 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23057 synchronized (mPackages) { 23058 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23059 } 23060 } 23061 23062 @Override 23063 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23064 synchronized (mPackages) { 23065 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23066 } 23067 } 23068 23069 @Override 23070 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23071 synchronized (mPackages) { 23072 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23073 } 23074 } 23075 23076 @Override 23077 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23078 synchronized (mPackages) { 23079 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23080 packageName, userId); 23081 } 23082 } 23083 23084 @Override 23085 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23086 synchronized (mPackages) { 23087 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23088 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23089 packageName, userId); 23090 } 23091 } 23092 23093 @Override 23094 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23095 synchronized (mPackages) { 23096 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23097 packageName, userId); 23098 } 23099 } 23100 23101 @Override 23102 public void setKeepUninstalledPackages(final List<String> packageList) { 23103 Preconditions.checkNotNull(packageList); 23104 List<String> removedFromList = null; 23105 synchronized (mPackages) { 23106 if (mKeepUninstalledPackages != null) { 23107 final int packagesCount = mKeepUninstalledPackages.size(); 23108 for (int i = 0; i < packagesCount; i++) { 23109 String oldPackage = mKeepUninstalledPackages.get(i); 23110 if (packageList != null && packageList.contains(oldPackage)) { 23111 continue; 23112 } 23113 if (removedFromList == null) { 23114 removedFromList = new ArrayList<>(); 23115 } 23116 removedFromList.add(oldPackage); 23117 } 23118 } 23119 mKeepUninstalledPackages = new ArrayList<>(packageList); 23120 if (removedFromList != null) { 23121 final int removedCount = removedFromList.size(); 23122 for (int i = 0; i < removedCount; i++) { 23123 deletePackageIfUnusedLPr(removedFromList.get(i)); 23124 } 23125 } 23126 } 23127 } 23128 23129 @Override 23130 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23131 synchronized (mPackages) { 23132 // If we do not support permission review, done. 23133 if (!mPermissionReviewRequired) { 23134 return false; 23135 } 23136 23137 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23138 if (packageSetting == null) { 23139 return false; 23140 } 23141 23142 // Permission review applies only to apps not supporting the new permission model. 23143 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23144 return false; 23145 } 23146 23147 // Legacy apps have the permission and get user consent on launch. 23148 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23149 return permissionsState.isPermissionReviewRequired(userId); 23150 } 23151 } 23152 23153 @Override 23154 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23155 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23156 } 23157 23158 @Override 23159 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23160 int userId) { 23161 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23162 } 23163 23164 @Override 23165 public void setDeviceAndProfileOwnerPackages( 23166 int deviceOwnerUserId, String deviceOwnerPackage, 23167 SparseArray<String> profileOwnerPackages) { 23168 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23169 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23170 } 23171 23172 @Override 23173 public boolean isPackageDataProtected(int userId, String packageName) { 23174 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23175 } 23176 23177 @Override 23178 public boolean isPackageEphemeral(int userId, String packageName) { 23179 synchronized (mPackages) { 23180 final PackageSetting ps = mSettings.mPackages.get(packageName); 23181 return ps != null ? ps.getInstantApp(userId) : false; 23182 } 23183 } 23184 23185 @Override 23186 public boolean wasPackageEverLaunched(String packageName, int userId) { 23187 synchronized (mPackages) { 23188 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23189 } 23190 } 23191 23192 @Override 23193 public void grantRuntimePermission(String packageName, String name, int userId, 23194 boolean overridePolicy) { 23195 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23196 overridePolicy); 23197 } 23198 23199 @Override 23200 public void revokeRuntimePermission(String packageName, String name, int userId, 23201 boolean overridePolicy) { 23202 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23203 overridePolicy); 23204 } 23205 23206 @Override 23207 public String getNameForUid(int uid) { 23208 return PackageManagerService.this.getNameForUid(uid); 23209 } 23210 23211 @Override 23212 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23213 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23214 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23215 responseObj, origIntent, resolvedType, callingPackage, userId); 23216 } 23217 23218 @Override 23219 public void grantEphemeralAccess(int userId, Intent intent, 23220 int targetAppId, int ephemeralAppId) { 23221 synchronized (mPackages) { 23222 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23223 targetAppId, ephemeralAppId); 23224 } 23225 } 23226 23227 @Override 23228 public boolean isInstantAppInstallerComponent(ComponentName component) { 23229 synchronized (mPackages) { 23230 return mInstantAppInstallerActivity != null 23231 && mInstantAppInstallerActivity.getComponentName().equals(component); 23232 } 23233 } 23234 23235 @Override 23236 public void pruneInstantApps() { 23237 synchronized (mPackages) { 23238 mInstantAppRegistry.pruneInstantAppsLPw(); 23239 } 23240 } 23241 23242 @Override 23243 public String getSetupWizardPackageName() { 23244 return mSetupWizardPackage; 23245 } 23246 23247 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23248 if (policy != null) { 23249 mExternalSourcesPolicy = policy; 23250 } 23251 } 23252 23253 @Override 23254 public boolean isPackagePersistent(String packageName) { 23255 synchronized (mPackages) { 23256 PackageParser.Package pkg = mPackages.get(packageName); 23257 return pkg != null 23258 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23259 | ApplicationInfo.FLAG_PERSISTENT)) == 23260 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23261 : false; 23262 } 23263 } 23264 23265 @Override 23266 public List<PackageInfo> getOverlayPackages(int userId) { 23267 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23268 synchronized (mPackages) { 23269 for (PackageParser.Package p : mPackages.values()) { 23270 if (p.mOverlayTarget != null) { 23271 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23272 if (pkg != null) { 23273 overlayPackages.add(pkg); 23274 } 23275 } 23276 } 23277 } 23278 return overlayPackages; 23279 } 23280 23281 @Override 23282 public List<String> getTargetPackageNames(int userId) { 23283 List<String> targetPackages = new ArrayList<>(); 23284 synchronized (mPackages) { 23285 for (PackageParser.Package p : mPackages.values()) { 23286 if (p.mOverlayTarget == null) { 23287 targetPackages.add(p.packageName); 23288 } 23289 } 23290 } 23291 return targetPackages; 23292 } 23293 23294 @Override 23295 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23296 @Nullable List<String> overlayPackageNames) { 23297 synchronized (mPackages) { 23298 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23299 Slog.e(TAG, "failed to find package " + targetPackageName); 23300 return false; 23301 } 23302 23303 ArrayList<String> paths = null; 23304 if (overlayPackageNames != null) { 23305 final int N = overlayPackageNames.size(); 23306 paths = new ArrayList<>(N); 23307 for (int i = 0; i < N; i++) { 23308 final String packageName = overlayPackageNames.get(i); 23309 final PackageParser.Package pkg = mPackages.get(packageName); 23310 if (pkg == null) { 23311 Slog.e(TAG, "failed to find package " + packageName); 23312 return false; 23313 } 23314 paths.add(pkg.baseCodePath); 23315 } 23316 } 23317 23318 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23319 mEnabledOverlayPaths.get(userId); 23320 if (userSpecificOverlays == null) { 23321 userSpecificOverlays = new ArrayMap<>(); 23322 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23323 } 23324 23325 if (paths != null && paths.size() > 0) { 23326 userSpecificOverlays.put(targetPackageName, paths); 23327 } else { 23328 userSpecificOverlays.remove(targetPackageName); 23329 } 23330 return true; 23331 } 23332 } 23333 23334 @Override 23335 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23336 int flags, int userId) { 23337 return resolveIntentInternal( 23338 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23339 } 23340 23341 @Override 23342 public ResolveInfo resolveService(Intent intent, String resolvedType, 23343 int flags, int userId, int callingUid) { 23344 return resolveServiceInternal( 23345 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23346 } 23347 23348 23349 @Override 23350 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23351 synchronized (mPackages) { 23352 mIsolatedOwners.put(isolatedUid, ownerUid); 23353 } 23354 } 23355 23356 @Override 23357 public void removeIsolatedUid(int isolatedUid) { 23358 synchronized (mPackages) { 23359 mIsolatedOwners.delete(isolatedUid); 23360 } 23361 } 23362 } 23363 23364 @Override 23365 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23366 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23367 synchronized (mPackages) { 23368 final long identity = Binder.clearCallingIdentity(); 23369 try { 23370 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23371 packageNames, userId); 23372 } finally { 23373 Binder.restoreCallingIdentity(identity); 23374 } 23375 } 23376 } 23377 23378 @Override 23379 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23380 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23381 synchronized (mPackages) { 23382 final long identity = Binder.clearCallingIdentity(); 23383 try { 23384 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23385 packageNames, userId); 23386 } finally { 23387 Binder.restoreCallingIdentity(identity); 23388 } 23389 } 23390 } 23391 23392 private static void enforceSystemOrPhoneCaller(String tag) { 23393 int callingUid = Binder.getCallingUid(); 23394 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23395 throw new SecurityException( 23396 "Cannot call " + tag + " from UID " + callingUid); 23397 } 23398 } 23399 23400 boolean isHistoricalPackageUsageAvailable() { 23401 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23402 } 23403 23404 /** 23405 * Return a <b>copy</b> of the collection of packages known to the package manager. 23406 * @return A copy of the values of mPackages. 23407 */ 23408 Collection<PackageParser.Package> getPackages() { 23409 synchronized (mPackages) { 23410 return new ArrayList<>(mPackages.values()); 23411 } 23412 } 23413 23414 /** 23415 * Logs process start information (including base APK hash) to the security log. 23416 * @hide 23417 */ 23418 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23419 String apkFile, int pid) { 23420 if (!SecurityLog.isLoggingEnabled()) { 23421 return; 23422 } 23423 Bundle data = new Bundle(); 23424 data.putLong("startTimestamp", System.currentTimeMillis()); 23425 data.putString("processName", processName); 23426 data.putInt("uid", uid); 23427 data.putString("seinfo", seinfo); 23428 data.putString("apkFile", apkFile); 23429 data.putInt("pid", pid); 23430 Message msg = mProcessLoggingHandler.obtainMessage( 23431 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23432 msg.setData(data); 23433 mProcessLoggingHandler.sendMessage(msg); 23434 } 23435 23436 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23437 return mCompilerStats.getPackageStats(pkgName); 23438 } 23439 23440 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23441 return getOrCreateCompilerPackageStats(pkg.packageName); 23442 } 23443 23444 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23445 return mCompilerStats.getOrCreatePackageStats(pkgName); 23446 } 23447 23448 public void deleteCompilerPackageStats(String pkgName) { 23449 mCompilerStats.deletePackageStats(pkgName); 23450 } 23451 23452 @Override 23453 public int getInstallReason(String packageName, int userId) { 23454 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23455 true /* requireFullPermission */, false /* checkShell */, 23456 "get install reason"); 23457 synchronized (mPackages) { 23458 final PackageSetting ps = mSettings.mPackages.get(packageName); 23459 if (ps != null) { 23460 return ps.getInstallReason(userId); 23461 } 23462 } 23463 return PackageManager.INSTALL_REASON_UNKNOWN; 23464 } 23465 23466 @Override 23467 public boolean canRequestPackageInstalls(String packageName, int userId) { 23468 int callingUid = Binder.getCallingUid(); 23469 int uid = getPackageUid(packageName, 0, userId); 23470 if (callingUid != uid && callingUid != Process.ROOT_UID 23471 && callingUid != Process.SYSTEM_UID) { 23472 throw new SecurityException( 23473 "Caller uid " + callingUid + " does not own package " + packageName); 23474 } 23475 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23476 if (info == null) { 23477 return false; 23478 } 23479 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23480 throw new UnsupportedOperationException( 23481 "Operation only supported on apps targeting Android O or higher"); 23482 } 23483 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23484 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23485 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23486 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23487 } 23488 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23489 return false; 23490 } 23491 if (mExternalSourcesPolicy != null) { 23492 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23493 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23494 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23495 } 23496 } 23497 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23498 } 23499 23500 @Override 23501 public ComponentName getInstantAppResolverSettingsComponent() { 23502 return mInstantAppResolverSettingsComponent; 23503 } 23504} 23505