PackageManagerService.java revision d46a1604b7e95f7c04966d2961f59858651495c2
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppRequest; 132import android.content.pm.AuxiliaryResolveInfo; 133import android.content.pm.FallbackCategoryProvider; 134import android.content.pm.FeatureInfo; 135import android.content.pm.IOnPermissionsChangeListener; 136import android.content.pm.IPackageDataObserver; 137import android.content.pm.IPackageDeleteObserver; 138import android.content.pm.IPackageDeleteObserver2; 139import android.content.pm.IPackageInstallObserver2; 140import android.content.pm.IPackageInstaller; 141import android.content.pm.IPackageManager; 142import android.content.pm.IPackageMoveObserver; 143import android.content.pm.IPackageStatsObserver; 144import android.content.pm.InstantAppInfo; 145import android.content.pm.InstantAppResolveInfo; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.DumpUtils; 258import com.android.internal.util.FastPrintWriter; 259import com.android.internal.util.FastXmlSerializer; 260import com.android.internal.util.IndentingPrintWriter; 261import com.android.internal.util.Preconditions; 262import com.android.internal.util.XmlUtils; 263import com.android.server.AttributeCache; 264import com.android.server.DeviceIdleController; 265import com.android.server.EventLogTags; 266import com.android.server.FgThread; 267import com.android.server.IntentResolver; 268import com.android.server.LocalServices; 269import com.android.server.LockGuard; 270import com.android.server.ServiceThread; 271import com.android.server.SystemConfig; 272import com.android.server.SystemServerInitThreadPool; 273import com.android.server.Watchdog; 274import com.android.server.net.NetworkPolicyManagerInternal; 275import com.android.server.pm.BackgroundDexOptService; 276import com.android.server.pm.Installer.InstallerException; 277import com.android.server.pm.PermissionsState.PermissionState; 278import com.android.server.pm.Settings.DatabaseVersion; 279import com.android.server.pm.Settings.VersionInfo; 280import com.android.server.pm.dex.DexManager; 281import com.android.server.storage.DeviceStorageMonitorInternal; 282 283import dalvik.system.CloseGuard; 284import dalvik.system.DexFile; 285import dalvik.system.VMRuntime; 286 287import libcore.io.IoUtils; 288import libcore.util.EmptyArray; 289 290import org.xmlpull.v1.XmlPullParser; 291import org.xmlpull.v1.XmlPullParserException; 292import org.xmlpull.v1.XmlSerializer; 293 294import java.io.BufferedOutputStream; 295import java.io.BufferedReader; 296import java.io.ByteArrayInputStream; 297import java.io.ByteArrayOutputStream; 298import java.io.File; 299import java.io.FileDescriptor; 300import java.io.FileInputStream; 301import java.io.FileNotFoundException; 302import java.io.FileOutputStream; 303import java.io.FileReader; 304import java.io.FilenameFilter; 305import java.io.IOException; 306import java.io.PrintWriter; 307import java.nio.charset.StandardCharsets; 308import java.security.DigestInputStream; 309import java.security.MessageDigest; 310import java.security.NoSuchAlgorithmException; 311import java.security.PublicKey; 312import java.security.SecureRandom; 313import java.security.cert.Certificate; 314import java.security.cert.CertificateEncodingException; 315import java.security.cert.CertificateException; 316import java.text.SimpleDateFormat; 317import java.util.ArrayList; 318import java.util.Arrays; 319import java.util.Collection; 320import java.util.Collections; 321import java.util.Comparator; 322import java.util.Date; 323import java.util.HashMap; 324import java.util.HashSet; 325import java.util.Iterator; 326import java.util.List; 327import java.util.Map; 328import java.util.Objects; 329import java.util.Set; 330import java.util.concurrent.CountDownLatch; 331import java.util.concurrent.Future; 332import java.util.concurrent.TimeUnit; 333import java.util.concurrent.atomic.AtomicBoolean; 334import java.util.concurrent.atomic.AtomicInteger; 335 336/** 337 * Keep track of all those APKs everywhere. 338 * <p> 339 * Internally there are two important locks: 340 * <ul> 341 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 342 * and other related state. It is a fine-grained lock that should only be held 343 * momentarily, as it's one of the most contended locks in the system. 344 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 345 * operations typically involve heavy lifting of application data on disk. Since 346 * {@code installd} is single-threaded, and it's operations can often be slow, 347 * this lock should never be acquired while already holding {@link #mPackages}. 348 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 349 * holding {@link #mInstallLock}. 350 * </ul> 351 * Many internal methods rely on the caller to hold the appropriate locks, and 352 * this contract is expressed through method name suffixes: 353 * <ul> 354 * <li>fooLI(): the caller must hold {@link #mInstallLock} 355 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 356 * being modified must be frozen 357 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 358 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 359 * </ul> 360 * <p> 361 * Because this class is very central to the platform's security; please run all 362 * CTS and unit tests whenever making modifications: 363 * 364 * <pre> 365 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 366 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 367 * </pre> 368 */ 369public class PackageManagerService extends IPackageManager.Stub { 370 static final String TAG = "PackageManager"; 371 static final boolean DEBUG_SETTINGS = false; 372 static final boolean DEBUG_PREFERRED = false; 373 static final boolean DEBUG_UPGRADE = false; 374 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 375 private static final boolean DEBUG_BACKUP = false; 376 private static final boolean DEBUG_INSTALL = false; 377 private static final boolean DEBUG_REMOVE = false; 378 private static final boolean DEBUG_BROADCASTS = false; 379 private static final boolean DEBUG_SHOW_INFO = false; 380 private static final boolean DEBUG_PACKAGE_INFO = false; 381 private static final boolean DEBUG_INTENT_MATCHING = false; 382 private static final boolean DEBUG_PACKAGE_SCANNING = false; 383 private static final boolean DEBUG_VERIFY = false; 384 private static final boolean DEBUG_FILTERS = false; 385 386 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 387 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 388 // user, but by default initialize to this. 389 public static final boolean DEBUG_DEXOPT = false; 390 391 private static final boolean DEBUG_ABI_SELECTION = false; 392 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 393 private static final boolean DEBUG_TRIAGED_MISSING = false; 394 private static final boolean DEBUG_APP_DATA = false; 395 396 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 397 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 398 399 private static final boolean DISABLE_EPHEMERAL_APPS = false; 400 private static final boolean HIDE_EPHEMERAL_APIS = false; 401 402 private static final boolean ENABLE_FREE_CACHE_V2 = 403 SystemProperties.getBoolean("fw.free_cache_v2", true); 404 405 private static final int RADIO_UID = Process.PHONE_UID; 406 private static final int LOG_UID = Process.LOG_UID; 407 private static final int NFC_UID = Process.NFC_UID; 408 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 409 private static final int SHELL_UID = Process.SHELL_UID; 410 411 // Cap the size of permission trees that 3rd party apps can define 412 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 413 414 // Suffix used during package installation when copying/moving 415 // package apks to install directory. 416 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 417 418 static final int SCAN_NO_DEX = 1<<1; 419 static final int SCAN_FORCE_DEX = 1<<2; 420 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 421 static final int SCAN_NEW_INSTALL = 1<<4; 422 static final int SCAN_UPDATE_TIME = 1<<5; 423 static final int SCAN_BOOTING = 1<<6; 424 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 425 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 426 static final int SCAN_REPLACING = 1<<9; 427 static final int SCAN_REQUIRE_KNOWN = 1<<10; 428 static final int SCAN_MOVE = 1<<11; 429 static final int SCAN_INITIAL = 1<<12; 430 static final int SCAN_CHECK_ONLY = 1<<13; 431 static final int SCAN_DONT_KILL_APP = 1<<14; 432 static final int SCAN_IGNORE_FROZEN = 1<<15; 433 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 434 static final int SCAN_AS_INSTANT_APP = 1<<17; 435 static final int SCAN_AS_FULL_APP = 1<<18; 436 /** Should not be with the scan flags */ 437 static final int FLAGS_REMOVE_CHATTY = 1<<31; 438 439 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 440 441 private static final int[] EMPTY_INT_ARRAY = new int[0]; 442 443 /** 444 * Timeout (in milliseconds) after which the watchdog should declare that 445 * our handler thread is wedged. The usual default for such things is one 446 * minute but we sometimes do very lengthy I/O operations on this thread, 447 * such as installing multi-gigabyte applications, so ours needs to be longer. 448 */ 449 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 450 451 /** 452 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 453 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 454 * settings entry if available, otherwise we use the hardcoded default. If it's been 455 * more than this long since the last fstrim, we force one during the boot sequence. 456 * 457 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 458 * one gets run at the next available charging+idle time. This final mandatory 459 * no-fstrim check kicks in only of the other scheduling criteria is never met. 460 */ 461 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 462 463 /** 464 * Whether verification is enabled by default. 465 */ 466 private static final boolean DEFAULT_VERIFY_ENABLE = true; 467 468 /** 469 * The default maximum time to wait for the verification agent to return in 470 * milliseconds. 471 */ 472 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 473 474 /** 475 * The default response for package verification timeout. 476 * 477 * This can be either PackageManager.VERIFICATION_ALLOW or 478 * PackageManager.VERIFICATION_REJECT. 479 */ 480 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 481 482 static final String PLATFORM_PACKAGE_NAME = "android"; 483 484 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 485 486 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 487 DEFAULT_CONTAINER_PACKAGE, 488 "com.android.defcontainer.DefaultContainerService"); 489 490 private static final String KILL_APP_REASON_GIDS_CHANGED = 491 "permission grant or revoke changed gids"; 492 493 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 494 "permissions revoked"; 495 496 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 497 498 private static final String PACKAGE_SCHEME = "package"; 499 500 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 501 502 /** Permission grant: not grant the permission. */ 503 private static final int GRANT_DENIED = 1; 504 505 /** Permission grant: grant the permission as an install permission. */ 506 private static final int GRANT_INSTALL = 2; 507 508 /** Permission grant: grant the permission as a runtime one. */ 509 private static final int GRANT_RUNTIME = 3; 510 511 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 512 private static final int GRANT_UPGRADE = 4; 513 514 /** Canonical intent used to identify what counts as a "web browser" app */ 515 private static final Intent sBrowserIntent; 516 static { 517 sBrowserIntent = new Intent(); 518 sBrowserIntent.setAction(Intent.ACTION_VIEW); 519 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 520 sBrowserIntent.setData(Uri.parse("http:")); 521 } 522 523 /** 524 * The set of all protected actions [i.e. those actions for which a high priority 525 * intent filter is disallowed]. 526 */ 527 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 528 static { 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 531 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 532 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 533 } 534 535 // Compilation reasons. 536 public static final int REASON_FIRST_BOOT = 0; 537 public static final int REASON_BOOT = 1; 538 public static final int REASON_INSTALL = 2; 539 public static final int REASON_BACKGROUND_DEXOPT = 3; 540 public static final int REASON_AB_OTA = 4; 541 public static final int REASON_FORCED_DEXOPT = 5; 542 543 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 544 545 /** All dangerous permission names in the same order as the events in MetricsEvent */ 546 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 547 Manifest.permission.READ_CALENDAR, 548 Manifest.permission.WRITE_CALENDAR, 549 Manifest.permission.CAMERA, 550 Manifest.permission.READ_CONTACTS, 551 Manifest.permission.WRITE_CONTACTS, 552 Manifest.permission.GET_ACCOUNTS, 553 Manifest.permission.ACCESS_FINE_LOCATION, 554 Manifest.permission.ACCESS_COARSE_LOCATION, 555 Manifest.permission.RECORD_AUDIO, 556 Manifest.permission.READ_PHONE_STATE, 557 Manifest.permission.CALL_PHONE, 558 Manifest.permission.READ_CALL_LOG, 559 Manifest.permission.WRITE_CALL_LOG, 560 Manifest.permission.ADD_VOICEMAIL, 561 Manifest.permission.USE_SIP, 562 Manifest.permission.PROCESS_OUTGOING_CALLS, 563 Manifest.permission.READ_CELL_BROADCASTS, 564 Manifest.permission.BODY_SENSORS, 565 Manifest.permission.SEND_SMS, 566 Manifest.permission.RECEIVE_SMS, 567 Manifest.permission.READ_SMS, 568 Manifest.permission.RECEIVE_WAP_PUSH, 569 Manifest.permission.RECEIVE_MMS, 570 Manifest.permission.READ_EXTERNAL_STORAGE, 571 Manifest.permission.WRITE_EXTERNAL_STORAGE, 572 Manifest.permission.READ_PHONE_NUMBERS, 573 Manifest.permission.ANSWER_PHONE_CALLS); 574 575 576 /** 577 * Version number for the package parser cache. Increment this whenever the format or 578 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 579 */ 580 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 581 582 /** 583 * Whether the package parser cache is enabled. 584 */ 585 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 586 587 final ServiceThread mHandlerThread; 588 589 final PackageHandler mHandler; 590 591 private final ProcessLoggingHandler mProcessLoggingHandler; 592 593 /** 594 * Messages for {@link #mHandler} that need to wait for system ready before 595 * being dispatched. 596 */ 597 private ArrayList<Message> mPostSystemReadyMessages; 598 599 final int mSdkVersion = Build.VERSION.SDK_INT; 600 601 final Context mContext; 602 final boolean mFactoryTest; 603 final boolean mOnlyCore; 604 final DisplayMetrics mMetrics; 605 final int mDefParseFlags; 606 final String[] mSeparateProcesses; 607 final boolean mIsUpgrade; 608 final boolean mIsPreNUpgrade; 609 final boolean mIsPreNMR1Upgrade; 610 611 @GuardedBy("mPackages") 612 private boolean mDexOptDialogShown; 613 614 /** The location for ASEC container files on internal storage. */ 615 final String mAsecInternalPath; 616 617 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 618 // LOCK HELD. Can be called with mInstallLock held. 619 @GuardedBy("mInstallLock") 620 final Installer mInstaller; 621 622 /** Directory where installed third-party apps stored */ 623 final File mAppInstallDir; 624 625 /** 626 * Directory to which applications installed internally have their 627 * 32 bit native libraries copied. 628 */ 629 private File mAppLib32InstallDir; 630 631 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 632 // apps. 633 final File mDrmAppPrivateInstallDir; 634 635 // ---------------------------------------------------------------- 636 637 // Lock for state used when installing and doing other long running 638 // operations. Methods that must be called with this lock held have 639 // the suffix "LI". 640 final Object mInstallLock = new Object(); 641 642 // ---------------------------------------------------------------- 643 644 // Keys are String (package name), values are Package. This also serves 645 // as the lock for the global state. Methods that must be called with 646 // this lock held have the prefix "LP". 647 @GuardedBy("mPackages") 648 final ArrayMap<String, PackageParser.Package> mPackages = 649 new ArrayMap<String, PackageParser.Package>(); 650 651 final ArrayMap<String, Set<String>> mKnownCodebase = 652 new ArrayMap<String, Set<String>>(); 653 654 // Keys are isolated uids and values are the uid of the application 655 // that created the isolated proccess. 656 @GuardedBy("mPackages") 657 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 658 659 // List of APK paths to load for each user and package. This data is never 660 // persisted by the package manager. Instead, the overlay manager will 661 // ensure the data is up-to-date in runtime. 662 @GuardedBy("mPackages") 663 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 664 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 665 666 /** 667 * Tracks new system packages [received in an OTA] that we expect to 668 * find updated user-installed versions. Keys are package name, values 669 * are package location. 670 */ 671 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 672 /** 673 * Tracks high priority intent filters for protected actions. During boot, certain 674 * filter actions are protected and should never be allowed to have a high priority 675 * intent filter for them. However, there is one, and only one exception -- the 676 * setup wizard. It must be able to define a high priority intent filter for these 677 * actions to ensure there are no escapes from the wizard. We need to delay processing 678 * of these during boot as we need to look at all of the system packages in order 679 * to know which component is the setup wizard. 680 */ 681 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 682 /** 683 * Whether or not processing protected filters should be deferred. 684 */ 685 private boolean mDeferProtectedFilters = true; 686 687 /** 688 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 689 */ 690 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 691 /** 692 * Whether or not system app permissions should be promoted from install to runtime. 693 */ 694 boolean mPromoteSystemApps; 695 696 @GuardedBy("mPackages") 697 final Settings mSettings; 698 699 /** 700 * Set of package names that are currently "frozen", which means active 701 * surgery is being done on the code/data for that package. The platform 702 * will refuse to launch frozen packages to avoid race conditions. 703 * 704 * @see PackageFreezer 705 */ 706 @GuardedBy("mPackages") 707 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 708 709 final ProtectedPackages mProtectedPackages; 710 711 boolean mFirstBoot; 712 713 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 714 715 // System configuration read by SystemConfig. 716 final int[] mGlobalGids; 717 final SparseArray<ArraySet<String>> mSystemPermissions; 718 @GuardedBy("mAvailableFeatures") 719 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 720 721 // If mac_permissions.xml was found for seinfo labeling. 722 boolean mFoundPolicyFile; 723 724 private final InstantAppRegistry mInstantAppRegistry; 725 726 @GuardedBy("mPackages") 727 int mChangedPackagesSequenceNumber; 728 /** 729 * List of changed [installed, removed or updated] packages. 730 * mapping from user id -> sequence number -> package name 731 */ 732 @GuardedBy("mPackages") 733 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 734 /** 735 * The sequence number of the last change to a package. 736 * mapping from user id -> package name -> sequence number 737 */ 738 @GuardedBy("mPackages") 739 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 740 741 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 742 @Override public boolean hasFeature(String feature) { 743 return PackageManagerService.this.hasSystemFeature(feature, 0); 744 } 745 }; 746 747 public static final class SharedLibraryEntry { 748 public final String path; 749 public final String apk; 750 public final SharedLibraryInfo info; 751 752 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 753 String declaringPackageName, int declaringPackageVersionCode) { 754 path = _path; 755 apk = _apk; 756 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 757 declaringPackageName, declaringPackageVersionCode), null); 758 } 759 } 760 761 // Currently known shared libraries. 762 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 763 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 764 new ArrayMap<>(); 765 766 // All available activities, for your resolving pleasure. 767 final ActivityIntentResolver mActivities = 768 new ActivityIntentResolver(); 769 770 // All available receivers, for your resolving pleasure. 771 final ActivityIntentResolver mReceivers = 772 new ActivityIntentResolver(); 773 774 // All available services, for your resolving pleasure. 775 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 776 777 // All available providers, for your resolving pleasure. 778 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 779 780 // Mapping from provider base names (first directory in content URI codePath) 781 // to the provider information. 782 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 783 new ArrayMap<String, PackageParser.Provider>(); 784 785 // Mapping from instrumentation class names to info about them. 786 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 787 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 788 789 // Mapping from permission names to info about them. 790 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 791 new ArrayMap<String, PackageParser.PermissionGroup>(); 792 793 // Packages whose data we have transfered into another package, thus 794 // should no longer exist. 795 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 796 797 // Broadcast actions that are only available to the system. 798 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 799 800 /** List of packages waiting for verification. */ 801 final SparseArray<PackageVerificationState> mPendingVerification 802 = new SparseArray<PackageVerificationState>(); 803 804 /** Set of packages associated with each app op permission. */ 805 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 806 807 final PackageInstallerService mInstallerService; 808 809 private final PackageDexOptimizer mPackageDexOptimizer; 810 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 811 // is used by other apps). 812 private final DexManager mDexManager; 813 814 private AtomicInteger mNextMoveId = new AtomicInteger(); 815 private final MoveCallbacks mMoveCallbacks; 816 817 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 818 819 // Cache of users who need badging. 820 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 821 822 /** Token for keys in mPendingVerification. */ 823 private int mPendingVerificationToken = 0; 824 825 volatile boolean mSystemReady; 826 volatile boolean mSafeMode; 827 volatile boolean mHasSystemUidErrors; 828 829 ApplicationInfo mAndroidApplication; 830 final ActivityInfo mResolveActivity = new ActivityInfo(); 831 final ResolveInfo mResolveInfo = new ResolveInfo(); 832 ComponentName mResolveComponentName; 833 PackageParser.Package mPlatformPackage; 834 ComponentName mCustomResolverComponentName; 835 836 boolean mResolverReplaced = false; 837 838 private final @Nullable ComponentName mIntentFilterVerifierComponent; 839 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 840 841 private int mIntentFilterVerificationToken = 0; 842 843 /** The service connection to the ephemeral resolver */ 844 final EphemeralResolverConnection mInstantAppResolverConnection; 845 /** Component used to show resolver settings for Instant Apps */ 846 final ComponentName mInstantAppResolverSettingsComponent; 847 848 /** Component used to install ephemeral applications */ 849 ComponentName mInstantAppInstallerComponent; 850 ActivityInfo mInstantAppInstallerActivity; 851 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 852 853 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 854 = new SparseArray<IntentFilterVerificationState>(); 855 856 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 857 858 // List of packages names to keep cached, even if they are uninstalled for all users 859 private List<String> mKeepUninstalledPackages; 860 861 private UserManagerInternal mUserManagerInternal; 862 863 private DeviceIdleController.LocalService mDeviceIdleController; 864 865 private File mCacheDir; 866 867 private ArraySet<String> mPrivappPermissionsViolations; 868 869 private Future<?> mPrepareAppDataFuture; 870 871 private static class IFVerificationParams { 872 PackageParser.Package pkg; 873 boolean replacing; 874 int userId; 875 int verifierUid; 876 877 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 878 int _userId, int _verifierUid) { 879 pkg = _pkg; 880 replacing = _replacing; 881 userId = _userId; 882 replacing = _replacing; 883 verifierUid = _verifierUid; 884 } 885 } 886 887 private interface IntentFilterVerifier<T extends IntentFilter> { 888 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 889 T filter, String packageName); 890 void startVerifications(int userId); 891 void receiveVerificationResponse(int verificationId); 892 } 893 894 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 895 private Context mContext; 896 private ComponentName mIntentFilterVerifierComponent; 897 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 898 899 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 900 mContext = context; 901 mIntentFilterVerifierComponent = verifierComponent; 902 } 903 904 private String getDefaultScheme() { 905 return IntentFilter.SCHEME_HTTPS; 906 } 907 908 @Override 909 public void startVerifications(int userId) { 910 // Launch verifications requests 911 int count = mCurrentIntentFilterVerifications.size(); 912 for (int n=0; n<count; n++) { 913 int verificationId = mCurrentIntentFilterVerifications.get(n); 914 final IntentFilterVerificationState ivs = 915 mIntentFilterVerificationStates.get(verificationId); 916 917 String packageName = ivs.getPackageName(); 918 919 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 920 final int filterCount = filters.size(); 921 ArraySet<String> domainsSet = new ArraySet<>(); 922 for (int m=0; m<filterCount; m++) { 923 PackageParser.ActivityIntentInfo filter = filters.get(m); 924 domainsSet.addAll(filter.getHostsList()); 925 } 926 synchronized (mPackages) { 927 if (mSettings.createIntentFilterVerificationIfNeededLPw( 928 packageName, domainsSet) != null) { 929 scheduleWriteSettingsLocked(); 930 } 931 } 932 sendVerificationRequest(userId, verificationId, ivs); 933 } 934 mCurrentIntentFilterVerifications.clear(); 935 } 936 937 private void sendVerificationRequest(int userId, int verificationId, 938 IntentFilterVerificationState ivs) { 939 940 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 943 verificationId); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 946 getDefaultScheme()); 947 verificationIntent.putExtra( 948 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 949 ivs.getHostsString()); 950 verificationIntent.putExtra( 951 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 952 ivs.getPackageName()); 953 verificationIntent.setComponent(mIntentFilterVerifierComponent); 954 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 955 956 UserHandle user = new UserHandle(userId); 957 mContext.sendBroadcastAsUser(verificationIntent, user); 958 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 959 "Sending IntentFilter verification broadcast"); 960 } 961 962 public void receiveVerificationResponse(int verificationId) { 963 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 964 965 final boolean verified = ivs.isVerified(); 966 967 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 968 final int count = filters.size(); 969 if (DEBUG_DOMAIN_VERIFICATION) { 970 Slog.i(TAG, "Received verification response " + verificationId 971 + " for " + count + " filters, verified=" + verified); 972 } 973 for (int n=0; n<count; n++) { 974 PackageParser.ActivityIntentInfo filter = filters.get(n); 975 filter.setVerified(verified); 976 977 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 978 + " verified with result:" + verified + " and hosts:" 979 + ivs.getHostsString()); 980 } 981 982 mIntentFilterVerificationStates.remove(verificationId); 983 984 final String packageName = ivs.getPackageName(); 985 IntentFilterVerificationInfo ivi = null; 986 987 synchronized (mPackages) { 988 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 989 } 990 if (ivi == null) { 991 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 992 + verificationId + " packageName:" + packageName); 993 return; 994 } 995 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 996 "Updating IntentFilterVerificationInfo for package " + packageName 997 +" verificationId:" + verificationId); 998 999 synchronized (mPackages) { 1000 if (verified) { 1001 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1002 } else { 1003 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1004 } 1005 scheduleWriteSettingsLocked(); 1006 1007 final int userId = ivs.getUserId(); 1008 if (userId != UserHandle.USER_ALL) { 1009 final int userStatus = 1010 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1011 1012 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1013 boolean needUpdate = false; 1014 1015 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1016 // already been set by the User thru the Disambiguation dialog 1017 switch (userStatus) { 1018 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1019 if (verified) { 1020 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1021 } else { 1022 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1023 } 1024 needUpdate = true; 1025 break; 1026 1027 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1028 if (verified) { 1029 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1030 needUpdate = true; 1031 } 1032 break; 1033 1034 default: 1035 // Nothing to do 1036 } 1037 1038 if (needUpdate) { 1039 mSettings.updateIntentFilterVerificationStatusLPw( 1040 packageName, updatedStatus, userId); 1041 scheduleWritePackageRestrictionsLocked(userId); 1042 } 1043 } 1044 } 1045 } 1046 1047 @Override 1048 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1049 ActivityIntentInfo filter, String packageName) { 1050 if (!hasValidDomains(filter)) { 1051 return false; 1052 } 1053 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1054 if (ivs == null) { 1055 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1056 packageName); 1057 } 1058 if (DEBUG_DOMAIN_VERIFICATION) { 1059 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1060 } 1061 ivs.addFilter(filter); 1062 return true; 1063 } 1064 1065 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1066 int userId, int verificationId, String packageName) { 1067 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1068 verifierUid, userId, packageName); 1069 ivs.setPendingState(); 1070 synchronized (mPackages) { 1071 mIntentFilterVerificationStates.append(verificationId, ivs); 1072 mCurrentIntentFilterVerifications.add(verificationId); 1073 } 1074 return ivs; 1075 } 1076 } 1077 1078 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1079 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1080 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1081 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1082 } 1083 1084 // Set of pending broadcasts for aggregating enable/disable of components. 1085 static class PendingPackageBroadcasts { 1086 // for each user id, a map of <package name -> components within that package> 1087 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1088 1089 public PendingPackageBroadcasts() { 1090 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1091 } 1092 1093 public ArrayList<String> get(int userId, String packageName) { 1094 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1095 return packages.get(packageName); 1096 } 1097 1098 public void put(int userId, String packageName, ArrayList<String> components) { 1099 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1100 packages.put(packageName, components); 1101 } 1102 1103 public void remove(int userId, String packageName) { 1104 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1105 if (packages != null) { 1106 packages.remove(packageName); 1107 } 1108 } 1109 1110 public void remove(int userId) { 1111 mUidMap.remove(userId); 1112 } 1113 1114 public int userIdCount() { 1115 return mUidMap.size(); 1116 } 1117 1118 public int userIdAt(int n) { 1119 return mUidMap.keyAt(n); 1120 } 1121 1122 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1123 return mUidMap.get(userId); 1124 } 1125 1126 public int size() { 1127 // total number of pending broadcast entries across all userIds 1128 int num = 0; 1129 for (int i = 0; i< mUidMap.size(); i++) { 1130 num += mUidMap.valueAt(i).size(); 1131 } 1132 return num; 1133 } 1134 1135 public void clear() { 1136 mUidMap.clear(); 1137 } 1138 1139 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1140 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1141 if (map == null) { 1142 map = new ArrayMap<String, ArrayList<String>>(); 1143 mUidMap.put(userId, map); 1144 } 1145 return map; 1146 } 1147 } 1148 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1149 1150 // Service Connection to remote media container service to copy 1151 // package uri's from external media onto secure containers 1152 // or internal storage. 1153 private IMediaContainerService mContainerService = null; 1154 1155 static final int SEND_PENDING_BROADCAST = 1; 1156 static final int MCS_BOUND = 3; 1157 static final int END_COPY = 4; 1158 static final int INIT_COPY = 5; 1159 static final int MCS_UNBIND = 6; 1160 static final int START_CLEANING_PACKAGE = 7; 1161 static final int FIND_INSTALL_LOC = 8; 1162 static final int POST_INSTALL = 9; 1163 static final int MCS_RECONNECT = 10; 1164 static final int MCS_GIVE_UP = 11; 1165 static final int UPDATED_MEDIA_STATUS = 12; 1166 static final int WRITE_SETTINGS = 13; 1167 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1168 static final int PACKAGE_VERIFIED = 15; 1169 static final int CHECK_PENDING_VERIFICATION = 16; 1170 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1171 static final int INTENT_FILTER_VERIFIED = 18; 1172 static final int WRITE_PACKAGE_LIST = 19; 1173 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1174 1175 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1176 1177 // Delay time in millisecs 1178 static final int BROADCAST_DELAY = 10 * 1000; 1179 1180 static UserManagerService sUserManager; 1181 1182 // Stores a list of users whose package restrictions file needs to be updated 1183 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1184 1185 final private DefaultContainerConnection mDefContainerConn = 1186 new DefaultContainerConnection(); 1187 class DefaultContainerConnection implements ServiceConnection { 1188 public void onServiceConnected(ComponentName name, IBinder service) { 1189 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1190 final IMediaContainerService imcs = IMediaContainerService.Stub 1191 .asInterface(Binder.allowBlocking(service)); 1192 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1193 } 1194 1195 public void onServiceDisconnected(ComponentName name) { 1196 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1197 } 1198 } 1199 1200 // Recordkeeping of restore-after-install operations that are currently in flight 1201 // between the Package Manager and the Backup Manager 1202 static class PostInstallData { 1203 public InstallArgs args; 1204 public PackageInstalledInfo res; 1205 1206 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1207 args = _a; 1208 res = _r; 1209 } 1210 } 1211 1212 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1213 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1214 1215 // XML tags for backup/restore of various bits of state 1216 private static final String TAG_PREFERRED_BACKUP = "pa"; 1217 private static final String TAG_DEFAULT_APPS = "da"; 1218 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1219 1220 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1221 private static final String TAG_ALL_GRANTS = "rt-grants"; 1222 private static final String TAG_GRANT = "grant"; 1223 private static final String ATTR_PACKAGE_NAME = "pkg"; 1224 1225 private static final String TAG_PERMISSION = "perm"; 1226 private static final String ATTR_PERMISSION_NAME = "name"; 1227 private static final String ATTR_IS_GRANTED = "g"; 1228 private static final String ATTR_USER_SET = "set"; 1229 private static final String ATTR_USER_FIXED = "fixed"; 1230 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1231 1232 // System/policy permission grants are not backed up 1233 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_POLICY_FIXED 1235 | FLAG_PERMISSION_SYSTEM_FIXED 1236 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1237 1238 // And we back up these user-adjusted states 1239 private static final int USER_RUNTIME_GRANT_MASK = 1240 FLAG_PERMISSION_USER_SET 1241 | FLAG_PERMISSION_USER_FIXED 1242 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1243 1244 final @Nullable String mRequiredVerifierPackage; 1245 final @NonNull String mRequiredInstallerPackage; 1246 final @NonNull String mRequiredUninstallerPackage; 1247 final @Nullable String mSetupWizardPackage; 1248 final @Nullable String mStorageManagerPackage; 1249 final @NonNull String mServicesSystemSharedLibraryPackageName; 1250 final @NonNull String mSharedSystemSharedLibraryPackageName; 1251 1252 final boolean mPermissionReviewRequired; 1253 1254 private final PackageUsage mPackageUsage = new PackageUsage(); 1255 private final CompilerStats mCompilerStats = new CompilerStats(); 1256 1257 class PackageHandler extends Handler { 1258 private boolean mBound = false; 1259 final ArrayList<HandlerParams> mPendingInstalls = 1260 new ArrayList<HandlerParams>(); 1261 1262 private boolean connectToService() { 1263 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1264 " DefaultContainerService"); 1265 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1267 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1268 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1270 mBound = true; 1271 return true; 1272 } 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 return false; 1275 } 1276 1277 private void disconnectService() { 1278 mContainerService = null; 1279 mBound = false; 1280 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1281 mContext.unbindService(mDefContainerConn); 1282 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1283 } 1284 1285 PackageHandler(Looper looper) { 1286 super(looper); 1287 } 1288 1289 public void handleMessage(Message msg) { 1290 try { 1291 doHandleMessage(msg); 1292 } finally { 1293 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1294 } 1295 } 1296 1297 void doHandleMessage(Message msg) { 1298 switch (msg.what) { 1299 case INIT_COPY: { 1300 HandlerParams params = (HandlerParams) msg.obj; 1301 int idx = mPendingInstalls.size(); 1302 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1303 // If a bind was already initiated we dont really 1304 // need to do anything. The pending install 1305 // will be processed later on. 1306 if (!mBound) { 1307 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1308 System.identityHashCode(mHandler)); 1309 // If this is the only one pending we might 1310 // have to bind to the service again. 1311 if (!connectToService()) { 1312 Slog.e(TAG, "Failed to bind to media container service"); 1313 params.serviceError(); 1314 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1315 System.identityHashCode(mHandler)); 1316 if (params.traceMethod != null) { 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1318 params.traceCookie); 1319 } 1320 return; 1321 } else { 1322 // Once we bind to the service, the first 1323 // pending request will be processed. 1324 mPendingInstalls.add(idx, params); 1325 } 1326 } else { 1327 mPendingInstalls.add(idx, params); 1328 // Already bound to the service. Just make 1329 // sure we trigger off processing the first request. 1330 if (idx == 0) { 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 } 1334 break; 1335 } 1336 case MCS_BOUND: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1338 if (msg.obj != null) { 1339 mContainerService = (IMediaContainerService) msg.obj; 1340 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1341 System.identityHashCode(mHandler)); 1342 } 1343 if (mContainerService == null) { 1344 if (!mBound) { 1345 // Something seriously wrong since we are not bound and we are not 1346 // waiting for connection. Bail out. 1347 Slog.e(TAG, "Cannot bind to media container service"); 1348 for (HandlerParams params : mPendingInstalls) { 1349 // Indicate service bind error 1350 params.serviceError(); 1351 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1352 System.identityHashCode(params)); 1353 if (params.traceMethod != null) { 1354 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1355 params.traceMethod, params.traceCookie); 1356 } 1357 return; 1358 } 1359 mPendingInstalls.clear(); 1360 } else { 1361 Slog.w(TAG, "Waiting to connect to media container service"); 1362 } 1363 } else if (mPendingInstalls.size() > 0) { 1364 HandlerParams params = mPendingInstalls.get(0); 1365 if (params != null) { 1366 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1367 System.identityHashCode(params)); 1368 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1369 if (params.startCopy()) { 1370 // We are done... look for more work or to 1371 // go idle. 1372 if (DEBUG_SD_INSTALL) Log.i(TAG, 1373 "Checking for more work or unbind..."); 1374 // Delete pending install 1375 if (mPendingInstalls.size() > 0) { 1376 mPendingInstalls.remove(0); 1377 } 1378 if (mPendingInstalls.size() == 0) { 1379 if (mBound) { 1380 if (DEBUG_SD_INSTALL) Log.i(TAG, 1381 "Posting delayed MCS_UNBIND"); 1382 removeMessages(MCS_UNBIND); 1383 Message ubmsg = obtainMessage(MCS_UNBIND); 1384 // Unbind after a little delay, to avoid 1385 // continual thrashing. 1386 sendMessageDelayed(ubmsg, 10000); 1387 } 1388 } else { 1389 // There are more pending requests in queue. 1390 // Just post MCS_BOUND message to trigger processing 1391 // of next pending install. 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, 1393 "Posting MCS_BOUND for next work"); 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1398 } 1399 } else { 1400 // Should never happen ideally. 1401 Slog.w(TAG, "Empty queue"); 1402 } 1403 break; 1404 } 1405 case MCS_RECONNECT: { 1406 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1407 if (mPendingInstalls.size() > 0) { 1408 if (mBound) { 1409 disconnectService(); 1410 } 1411 if (!connectToService()) { 1412 Slog.e(TAG, "Failed to bind to media container service"); 1413 for (HandlerParams params : mPendingInstalls) { 1414 // Indicate service bind error 1415 params.serviceError(); 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1417 System.identityHashCode(params)); 1418 } 1419 mPendingInstalls.clear(); 1420 } 1421 } 1422 break; 1423 } 1424 case MCS_UNBIND: { 1425 // If there is no actual work left, then time to unbind. 1426 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1427 1428 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1429 if (mBound) { 1430 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1431 1432 disconnectService(); 1433 } 1434 } else if (mPendingInstalls.size() > 0) { 1435 // There are more pending requests in queue. 1436 // Just post MCS_BOUND message to trigger processing 1437 // of next pending install. 1438 mHandler.sendEmptyMessage(MCS_BOUND); 1439 } 1440 1441 break; 1442 } 1443 case MCS_GIVE_UP: { 1444 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1445 HandlerParams params = mPendingInstalls.remove(0); 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1447 System.identityHashCode(params)); 1448 break; 1449 } 1450 case SEND_PENDING_BROADCAST: { 1451 String packages[]; 1452 ArrayList<String> components[]; 1453 int size = 0; 1454 int uids[]; 1455 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1456 synchronized (mPackages) { 1457 if (mPendingBroadcasts == null) { 1458 return; 1459 } 1460 size = mPendingBroadcasts.size(); 1461 if (size <= 0) { 1462 // Nothing to be done. Just return 1463 return; 1464 } 1465 packages = new String[size]; 1466 components = new ArrayList[size]; 1467 uids = new int[size]; 1468 int i = 0; // filling out the above arrays 1469 1470 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1471 int packageUserId = mPendingBroadcasts.userIdAt(n); 1472 Iterator<Map.Entry<String, ArrayList<String>>> it 1473 = mPendingBroadcasts.packagesForUserId(packageUserId) 1474 .entrySet().iterator(); 1475 while (it.hasNext() && i < size) { 1476 Map.Entry<String, ArrayList<String>> ent = it.next(); 1477 packages[i] = ent.getKey(); 1478 components[i] = ent.getValue(); 1479 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1480 uids[i] = (ps != null) 1481 ? UserHandle.getUid(packageUserId, ps.appId) 1482 : -1; 1483 i++; 1484 } 1485 } 1486 size = i; 1487 mPendingBroadcasts.clear(); 1488 } 1489 // Send broadcasts 1490 for (int i = 0; i < size; i++) { 1491 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 break; 1495 } 1496 case START_CLEANING_PACKAGE: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 final String packageName = (String)msg.obj; 1499 final int userId = msg.arg1; 1500 final boolean andCode = msg.arg2 != 0; 1501 synchronized (mPackages) { 1502 if (userId == UserHandle.USER_ALL) { 1503 int[] users = sUserManager.getUserIds(); 1504 for (int user : users) { 1505 mSettings.addPackageToCleanLPw( 1506 new PackageCleanItem(user, packageName, andCode)); 1507 } 1508 } else { 1509 mSettings.addPackageToCleanLPw( 1510 new PackageCleanItem(userId, packageName, andCode)); 1511 } 1512 } 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1514 startCleaningPackages(); 1515 } break; 1516 case POST_INSTALL: { 1517 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1518 1519 PostInstallData data = mRunningInstalls.get(msg.arg1); 1520 final boolean didRestore = (msg.arg2 != 0); 1521 mRunningInstalls.delete(msg.arg1); 1522 1523 if (data != null) { 1524 InstallArgs args = data.args; 1525 PackageInstalledInfo parentRes = data.res; 1526 1527 final boolean grantPermissions = (args.installFlags 1528 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1529 final boolean killApp = (args.installFlags 1530 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1531 final String[] grantedPermissions = args.installGrantPermissions; 1532 1533 // Handle the parent package 1534 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1535 grantedPermissions, didRestore, args.installerPackageName, 1536 args.observer); 1537 1538 // Handle the child packages 1539 final int childCount = (parentRes.addedChildPackages != null) 1540 ? parentRes.addedChildPackages.size() : 0; 1541 for (int i = 0; i < childCount; i++) { 1542 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1543 handlePackagePostInstall(childRes, grantPermissions, killApp, 1544 grantedPermissions, false, args.installerPackageName, 1545 args.observer); 1546 } 1547 1548 // Log tracing if needed 1549 if (args.traceMethod != null) { 1550 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1551 args.traceCookie); 1552 } 1553 } else { 1554 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1555 } 1556 1557 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1558 } break; 1559 case UPDATED_MEDIA_STATUS: { 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1561 boolean reportStatus = msg.arg1 == 1; 1562 boolean doGc = msg.arg2 == 1; 1563 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1564 if (doGc) { 1565 // Force a gc to clear up stale containers. 1566 Runtime.getRuntime().gc(); 1567 } 1568 if (msg.obj != null) { 1569 @SuppressWarnings("unchecked") 1570 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1572 // Unload containers 1573 unloadAllContainers(args); 1574 } 1575 if (reportStatus) { 1576 try { 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, 1578 "Invoking StorageManagerService call back"); 1579 PackageHelper.getStorageManager().finishMediaUpdate(); 1580 } catch (RemoteException e) { 1581 Log.e(TAG, "StorageManagerService not running?"); 1582 } 1583 } 1584 } break; 1585 case WRITE_SETTINGS: { 1586 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1587 synchronized (mPackages) { 1588 removeMessages(WRITE_SETTINGS); 1589 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1590 mSettings.writeLPr(); 1591 mDirtyUsers.clear(); 1592 } 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1594 } break; 1595 case WRITE_PACKAGE_RESTRICTIONS: { 1596 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1597 synchronized (mPackages) { 1598 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1599 for (int userId : mDirtyUsers) { 1600 mSettings.writePackageRestrictionsLPr(userId); 1601 } 1602 mDirtyUsers.clear(); 1603 } 1604 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1605 } break; 1606 case WRITE_PACKAGE_LIST: { 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1608 synchronized (mPackages) { 1609 removeMessages(WRITE_PACKAGE_LIST); 1610 mSettings.writePackageListLPr(msg.arg1); 1611 } 1612 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1613 } break; 1614 case CHECK_PENDING_VERIFICATION: { 1615 final int verificationId = msg.arg1; 1616 final PackageVerificationState state = mPendingVerification.get(verificationId); 1617 1618 if ((state != null) && !state.timeoutExtended()) { 1619 final InstallArgs args = state.getInstallArgs(); 1620 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1621 1622 Slog.i(TAG, "Verification timed out for " + originUri); 1623 mPendingVerification.remove(verificationId); 1624 1625 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1626 1627 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1628 Slog.i(TAG, "Continuing with installation of " + originUri); 1629 state.setVerifierResponse(Binder.getCallingUid(), 1630 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1631 broadcastPackageVerified(verificationId, originUri, 1632 PackageManager.VERIFICATION_ALLOW, 1633 state.getInstallArgs().getUser()); 1634 try { 1635 ret = args.copyApk(mContainerService, true); 1636 } catch (RemoteException e) { 1637 Slog.e(TAG, "Could not contact the ContainerService"); 1638 } 1639 } else { 1640 broadcastPackageVerified(verificationId, originUri, 1641 PackageManager.VERIFICATION_REJECT, 1642 state.getInstallArgs().getUser()); 1643 } 1644 1645 Trace.asyncTraceEnd( 1646 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1647 1648 processPendingInstall(args, ret); 1649 mHandler.sendEmptyMessage(MCS_UNBIND); 1650 } 1651 break; 1652 } 1653 case PACKAGE_VERIFIED: { 1654 final int verificationId = msg.arg1; 1655 1656 final PackageVerificationState state = mPendingVerification.get(verificationId); 1657 if (state == null) { 1658 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1659 break; 1660 } 1661 1662 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1663 1664 state.setVerifierResponse(response.callerUid, response.code); 1665 1666 if (state.isVerificationComplete()) { 1667 mPendingVerification.remove(verificationId); 1668 1669 final InstallArgs args = state.getInstallArgs(); 1670 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1671 1672 int ret; 1673 if (state.isInstallAllowed()) { 1674 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1675 broadcastPackageVerified(verificationId, originUri, 1676 response.code, state.getInstallArgs().getUser()); 1677 try { 1678 ret = args.copyApk(mContainerService, true); 1679 } catch (RemoteException e) { 1680 Slog.e(TAG, "Could not contact the ContainerService"); 1681 } 1682 } else { 1683 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1684 } 1685 1686 Trace.asyncTraceEnd( 1687 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1688 1689 processPendingInstall(args, ret); 1690 mHandler.sendEmptyMessage(MCS_UNBIND); 1691 } 1692 1693 break; 1694 } 1695 case START_INTENT_FILTER_VERIFICATIONS: { 1696 IFVerificationParams params = (IFVerificationParams) msg.obj; 1697 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1698 params.replacing, params.pkg); 1699 break; 1700 } 1701 case INTENT_FILTER_VERIFIED: { 1702 final int verificationId = msg.arg1; 1703 1704 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1705 verificationId); 1706 if (state == null) { 1707 Slog.w(TAG, "Invalid IntentFilter verification token " 1708 + verificationId + " received"); 1709 break; 1710 } 1711 1712 final int userId = state.getUserId(); 1713 1714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1715 "Processing IntentFilter verification with token:" 1716 + verificationId + " and userId:" + userId); 1717 1718 final IntentFilterVerificationResponse response = 1719 (IntentFilterVerificationResponse) msg.obj; 1720 1721 state.setVerifierResponse(response.callerUid, response.code); 1722 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1724 "IntentFilter verification with token:" + verificationId 1725 + " and userId:" + userId 1726 + " is settings verifier response with response code:" 1727 + response.code); 1728 1729 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1731 + response.getFailedDomainsString()); 1732 } 1733 1734 if (state.isVerificationComplete()) { 1735 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1736 } else { 1737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1738 "IntentFilter verification with token:" + verificationId 1739 + " was not said to be complete"); 1740 } 1741 1742 break; 1743 } 1744 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1745 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1746 mInstantAppResolverConnection, 1747 (InstantAppRequest) msg.obj, 1748 mInstantAppInstallerActivity, 1749 mHandler); 1750 } 1751 } 1752 } 1753 } 1754 1755 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1756 boolean killApp, String[] grantedPermissions, 1757 boolean launchedForRestore, String installerPackage, 1758 IPackageInstallObserver2 installObserver) { 1759 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1760 // Send the removed broadcasts 1761 if (res.removedInfo != null) { 1762 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1763 } 1764 1765 // Now that we successfully installed the package, grant runtime 1766 // permissions if requested before broadcasting the install. Also 1767 // for legacy apps in permission review mode we clear the permission 1768 // review flag which is used to emulate runtime permissions for 1769 // legacy apps. 1770 if (grantPermissions) { 1771 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1772 } 1773 1774 final boolean update = res.removedInfo != null 1775 && res.removedInfo.removedPackage != null; 1776 1777 // If this is the first time we have child packages for a disabled privileged 1778 // app that had no children, we grant requested runtime permissions to the new 1779 // children if the parent on the system image had them already granted. 1780 if (res.pkg.parentPackage != null) { 1781 synchronized (mPackages) { 1782 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1783 } 1784 } 1785 1786 synchronized (mPackages) { 1787 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1788 } 1789 1790 final String packageName = res.pkg.applicationInfo.packageName; 1791 1792 // Determine the set of users who are adding this package for 1793 // the first time vs. those who are seeing an update. 1794 int[] firstUsers = EMPTY_INT_ARRAY; 1795 int[] updateUsers = EMPTY_INT_ARRAY; 1796 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1797 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1798 for (int newUser : res.newUsers) { 1799 if (ps.getInstantApp(newUser)) { 1800 continue; 1801 } 1802 if (allNewUsers) { 1803 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1804 continue; 1805 } 1806 boolean isNew = true; 1807 for (int origUser : res.origUsers) { 1808 if (origUser == newUser) { 1809 isNew = false; 1810 break; 1811 } 1812 } 1813 if (isNew) { 1814 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1815 } else { 1816 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1817 } 1818 } 1819 1820 // Send installed broadcasts if the package is not a static shared lib. 1821 if (res.pkg.staticSharedLibName == null) { 1822 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1823 1824 // Send added for users that see the package for the first time 1825 // sendPackageAddedForNewUsers also deals with system apps 1826 int appId = UserHandle.getAppId(res.uid); 1827 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1828 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1829 1830 // Send added for users that don't see the package for the first time 1831 Bundle extras = new Bundle(1); 1832 extras.putInt(Intent.EXTRA_UID, res.uid); 1833 if (update) { 1834 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1835 } 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1837 extras, 0 /*flags*/, null /*targetPackage*/, 1838 null /*finishedReceiver*/, updateUsers); 1839 1840 // Send replaced for users that don't see the package for the first time 1841 if (update) { 1842 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1843 packageName, extras, 0 /*flags*/, 1844 null /*targetPackage*/, null /*finishedReceiver*/, 1845 updateUsers); 1846 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1847 null /*package*/, null /*extras*/, 0 /*flags*/, 1848 packageName /*targetPackage*/, 1849 null /*finishedReceiver*/, updateUsers); 1850 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1851 // First-install and we did a restore, so we're responsible for the 1852 // first-launch broadcast. 1853 if (DEBUG_BACKUP) { 1854 Slog.i(TAG, "Post-restore of " + packageName 1855 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1856 } 1857 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1858 } 1859 1860 // Send broadcast package appeared if forward locked/external for all users 1861 // treat asec-hosted packages like removable media on upgrade 1862 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1863 if (DEBUG_INSTALL) { 1864 Slog.i(TAG, "upgrading pkg " + res.pkg 1865 + " is ASEC-hosted -> AVAILABLE"); 1866 } 1867 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1868 ArrayList<String> pkgList = new ArrayList<>(1); 1869 pkgList.add(packageName); 1870 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1871 } 1872 } 1873 1874 // Work that needs to happen on first install within each user 1875 if (firstUsers != null && firstUsers.length > 0) { 1876 synchronized (mPackages) { 1877 for (int userId : firstUsers) { 1878 // If this app is a browser and it's newly-installed for some 1879 // users, clear any default-browser state in those users. The 1880 // app's nature doesn't depend on the user, so we can just check 1881 // its browser nature in any user and generalize. 1882 if (packageIsBrowser(packageName, userId)) { 1883 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1884 } 1885 1886 // We may also need to apply pending (restored) runtime 1887 // permission grants within these users. 1888 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1889 } 1890 } 1891 } 1892 1893 // Log current value of "unknown sources" setting 1894 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1895 getUnknownSourcesSettings()); 1896 1897 // Force a gc to clear up things 1898 Runtime.getRuntime().gc(); 1899 1900 // Remove the replaced package's older resources safely now 1901 // We delete after a gc for applications on sdcard. 1902 if (res.removedInfo != null && res.removedInfo.args != null) { 1903 synchronized (mInstallLock) { 1904 res.removedInfo.args.doPostDeleteLI(true); 1905 } 1906 } 1907 1908 // Notify DexManager that the package was installed for new users. 1909 // The updated users should already be indexed and the package code paths 1910 // should not change. 1911 // Don't notify the manager for ephemeral apps as they are not expected to 1912 // survive long enough to benefit of background optimizations. 1913 for (int userId : firstUsers) { 1914 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1915 mDexManager.notifyPackageInstalled(info, userId); 1916 } 1917 } 1918 1919 // If someone is watching installs - notify them 1920 if (installObserver != null) { 1921 try { 1922 Bundle extras = extrasForInstallResult(res); 1923 installObserver.onPackageInstalled(res.name, res.returnCode, 1924 res.returnMsg, extras); 1925 } catch (RemoteException e) { 1926 Slog.i(TAG, "Observer no longer exists."); 1927 } 1928 } 1929 } 1930 1931 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1932 PackageParser.Package pkg) { 1933 if (pkg.parentPackage == null) { 1934 return; 1935 } 1936 if (pkg.requestedPermissions == null) { 1937 return; 1938 } 1939 final PackageSetting disabledSysParentPs = mSettings 1940 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1941 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1942 || !disabledSysParentPs.isPrivileged() 1943 || (disabledSysParentPs.childPackageNames != null 1944 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1945 return; 1946 } 1947 final int[] allUserIds = sUserManager.getUserIds(); 1948 final int permCount = pkg.requestedPermissions.size(); 1949 for (int i = 0; i < permCount; i++) { 1950 String permission = pkg.requestedPermissions.get(i); 1951 BasePermission bp = mSettings.mPermissions.get(permission); 1952 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1953 continue; 1954 } 1955 for (int userId : allUserIds) { 1956 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1957 permission, userId)) { 1958 grantRuntimePermission(pkg.packageName, permission, userId); 1959 } 1960 } 1961 } 1962 } 1963 1964 private StorageEventListener mStorageListener = new StorageEventListener() { 1965 @Override 1966 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1967 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1968 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1969 final String volumeUuid = vol.getFsUuid(); 1970 1971 // Clean up any users or apps that were removed or recreated 1972 // while this volume was missing 1973 sUserManager.reconcileUsers(volumeUuid); 1974 reconcileApps(volumeUuid); 1975 1976 // Clean up any install sessions that expired or were 1977 // cancelled while this volume was missing 1978 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1979 1980 loadPrivatePackages(vol); 1981 1982 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1983 unloadPrivatePackages(vol); 1984 } 1985 } 1986 1987 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1988 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1989 updateExternalMediaStatus(true, false); 1990 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1991 updateExternalMediaStatus(false, false); 1992 } 1993 } 1994 } 1995 1996 @Override 1997 public void onVolumeForgotten(String fsUuid) { 1998 if (TextUtils.isEmpty(fsUuid)) { 1999 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2000 return; 2001 } 2002 2003 // Remove any apps installed on the forgotten volume 2004 synchronized (mPackages) { 2005 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2006 for (PackageSetting ps : packages) { 2007 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2008 deletePackageVersioned(new VersionedPackage(ps.name, 2009 PackageManager.VERSION_CODE_HIGHEST), 2010 new LegacyPackageDeleteObserver(null).getBinder(), 2011 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2012 // Try very hard to release any references to this package 2013 // so we don't risk the system server being killed due to 2014 // open FDs 2015 AttributeCache.instance().removePackage(ps.name); 2016 } 2017 2018 mSettings.onVolumeForgotten(fsUuid); 2019 mSettings.writeLPr(); 2020 } 2021 } 2022 }; 2023 2024 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2025 String[] grantedPermissions) { 2026 for (int userId : userIds) { 2027 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2028 } 2029 } 2030 2031 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2032 String[] grantedPermissions) { 2033 SettingBase sb = (SettingBase) pkg.mExtras; 2034 if (sb == null) { 2035 return; 2036 } 2037 2038 PermissionsState permissionsState = sb.getPermissionsState(); 2039 2040 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2041 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2042 2043 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2044 >= Build.VERSION_CODES.M; 2045 2046 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2047 2048 for (String permission : pkg.requestedPermissions) { 2049 final BasePermission bp; 2050 synchronized (mPackages) { 2051 bp = mSettings.mPermissions.get(permission); 2052 } 2053 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2054 && (!instantApp || bp.isInstant()) 2055 && (grantedPermissions == null 2056 || ArrayUtils.contains(grantedPermissions, permission))) { 2057 final int flags = permissionsState.getPermissionFlags(permission, userId); 2058 if (supportsRuntimePermissions) { 2059 // Installer cannot change immutable permissions. 2060 if ((flags & immutableFlags) == 0) { 2061 grantRuntimePermission(pkg.packageName, permission, userId); 2062 } 2063 } else if (mPermissionReviewRequired) { 2064 // In permission review mode we clear the review flag when we 2065 // are asked to install the app with all permissions granted. 2066 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2067 updatePermissionFlags(permission, pkg.packageName, 2068 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2069 } 2070 } 2071 } 2072 } 2073 } 2074 2075 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2076 Bundle extras = null; 2077 switch (res.returnCode) { 2078 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2079 extras = new Bundle(); 2080 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2081 res.origPermission); 2082 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2083 res.origPackage); 2084 break; 2085 } 2086 case PackageManager.INSTALL_SUCCEEDED: { 2087 extras = new Bundle(); 2088 extras.putBoolean(Intent.EXTRA_REPLACING, 2089 res.removedInfo != null && res.removedInfo.removedPackage != null); 2090 break; 2091 } 2092 } 2093 return extras; 2094 } 2095 2096 void scheduleWriteSettingsLocked() { 2097 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2098 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2099 } 2100 } 2101 2102 void scheduleWritePackageListLocked(int userId) { 2103 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2104 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2105 msg.arg1 = userId; 2106 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2107 } 2108 } 2109 2110 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2111 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2112 scheduleWritePackageRestrictionsLocked(userId); 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(int userId) { 2116 final int[] userIds = (userId == UserHandle.USER_ALL) 2117 ? sUserManager.getUserIds() : new int[]{userId}; 2118 for (int nextUserId : userIds) { 2119 if (!sUserManager.exists(nextUserId)) return; 2120 mDirtyUsers.add(nextUserId); 2121 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2122 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2123 } 2124 } 2125 } 2126 2127 public static PackageManagerService main(Context context, Installer installer, 2128 boolean factoryTest, boolean onlyCore) { 2129 // Self-check for initial settings. 2130 PackageManagerServiceCompilerMapping.checkProperties(); 2131 2132 PackageManagerService m = new PackageManagerService(context, installer, 2133 factoryTest, onlyCore); 2134 m.enableSystemUserPackages(); 2135 ServiceManager.addService("package", m); 2136 return m; 2137 } 2138 2139 private void enableSystemUserPackages() { 2140 if (!UserManager.isSplitSystemUser()) { 2141 return; 2142 } 2143 // For system user, enable apps based on the following conditions: 2144 // - app is whitelisted or belong to one of these groups: 2145 // -- system app which has no launcher icons 2146 // -- system app which has INTERACT_ACROSS_USERS permission 2147 // -- system IME app 2148 // - app is not in the blacklist 2149 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2150 Set<String> enableApps = new ArraySet<>(); 2151 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2152 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2153 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2154 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2155 enableApps.addAll(wlApps); 2156 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2157 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2158 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2159 enableApps.removeAll(blApps); 2160 Log.i(TAG, "Applications installed for system user: " + enableApps); 2161 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2162 UserHandle.SYSTEM); 2163 final int allAppsSize = allAps.size(); 2164 synchronized (mPackages) { 2165 for (int i = 0; i < allAppsSize; i++) { 2166 String pName = allAps.get(i); 2167 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2168 // Should not happen, but we shouldn't be failing if it does 2169 if (pkgSetting == null) { 2170 continue; 2171 } 2172 boolean install = enableApps.contains(pName); 2173 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2174 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2175 + " for system user"); 2176 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2177 } 2178 } 2179 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2180 } 2181 } 2182 2183 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2184 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2185 Context.DISPLAY_SERVICE); 2186 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2187 } 2188 2189 /** 2190 * Requests that files preopted on a secondary system partition be copied to the data partition 2191 * if possible. Note that the actual copying of the files is accomplished by init for security 2192 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2193 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2194 */ 2195 private static void requestCopyPreoptedFiles() { 2196 final int WAIT_TIME_MS = 100; 2197 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2198 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2199 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2200 // We will wait for up to 100 seconds. 2201 final long timeStart = SystemClock.uptimeMillis(); 2202 final long timeEnd = timeStart + 100 * 1000; 2203 long timeNow = timeStart; 2204 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2205 try { 2206 Thread.sleep(WAIT_TIME_MS); 2207 } catch (InterruptedException e) { 2208 // Do nothing 2209 } 2210 timeNow = SystemClock.uptimeMillis(); 2211 if (timeNow > timeEnd) { 2212 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2213 Slog.wtf(TAG, "cppreopt did not finish!"); 2214 break; 2215 } 2216 } 2217 2218 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2219 } 2220 } 2221 2222 public PackageManagerService(Context context, Installer installer, 2223 boolean factoryTest, boolean onlyCore) { 2224 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2226 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2227 SystemClock.uptimeMillis()); 2228 2229 if (mSdkVersion <= 0) { 2230 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2231 } 2232 2233 mContext = context; 2234 2235 mPermissionReviewRequired = context.getResources().getBoolean( 2236 R.bool.config_permissionReviewRequired); 2237 2238 mFactoryTest = factoryTest; 2239 mOnlyCore = onlyCore; 2240 mMetrics = new DisplayMetrics(); 2241 mSettings = new Settings(mPackages); 2242 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2245 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2246 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2247 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2248 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2249 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2250 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2251 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2252 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2253 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2254 2255 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2256 if (separateProcesses != null && separateProcesses.length() > 0) { 2257 if ("*".equals(separateProcesses)) { 2258 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2259 mSeparateProcesses = null; 2260 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2261 } else { 2262 mDefParseFlags = 0; 2263 mSeparateProcesses = separateProcesses.split(","); 2264 Slog.w(TAG, "Running with debug.separate_processes: " 2265 + separateProcesses); 2266 } 2267 } else { 2268 mDefParseFlags = 0; 2269 mSeparateProcesses = null; 2270 } 2271 2272 mInstaller = installer; 2273 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2274 "*dexopt*"); 2275 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2276 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2277 2278 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2279 FgThread.get().getLooper()); 2280 2281 getDefaultDisplayMetrics(context, mMetrics); 2282 2283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2284 SystemConfig systemConfig = SystemConfig.getInstance(); 2285 mGlobalGids = systemConfig.getGlobalGids(); 2286 mSystemPermissions = systemConfig.getSystemPermissions(); 2287 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2289 2290 mProtectedPackages = new ProtectedPackages(mContext); 2291 2292 synchronized (mInstallLock) { 2293 // writer 2294 synchronized (mPackages) { 2295 mHandlerThread = new ServiceThread(TAG, 2296 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2297 mHandlerThread.start(); 2298 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2299 mProcessLoggingHandler = new ProcessLoggingHandler(); 2300 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2301 2302 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2303 mInstantAppRegistry = new InstantAppRegistry(this); 2304 2305 File dataDir = Environment.getDataDirectory(); 2306 mAppInstallDir = new File(dataDir, "app"); 2307 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2308 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2309 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2310 sUserManager = new UserManagerService(context, this, 2311 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2312 2313 // Propagate permission configuration in to package manager. 2314 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2315 = systemConfig.getPermissions(); 2316 for (int i=0; i<permConfig.size(); i++) { 2317 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2318 BasePermission bp = mSettings.mPermissions.get(perm.name); 2319 if (bp == null) { 2320 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2321 mSettings.mPermissions.put(perm.name, bp); 2322 } 2323 if (perm.gids != null) { 2324 bp.setGids(perm.gids, perm.perUser); 2325 } 2326 } 2327 2328 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2329 final int builtInLibCount = libConfig.size(); 2330 for (int i = 0; i < builtInLibCount; i++) { 2331 String name = libConfig.keyAt(i); 2332 String path = libConfig.valueAt(i); 2333 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2334 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2335 } 2336 2337 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2338 2339 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2340 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2342 2343 // Clean up orphaned packages for which the code path doesn't exist 2344 // and they are an update to a system app - caused by bug/32321269 2345 final int packageSettingCount = mSettings.mPackages.size(); 2346 for (int i = packageSettingCount - 1; i >= 0; i--) { 2347 PackageSetting ps = mSettings.mPackages.valueAt(i); 2348 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2349 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2350 mSettings.mPackages.removeAt(i); 2351 mSettings.enableSystemPackageLPw(ps.name); 2352 } 2353 } 2354 2355 if (mFirstBoot) { 2356 requestCopyPreoptedFiles(); 2357 } 2358 2359 String customResolverActivity = Resources.getSystem().getString( 2360 R.string.config_customResolverActivity); 2361 if (TextUtils.isEmpty(customResolverActivity)) { 2362 customResolverActivity = null; 2363 } else { 2364 mCustomResolverComponentName = ComponentName.unflattenFromString( 2365 customResolverActivity); 2366 } 2367 2368 long startTime = SystemClock.uptimeMillis(); 2369 2370 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2371 startTime); 2372 2373 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2374 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2375 2376 if (bootClassPath == null) { 2377 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2378 } 2379 2380 if (systemServerClassPath == null) { 2381 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2382 } 2383 2384 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2385 2386 final VersionInfo ver = mSettings.getInternalVersion(); 2387 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2388 if (mIsUpgrade) { 2389 logCriticalInfo(Log.INFO, 2390 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2391 } 2392 2393 // when upgrading from pre-M, promote system app permissions from install to runtime 2394 mPromoteSystemApps = 2395 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2396 2397 // When upgrading from pre-N, we need to handle package extraction like first boot, 2398 // as there is no profiling data available. 2399 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2400 2401 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2402 2403 // save off the names of pre-existing system packages prior to scanning; we don't 2404 // want to automatically grant runtime permissions for new system apps 2405 if (mPromoteSystemApps) { 2406 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2407 while (pkgSettingIter.hasNext()) { 2408 PackageSetting ps = pkgSettingIter.next(); 2409 if (isSystemApp(ps)) { 2410 mExistingSystemPackages.add(ps.name); 2411 } 2412 } 2413 } 2414 2415 mCacheDir = preparePackageParserCache(mIsUpgrade); 2416 2417 // Set flag to monitor and not change apk file paths when 2418 // scanning install directories. 2419 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2420 2421 if (mIsUpgrade || mFirstBoot) { 2422 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2423 } 2424 2425 // Collect vendor overlay packages. (Do this before scanning any apps.) 2426 // For security and version matching reason, only consider 2427 // overlay packages if they reside in the right directory. 2428 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2432 2433 // Find base frameworks (resource packages without code). 2434 scanDirTracedLI(frameworkDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED, 2438 scanFlags | SCAN_NO_DEX, 0); 2439 2440 // Collected privileged system packages. 2441 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2442 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR 2445 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2446 2447 // Collect ordinary system packages. 2448 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2449 scanDirTracedLI(systemAppDir, mDefParseFlags 2450 | PackageParser.PARSE_IS_SYSTEM 2451 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2452 2453 // Collect all vendor packages. 2454 File vendorAppDir = new File("/vendor/app"); 2455 try { 2456 vendorAppDir = vendorAppDir.getCanonicalFile(); 2457 } catch (IOException e) { 2458 // failed to look up canonical path, continue with original one 2459 } 2460 scanDirTracedLI(vendorAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Collect all OEM packages. 2465 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2466 scanDirTracedLI(oemAppDir, mDefParseFlags 2467 | PackageParser.PARSE_IS_SYSTEM 2468 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2469 2470 // Prune any system packages that no longer exist. 2471 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2472 if (!mOnlyCore) { 2473 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2474 while (psit.hasNext()) { 2475 PackageSetting ps = psit.next(); 2476 2477 /* 2478 * If this is not a system app, it can't be a 2479 * disable system app. 2480 */ 2481 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2482 continue; 2483 } 2484 2485 /* 2486 * If the package is scanned, it's not erased. 2487 */ 2488 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2489 if (scannedPkg != null) { 2490 /* 2491 * If the system app is both scanned and in the 2492 * disabled packages list, then it must have been 2493 * added via OTA. Remove it from the currently 2494 * scanned package so the previously user-installed 2495 * application can be scanned. 2496 */ 2497 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2498 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2499 + ps.name + "; removing system app. Last known codePath=" 2500 + ps.codePathString + ", installStatus=" + ps.installStatus 2501 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2502 + scannedPkg.mVersionCode); 2503 removePackageLI(scannedPkg, true); 2504 mExpectingBetter.put(ps.name, ps.codePath); 2505 } 2506 2507 continue; 2508 } 2509 2510 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2511 psit.remove(); 2512 logCriticalInfo(Log.WARN, "System package " + ps.name 2513 + " no longer exists; it's data will be wiped"); 2514 // Actual deletion of code and data will be handled by later 2515 // reconciliation step 2516 } else { 2517 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2518 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2519 possiblyDeletedUpdatedSystemApps.add(ps.name); 2520 } 2521 } 2522 } 2523 } 2524 2525 //look for any incomplete package installations 2526 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2527 for (int i = 0; i < deletePkgsList.size(); i++) { 2528 // Actual deletion of code and data will be handled by later 2529 // reconciliation step 2530 final String packageName = deletePkgsList.get(i).name; 2531 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2532 synchronized (mPackages) { 2533 mSettings.removePackageLPw(packageName); 2534 } 2535 } 2536 2537 //delete tmp files 2538 deleteTempPackageFiles(); 2539 2540 // Remove any shared userIDs that have no associated packages 2541 mSettings.pruneSharedUsersLPw(); 2542 2543 if (!mOnlyCore) { 2544 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2545 SystemClock.uptimeMillis()); 2546 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2549 | PackageParser.PARSE_FORWARD_LOCK, 2550 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2551 2552 /** 2553 * Remove disable package settings for any updated system 2554 * apps that were removed via an OTA. If they're not a 2555 * previously-updated app, remove them completely. 2556 * Otherwise, just revoke their system-level permissions. 2557 */ 2558 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2559 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2560 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2561 2562 String msg; 2563 if (deletedPkg == null) { 2564 msg = "Updated system package " + deletedAppName 2565 + " no longer exists; it's data will be wiped"; 2566 // Actual deletion of code and data will be handled by later 2567 // reconciliation step 2568 } else { 2569 msg = "Updated system app + " + deletedAppName 2570 + " no longer present; removing system privileges for " 2571 + deletedAppName; 2572 2573 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2574 2575 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2576 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2577 } 2578 logCriticalInfo(Log.WARN, msg); 2579 } 2580 2581 /** 2582 * Make sure all system apps that we expected to appear on 2583 * the userdata partition actually showed up. If they never 2584 * appeared, crawl back and revive the system version. 2585 */ 2586 for (int i = 0; i < mExpectingBetter.size(); i++) { 2587 final String packageName = mExpectingBetter.keyAt(i); 2588 if (!mPackages.containsKey(packageName)) { 2589 final File scanFile = mExpectingBetter.valueAt(i); 2590 2591 logCriticalInfo(Log.WARN, "Expected better " + packageName 2592 + " but never showed up; reverting to system"); 2593 2594 int reparseFlags = mDefParseFlags; 2595 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR 2598 | PackageParser.PARSE_IS_PRIVILEGED; 2599 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2600 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2601 | PackageParser.PARSE_IS_SYSTEM_DIR; 2602 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2603 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR; 2605 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2606 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2607 | PackageParser.PARSE_IS_SYSTEM_DIR; 2608 } else { 2609 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2610 continue; 2611 } 2612 2613 mSettings.enableSystemPackageLPw(packageName); 2614 2615 try { 2616 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2617 } catch (PackageManagerException e) { 2618 Slog.e(TAG, "Failed to parse original system package: " 2619 + e.getMessage()); 2620 } 2621 } 2622 } 2623 } 2624 mExpectingBetter.clear(); 2625 2626 // Resolve the storage manager. 2627 mStorageManagerPackage = getStorageManagerPackageName(); 2628 2629 // Resolve protected action filters. Only the setup wizard is allowed to 2630 // have a high priority filter for these actions. 2631 mSetupWizardPackage = getSetupWizardPackageName(); 2632 if (mProtectedFilters.size() > 0) { 2633 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2634 Slog.i(TAG, "No setup wizard;" 2635 + " All protected intents capped to priority 0"); 2636 } 2637 for (ActivityIntentInfo filter : mProtectedFilters) { 2638 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2639 if (DEBUG_FILTERS) { 2640 Slog.i(TAG, "Found setup wizard;" 2641 + " allow priority " + filter.getPriority() + ";" 2642 + " package: " + filter.activity.info.packageName 2643 + " activity: " + filter.activity.className 2644 + " priority: " + filter.getPriority()); 2645 } 2646 // skip setup wizard; allow it to keep the high priority filter 2647 continue; 2648 } 2649 Slog.w(TAG, "Protected action; cap priority to 0;" 2650 + " package: " + filter.activity.info.packageName 2651 + " activity: " + filter.activity.className 2652 + " origPrio: " + filter.getPriority()); 2653 filter.setPriority(0); 2654 } 2655 } 2656 mDeferProtectedFilters = false; 2657 mProtectedFilters.clear(); 2658 2659 // Now that we know all of the shared libraries, update all clients to have 2660 // the correct library paths. 2661 updateAllSharedLibrariesLPw(null); 2662 2663 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2664 // NOTE: We ignore potential failures here during a system scan (like 2665 // the rest of the commands above) because there's precious little we 2666 // can do about it. A settings error is reported, though. 2667 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2668 } 2669 2670 // Now that we know all the packages we are keeping, 2671 // read and update their last usage times. 2672 mPackageUsage.read(mPackages); 2673 mCompilerStats.read(); 2674 2675 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2676 SystemClock.uptimeMillis()); 2677 Slog.i(TAG, "Time to scan packages: " 2678 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2679 + " seconds"); 2680 2681 // If the platform SDK has changed since the last time we booted, 2682 // we need to re-grant app permission to catch any new ones that 2683 // appear. This is really a hack, and means that apps can in some 2684 // cases get permissions that the user didn't initially explicitly 2685 // allow... it would be nice to have some better way to handle 2686 // this situation. 2687 int updateFlags = UPDATE_PERMISSIONS_ALL; 2688 if (ver.sdkVersion != mSdkVersion) { 2689 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2690 + mSdkVersion + "; regranting permissions for internal storage"); 2691 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2692 } 2693 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2694 ver.sdkVersion = mSdkVersion; 2695 2696 // If this is the first boot or an update from pre-M, and it is a normal 2697 // boot, then we need to initialize the default preferred apps across 2698 // all defined users. 2699 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2700 for (UserInfo user : sUserManager.getUsers(true)) { 2701 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2702 applyFactoryDefaultBrowserLPw(user.id); 2703 primeDomainVerificationsLPw(user.id); 2704 } 2705 } 2706 2707 // Prepare storage for system user really early during boot, 2708 // since core system apps like SettingsProvider and SystemUI 2709 // can't wait for user to start 2710 final int storageFlags; 2711 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2712 storageFlags = StorageManager.FLAG_STORAGE_DE; 2713 } else { 2714 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2715 } 2716 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2717 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2718 true /* onlyCoreApps */); 2719 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2720 if (deferPackages == null || deferPackages.isEmpty()) { 2721 return; 2722 } 2723 int count = 0; 2724 for (String pkgName : deferPackages) { 2725 PackageParser.Package pkg = null; 2726 synchronized (mPackages) { 2727 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2728 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2729 pkg = ps.pkg; 2730 } 2731 } 2732 if (pkg != null) { 2733 synchronized (mInstallLock) { 2734 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2735 true /* maybeMigrateAppData */); 2736 } 2737 count++; 2738 } 2739 } 2740 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2741 }, "prepareAppData"); 2742 2743 // If this is first boot after an OTA, and a normal boot, then 2744 // we need to clear code cache directories. 2745 // Note that we do *not* clear the application profiles. These remain valid 2746 // across OTAs and are used to drive profile verification (post OTA) and 2747 // profile compilation (without waiting to collect a fresh set of profiles). 2748 if (mIsUpgrade && !onlyCore) { 2749 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2750 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2751 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2752 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2753 // No apps are running this early, so no need to freeze 2754 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2755 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2756 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2757 } 2758 } 2759 ver.fingerprint = Build.FINGERPRINT; 2760 } 2761 2762 checkDefaultBrowser(); 2763 2764 // clear only after permissions and other defaults have been updated 2765 mExistingSystemPackages.clear(); 2766 mPromoteSystemApps = false; 2767 2768 // All the changes are done during package scanning. 2769 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2770 2771 // can downgrade to reader 2772 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2773 mSettings.writeLPr(); 2774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2775 2776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2777 SystemClock.uptimeMillis()); 2778 2779 if (!mOnlyCore) { 2780 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2781 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2782 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2783 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2784 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2785 mIntentFilterVerifierComponent); 2786 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2787 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2788 SharedLibraryInfo.VERSION_UNDEFINED); 2789 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2790 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2791 SharedLibraryInfo.VERSION_UNDEFINED); 2792 } else { 2793 mRequiredVerifierPackage = null; 2794 mRequiredInstallerPackage = null; 2795 mRequiredUninstallerPackage = null; 2796 mIntentFilterVerifierComponent = null; 2797 mIntentFilterVerifier = null; 2798 mServicesSystemSharedLibraryPackageName = null; 2799 mSharedSystemSharedLibraryPackageName = null; 2800 } 2801 2802 mInstallerService = new PackageInstallerService(context, this); 2803 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2804 if (ephemeralResolverComponent != null) { 2805 if (DEBUG_EPHEMERAL) { 2806 Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent); 2807 } 2808 mInstantAppResolverConnection = 2809 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2810 mInstantAppResolverSettingsComponent = 2811 getEphemeralResolverSettingsLPr(ephemeralResolverComponent); 2812 } else { 2813 mInstantAppResolverConnection = null; 2814 mInstantAppResolverSettingsComponent = null; 2815 } 2816 updateInstantAppInstallerLocked(); 2817 2818 // Read and update the usage of dex files. 2819 // Do this at the end of PM init so that all the packages have their 2820 // data directory reconciled. 2821 // At this point we know the code paths of the packages, so we can validate 2822 // the disk file and build the internal cache. 2823 // The usage file is expected to be small so loading and verifying it 2824 // should take a fairly small time compare to the other activities (e.g. package 2825 // scanning). 2826 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2827 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2828 for (int userId : currentUserIds) { 2829 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2830 } 2831 mDexManager.load(userPackages); 2832 } // synchronized (mPackages) 2833 } // synchronized (mInstallLock) 2834 2835 // Now after opening every single application zip, make sure they 2836 // are all flushed. Not really needed, but keeps things nice and 2837 // tidy. 2838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2839 Runtime.getRuntime().gc(); 2840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2841 2842 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2843 FallbackCategoryProvider.loadFallbacks(); 2844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2845 2846 // The initial scanning above does many calls into installd while 2847 // holding the mPackages lock, but we're mostly interested in yelling 2848 // once we have a booted system. 2849 mInstaller.setWarnIfHeld(mPackages); 2850 2851 // Expose private service for system components to use. 2852 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2854 } 2855 2856 private void updateInstantAppInstallerLocked() { 2857 final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent; 2858 final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr(); 2859 ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null 2860 ? null : newInstantAppInstaller.getComponentName(); 2861 2862 if (newInstantAppInstallerComponent != null 2863 && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) { 2864 if (DEBUG_EPHEMERAL) { 2865 Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent); 2866 } 2867 setUpInstantAppInstallerActivityLP(newInstantAppInstaller); 2868 } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) { 2869 Slog.d(TAG, "Unset ephemeral installer; none available"); 2870 } 2871 mInstantAppInstallerComponent = newInstantAppInstallerComponent; 2872 } 2873 2874 private static File preparePackageParserCache(boolean isUpgrade) { 2875 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2876 return null; 2877 } 2878 2879 // Disable package parsing on eng builds to allow for faster incremental development. 2880 if ("eng".equals(Build.TYPE)) { 2881 return null; 2882 } 2883 2884 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2885 Slog.i(TAG, "Disabling package parser cache due to system property."); 2886 return null; 2887 } 2888 2889 // The base directory for the package parser cache lives under /data/system/. 2890 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2891 "package_cache"); 2892 if (cacheBaseDir == null) { 2893 return null; 2894 } 2895 2896 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2897 // This also serves to "GC" unused entries when the package cache version changes (which 2898 // can only happen during upgrades). 2899 if (isUpgrade) { 2900 FileUtils.deleteContents(cacheBaseDir); 2901 } 2902 2903 2904 // Return the versioned package cache directory. This is something like 2905 // "/data/system/package_cache/1" 2906 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2907 2908 // The following is a workaround to aid development on non-numbered userdebug 2909 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2910 // the system partition is newer. 2911 // 2912 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2913 // that starts with "eng." to signify that this is an engineering build and not 2914 // destined for release. 2915 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2916 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2917 2918 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2919 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2920 // in general and should not be used for production changes. In this specific case, 2921 // we know that they will work. 2922 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2923 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2924 FileUtils.deleteContents(cacheBaseDir); 2925 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2926 } 2927 } 2928 2929 return cacheDir; 2930 } 2931 2932 @Override 2933 public boolean isFirstBoot() { 2934 return mFirstBoot; 2935 } 2936 2937 @Override 2938 public boolean isOnlyCoreApps() { 2939 return mOnlyCore; 2940 } 2941 2942 @Override 2943 public boolean isUpgrade() { 2944 return mIsUpgrade; 2945 } 2946 2947 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2948 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2949 2950 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2951 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2952 UserHandle.USER_SYSTEM); 2953 if (matches.size() == 1) { 2954 return matches.get(0).getComponentInfo().packageName; 2955 } else if (matches.size() == 0) { 2956 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2957 return null; 2958 } 2959 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2960 } 2961 2962 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2963 synchronized (mPackages) { 2964 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2965 if (libraryEntry == null) { 2966 throw new IllegalStateException("Missing required shared library:" + name); 2967 } 2968 return libraryEntry.apk; 2969 } 2970 } 2971 2972 private @NonNull String getRequiredInstallerLPr() { 2973 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2974 intent.addCategory(Intent.CATEGORY_DEFAULT); 2975 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2976 2977 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2978 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2979 UserHandle.USER_SYSTEM); 2980 if (matches.size() == 1) { 2981 ResolveInfo resolveInfo = matches.get(0); 2982 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2983 throw new RuntimeException("The installer must be a privileged app"); 2984 } 2985 return matches.get(0).getComponentInfo().packageName; 2986 } else { 2987 throw new RuntimeException("There must be exactly one installer; found " + matches); 2988 } 2989 } 2990 2991 private @NonNull String getRequiredUninstallerLPr() { 2992 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2993 intent.addCategory(Intent.CATEGORY_DEFAULT); 2994 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2995 2996 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2997 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2998 UserHandle.USER_SYSTEM); 2999 if (resolveInfo == null || 3000 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3001 throw new RuntimeException("There must be exactly one uninstaller; found " 3002 + resolveInfo); 3003 } 3004 return resolveInfo.getComponentInfo().packageName; 3005 } 3006 3007 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3008 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3009 3010 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3011 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3012 UserHandle.USER_SYSTEM); 3013 ResolveInfo best = null; 3014 final int N = matches.size(); 3015 for (int i = 0; i < N; i++) { 3016 final ResolveInfo cur = matches.get(i); 3017 final String packageName = cur.getComponentInfo().packageName; 3018 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3019 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3020 continue; 3021 } 3022 3023 if (best == null || cur.priority > best.priority) { 3024 best = cur; 3025 } 3026 } 3027 3028 if (best != null) { 3029 return best.getComponentInfo().getComponentName(); 3030 } else { 3031 throw new RuntimeException("There must be at least one intent filter verifier"); 3032 } 3033 } 3034 3035 private @Nullable ComponentName getEphemeralResolverLPr() { 3036 final String[] packageArray = 3037 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3038 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3039 if (DEBUG_EPHEMERAL) { 3040 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3041 } 3042 return null; 3043 } 3044 3045 final int callingUid = Binder.getCallingUid(); 3046 final int resolveFlags = 3047 MATCH_DIRECT_BOOT_AWARE 3048 | MATCH_DIRECT_BOOT_UNAWARE 3049 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3050 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE); 3051 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3052 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3053 3054 final int N = resolvers.size(); 3055 if (N == 0) { 3056 if (DEBUG_EPHEMERAL) { 3057 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3058 } 3059 return null; 3060 } 3061 3062 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3063 for (int i = 0; i < N; i++) { 3064 final ResolveInfo info = resolvers.get(i); 3065 3066 if (info.serviceInfo == null) { 3067 continue; 3068 } 3069 3070 final String packageName = info.serviceInfo.packageName; 3071 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3072 if (DEBUG_EPHEMERAL) { 3073 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3074 + " pkg: " + packageName + ", info:" + info); 3075 } 3076 continue; 3077 } 3078 3079 if (DEBUG_EPHEMERAL) { 3080 Slog.v(TAG, "Ephemeral resolver found;" 3081 + " pkg: " + packageName + ", info:" + info); 3082 } 3083 return new ComponentName(packageName, info.serviceInfo.name); 3084 } 3085 if (DEBUG_EPHEMERAL) { 3086 Slog.v(TAG, "Ephemeral resolver NOT found"); 3087 } 3088 return null; 3089 } 3090 3091 private @Nullable ActivityInfo getEphemeralInstallerLPr() { 3092 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3093 intent.addCategory(Intent.CATEGORY_DEFAULT); 3094 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3095 3096 final int resolveFlags = 3097 MATCH_DIRECT_BOOT_AWARE 3098 | MATCH_DIRECT_BOOT_UNAWARE 3099 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3100 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3101 resolveFlags, UserHandle.USER_SYSTEM); 3102 Iterator<ResolveInfo> iter = matches.iterator(); 3103 while (iter.hasNext()) { 3104 final ResolveInfo rInfo = iter.next(); 3105 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3106 if (ps != null) { 3107 final PermissionsState permissionsState = ps.getPermissionsState(); 3108 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3109 continue; 3110 } 3111 } 3112 iter.remove(); 3113 } 3114 if (matches.size() == 0) { 3115 return null; 3116 } else if (matches.size() == 1) { 3117 return (ActivityInfo) matches.get(0).getComponentInfo(); 3118 } else { 3119 throw new RuntimeException( 3120 "There must be at most one ephemeral installer; found " + matches); 3121 } 3122 } 3123 3124 private @Nullable ComponentName getEphemeralResolverSettingsLPr( 3125 @NonNull ComponentName resolver) { 3126 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3127 .addCategory(Intent.CATEGORY_DEFAULT) 3128 .setPackage(resolver.getPackageName()); 3129 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3130 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3131 UserHandle.USER_SYSTEM); 3132 if (matches.isEmpty()) { 3133 return null; 3134 } 3135 return matches.get(0).getComponentInfo().getComponentName(); 3136 } 3137 3138 private void primeDomainVerificationsLPw(int userId) { 3139 if (DEBUG_DOMAIN_VERIFICATION) { 3140 Slog.d(TAG, "Priming domain verifications in user " + userId); 3141 } 3142 3143 SystemConfig systemConfig = SystemConfig.getInstance(); 3144 ArraySet<String> packages = systemConfig.getLinkedApps(); 3145 3146 for (String packageName : packages) { 3147 PackageParser.Package pkg = mPackages.get(packageName); 3148 if (pkg != null) { 3149 if (!pkg.isSystemApp()) { 3150 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3151 continue; 3152 } 3153 3154 ArraySet<String> domains = null; 3155 for (PackageParser.Activity a : pkg.activities) { 3156 for (ActivityIntentInfo filter : a.intents) { 3157 if (hasValidDomains(filter)) { 3158 if (domains == null) { 3159 domains = new ArraySet<String>(); 3160 } 3161 domains.addAll(filter.getHostsList()); 3162 } 3163 } 3164 } 3165 3166 if (domains != null && domains.size() > 0) { 3167 if (DEBUG_DOMAIN_VERIFICATION) { 3168 Slog.v(TAG, " + " + packageName); 3169 } 3170 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3171 // state w.r.t. the formal app-linkage "no verification attempted" state; 3172 // and then 'always' in the per-user state actually used for intent resolution. 3173 final IntentFilterVerificationInfo ivi; 3174 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3175 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3176 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3177 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3178 } else { 3179 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3180 + "' does not handle web links"); 3181 } 3182 } else { 3183 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3184 } 3185 } 3186 3187 scheduleWritePackageRestrictionsLocked(userId); 3188 scheduleWriteSettingsLocked(); 3189 } 3190 3191 private void applyFactoryDefaultBrowserLPw(int userId) { 3192 // The default browser app's package name is stored in a string resource, 3193 // with a product-specific overlay used for vendor customization. 3194 String browserPkg = mContext.getResources().getString( 3195 com.android.internal.R.string.default_browser); 3196 if (!TextUtils.isEmpty(browserPkg)) { 3197 // non-empty string => required to be a known package 3198 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3199 if (ps == null) { 3200 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3201 browserPkg = null; 3202 } else { 3203 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3204 } 3205 } 3206 3207 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3208 // default. If there's more than one, just leave everything alone. 3209 if (browserPkg == null) { 3210 calculateDefaultBrowserLPw(userId); 3211 } 3212 } 3213 3214 private void calculateDefaultBrowserLPw(int userId) { 3215 List<String> allBrowsers = resolveAllBrowserApps(userId); 3216 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3217 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3218 } 3219 3220 private List<String> resolveAllBrowserApps(int userId) { 3221 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3222 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3223 PackageManager.MATCH_ALL, userId); 3224 3225 final int count = list.size(); 3226 List<String> result = new ArrayList<String>(count); 3227 for (int i=0; i<count; i++) { 3228 ResolveInfo info = list.get(i); 3229 if (info.activityInfo == null 3230 || !info.handleAllWebDataURI 3231 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3232 || result.contains(info.activityInfo.packageName)) { 3233 continue; 3234 } 3235 result.add(info.activityInfo.packageName); 3236 } 3237 3238 return result; 3239 } 3240 3241 private boolean packageIsBrowser(String packageName, int userId) { 3242 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3243 PackageManager.MATCH_ALL, userId); 3244 final int N = list.size(); 3245 for (int i = 0; i < N; i++) { 3246 ResolveInfo info = list.get(i); 3247 if (packageName.equals(info.activityInfo.packageName)) { 3248 return true; 3249 } 3250 } 3251 return false; 3252 } 3253 3254 private void checkDefaultBrowser() { 3255 final int myUserId = UserHandle.myUserId(); 3256 final String packageName = getDefaultBrowserPackageName(myUserId); 3257 if (packageName != null) { 3258 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3259 if (info == null) { 3260 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3261 synchronized (mPackages) { 3262 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3263 } 3264 } 3265 } 3266 } 3267 3268 @Override 3269 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3270 throws RemoteException { 3271 try { 3272 return super.onTransact(code, data, reply, flags); 3273 } catch (RuntimeException e) { 3274 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3275 Slog.wtf(TAG, "Package Manager Crash", e); 3276 } 3277 throw e; 3278 } 3279 } 3280 3281 static int[] appendInts(int[] cur, int[] add) { 3282 if (add == null) return cur; 3283 if (cur == null) return add; 3284 final int N = add.length; 3285 for (int i=0; i<N; i++) { 3286 cur = appendInt(cur, add[i]); 3287 } 3288 return cur; 3289 } 3290 3291 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3292 if (!sUserManager.exists(userId)) return null; 3293 if (ps == null) { 3294 return null; 3295 } 3296 final PackageParser.Package p = ps.pkg; 3297 if (p == null) { 3298 return null; 3299 } 3300 // Filter out ephemeral app metadata: 3301 // * The system/shell/root can see metadata for any app 3302 // * An installed app can see metadata for 1) other installed apps 3303 // and 2) ephemeral apps that have explicitly interacted with it 3304 // * Ephemeral apps can only see their own data and exposed installed apps 3305 // * Holding a signature permission allows seeing instant apps 3306 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3307 if (callingAppId != Process.SYSTEM_UID 3308 && callingAppId != Process.SHELL_UID 3309 && callingAppId != Process.ROOT_UID 3310 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3311 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3312 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3313 if (instantAppPackageName != null) { 3314 // ephemeral apps can only get information on themselves or 3315 // installed apps that are exposed. 3316 if (!instantAppPackageName.equals(p.packageName) 3317 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3318 return null; 3319 } 3320 } else { 3321 if (ps.getInstantApp(userId)) { 3322 // only get access to the ephemeral app if we've been granted access 3323 if (!mInstantAppRegistry.isInstantAccessGranted( 3324 userId, callingAppId, ps.appId)) { 3325 return null; 3326 } 3327 } 3328 } 3329 } 3330 3331 final PermissionsState permissionsState = ps.getPermissionsState(); 3332 3333 // Compute GIDs only if requested 3334 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3335 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3336 // Compute granted permissions only if package has requested permissions 3337 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3338 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3339 final PackageUserState state = ps.readUserState(userId); 3340 3341 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3342 && ps.isSystem()) { 3343 flags |= MATCH_ANY_USER; 3344 } 3345 3346 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3347 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3348 3349 if (packageInfo == null) { 3350 return null; 3351 } 3352 3353 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3354 3355 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3356 resolveExternalPackageNameLPr(p); 3357 3358 return packageInfo; 3359 } 3360 3361 @Override 3362 public void checkPackageStartable(String packageName, int userId) { 3363 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3364 3365 synchronized (mPackages) { 3366 final PackageSetting ps = mSettings.mPackages.get(packageName); 3367 if (ps == null) { 3368 throw new SecurityException("Package " + packageName + " was not found!"); 3369 } 3370 3371 if (!ps.getInstalled(userId)) { 3372 throw new SecurityException( 3373 "Package " + packageName + " was not installed for user " + userId + "!"); 3374 } 3375 3376 if (mSafeMode && !ps.isSystem()) { 3377 throw new SecurityException("Package " + packageName + " not a system app!"); 3378 } 3379 3380 if (mFrozenPackages.contains(packageName)) { 3381 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3382 } 3383 3384 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3385 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3386 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3387 } 3388 } 3389 } 3390 3391 @Override 3392 public boolean isPackageAvailable(String packageName, int userId) { 3393 if (!sUserManager.exists(userId)) return false; 3394 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3395 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3396 synchronized (mPackages) { 3397 PackageParser.Package p = mPackages.get(packageName); 3398 if (p != null) { 3399 final PackageSetting ps = (PackageSetting) p.mExtras; 3400 if (ps != null) { 3401 final PackageUserState state = ps.readUserState(userId); 3402 if (state != null) { 3403 return PackageParser.isAvailable(state); 3404 } 3405 } 3406 } 3407 } 3408 return false; 3409 } 3410 3411 @Override 3412 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3413 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3414 flags, userId); 3415 } 3416 3417 @Override 3418 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3419 int flags, int userId) { 3420 return getPackageInfoInternal(versionedPackage.getPackageName(), 3421 // TODO: We will change version code to long, so in the new API it is long 3422 (int) versionedPackage.getVersionCode(), flags, userId); 3423 } 3424 3425 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3426 int flags, int userId) { 3427 if (!sUserManager.exists(userId)) return null; 3428 flags = updateFlagsForPackage(flags, userId, packageName); 3429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3430 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3431 3432 // reader 3433 synchronized (mPackages) { 3434 // Normalize package name to handle renamed packages and static libs 3435 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3436 3437 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3438 if (matchFactoryOnly) { 3439 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3440 if (ps != null) { 3441 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3442 return null; 3443 } 3444 return generatePackageInfo(ps, flags, userId); 3445 } 3446 } 3447 3448 PackageParser.Package p = mPackages.get(packageName); 3449 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3450 return null; 3451 } 3452 if (DEBUG_PACKAGE_INFO) 3453 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3454 if (p != null) { 3455 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3456 Binder.getCallingUid(), userId)) { 3457 return null; 3458 } 3459 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3460 } 3461 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3462 final PackageSetting ps = mSettings.mPackages.get(packageName); 3463 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3464 return null; 3465 } 3466 return generatePackageInfo(ps, flags, userId); 3467 } 3468 } 3469 return null; 3470 } 3471 3472 3473 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3474 // System/shell/root get to see all static libs 3475 final int appId = UserHandle.getAppId(uid); 3476 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3477 || appId == Process.ROOT_UID) { 3478 return false; 3479 } 3480 3481 // No package means no static lib as it is always on internal storage 3482 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3483 return false; 3484 } 3485 3486 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3487 ps.pkg.staticSharedLibVersion); 3488 if (libEntry == null) { 3489 return false; 3490 } 3491 3492 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3493 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3494 if (uidPackageNames == null) { 3495 return true; 3496 } 3497 3498 for (String uidPackageName : uidPackageNames) { 3499 if (ps.name.equals(uidPackageName)) { 3500 return false; 3501 } 3502 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3503 if (uidPs != null) { 3504 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3505 libEntry.info.getName()); 3506 if (index < 0) { 3507 continue; 3508 } 3509 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3510 return false; 3511 } 3512 } 3513 } 3514 return true; 3515 } 3516 3517 @Override 3518 public String[] currentToCanonicalPackageNames(String[] names) { 3519 String[] out = new String[names.length]; 3520 // reader 3521 synchronized (mPackages) { 3522 for (int i=names.length-1; i>=0; i--) { 3523 PackageSetting ps = mSettings.mPackages.get(names[i]); 3524 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3525 } 3526 } 3527 return out; 3528 } 3529 3530 @Override 3531 public String[] canonicalToCurrentPackageNames(String[] names) { 3532 String[] out = new String[names.length]; 3533 // reader 3534 synchronized (mPackages) { 3535 for (int i=names.length-1; i>=0; i--) { 3536 String cur = mSettings.getRenamedPackageLPr(names[i]); 3537 out[i] = cur != null ? cur : names[i]; 3538 } 3539 } 3540 return out; 3541 } 3542 3543 @Override 3544 public int getPackageUid(String packageName, int flags, int userId) { 3545 if (!sUserManager.exists(userId)) return -1; 3546 flags = updateFlagsForPackage(flags, userId, packageName); 3547 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3548 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3549 3550 // reader 3551 synchronized (mPackages) { 3552 final PackageParser.Package p = mPackages.get(packageName); 3553 if (p != null && p.isMatch(flags)) { 3554 return UserHandle.getUid(userId, p.applicationInfo.uid); 3555 } 3556 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3557 final PackageSetting ps = mSettings.mPackages.get(packageName); 3558 if (ps != null && ps.isMatch(flags)) { 3559 return UserHandle.getUid(userId, ps.appId); 3560 } 3561 } 3562 } 3563 3564 return -1; 3565 } 3566 3567 @Override 3568 public int[] getPackageGids(String packageName, int flags, int userId) { 3569 if (!sUserManager.exists(userId)) return null; 3570 flags = updateFlagsForPackage(flags, userId, packageName); 3571 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3572 false /* requireFullPermission */, false /* checkShell */, 3573 "getPackageGids"); 3574 3575 // reader 3576 synchronized (mPackages) { 3577 final PackageParser.Package p = mPackages.get(packageName); 3578 if (p != null && p.isMatch(flags)) { 3579 PackageSetting ps = (PackageSetting) p.mExtras; 3580 // TODO: Shouldn't this be checking for package installed state for userId and 3581 // return null? 3582 return ps.getPermissionsState().computeGids(userId); 3583 } 3584 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3585 final PackageSetting ps = mSettings.mPackages.get(packageName); 3586 if (ps != null && ps.isMatch(flags)) { 3587 return ps.getPermissionsState().computeGids(userId); 3588 } 3589 } 3590 } 3591 3592 return null; 3593 } 3594 3595 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3596 if (bp.perm != null) { 3597 return PackageParser.generatePermissionInfo(bp.perm, flags); 3598 } 3599 PermissionInfo pi = new PermissionInfo(); 3600 pi.name = bp.name; 3601 pi.packageName = bp.sourcePackage; 3602 pi.nonLocalizedLabel = bp.name; 3603 pi.protectionLevel = bp.protectionLevel; 3604 return pi; 3605 } 3606 3607 @Override 3608 public PermissionInfo getPermissionInfo(String name, int flags) { 3609 // reader 3610 synchronized (mPackages) { 3611 final BasePermission p = mSettings.mPermissions.get(name); 3612 if (p != null) { 3613 return generatePermissionInfo(p, flags); 3614 } 3615 return null; 3616 } 3617 } 3618 3619 @Override 3620 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3621 int flags) { 3622 // reader 3623 synchronized (mPackages) { 3624 if (group != null && !mPermissionGroups.containsKey(group)) { 3625 // This is thrown as NameNotFoundException 3626 return null; 3627 } 3628 3629 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3630 for (BasePermission p : mSettings.mPermissions.values()) { 3631 if (group == null) { 3632 if (p.perm == null || p.perm.info.group == null) { 3633 out.add(generatePermissionInfo(p, flags)); 3634 } 3635 } else { 3636 if (p.perm != null && group.equals(p.perm.info.group)) { 3637 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3638 } 3639 } 3640 } 3641 return new ParceledListSlice<>(out); 3642 } 3643 } 3644 3645 @Override 3646 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3647 // reader 3648 synchronized (mPackages) { 3649 return PackageParser.generatePermissionGroupInfo( 3650 mPermissionGroups.get(name), flags); 3651 } 3652 } 3653 3654 @Override 3655 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3656 // reader 3657 synchronized (mPackages) { 3658 final int N = mPermissionGroups.size(); 3659 ArrayList<PermissionGroupInfo> out 3660 = new ArrayList<PermissionGroupInfo>(N); 3661 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3662 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3663 } 3664 return new ParceledListSlice<>(out); 3665 } 3666 } 3667 3668 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3669 int uid, int userId) { 3670 if (!sUserManager.exists(userId)) return null; 3671 PackageSetting ps = mSettings.mPackages.get(packageName); 3672 if (ps != null) { 3673 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3674 return null; 3675 } 3676 if (ps.pkg == null) { 3677 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3678 if (pInfo != null) { 3679 return pInfo.applicationInfo; 3680 } 3681 return null; 3682 } 3683 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3684 ps.readUserState(userId), userId); 3685 if (ai != null) { 3686 rebaseEnabledOverlays(ai, userId); 3687 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3688 } 3689 return ai; 3690 } 3691 return null; 3692 } 3693 3694 @Override 3695 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3696 if (!sUserManager.exists(userId)) return null; 3697 flags = updateFlagsForApplication(flags, userId, packageName); 3698 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3699 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3700 3701 // writer 3702 synchronized (mPackages) { 3703 // Normalize package name to handle renamed packages and static libs 3704 packageName = resolveInternalPackageNameLPr(packageName, 3705 PackageManager.VERSION_CODE_HIGHEST); 3706 3707 PackageParser.Package p = mPackages.get(packageName); 3708 if (DEBUG_PACKAGE_INFO) Log.v( 3709 TAG, "getApplicationInfo " + packageName 3710 + ": " + p); 3711 if (p != null) { 3712 PackageSetting ps = mSettings.mPackages.get(packageName); 3713 if (ps == null) return null; 3714 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3715 return null; 3716 } 3717 // Note: isEnabledLP() does not apply here - always return info 3718 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3719 p, flags, ps.readUserState(userId), userId); 3720 if (ai != null) { 3721 rebaseEnabledOverlays(ai, userId); 3722 ai.packageName = resolveExternalPackageNameLPr(p); 3723 } 3724 return ai; 3725 } 3726 if ("android".equals(packageName)||"system".equals(packageName)) { 3727 return mAndroidApplication; 3728 } 3729 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3730 // Already generates the external package name 3731 return generateApplicationInfoFromSettingsLPw(packageName, 3732 Binder.getCallingUid(), flags, userId); 3733 } 3734 } 3735 return null; 3736 } 3737 3738 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3739 List<String> paths = new ArrayList<>(); 3740 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3741 mEnabledOverlayPaths.get(userId); 3742 if (userSpecificOverlays != null) { 3743 if (!"android".equals(ai.packageName)) { 3744 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3745 if (frameworkOverlays != null) { 3746 paths.addAll(frameworkOverlays); 3747 } 3748 } 3749 3750 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3751 if (appOverlays != null) { 3752 paths.addAll(appOverlays); 3753 } 3754 } 3755 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3756 } 3757 3758 private String normalizePackageNameLPr(String packageName) { 3759 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3760 return normalizedPackageName != null ? normalizedPackageName : packageName; 3761 } 3762 3763 @Override 3764 public void deletePreloadsFileCache() { 3765 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3766 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3767 } 3768 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3769 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3770 FileUtils.deleteContents(dir); 3771 } 3772 3773 @Override 3774 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3775 final IPackageDataObserver observer) { 3776 mContext.enforceCallingOrSelfPermission( 3777 android.Manifest.permission.CLEAR_APP_CACHE, null); 3778 mHandler.post(() -> { 3779 boolean success = false; 3780 try { 3781 freeStorage(volumeUuid, freeStorageSize, 0); 3782 success = true; 3783 } catch (IOException e) { 3784 Slog.w(TAG, e); 3785 } 3786 if (observer != null) { 3787 try { 3788 observer.onRemoveCompleted(null, success); 3789 } catch (RemoteException e) { 3790 Slog.w(TAG, e); 3791 } 3792 } 3793 }); 3794 } 3795 3796 @Override 3797 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3798 final IntentSender pi) { 3799 mContext.enforceCallingOrSelfPermission( 3800 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3801 mHandler.post(() -> { 3802 boolean success = false; 3803 try { 3804 freeStorage(volumeUuid, freeStorageSize, 0); 3805 success = true; 3806 } catch (IOException e) { 3807 Slog.w(TAG, e); 3808 } 3809 if (pi != null) { 3810 try { 3811 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3812 } catch (SendIntentException e) { 3813 Slog.w(TAG, e); 3814 } 3815 } 3816 }); 3817 } 3818 3819 /** 3820 * Blocking call to clear various types of cached data across the system 3821 * until the requested bytes are available. 3822 */ 3823 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3824 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3825 final File file = storage.findPathForUuid(volumeUuid); 3826 if (file.getUsableSpace() >= bytes) return; 3827 3828 if (ENABLE_FREE_CACHE_V2) { 3829 final boolean aggressive = (storageFlags 3830 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3831 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3832 volumeUuid); 3833 3834 // 1. Pre-flight to determine if we have any chance to succeed 3835 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3836 if (internalVolume && (aggressive || SystemProperties 3837 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3838 deletePreloadsFileCache(); 3839 if (file.getUsableSpace() >= bytes) return; 3840 } 3841 3842 // 3. Consider parsed APK data (aggressive only) 3843 if (internalVolume && aggressive) { 3844 FileUtils.deleteContents(mCacheDir); 3845 if (file.getUsableSpace() >= bytes) return; 3846 } 3847 3848 // 4. Consider cached app data (above quotas) 3849 try { 3850 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3851 } catch (InstallerException ignored) { 3852 } 3853 if (file.getUsableSpace() >= bytes) return; 3854 3855 // 5. Consider shared libraries with refcount=0 and age>2h 3856 // 6. Consider dexopt output (aggressive only) 3857 // 7. Consider ephemeral apps not used in last week 3858 3859 // 8. Consider cached app data (below quotas) 3860 try { 3861 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3862 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3863 } catch (InstallerException ignored) { 3864 } 3865 if (file.getUsableSpace() >= bytes) return; 3866 3867 // 9. Consider DropBox entries 3868 // 10. Consider ephemeral cookies 3869 3870 } else { 3871 try { 3872 mInstaller.freeCache(volumeUuid, bytes, 0); 3873 } catch (InstallerException ignored) { 3874 } 3875 if (file.getUsableSpace() >= bytes) return; 3876 } 3877 3878 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3879 } 3880 3881 /** 3882 * Update given flags based on encryption status of current user. 3883 */ 3884 private int updateFlags(int flags, int userId) { 3885 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3886 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3887 // Caller expressed an explicit opinion about what encryption 3888 // aware/unaware components they want to see, so fall through and 3889 // give them what they want 3890 } else { 3891 // Caller expressed no opinion, so match based on user state 3892 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3893 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3894 } else { 3895 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3896 } 3897 } 3898 return flags; 3899 } 3900 3901 private UserManagerInternal getUserManagerInternal() { 3902 if (mUserManagerInternal == null) { 3903 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3904 } 3905 return mUserManagerInternal; 3906 } 3907 3908 private DeviceIdleController.LocalService getDeviceIdleController() { 3909 if (mDeviceIdleController == null) { 3910 mDeviceIdleController = 3911 LocalServices.getService(DeviceIdleController.LocalService.class); 3912 } 3913 return mDeviceIdleController; 3914 } 3915 3916 /** 3917 * Update given flags when being used to request {@link PackageInfo}. 3918 */ 3919 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3920 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3921 boolean triaged = true; 3922 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3923 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3924 // Caller is asking for component details, so they'd better be 3925 // asking for specific encryption matching behavior, or be triaged 3926 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3927 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3928 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3929 triaged = false; 3930 } 3931 } 3932 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3933 | PackageManager.MATCH_SYSTEM_ONLY 3934 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3935 triaged = false; 3936 } 3937 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3938 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3939 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3940 + Debug.getCallers(5)); 3941 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3942 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3943 // If the caller wants all packages and has a restricted profile associated with it, 3944 // then match all users. This is to make sure that launchers that need to access work 3945 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3946 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3947 flags |= PackageManager.MATCH_ANY_USER; 3948 } 3949 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3950 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3951 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3952 } 3953 return updateFlags(flags, userId); 3954 } 3955 3956 /** 3957 * Update given flags when being used to request {@link ApplicationInfo}. 3958 */ 3959 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3960 return updateFlagsForPackage(flags, userId, cookie); 3961 } 3962 3963 /** 3964 * Update given flags when being used to request {@link ComponentInfo}. 3965 */ 3966 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3967 if (cookie instanceof Intent) { 3968 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3969 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3970 } 3971 } 3972 3973 boolean triaged = true; 3974 // Caller is asking for component details, so they'd better be 3975 // asking for specific encryption matching behavior, or be triaged 3976 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3977 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3978 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3979 triaged = false; 3980 } 3981 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3982 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3983 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3984 } 3985 3986 return updateFlags(flags, userId); 3987 } 3988 3989 /** 3990 * Update given intent when being used to request {@link ResolveInfo}. 3991 */ 3992 private Intent updateIntentForResolve(Intent intent) { 3993 if (intent.getSelector() != null) { 3994 intent = intent.getSelector(); 3995 } 3996 if (DEBUG_PREFERRED) { 3997 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3998 } 3999 return intent; 4000 } 4001 4002 /** 4003 * Update given flags when being used to request {@link ResolveInfo}. 4004 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4005 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4006 * flag set. However, this flag is only honoured in three circumstances: 4007 * <ul> 4008 * <li>when called from a system process</li> 4009 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4010 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4011 * action and a {@code android.intent.category.BROWSABLE} category</li> 4012 * </ul> 4013 */ 4014 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4015 boolean includeInstantApps) { 4016 // Safe mode means we shouldn't match any third-party components 4017 if (mSafeMode) { 4018 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4019 } 4020 if (getInstantAppPackageName(callingUid) != null) { 4021 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4022 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4023 flags |= PackageManager.MATCH_INSTANT; 4024 } else { 4025 // Otherwise, prevent leaking ephemeral components 4026 final boolean isSpecialProcess = 4027 callingUid == Process.SYSTEM_UID 4028 || callingUid == Process.SHELL_UID 4029 || callingUid == 0; 4030 final boolean allowMatchInstant = 4031 (includeInstantApps 4032 && Intent.ACTION_VIEW.equals(intent.getAction()) 4033 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4034 && hasWebURI(intent)) 4035 || isSpecialProcess 4036 || mContext.checkCallingOrSelfPermission( 4037 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4038 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4039 if (!allowMatchInstant) { 4040 flags &= ~PackageManager.MATCH_INSTANT; 4041 } 4042 } 4043 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4044 } 4045 4046 @Override 4047 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4048 if (!sUserManager.exists(userId)) return null; 4049 flags = updateFlagsForComponent(flags, userId, component); 4050 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4051 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4052 synchronized (mPackages) { 4053 PackageParser.Activity a = mActivities.mActivities.get(component); 4054 4055 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4056 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4057 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4058 if (ps == null) return null; 4059 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4060 userId); 4061 } 4062 if (mResolveComponentName.equals(component)) { 4063 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4064 new PackageUserState(), userId); 4065 } 4066 } 4067 return null; 4068 } 4069 4070 @Override 4071 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4072 String resolvedType) { 4073 synchronized (mPackages) { 4074 if (component.equals(mResolveComponentName)) { 4075 // The resolver supports EVERYTHING! 4076 return true; 4077 } 4078 PackageParser.Activity a = mActivities.mActivities.get(component); 4079 if (a == null) { 4080 return false; 4081 } 4082 for (int i=0; i<a.intents.size(); i++) { 4083 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4084 intent.getData(), intent.getCategories(), TAG) >= 0) { 4085 return true; 4086 } 4087 } 4088 return false; 4089 } 4090 } 4091 4092 @Override 4093 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4094 if (!sUserManager.exists(userId)) return null; 4095 flags = updateFlagsForComponent(flags, userId, component); 4096 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4097 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4098 synchronized (mPackages) { 4099 PackageParser.Activity a = mReceivers.mActivities.get(component); 4100 if (DEBUG_PACKAGE_INFO) Log.v( 4101 TAG, "getReceiverInfo " + component + ": " + a); 4102 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4103 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4104 if (ps == null) return null; 4105 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4106 ps.readUserState(userId), userId); 4107 if (ri != null) { 4108 rebaseEnabledOverlays(ri.applicationInfo, userId); 4109 } 4110 return ri; 4111 } 4112 } 4113 return null; 4114 } 4115 4116 @Override 4117 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4118 if (!sUserManager.exists(userId)) return null; 4119 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4120 4121 flags = updateFlagsForPackage(flags, userId, null); 4122 4123 final boolean canSeeStaticLibraries = 4124 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4125 == PERMISSION_GRANTED 4126 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4127 == PERMISSION_GRANTED 4128 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4129 == PERMISSION_GRANTED 4130 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4131 == PERMISSION_GRANTED; 4132 4133 synchronized (mPackages) { 4134 List<SharedLibraryInfo> result = null; 4135 4136 final int libCount = mSharedLibraries.size(); 4137 for (int i = 0; i < libCount; i++) { 4138 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4139 if (versionedLib == null) { 4140 continue; 4141 } 4142 4143 final int versionCount = versionedLib.size(); 4144 for (int j = 0; j < versionCount; j++) { 4145 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4146 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4147 break; 4148 } 4149 final long identity = Binder.clearCallingIdentity(); 4150 try { 4151 // TODO: We will change version code to long, so in the new API it is long 4152 PackageInfo packageInfo = getPackageInfoVersioned( 4153 libInfo.getDeclaringPackage(), flags, userId); 4154 if (packageInfo == null) { 4155 continue; 4156 } 4157 } finally { 4158 Binder.restoreCallingIdentity(identity); 4159 } 4160 4161 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4162 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4163 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4164 4165 if (result == null) { 4166 result = new ArrayList<>(); 4167 } 4168 result.add(resLibInfo); 4169 } 4170 } 4171 4172 return result != null ? new ParceledListSlice<>(result) : null; 4173 } 4174 } 4175 4176 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4177 SharedLibraryInfo libInfo, int flags, int userId) { 4178 List<VersionedPackage> versionedPackages = null; 4179 final int packageCount = mSettings.mPackages.size(); 4180 for (int i = 0; i < packageCount; i++) { 4181 PackageSetting ps = mSettings.mPackages.valueAt(i); 4182 4183 if (ps == null) { 4184 continue; 4185 } 4186 4187 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4188 continue; 4189 } 4190 4191 final String libName = libInfo.getName(); 4192 if (libInfo.isStatic()) { 4193 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4194 if (libIdx < 0) { 4195 continue; 4196 } 4197 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4198 continue; 4199 } 4200 if (versionedPackages == null) { 4201 versionedPackages = new ArrayList<>(); 4202 } 4203 // If the dependent is a static shared lib, use the public package name 4204 String dependentPackageName = ps.name; 4205 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4206 dependentPackageName = ps.pkg.manifestPackageName; 4207 } 4208 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4209 } else if (ps.pkg != null) { 4210 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4211 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4212 if (versionedPackages == null) { 4213 versionedPackages = new ArrayList<>(); 4214 } 4215 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4216 } 4217 } 4218 } 4219 4220 return versionedPackages; 4221 } 4222 4223 @Override 4224 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4225 if (!sUserManager.exists(userId)) return null; 4226 flags = updateFlagsForComponent(flags, userId, component); 4227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4228 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4229 synchronized (mPackages) { 4230 PackageParser.Service s = mServices.mServices.get(component); 4231 if (DEBUG_PACKAGE_INFO) Log.v( 4232 TAG, "getServiceInfo " + component + ": " + s); 4233 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4234 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4235 if (ps == null) return null; 4236 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4237 ps.readUserState(userId), userId); 4238 if (si != null) { 4239 rebaseEnabledOverlays(si.applicationInfo, userId); 4240 } 4241 return si; 4242 } 4243 } 4244 return null; 4245 } 4246 4247 @Override 4248 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4249 if (!sUserManager.exists(userId)) return null; 4250 flags = updateFlagsForComponent(flags, userId, component); 4251 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4252 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4253 synchronized (mPackages) { 4254 PackageParser.Provider p = mProviders.mProviders.get(component); 4255 if (DEBUG_PACKAGE_INFO) Log.v( 4256 TAG, "getProviderInfo " + component + ": " + p); 4257 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4258 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4259 if (ps == null) return null; 4260 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4261 ps.readUserState(userId), userId); 4262 if (pi != null) { 4263 rebaseEnabledOverlays(pi.applicationInfo, userId); 4264 } 4265 return pi; 4266 } 4267 } 4268 return null; 4269 } 4270 4271 @Override 4272 public String[] getSystemSharedLibraryNames() { 4273 synchronized (mPackages) { 4274 Set<String> libs = null; 4275 final int libCount = mSharedLibraries.size(); 4276 for (int i = 0; i < libCount; i++) { 4277 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4278 if (versionedLib == null) { 4279 continue; 4280 } 4281 final int versionCount = versionedLib.size(); 4282 for (int j = 0; j < versionCount; j++) { 4283 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4284 if (!libEntry.info.isStatic()) { 4285 if (libs == null) { 4286 libs = new ArraySet<>(); 4287 } 4288 libs.add(libEntry.info.getName()); 4289 break; 4290 } 4291 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4292 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4293 UserHandle.getUserId(Binder.getCallingUid()))) { 4294 if (libs == null) { 4295 libs = new ArraySet<>(); 4296 } 4297 libs.add(libEntry.info.getName()); 4298 break; 4299 } 4300 } 4301 } 4302 4303 if (libs != null) { 4304 String[] libsArray = new String[libs.size()]; 4305 libs.toArray(libsArray); 4306 return libsArray; 4307 } 4308 4309 return null; 4310 } 4311 } 4312 4313 @Override 4314 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4315 synchronized (mPackages) { 4316 return mServicesSystemSharedLibraryPackageName; 4317 } 4318 } 4319 4320 @Override 4321 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4322 synchronized (mPackages) { 4323 return mSharedSystemSharedLibraryPackageName; 4324 } 4325 } 4326 4327 private void updateSequenceNumberLP(String packageName, int[] userList) { 4328 for (int i = userList.length - 1; i >= 0; --i) { 4329 final int userId = userList[i]; 4330 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4331 if (changedPackages == null) { 4332 changedPackages = new SparseArray<>(); 4333 mChangedPackages.put(userId, changedPackages); 4334 } 4335 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4336 if (sequenceNumbers == null) { 4337 sequenceNumbers = new HashMap<>(); 4338 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4339 } 4340 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4341 if (sequenceNumber != null) { 4342 changedPackages.remove(sequenceNumber); 4343 } 4344 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4345 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4346 } 4347 mChangedPackagesSequenceNumber++; 4348 } 4349 4350 @Override 4351 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4352 synchronized (mPackages) { 4353 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4354 return null; 4355 } 4356 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4357 if (changedPackages == null) { 4358 return null; 4359 } 4360 final List<String> packageNames = 4361 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4362 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4363 final String packageName = changedPackages.get(i); 4364 if (packageName != null) { 4365 packageNames.add(packageName); 4366 } 4367 } 4368 return packageNames.isEmpty() 4369 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4370 } 4371 } 4372 4373 @Override 4374 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4375 ArrayList<FeatureInfo> res; 4376 synchronized (mAvailableFeatures) { 4377 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4378 res.addAll(mAvailableFeatures.values()); 4379 } 4380 final FeatureInfo fi = new FeatureInfo(); 4381 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4382 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4383 res.add(fi); 4384 4385 return new ParceledListSlice<>(res); 4386 } 4387 4388 @Override 4389 public boolean hasSystemFeature(String name, int version) { 4390 synchronized (mAvailableFeatures) { 4391 final FeatureInfo feat = mAvailableFeatures.get(name); 4392 if (feat == null) { 4393 return false; 4394 } else { 4395 return feat.version >= version; 4396 } 4397 } 4398 } 4399 4400 @Override 4401 public int checkPermission(String permName, String pkgName, int userId) { 4402 if (!sUserManager.exists(userId)) { 4403 return PackageManager.PERMISSION_DENIED; 4404 } 4405 4406 synchronized (mPackages) { 4407 final PackageParser.Package p = mPackages.get(pkgName); 4408 if (p != null && p.mExtras != null) { 4409 final PackageSetting ps = (PackageSetting) p.mExtras; 4410 final PermissionsState permissionsState = ps.getPermissionsState(); 4411 if (permissionsState.hasPermission(permName, userId)) { 4412 return PackageManager.PERMISSION_GRANTED; 4413 } 4414 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4415 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4416 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4417 return PackageManager.PERMISSION_GRANTED; 4418 } 4419 } 4420 } 4421 4422 return PackageManager.PERMISSION_DENIED; 4423 } 4424 4425 @Override 4426 public int checkUidPermission(String permName, int uid) { 4427 final int userId = UserHandle.getUserId(uid); 4428 4429 if (!sUserManager.exists(userId)) { 4430 return PackageManager.PERMISSION_DENIED; 4431 } 4432 4433 synchronized (mPackages) { 4434 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4435 if (obj != null) { 4436 final SettingBase ps = (SettingBase) obj; 4437 final PermissionsState permissionsState = ps.getPermissionsState(); 4438 if (permissionsState.hasPermission(permName, userId)) { 4439 return PackageManager.PERMISSION_GRANTED; 4440 } 4441 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4442 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4443 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4444 return PackageManager.PERMISSION_GRANTED; 4445 } 4446 } else { 4447 ArraySet<String> perms = mSystemPermissions.get(uid); 4448 if (perms != null) { 4449 if (perms.contains(permName)) { 4450 return PackageManager.PERMISSION_GRANTED; 4451 } 4452 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4453 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4454 return PackageManager.PERMISSION_GRANTED; 4455 } 4456 } 4457 } 4458 } 4459 4460 return PackageManager.PERMISSION_DENIED; 4461 } 4462 4463 @Override 4464 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4465 if (UserHandle.getCallingUserId() != userId) { 4466 mContext.enforceCallingPermission( 4467 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4468 "isPermissionRevokedByPolicy for user " + userId); 4469 } 4470 4471 if (checkPermission(permission, packageName, userId) 4472 == PackageManager.PERMISSION_GRANTED) { 4473 return false; 4474 } 4475 4476 final long identity = Binder.clearCallingIdentity(); 4477 try { 4478 final int flags = getPermissionFlags(permission, packageName, userId); 4479 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4480 } finally { 4481 Binder.restoreCallingIdentity(identity); 4482 } 4483 } 4484 4485 @Override 4486 public String getPermissionControllerPackageName() { 4487 synchronized (mPackages) { 4488 return mRequiredInstallerPackage; 4489 } 4490 } 4491 4492 /** 4493 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4494 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4495 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4496 * @param message the message to log on security exception 4497 */ 4498 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4499 boolean checkShell, String message) { 4500 if (userId < 0) { 4501 throw new IllegalArgumentException("Invalid userId " + userId); 4502 } 4503 if (checkShell) { 4504 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4505 } 4506 if (userId == UserHandle.getUserId(callingUid)) return; 4507 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4508 if (requireFullPermission) { 4509 mContext.enforceCallingOrSelfPermission( 4510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4511 } else { 4512 try { 4513 mContext.enforceCallingOrSelfPermission( 4514 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4515 } catch (SecurityException se) { 4516 mContext.enforceCallingOrSelfPermission( 4517 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4518 } 4519 } 4520 } 4521 } 4522 4523 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4524 if (callingUid == Process.SHELL_UID) { 4525 if (userHandle >= 0 4526 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4527 throw new SecurityException("Shell does not have permission to access user " 4528 + userHandle); 4529 } else if (userHandle < 0) { 4530 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4531 + Debug.getCallers(3)); 4532 } 4533 } 4534 } 4535 4536 private BasePermission findPermissionTreeLP(String permName) { 4537 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4538 if (permName.startsWith(bp.name) && 4539 permName.length() > bp.name.length() && 4540 permName.charAt(bp.name.length()) == '.') { 4541 return bp; 4542 } 4543 } 4544 return null; 4545 } 4546 4547 private BasePermission checkPermissionTreeLP(String permName) { 4548 if (permName != null) { 4549 BasePermission bp = findPermissionTreeLP(permName); 4550 if (bp != null) { 4551 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4552 return bp; 4553 } 4554 throw new SecurityException("Calling uid " 4555 + Binder.getCallingUid() 4556 + " is not allowed to add to permission tree " 4557 + bp.name + " owned by uid " + bp.uid); 4558 } 4559 } 4560 throw new SecurityException("No permission tree found for " + permName); 4561 } 4562 4563 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4564 if (s1 == null) { 4565 return s2 == null; 4566 } 4567 if (s2 == null) { 4568 return false; 4569 } 4570 if (s1.getClass() != s2.getClass()) { 4571 return false; 4572 } 4573 return s1.equals(s2); 4574 } 4575 4576 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4577 if (pi1.icon != pi2.icon) return false; 4578 if (pi1.logo != pi2.logo) return false; 4579 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4580 if (!compareStrings(pi1.name, pi2.name)) return false; 4581 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4582 // We'll take care of setting this one. 4583 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4584 // These are not currently stored in settings. 4585 //if (!compareStrings(pi1.group, pi2.group)) return false; 4586 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4587 //if (pi1.labelRes != pi2.labelRes) return false; 4588 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4589 return true; 4590 } 4591 4592 int permissionInfoFootprint(PermissionInfo info) { 4593 int size = info.name.length(); 4594 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4595 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4596 return size; 4597 } 4598 4599 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4600 int size = 0; 4601 for (BasePermission perm : mSettings.mPermissions.values()) { 4602 if (perm.uid == tree.uid) { 4603 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4604 } 4605 } 4606 return size; 4607 } 4608 4609 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4610 // We calculate the max size of permissions defined by this uid and throw 4611 // if that plus the size of 'info' would exceed our stated maximum. 4612 if (tree.uid != Process.SYSTEM_UID) { 4613 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4614 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4615 throw new SecurityException("Permission tree size cap exceeded"); 4616 } 4617 } 4618 } 4619 4620 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4621 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4622 throw new SecurityException("Label must be specified in permission"); 4623 } 4624 BasePermission tree = checkPermissionTreeLP(info.name); 4625 BasePermission bp = mSettings.mPermissions.get(info.name); 4626 boolean added = bp == null; 4627 boolean changed = true; 4628 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4629 if (added) { 4630 enforcePermissionCapLocked(info, tree); 4631 bp = new BasePermission(info.name, tree.sourcePackage, 4632 BasePermission.TYPE_DYNAMIC); 4633 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4634 throw new SecurityException( 4635 "Not allowed to modify non-dynamic permission " 4636 + info.name); 4637 } else { 4638 if (bp.protectionLevel == fixedLevel 4639 && bp.perm.owner.equals(tree.perm.owner) 4640 && bp.uid == tree.uid 4641 && comparePermissionInfos(bp.perm.info, info)) { 4642 changed = false; 4643 } 4644 } 4645 bp.protectionLevel = fixedLevel; 4646 info = new PermissionInfo(info); 4647 info.protectionLevel = fixedLevel; 4648 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4649 bp.perm.info.packageName = tree.perm.info.packageName; 4650 bp.uid = tree.uid; 4651 if (added) { 4652 mSettings.mPermissions.put(info.name, bp); 4653 } 4654 if (changed) { 4655 if (!async) { 4656 mSettings.writeLPr(); 4657 } else { 4658 scheduleWriteSettingsLocked(); 4659 } 4660 } 4661 return added; 4662 } 4663 4664 @Override 4665 public boolean addPermission(PermissionInfo info) { 4666 synchronized (mPackages) { 4667 return addPermissionLocked(info, false); 4668 } 4669 } 4670 4671 @Override 4672 public boolean addPermissionAsync(PermissionInfo info) { 4673 synchronized (mPackages) { 4674 return addPermissionLocked(info, true); 4675 } 4676 } 4677 4678 @Override 4679 public void removePermission(String name) { 4680 synchronized (mPackages) { 4681 checkPermissionTreeLP(name); 4682 BasePermission bp = mSettings.mPermissions.get(name); 4683 if (bp != null) { 4684 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4685 throw new SecurityException( 4686 "Not allowed to modify non-dynamic permission " 4687 + name); 4688 } 4689 mSettings.mPermissions.remove(name); 4690 mSettings.writeLPr(); 4691 } 4692 } 4693 } 4694 4695 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4696 BasePermission bp) { 4697 int index = pkg.requestedPermissions.indexOf(bp.name); 4698 if (index == -1) { 4699 throw new SecurityException("Package " + pkg.packageName 4700 + " has not requested permission " + bp.name); 4701 } 4702 if (!bp.isRuntime() && !bp.isDevelopment()) { 4703 throw new SecurityException("Permission " + bp.name 4704 + " is not a changeable permission type"); 4705 } 4706 } 4707 4708 @Override 4709 public void grantRuntimePermission(String packageName, String name, final int userId) { 4710 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4711 } 4712 4713 private void grantRuntimePermission(String packageName, String name, final int userId, 4714 boolean overridePolicy) { 4715 if (!sUserManager.exists(userId)) { 4716 Log.e(TAG, "No such user:" + userId); 4717 return; 4718 } 4719 4720 mContext.enforceCallingOrSelfPermission( 4721 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4722 "grantRuntimePermission"); 4723 4724 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4725 true /* requireFullPermission */, true /* checkShell */, 4726 "grantRuntimePermission"); 4727 4728 final int uid; 4729 final SettingBase sb; 4730 4731 synchronized (mPackages) { 4732 final PackageParser.Package pkg = mPackages.get(packageName); 4733 if (pkg == null) { 4734 throw new IllegalArgumentException("Unknown package: " + packageName); 4735 } 4736 4737 final BasePermission bp = mSettings.mPermissions.get(name); 4738 if (bp == null) { 4739 throw new IllegalArgumentException("Unknown permission: " + name); 4740 } 4741 4742 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4743 4744 // If a permission review is required for legacy apps we represent 4745 // their permissions as always granted runtime ones since we need 4746 // to keep the review required permission flag per user while an 4747 // install permission's state is shared across all users. 4748 if (mPermissionReviewRequired 4749 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4750 && bp.isRuntime()) { 4751 return; 4752 } 4753 4754 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4755 sb = (SettingBase) pkg.mExtras; 4756 if (sb == null) { 4757 throw new IllegalArgumentException("Unknown package: " + packageName); 4758 } 4759 4760 final PermissionsState permissionsState = sb.getPermissionsState(); 4761 4762 final int flags = permissionsState.getPermissionFlags(name, userId); 4763 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4764 throw new SecurityException("Cannot grant system fixed permission " 4765 + name + " for package " + packageName); 4766 } 4767 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4768 throw new SecurityException("Cannot grant policy fixed permission " 4769 + name + " for package " + packageName); 4770 } 4771 4772 if (bp.isDevelopment()) { 4773 // Development permissions must be handled specially, since they are not 4774 // normal runtime permissions. For now they apply to all users. 4775 if (permissionsState.grantInstallPermission(bp) != 4776 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4777 scheduleWriteSettingsLocked(); 4778 } 4779 return; 4780 } 4781 4782 final PackageSetting ps = mSettings.mPackages.get(packageName); 4783 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4784 throw new SecurityException("Cannot grant non-ephemeral permission" 4785 + name + " for package " + packageName); 4786 } 4787 4788 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4789 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4790 return; 4791 } 4792 4793 final int result = permissionsState.grantRuntimePermission(bp, userId); 4794 switch (result) { 4795 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4796 return; 4797 } 4798 4799 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4800 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4801 mHandler.post(new Runnable() { 4802 @Override 4803 public void run() { 4804 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4805 } 4806 }); 4807 } 4808 break; 4809 } 4810 4811 if (bp.isRuntime()) { 4812 logPermissionGranted(mContext, name, packageName); 4813 } 4814 4815 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4816 4817 // Not critical if that is lost - app has to request again. 4818 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4819 } 4820 4821 // Only need to do this if user is initialized. Otherwise it's a new user 4822 // and there are no processes running as the user yet and there's no need 4823 // to make an expensive call to remount processes for the changed permissions. 4824 if (READ_EXTERNAL_STORAGE.equals(name) 4825 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4826 final long token = Binder.clearCallingIdentity(); 4827 try { 4828 if (sUserManager.isInitialized(userId)) { 4829 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4830 StorageManagerInternal.class); 4831 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4832 } 4833 } finally { 4834 Binder.restoreCallingIdentity(token); 4835 } 4836 } 4837 } 4838 4839 @Override 4840 public void revokeRuntimePermission(String packageName, String name, int userId) { 4841 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4842 } 4843 4844 private void revokeRuntimePermission(String packageName, String name, int userId, 4845 boolean overridePolicy) { 4846 if (!sUserManager.exists(userId)) { 4847 Log.e(TAG, "No such user:" + userId); 4848 return; 4849 } 4850 4851 mContext.enforceCallingOrSelfPermission( 4852 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4853 "revokeRuntimePermission"); 4854 4855 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4856 true /* requireFullPermission */, true /* checkShell */, 4857 "revokeRuntimePermission"); 4858 4859 final int appId; 4860 4861 synchronized (mPackages) { 4862 final PackageParser.Package pkg = mPackages.get(packageName); 4863 if (pkg == null) { 4864 throw new IllegalArgumentException("Unknown package: " + packageName); 4865 } 4866 4867 final BasePermission bp = mSettings.mPermissions.get(name); 4868 if (bp == null) { 4869 throw new IllegalArgumentException("Unknown permission: " + name); 4870 } 4871 4872 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4873 4874 // If a permission review is required for legacy apps we represent 4875 // their permissions as always granted runtime ones since we need 4876 // to keep the review required permission flag per user while an 4877 // install permission's state is shared across all users. 4878 if (mPermissionReviewRequired 4879 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4880 && bp.isRuntime()) { 4881 return; 4882 } 4883 4884 SettingBase sb = (SettingBase) pkg.mExtras; 4885 if (sb == null) { 4886 throw new IllegalArgumentException("Unknown package: " + packageName); 4887 } 4888 4889 final PermissionsState permissionsState = sb.getPermissionsState(); 4890 4891 final int flags = permissionsState.getPermissionFlags(name, userId); 4892 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4893 throw new SecurityException("Cannot revoke system fixed permission " 4894 + name + " for package " + packageName); 4895 } 4896 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4897 throw new SecurityException("Cannot revoke policy fixed permission " 4898 + name + " for package " + packageName); 4899 } 4900 4901 if (bp.isDevelopment()) { 4902 // Development permissions must be handled specially, since they are not 4903 // normal runtime permissions. For now they apply to all users. 4904 if (permissionsState.revokeInstallPermission(bp) != 4905 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4906 scheduleWriteSettingsLocked(); 4907 } 4908 return; 4909 } 4910 4911 if (permissionsState.revokeRuntimePermission(bp, userId) == 4912 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4913 return; 4914 } 4915 4916 if (bp.isRuntime()) { 4917 logPermissionRevoked(mContext, name, packageName); 4918 } 4919 4920 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4921 4922 // Critical, after this call app should never have the permission. 4923 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4924 4925 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4926 } 4927 4928 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4929 } 4930 4931 /** 4932 * Get the first event id for the permission. 4933 * 4934 * <p>There are four events for each permission: <ul> 4935 * <li>Request permission: first id + 0</li> 4936 * <li>Grant permission: first id + 1</li> 4937 * <li>Request for permission denied: first id + 2</li> 4938 * <li>Revoke permission: first id + 3</li> 4939 * </ul></p> 4940 * 4941 * @param name name of the permission 4942 * 4943 * @return The first event id for the permission 4944 */ 4945 private static int getBaseEventId(@NonNull String name) { 4946 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4947 4948 if (eventIdIndex == -1) { 4949 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4950 || "user".equals(Build.TYPE)) { 4951 Log.i(TAG, "Unknown permission " + name); 4952 4953 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4954 } else { 4955 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4956 // 4957 // Also update 4958 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4959 // - metrics_constants.proto 4960 throw new IllegalStateException("Unknown permission " + name); 4961 } 4962 } 4963 4964 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4965 } 4966 4967 /** 4968 * Log that a permission was revoked. 4969 * 4970 * @param context Context of the caller 4971 * @param name name of the permission 4972 * @param packageName package permission if for 4973 */ 4974 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4975 @NonNull String packageName) { 4976 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4977 } 4978 4979 /** 4980 * Log that a permission request was granted. 4981 * 4982 * @param context Context of the caller 4983 * @param name name of the permission 4984 * @param packageName package permission if for 4985 */ 4986 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4987 @NonNull String packageName) { 4988 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4989 } 4990 4991 @Override 4992 public void resetRuntimePermissions() { 4993 mContext.enforceCallingOrSelfPermission( 4994 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4995 "revokeRuntimePermission"); 4996 4997 int callingUid = Binder.getCallingUid(); 4998 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4999 mContext.enforceCallingOrSelfPermission( 5000 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5001 "resetRuntimePermissions"); 5002 } 5003 5004 synchronized (mPackages) { 5005 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5006 for (int userId : UserManagerService.getInstance().getUserIds()) { 5007 final int packageCount = mPackages.size(); 5008 for (int i = 0; i < packageCount; i++) { 5009 PackageParser.Package pkg = mPackages.valueAt(i); 5010 if (!(pkg.mExtras instanceof PackageSetting)) { 5011 continue; 5012 } 5013 PackageSetting ps = (PackageSetting) pkg.mExtras; 5014 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5015 } 5016 } 5017 } 5018 } 5019 5020 @Override 5021 public int getPermissionFlags(String name, String packageName, int userId) { 5022 if (!sUserManager.exists(userId)) { 5023 return 0; 5024 } 5025 5026 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5027 5028 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5029 true /* requireFullPermission */, false /* checkShell */, 5030 "getPermissionFlags"); 5031 5032 synchronized (mPackages) { 5033 final PackageParser.Package pkg = mPackages.get(packageName); 5034 if (pkg == null) { 5035 return 0; 5036 } 5037 5038 final BasePermission bp = mSettings.mPermissions.get(name); 5039 if (bp == null) { 5040 return 0; 5041 } 5042 5043 SettingBase sb = (SettingBase) pkg.mExtras; 5044 if (sb == null) { 5045 return 0; 5046 } 5047 5048 PermissionsState permissionsState = sb.getPermissionsState(); 5049 return permissionsState.getPermissionFlags(name, userId); 5050 } 5051 } 5052 5053 @Override 5054 public void updatePermissionFlags(String name, String packageName, int flagMask, 5055 int flagValues, int userId) { 5056 if (!sUserManager.exists(userId)) { 5057 return; 5058 } 5059 5060 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5061 5062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5063 true /* requireFullPermission */, true /* checkShell */, 5064 "updatePermissionFlags"); 5065 5066 // Only the system can change these flags and nothing else. 5067 if (getCallingUid() != Process.SYSTEM_UID) { 5068 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5069 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5070 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5071 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5072 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5073 } 5074 5075 synchronized (mPackages) { 5076 final PackageParser.Package pkg = mPackages.get(packageName); 5077 if (pkg == null) { 5078 throw new IllegalArgumentException("Unknown package: " + packageName); 5079 } 5080 5081 final BasePermission bp = mSettings.mPermissions.get(name); 5082 if (bp == null) { 5083 throw new IllegalArgumentException("Unknown permission: " + name); 5084 } 5085 5086 SettingBase sb = (SettingBase) pkg.mExtras; 5087 if (sb == null) { 5088 throw new IllegalArgumentException("Unknown package: " + packageName); 5089 } 5090 5091 PermissionsState permissionsState = sb.getPermissionsState(); 5092 5093 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5094 5095 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5096 // Install and runtime permissions are stored in different places, 5097 // so figure out what permission changed and persist the change. 5098 if (permissionsState.getInstallPermissionState(name) != null) { 5099 scheduleWriteSettingsLocked(); 5100 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5101 || hadState) { 5102 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5103 } 5104 } 5105 } 5106 } 5107 5108 /** 5109 * Update the permission flags for all packages and runtime permissions of a user in order 5110 * to allow device or profile owner to remove POLICY_FIXED. 5111 */ 5112 @Override 5113 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5114 if (!sUserManager.exists(userId)) { 5115 return; 5116 } 5117 5118 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5119 5120 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5121 true /* requireFullPermission */, true /* checkShell */, 5122 "updatePermissionFlagsForAllApps"); 5123 5124 // Only the system can change system fixed flags. 5125 if (getCallingUid() != Process.SYSTEM_UID) { 5126 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5127 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5128 } 5129 5130 synchronized (mPackages) { 5131 boolean changed = false; 5132 final int packageCount = mPackages.size(); 5133 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5134 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5135 SettingBase sb = (SettingBase) pkg.mExtras; 5136 if (sb == null) { 5137 continue; 5138 } 5139 PermissionsState permissionsState = sb.getPermissionsState(); 5140 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5141 userId, flagMask, flagValues); 5142 } 5143 if (changed) { 5144 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5145 } 5146 } 5147 } 5148 5149 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5150 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5151 != PackageManager.PERMISSION_GRANTED 5152 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5153 != PackageManager.PERMISSION_GRANTED) { 5154 throw new SecurityException(message + " requires " 5155 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5156 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5157 } 5158 } 5159 5160 @Override 5161 public boolean shouldShowRequestPermissionRationale(String permissionName, 5162 String packageName, int userId) { 5163 if (UserHandle.getCallingUserId() != userId) { 5164 mContext.enforceCallingPermission( 5165 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5166 "canShowRequestPermissionRationale for user " + userId); 5167 } 5168 5169 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5170 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5171 return false; 5172 } 5173 5174 if (checkPermission(permissionName, packageName, userId) 5175 == PackageManager.PERMISSION_GRANTED) { 5176 return false; 5177 } 5178 5179 final int flags; 5180 5181 final long identity = Binder.clearCallingIdentity(); 5182 try { 5183 flags = getPermissionFlags(permissionName, 5184 packageName, userId); 5185 } finally { 5186 Binder.restoreCallingIdentity(identity); 5187 } 5188 5189 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5190 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5191 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5192 5193 if ((flags & fixedFlags) != 0) { 5194 return false; 5195 } 5196 5197 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5198 } 5199 5200 @Override 5201 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5202 mContext.enforceCallingOrSelfPermission( 5203 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5204 "addOnPermissionsChangeListener"); 5205 5206 synchronized (mPackages) { 5207 mOnPermissionChangeListeners.addListenerLocked(listener); 5208 } 5209 } 5210 5211 @Override 5212 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5213 synchronized (mPackages) { 5214 mOnPermissionChangeListeners.removeListenerLocked(listener); 5215 } 5216 } 5217 5218 @Override 5219 public boolean isProtectedBroadcast(String actionName) { 5220 synchronized (mPackages) { 5221 if (mProtectedBroadcasts.contains(actionName)) { 5222 return true; 5223 } else if (actionName != null) { 5224 // TODO: remove these terrible hacks 5225 if (actionName.startsWith("android.net.netmon.lingerExpired") 5226 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5227 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5228 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5229 return true; 5230 } 5231 } 5232 } 5233 return false; 5234 } 5235 5236 @Override 5237 public int checkSignatures(String pkg1, String pkg2) { 5238 synchronized (mPackages) { 5239 final PackageParser.Package p1 = mPackages.get(pkg1); 5240 final PackageParser.Package p2 = mPackages.get(pkg2); 5241 if (p1 == null || p1.mExtras == null 5242 || p2 == null || p2.mExtras == null) { 5243 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5244 } 5245 return compareSignatures(p1.mSignatures, p2.mSignatures); 5246 } 5247 } 5248 5249 @Override 5250 public int checkUidSignatures(int uid1, int uid2) { 5251 // Map to base uids. 5252 uid1 = UserHandle.getAppId(uid1); 5253 uid2 = UserHandle.getAppId(uid2); 5254 // reader 5255 synchronized (mPackages) { 5256 Signature[] s1; 5257 Signature[] s2; 5258 Object obj = mSettings.getUserIdLPr(uid1); 5259 if (obj != null) { 5260 if (obj instanceof SharedUserSetting) { 5261 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5262 } else if (obj instanceof PackageSetting) { 5263 s1 = ((PackageSetting)obj).signatures.mSignatures; 5264 } else { 5265 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5266 } 5267 } else { 5268 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5269 } 5270 obj = mSettings.getUserIdLPr(uid2); 5271 if (obj != null) { 5272 if (obj instanceof SharedUserSetting) { 5273 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5274 } else if (obj instanceof PackageSetting) { 5275 s2 = ((PackageSetting)obj).signatures.mSignatures; 5276 } else { 5277 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5278 } 5279 } else { 5280 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5281 } 5282 return compareSignatures(s1, s2); 5283 } 5284 } 5285 5286 /** 5287 * This method should typically only be used when granting or revoking 5288 * permissions, since the app may immediately restart after this call. 5289 * <p> 5290 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5291 * guard your work against the app being relaunched. 5292 */ 5293 private void killUid(int appId, int userId, String reason) { 5294 final long identity = Binder.clearCallingIdentity(); 5295 try { 5296 IActivityManager am = ActivityManager.getService(); 5297 if (am != null) { 5298 try { 5299 am.killUid(appId, userId, reason); 5300 } catch (RemoteException e) { 5301 /* ignore - same process */ 5302 } 5303 } 5304 } finally { 5305 Binder.restoreCallingIdentity(identity); 5306 } 5307 } 5308 5309 /** 5310 * Compares two sets of signatures. Returns: 5311 * <br /> 5312 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5313 * <br /> 5314 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5315 * <br /> 5316 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5317 * <br /> 5318 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5319 * <br /> 5320 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5321 */ 5322 static int compareSignatures(Signature[] s1, Signature[] s2) { 5323 if (s1 == null) { 5324 return s2 == null 5325 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5326 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5327 } 5328 5329 if (s2 == null) { 5330 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5331 } 5332 5333 if (s1.length != s2.length) { 5334 return PackageManager.SIGNATURE_NO_MATCH; 5335 } 5336 5337 // Since both signature sets are of size 1, we can compare without HashSets. 5338 if (s1.length == 1) { 5339 return s1[0].equals(s2[0]) ? 5340 PackageManager.SIGNATURE_MATCH : 5341 PackageManager.SIGNATURE_NO_MATCH; 5342 } 5343 5344 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5345 for (Signature sig : s1) { 5346 set1.add(sig); 5347 } 5348 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5349 for (Signature sig : s2) { 5350 set2.add(sig); 5351 } 5352 // Make sure s2 contains all signatures in s1. 5353 if (set1.equals(set2)) { 5354 return PackageManager.SIGNATURE_MATCH; 5355 } 5356 return PackageManager.SIGNATURE_NO_MATCH; 5357 } 5358 5359 /** 5360 * If the database version for this type of package (internal storage or 5361 * external storage) is less than the version where package signatures 5362 * were updated, return true. 5363 */ 5364 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5365 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5366 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5367 } 5368 5369 /** 5370 * Used for backward compatibility to make sure any packages with 5371 * certificate chains get upgraded to the new style. {@code existingSigs} 5372 * will be in the old format (since they were stored on disk from before the 5373 * system upgrade) and {@code scannedSigs} will be in the newer format. 5374 */ 5375 private int compareSignaturesCompat(PackageSignatures existingSigs, 5376 PackageParser.Package scannedPkg) { 5377 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5378 return PackageManager.SIGNATURE_NO_MATCH; 5379 } 5380 5381 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5382 for (Signature sig : existingSigs.mSignatures) { 5383 existingSet.add(sig); 5384 } 5385 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5386 for (Signature sig : scannedPkg.mSignatures) { 5387 try { 5388 Signature[] chainSignatures = sig.getChainSignatures(); 5389 for (Signature chainSig : chainSignatures) { 5390 scannedCompatSet.add(chainSig); 5391 } 5392 } catch (CertificateEncodingException e) { 5393 scannedCompatSet.add(sig); 5394 } 5395 } 5396 /* 5397 * Make sure the expanded scanned set contains all signatures in the 5398 * existing one. 5399 */ 5400 if (scannedCompatSet.equals(existingSet)) { 5401 // Migrate the old signatures to the new scheme. 5402 existingSigs.assignSignatures(scannedPkg.mSignatures); 5403 // The new KeySets will be re-added later in the scanning process. 5404 synchronized (mPackages) { 5405 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5406 } 5407 return PackageManager.SIGNATURE_MATCH; 5408 } 5409 return PackageManager.SIGNATURE_NO_MATCH; 5410 } 5411 5412 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5413 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5414 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5415 } 5416 5417 private int compareSignaturesRecover(PackageSignatures existingSigs, 5418 PackageParser.Package scannedPkg) { 5419 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5420 return PackageManager.SIGNATURE_NO_MATCH; 5421 } 5422 5423 String msg = null; 5424 try { 5425 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5426 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5427 + scannedPkg.packageName); 5428 return PackageManager.SIGNATURE_MATCH; 5429 } 5430 } catch (CertificateException e) { 5431 msg = e.getMessage(); 5432 } 5433 5434 logCriticalInfo(Log.INFO, 5435 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5436 return PackageManager.SIGNATURE_NO_MATCH; 5437 } 5438 5439 @Override 5440 public List<String> getAllPackages() { 5441 synchronized (mPackages) { 5442 return new ArrayList<String>(mPackages.keySet()); 5443 } 5444 } 5445 5446 @Override 5447 public String[] getPackagesForUid(int uid) { 5448 final int userId = UserHandle.getUserId(uid); 5449 uid = UserHandle.getAppId(uid); 5450 // reader 5451 synchronized (mPackages) { 5452 Object obj = mSettings.getUserIdLPr(uid); 5453 if (obj instanceof SharedUserSetting) { 5454 final SharedUserSetting sus = (SharedUserSetting) obj; 5455 final int N = sus.packages.size(); 5456 String[] res = new String[N]; 5457 final Iterator<PackageSetting> it = sus.packages.iterator(); 5458 int i = 0; 5459 while (it.hasNext()) { 5460 PackageSetting ps = it.next(); 5461 if (ps.getInstalled(userId)) { 5462 res[i++] = ps.name; 5463 } else { 5464 res = ArrayUtils.removeElement(String.class, res, res[i]); 5465 } 5466 } 5467 return res; 5468 } else if (obj instanceof PackageSetting) { 5469 final PackageSetting ps = (PackageSetting) obj; 5470 if (ps.getInstalled(userId)) { 5471 return new String[]{ps.name}; 5472 } 5473 } 5474 } 5475 return null; 5476 } 5477 5478 @Override 5479 public String getNameForUid(int uid) { 5480 // reader 5481 synchronized (mPackages) { 5482 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5483 if (obj instanceof SharedUserSetting) { 5484 final SharedUserSetting sus = (SharedUserSetting) obj; 5485 return sus.name + ":" + sus.userId; 5486 } else if (obj instanceof PackageSetting) { 5487 final PackageSetting ps = (PackageSetting) obj; 5488 return ps.name; 5489 } 5490 } 5491 return null; 5492 } 5493 5494 @Override 5495 public int getUidForSharedUser(String sharedUserName) { 5496 if(sharedUserName == null) { 5497 return -1; 5498 } 5499 // reader 5500 synchronized (mPackages) { 5501 SharedUserSetting suid; 5502 try { 5503 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5504 if (suid != null) { 5505 return suid.userId; 5506 } 5507 } catch (PackageManagerException ignore) { 5508 // can't happen, but, still need to catch it 5509 } 5510 return -1; 5511 } 5512 } 5513 5514 @Override 5515 public int getFlagsForUid(int uid) { 5516 synchronized (mPackages) { 5517 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5518 if (obj instanceof SharedUserSetting) { 5519 final SharedUserSetting sus = (SharedUserSetting) obj; 5520 return sus.pkgFlags; 5521 } else if (obj instanceof PackageSetting) { 5522 final PackageSetting ps = (PackageSetting) obj; 5523 return ps.pkgFlags; 5524 } 5525 } 5526 return 0; 5527 } 5528 5529 @Override 5530 public int getPrivateFlagsForUid(int uid) { 5531 synchronized (mPackages) { 5532 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5533 if (obj instanceof SharedUserSetting) { 5534 final SharedUserSetting sus = (SharedUserSetting) obj; 5535 return sus.pkgPrivateFlags; 5536 } else if (obj instanceof PackageSetting) { 5537 final PackageSetting ps = (PackageSetting) obj; 5538 return ps.pkgPrivateFlags; 5539 } 5540 } 5541 return 0; 5542 } 5543 5544 @Override 5545 public boolean isUidPrivileged(int uid) { 5546 uid = UserHandle.getAppId(uid); 5547 // reader 5548 synchronized (mPackages) { 5549 Object obj = mSettings.getUserIdLPr(uid); 5550 if (obj instanceof SharedUserSetting) { 5551 final SharedUserSetting sus = (SharedUserSetting) obj; 5552 final Iterator<PackageSetting> it = sus.packages.iterator(); 5553 while (it.hasNext()) { 5554 if (it.next().isPrivileged()) { 5555 return true; 5556 } 5557 } 5558 } else if (obj instanceof PackageSetting) { 5559 final PackageSetting ps = (PackageSetting) obj; 5560 return ps.isPrivileged(); 5561 } 5562 } 5563 return false; 5564 } 5565 5566 @Override 5567 public String[] getAppOpPermissionPackages(String permissionName) { 5568 synchronized (mPackages) { 5569 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5570 if (pkgs == null) { 5571 return null; 5572 } 5573 return pkgs.toArray(new String[pkgs.size()]); 5574 } 5575 } 5576 5577 @Override 5578 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5579 int flags, int userId) { 5580 return resolveIntentInternal( 5581 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5582 } 5583 5584 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5585 int flags, int userId, boolean includeInstantApps) { 5586 try { 5587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5588 5589 if (!sUserManager.exists(userId)) return null; 5590 final int callingUid = Binder.getCallingUid(); 5591 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5592 enforceCrossUserPermission(callingUid, userId, 5593 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5594 5595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5596 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5597 flags, userId, includeInstantApps); 5598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5599 5600 final ResolveInfo bestChoice = 5601 chooseBestActivity(intent, resolvedType, flags, query, userId); 5602 return bestChoice; 5603 } finally { 5604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5605 } 5606 } 5607 5608 @Override 5609 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5610 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5611 throw new SecurityException( 5612 "findPersistentPreferredActivity can only be run by the system"); 5613 } 5614 if (!sUserManager.exists(userId)) { 5615 return null; 5616 } 5617 final int callingUid = Binder.getCallingUid(); 5618 intent = updateIntentForResolve(intent); 5619 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5620 final int flags = updateFlagsForResolve( 5621 0, userId, intent, callingUid, false /*includeInstantApps*/); 5622 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5623 userId); 5624 synchronized (mPackages) { 5625 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5626 userId); 5627 } 5628 } 5629 5630 @Override 5631 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5632 IntentFilter filter, int match, ComponentName activity) { 5633 final int userId = UserHandle.getCallingUserId(); 5634 if (DEBUG_PREFERRED) { 5635 Log.v(TAG, "setLastChosenActivity intent=" + intent 5636 + " resolvedType=" + resolvedType 5637 + " flags=" + flags 5638 + " filter=" + filter 5639 + " match=" + match 5640 + " activity=" + activity); 5641 filter.dump(new PrintStreamPrinter(System.out), " "); 5642 } 5643 intent.setComponent(null); 5644 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5645 userId); 5646 // Find any earlier preferred or last chosen entries and nuke them 5647 findPreferredActivity(intent, resolvedType, 5648 flags, query, 0, false, true, false, userId); 5649 // Add the new activity as the last chosen for this filter 5650 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5651 "Setting last chosen"); 5652 } 5653 5654 @Override 5655 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5656 final int userId = UserHandle.getCallingUserId(); 5657 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5658 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5659 userId); 5660 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5661 false, false, false, userId); 5662 } 5663 5664 /** 5665 * Returns whether or not instant apps have been disabled remotely. 5666 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5667 * held. Otherwise we run the risk of deadlock. 5668 */ 5669 private boolean isEphemeralDisabled() { 5670 // ephemeral apps have been disabled across the board 5671 if (DISABLE_EPHEMERAL_APPS) { 5672 return true; 5673 } 5674 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5675 if (!mSystemReady) { 5676 return true; 5677 } 5678 // we can't get a content resolver until the system is ready; these checks must happen last 5679 final ContentResolver resolver = mContext.getContentResolver(); 5680 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5681 return true; 5682 } 5683 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5684 } 5685 5686 private boolean isEphemeralAllowed( 5687 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5688 boolean skipPackageCheck) { 5689 final int callingUser = UserHandle.getCallingUserId(); 5690 if (callingUser != UserHandle.USER_SYSTEM) { 5691 return false; 5692 } 5693 if (mInstantAppResolverConnection == null) { 5694 return false; 5695 } 5696 if (mInstantAppInstallerComponent == null) { 5697 return false; 5698 } 5699 if (intent.getComponent() != null) { 5700 return false; 5701 } 5702 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5703 return false; 5704 } 5705 if (!skipPackageCheck && intent.getPackage() != null) { 5706 return false; 5707 } 5708 final boolean isWebUri = hasWebURI(intent); 5709 if (!isWebUri || intent.getData().getHost() == null) { 5710 return false; 5711 } 5712 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5713 // Or if there's already an ephemeral app installed that handles the action 5714 synchronized (mPackages) { 5715 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5716 for (int n = 0; n < count; n++) { 5717 ResolveInfo info = resolvedActivities.get(n); 5718 String packageName = info.activityInfo.packageName; 5719 PackageSetting ps = mSettings.mPackages.get(packageName); 5720 if (ps != null) { 5721 // Try to get the status from User settings first 5722 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5723 int status = (int) (packedStatus >> 32); 5724 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5725 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5726 if (DEBUG_EPHEMERAL) { 5727 Slog.v(TAG, "DENY ephemeral apps;" 5728 + " pkg: " + packageName + ", status: " + status); 5729 } 5730 return false; 5731 } 5732 if (ps.getInstantApp(userId)) { 5733 if (DEBUG_EPHEMERAL) { 5734 Slog.v(TAG, "DENY instant app installed;" 5735 + " pkg: " + packageName); 5736 } 5737 return false; 5738 } 5739 } 5740 } 5741 } 5742 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5743 return true; 5744 } 5745 5746 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5747 Intent origIntent, String resolvedType, String callingPackage, 5748 int userId) { 5749 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5750 new InstantAppRequest(responseObj, origIntent, resolvedType, 5751 callingPackage, userId)); 5752 mHandler.sendMessage(msg); 5753 } 5754 5755 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5756 int flags, List<ResolveInfo> query, int userId) { 5757 if (query != null) { 5758 final int N = query.size(); 5759 if (N == 1) { 5760 return query.get(0); 5761 } else if (N > 1) { 5762 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5763 // If there is more than one activity with the same priority, 5764 // then let the user decide between them. 5765 ResolveInfo r0 = query.get(0); 5766 ResolveInfo r1 = query.get(1); 5767 if (DEBUG_INTENT_MATCHING || debug) { 5768 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5769 + r1.activityInfo.name + "=" + r1.priority); 5770 } 5771 // If the first activity has a higher priority, or a different 5772 // default, then it is always desirable to pick it. 5773 if (r0.priority != r1.priority 5774 || r0.preferredOrder != r1.preferredOrder 5775 || r0.isDefault != r1.isDefault) { 5776 return query.get(0); 5777 } 5778 // If we have saved a preference for a preferred activity for 5779 // this Intent, use that. 5780 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5781 flags, query, r0.priority, true, false, debug, userId); 5782 if (ri != null) { 5783 return ri; 5784 } 5785 // If we have an ephemeral app, use it 5786 for (int i = 0; i < N; i++) { 5787 ri = query.get(i); 5788 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5789 return ri; 5790 } 5791 } 5792 ri = new ResolveInfo(mResolveInfo); 5793 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5794 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5795 // If all of the options come from the same package, show the application's 5796 // label and icon instead of the generic resolver's. 5797 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5798 // and then throw away the ResolveInfo itself, meaning that the caller loses 5799 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5800 // a fallback for this case; we only set the target package's resources on 5801 // the ResolveInfo, not the ActivityInfo. 5802 final String intentPackage = intent.getPackage(); 5803 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5804 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5805 ri.resolvePackageName = intentPackage; 5806 if (userNeedsBadging(userId)) { 5807 ri.noResourceId = true; 5808 } else { 5809 ri.icon = appi.icon; 5810 } 5811 ri.iconResourceId = appi.icon; 5812 ri.labelRes = appi.labelRes; 5813 } 5814 ri.activityInfo.applicationInfo = new ApplicationInfo( 5815 ri.activityInfo.applicationInfo); 5816 if (userId != 0) { 5817 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5818 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5819 } 5820 // Make sure that the resolver is displayable in car mode 5821 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5822 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5823 return ri; 5824 } 5825 } 5826 return null; 5827 } 5828 5829 /** 5830 * Return true if the given list is not empty and all of its contents have 5831 * an activityInfo with the given package name. 5832 */ 5833 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5834 if (ArrayUtils.isEmpty(list)) { 5835 return false; 5836 } 5837 for (int i = 0, N = list.size(); i < N; i++) { 5838 final ResolveInfo ri = list.get(i); 5839 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5840 if (ai == null || !packageName.equals(ai.packageName)) { 5841 return false; 5842 } 5843 } 5844 return true; 5845 } 5846 5847 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5848 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5849 final int N = query.size(); 5850 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5851 .get(userId); 5852 // Get the list of persistent preferred activities that handle the intent 5853 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5854 List<PersistentPreferredActivity> pprefs = ppir != null 5855 ? ppir.queryIntent(intent, resolvedType, 5856 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5857 userId) 5858 : null; 5859 if (pprefs != null && pprefs.size() > 0) { 5860 final int M = pprefs.size(); 5861 for (int i=0; i<M; i++) { 5862 final PersistentPreferredActivity ppa = pprefs.get(i); 5863 if (DEBUG_PREFERRED || debug) { 5864 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5865 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5866 + "\n component=" + ppa.mComponent); 5867 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5868 } 5869 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5870 flags | MATCH_DISABLED_COMPONENTS, userId); 5871 if (DEBUG_PREFERRED || debug) { 5872 Slog.v(TAG, "Found persistent preferred activity:"); 5873 if (ai != null) { 5874 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5875 } else { 5876 Slog.v(TAG, " null"); 5877 } 5878 } 5879 if (ai == null) { 5880 // This previously registered persistent preferred activity 5881 // component is no longer known. Ignore it and do NOT remove it. 5882 continue; 5883 } 5884 for (int j=0; j<N; j++) { 5885 final ResolveInfo ri = query.get(j); 5886 if (!ri.activityInfo.applicationInfo.packageName 5887 .equals(ai.applicationInfo.packageName)) { 5888 continue; 5889 } 5890 if (!ri.activityInfo.name.equals(ai.name)) { 5891 continue; 5892 } 5893 // Found a persistent preference that can handle the intent. 5894 if (DEBUG_PREFERRED || debug) { 5895 Slog.v(TAG, "Returning persistent preferred activity: " + 5896 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5897 } 5898 return ri; 5899 } 5900 } 5901 } 5902 return null; 5903 } 5904 5905 // TODO: handle preferred activities missing while user has amnesia 5906 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5907 List<ResolveInfo> query, int priority, boolean always, 5908 boolean removeMatches, boolean debug, int userId) { 5909 if (!sUserManager.exists(userId)) return null; 5910 final int callingUid = Binder.getCallingUid(); 5911 flags = updateFlagsForResolve( 5912 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5913 intent = updateIntentForResolve(intent); 5914 // writer 5915 synchronized (mPackages) { 5916 // Try to find a matching persistent preferred activity. 5917 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5918 debug, userId); 5919 5920 // If a persistent preferred activity matched, use it. 5921 if (pri != null) { 5922 return pri; 5923 } 5924 5925 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5926 // Get the list of preferred activities that handle the intent 5927 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5928 List<PreferredActivity> prefs = pir != null 5929 ? pir.queryIntent(intent, resolvedType, 5930 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5931 userId) 5932 : null; 5933 if (prefs != null && prefs.size() > 0) { 5934 boolean changed = false; 5935 try { 5936 // First figure out how good the original match set is. 5937 // We will only allow preferred activities that came 5938 // from the same match quality. 5939 int match = 0; 5940 5941 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5942 5943 final int N = query.size(); 5944 for (int j=0; j<N; j++) { 5945 final ResolveInfo ri = query.get(j); 5946 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5947 + ": 0x" + Integer.toHexString(match)); 5948 if (ri.match > match) { 5949 match = ri.match; 5950 } 5951 } 5952 5953 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5954 + Integer.toHexString(match)); 5955 5956 match &= IntentFilter.MATCH_CATEGORY_MASK; 5957 final int M = prefs.size(); 5958 for (int i=0; i<M; i++) { 5959 final PreferredActivity pa = prefs.get(i); 5960 if (DEBUG_PREFERRED || debug) { 5961 Slog.v(TAG, "Checking PreferredActivity ds=" 5962 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5963 + "\n component=" + pa.mPref.mComponent); 5964 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5965 } 5966 if (pa.mPref.mMatch != match) { 5967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5968 + Integer.toHexString(pa.mPref.mMatch)); 5969 continue; 5970 } 5971 // If it's not an "always" type preferred activity and that's what we're 5972 // looking for, skip it. 5973 if (always && !pa.mPref.mAlways) { 5974 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5975 continue; 5976 } 5977 final ActivityInfo ai = getActivityInfo( 5978 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5979 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5980 userId); 5981 if (DEBUG_PREFERRED || debug) { 5982 Slog.v(TAG, "Found preferred activity:"); 5983 if (ai != null) { 5984 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5985 } else { 5986 Slog.v(TAG, " null"); 5987 } 5988 } 5989 if (ai == null) { 5990 // This previously registered preferred activity 5991 // component is no longer known. Most likely an update 5992 // to the app was installed and in the new version this 5993 // component no longer exists. Clean it up by removing 5994 // it from the preferred activities list, and skip it. 5995 Slog.w(TAG, "Removing dangling preferred activity: " 5996 + pa.mPref.mComponent); 5997 pir.removeFilter(pa); 5998 changed = true; 5999 continue; 6000 } 6001 for (int j=0; j<N; j++) { 6002 final ResolveInfo ri = query.get(j); 6003 if (!ri.activityInfo.applicationInfo.packageName 6004 .equals(ai.applicationInfo.packageName)) { 6005 continue; 6006 } 6007 if (!ri.activityInfo.name.equals(ai.name)) { 6008 continue; 6009 } 6010 6011 if (removeMatches) { 6012 pir.removeFilter(pa); 6013 changed = true; 6014 if (DEBUG_PREFERRED) { 6015 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6016 } 6017 break; 6018 } 6019 6020 // Okay we found a previously set preferred or last chosen app. 6021 // If the result set is different from when this 6022 // was created, we need to clear it and re-ask the 6023 // user their preference, if we're looking for an "always" type entry. 6024 if (always && !pa.mPref.sameSet(query)) { 6025 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6026 + intent + " type " + resolvedType); 6027 if (DEBUG_PREFERRED) { 6028 Slog.v(TAG, "Removing preferred activity since set changed " 6029 + pa.mPref.mComponent); 6030 } 6031 pir.removeFilter(pa); 6032 // Re-add the filter as a "last chosen" entry (!always) 6033 PreferredActivity lastChosen = new PreferredActivity( 6034 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6035 pir.addFilter(lastChosen); 6036 changed = true; 6037 return null; 6038 } 6039 6040 // Yay! Either the set matched or we're looking for the last chosen 6041 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6042 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6043 return ri; 6044 } 6045 } 6046 } finally { 6047 if (changed) { 6048 if (DEBUG_PREFERRED) { 6049 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6050 } 6051 scheduleWritePackageRestrictionsLocked(userId); 6052 } 6053 } 6054 } 6055 } 6056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6057 return null; 6058 } 6059 6060 /* 6061 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6062 */ 6063 @Override 6064 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6065 int targetUserId) { 6066 mContext.enforceCallingOrSelfPermission( 6067 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6068 List<CrossProfileIntentFilter> matches = 6069 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6070 if (matches != null) { 6071 int size = matches.size(); 6072 for (int i = 0; i < size; i++) { 6073 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6074 } 6075 } 6076 if (hasWebURI(intent)) { 6077 // cross-profile app linking works only towards the parent. 6078 final int callingUid = Binder.getCallingUid(); 6079 final UserInfo parent = getProfileParent(sourceUserId); 6080 synchronized(mPackages) { 6081 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6082 false /*includeInstantApps*/); 6083 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6084 intent, resolvedType, flags, sourceUserId, parent.id); 6085 return xpDomainInfo != null; 6086 } 6087 } 6088 return false; 6089 } 6090 6091 private UserInfo getProfileParent(int userId) { 6092 final long identity = Binder.clearCallingIdentity(); 6093 try { 6094 return sUserManager.getProfileParent(userId); 6095 } finally { 6096 Binder.restoreCallingIdentity(identity); 6097 } 6098 } 6099 6100 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6101 String resolvedType, int userId) { 6102 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6103 if (resolver != null) { 6104 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6105 } 6106 return null; 6107 } 6108 6109 @Override 6110 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6111 String resolvedType, int flags, int userId) { 6112 try { 6113 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6114 6115 return new ParceledListSlice<>( 6116 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6117 } finally { 6118 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6119 } 6120 } 6121 6122 /** 6123 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6124 * instant, returns {@code null}. 6125 */ 6126 private String getInstantAppPackageName(int callingUid) { 6127 // If the caller is an isolated app use the owner's uid for the lookup. 6128 if (Process.isIsolated(callingUid)) { 6129 callingUid = mIsolatedOwners.get(callingUid); 6130 } 6131 final int appId = UserHandle.getAppId(callingUid); 6132 synchronized (mPackages) { 6133 final Object obj = mSettings.getUserIdLPr(appId); 6134 if (obj instanceof PackageSetting) { 6135 final PackageSetting ps = (PackageSetting) obj; 6136 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6137 return isInstantApp ? ps.pkg.packageName : null; 6138 } 6139 } 6140 return null; 6141 } 6142 6143 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6144 String resolvedType, int flags, int userId) { 6145 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6146 } 6147 6148 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6149 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6150 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6151 final int callingUid = Binder.getCallingUid(); 6152 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6153 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6154 enforceCrossUserPermission(callingUid, userId, 6155 false /* requireFullPermission */, false /* checkShell */, 6156 "query intent activities"); 6157 ComponentName comp = intent.getComponent(); 6158 if (comp == null) { 6159 if (intent.getSelector() != null) { 6160 intent = intent.getSelector(); 6161 comp = intent.getComponent(); 6162 } 6163 } 6164 6165 if (comp != null) { 6166 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6167 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6168 if (ai != null) { 6169 // When specifying an explicit component, we prevent the activity from being 6170 // used when either 1) the calling package is normal and the activity is within 6171 // an ephemeral application or 2) the calling package is ephemeral and the 6172 // activity is not visible to ephemeral applications. 6173 final boolean matchInstantApp = 6174 (flags & PackageManager.MATCH_INSTANT) != 0; 6175 final boolean matchVisibleToInstantAppOnly = 6176 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6177 final boolean isCallerInstantApp = 6178 instantAppPkgName != null; 6179 final boolean isTargetSameInstantApp = 6180 comp.getPackageName().equals(instantAppPkgName); 6181 final boolean isTargetInstantApp = 6182 (ai.applicationInfo.privateFlags 6183 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6184 final boolean isTargetHiddenFromInstantApp = 6185 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6186 final boolean blockResolution = 6187 !isTargetSameInstantApp 6188 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6189 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6190 && isTargetHiddenFromInstantApp)); 6191 if (!blockResolution) { 6192 final ResolveInfo ri = new ResolveInfo(); 6193 ri.activityInfo = ai; 6194 list.add(ri); 6195 } 6196 } 6197 return applyPostResolutionFilter(list, instantAppPkgName); 6198 } 6199 6200 // reader 6201 boolean sortResult = false; 6202 boolean addEphemeral = false; 6203 List<ResolveInfo> result; 6204 final String pkgName = intent.getPackage(); 6205 final boolean ephemeralDisabled = isEphemeralDisabled(); 6206 synchronized (mPackages) { 6207 if (pkgName == null) { 6208 List<CrossProfileIntentFilter> matchingFilters = 6209 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6210 // Check for results that need to skip the current profile. 6211 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6212 resolvedType, flags, userId); 6213 if (xpResolveInfo != null) { 6214 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6215 xpResult.add(xpResolveInfo); 6216 return applyPostResolutionFilter( 6217 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6218 } 6219 6220 // Check for results in the current profile. 6221 result = filterIfNotSystemUser(mActivities.queryIntent( 6222 intent, resolvedType, flags, userId), userId); 6223 addEphemeral = !ephemeralDisabled 6224 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6225 // Check for cross profile results. 6226 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6227 xpResolveInfo = queryCrossProfileIntents( 6228 matchingFilters, intent, resolvedType, flags, userId, 6229 hasNonNegativePriorityResult); 6230 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6231 boolean isVisibleToUser = filterIfNotSystemUser( 6232 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6233 if (isVisibleToUser) { 6234 result.add(xpResolveInfo); 6235 sortResult = true; 6236 } 6237 } 6238 if (hasWebURI(intent)) { 6239 CrossProfileDomainInfo xpDomainInfo = null; 6240 final UserInfo parent = getProfileParent(userId); 6241 if (parent != null) { 6242 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6243 flags, userId, parent.id); 6244 } 6245 if (xpDomainInfo != null) { 6246 if (xpResolveInfo != null) { 6247 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6248 // in the result. 6249 result.remove(xpResolveInfo); 6250 } 6251 if (result.size() == 0 && !addEphemeral) { 6252 // No result in current profile, but found candidate in parent user. 6253 // And we are not going to add emphemeral app, so we can return the 6254 // result straight away. 6255 result.add(xpDomainInfo.resolveInfo); 6256 return applyPostResolutionFilter(result, instantAppPkgName); 6257 } 6258 } else if (result.size() <= 1 && !addEphemeral) { 6259 // No result in parent user and <= 1 result in current profile, and we 6260 // are not going to add emphemeral app, so we can return the result without 6261 // further processing. 6262 return applyPostResolutionFilter(result, instantAppPkgName); 6263 } 6264 // We have more than one candidate (combining results from current and parent 6265 // profile), so we need filtering and sorting. 6266 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6267 intent, flags, result, xpDomainInfo, userId); 6268 sortResult = true; 6269 } 6270 } else { 6271 final PackageParser.Package pkg = mPackages.get(pkgName); 6272 if (pkg != null) { 6273 return applyPostResolutionFilter(filterIfNotSystemUser( 6274 mActivities.queryIntentForPackage( 6275 intent, resolvedType, flags, pkg.activities, userId), 6276 userId), instantAppPkgName); 6277 } else { 6278 // the caller wants to resolve for a particular package; however, there 6279 // were no installed results, so, try to find an ephemeral result 6280 addEphemeral = !ephemeralDisabled 6281 && isEphemeralAllowed( 6282 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6283 result = new ArrayList<ResolveInfo>(); 6284 } 6285 } 6286 } 6287 if (addEphemeral) { 6288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6289 final InstantAppRequest requestObject = new InstantAppRequest( 6290 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6291 null /*callingPackage*/, userId); 6292 final AuxiliaryResolveInfo auxiliaryResponse = 6293 InstantAppResolver.doInstantAppResolutionPhaseOne( 6294 mContext, mInstantAppResolverConnection, requestObject); 6295 if (auxiliaryResponse != null) { 6296 if (DEBUG_EPHEMERAL) { 6297 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6298 } 6299 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6300 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6301 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6302 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6303 // make sure this resolver is the default 6304 ephemeralInstaller.isDefault = true; 6305 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6306 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6307 // add a non-generic filter 6308 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6309 ephemeralInstaller.filter.addDataPath( 6310 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6311 ephemeralInstaller.instantAppAvailable = true; 6312 result.add(ephemeralInstaller); 6313 } 6314 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6315 } 6316 if (sortResult) { 6317 Collections.sort(result, mResolvePrioritySorter); 6318 } 6319 return applyPostResolutionFilter(result, instantAppPkgName); 6320 } 6321 6322 private static class CrossProfileDomainInfo { 6323 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6324 ResolveInfo resolveInfo; 6325 /* Best domain verification status of the activities found in the other profile */ 6326 int bestDomainVerificationStatus; 6327 } 6328 6329 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6330 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6331 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6332 sourceUserId)) { 6333 return null; 6334 } 6335 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6336 resolvedType, flags, parentUserId); 6337 6338 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6339 return null; 6340 } 6341 CrossProfileDomainInfo result = null; 6342 int size = resultTargetUser.size(); 6343 for (int i = 0; i < size; i++) { 6344 ResolveInfo riTargetUser = resultTargetUser.get(i); 6345 // Intent filter verification is only for filters that specify a host. So don't return 6346 // those that handle all web uris. 6347 if (riTargetUser.handleAllWebDataURI) { 6348 continue; 6349 } 6350 String packageName = riTargetUser.activityInfo.packageName; 6351 PackageSetting ps = mSettings.mPackages.get(packageName); 6352 if (ps == null) { 6353 continue; 6354 } 6355 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6356 int status = (int)(verificationState >> 32); 6357 if (result == null) { 6358 result = new CrossProfileDomainInfo(); 6359 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6360 sourceUserId, parentUserId); 6361 result.bestDomainVerificationStatus = status; 6362 } else { 6363 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6364 result.bestDomainVerificationStatus); 6365 } 6366 } 6367 // Don't consider matches with status NEVER across profiles. 6368 if (result != null && result.bestDomainVerificationStatus 6369 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6370 return null; 6371 } 6372 return result; 6373 } 6374 6375 /** 6376 * Verification statuses are ordered from the worse to the best, except for 6377 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6378 */ 6379 private int bestDomainVerificationStatus(int status1, int status2) { 6380 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6381 return status2; 6382 } 6383 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6384 return status1; 6385 } 6386 return (int) MathUtils.max(status1, status2); 6387 } 6388 6389 private boolean isUserEnabled(int userId) { 6390 long callingId = Binder.clearCallingIdentity(); 6391 try { 6392 UserInfo userInfo = sUserManager.getUserInfo(userId); 6393 return userInfo != null && userInfo.isEnabled(); 6394 } finally { 6395 Binder.restoreCallingIdentity(callingId); 6396 } 6397 } 6398 6399 /** 6400 * Filter out activities with systemUserOnly flag set, when current user is not System. 6401 * 6402 * @return filtered list 6403 */ 6404 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6405 if (userId == UserHandle.USER_SYSTEM) { 6406 return resolveInfos; 6407 } 6408 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6409 ResolveInfo info = resolveInfos.get(i); 6410 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6411 resolveInfos.remove(i); 6412 } 6413 } 6414 return resolveInfos; 6415 } 6416 6417 /** 6418 * Filters out ephemeral activities. 6419 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6420 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6421 * 6422 * @param resolveInfos The pre-filtered list of resolved activities 6423 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6424 * is performed. 6425 * @return A filtered list of resolved activities. 6426 */ 6427 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6428 String ephemeralPkgName) { 6429 // TODO: When adding on-demand split support for non-instant apps, remove this check 6430 // and always apply post filtering 6431 if (ephemeralPkgName == null) { 6432 return resolveInfos; 6433 } 6434 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6435 final ResolveInfo info = resolveInfos.get(i); 6436 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6437 // allow activities that are defined in the provided package 6438 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6439 if (info.activityInfo.splitName != null 6440 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6441 info.activityInfo.splitName)) { 6442 // requested activity is defined in a split that hasn't been installed yet. 6443 // add the installer to the resolve list 6444 if (DEBUG_EPHEMERAL) { 6445 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6446 } 6447 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6448 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6449 info.activityInfo.packageName, info.activityInfo.splitName, 6450 info.activityInfo.applicationInfo.versionCode); 6451 // make sure this resolver is the default 6452 installerInfo.isDefault = true; 6453 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6454 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6455 // add a non-generic filter 6456 installerInfo.filter = new IntentFilter(); 6457 // load resources from the correct package 6458 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6459 resolveInfos.set(i, installerInfo); 6460 } 6461 continue; 6462 } 6463 // allow activities that have been explicitly exposed to ephemeral apps 6464 if (!isEphemeralApp 6465 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6466 continue; 6467 } 6468 resolveInfos.remove(i); 6469 } 6470 return resolveInfos; 6471 } 6472 6473 /** 6474 * @param resolveInfos list of resolve infos in descending priority order 6475 * @return if the list contains a resolve info with non-negative priority 6476 */ 6477 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6478 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6479 } 6480 6481 private static boolean hasWebURI(Intent intent) { 6482 if (intent.getData() == null) { 6483 return false; 6484 } 6485 final String scheme = intent.getScheme(); 6486 if (TextUtils.isEmpty(scheme)) { 6487 return false; 6488 } 6489 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6490 } 6491 6492 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6493 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6494 int userId) { 6495 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6496 6497 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6498 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6499 candidates.size()); 6500 } 6501 6502 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6503 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6504 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6505 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6506 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6507 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6508 6509 synchronized (mPackages) { 6510 final int count = candidates.size(); 6511 // First, try to use linked apps. Partition the candidates into four lists: 6512 // one for the final results, one for the "do not use ever", one for "undefined status" 6513 // and finally one for "browser app type". 6514 for (int n=0; n<count; n++) { 6515 ResolveInfo info = candidates.get(n); 6516 String packageName = info.activityInfo.packageName; 6517 PackageSetting ps = mSettings.mPackages.get(packageName); 6518 if (ps != null) { 6519 // Add to the special match all list (Browser use case) 6520 if (info.handleAllWebDataURI) { 6521 matchAllList.add(info); 6522 continue; 6523 } 6524 // Try to get the status from User settings first 6525 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6526 int status = (int)(packedStatus >> 32); 6527 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6528 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6529 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6530 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6531 + " : linkgen=" + linkGeneration); 6532 } 6533 // Use link-enabled generation as preferredOrder, i.e. 6534 // prefer newly-enabled over earlier-enabled. 6535 info.preferredOrder = linkGeneration; 6536 alwaysList.add(info); 6537 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6538 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6539 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6540 } 6541 neverList.add(info); 6542 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6543 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6544 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6545 } 6546 alwaysAskList.add(info); 6547 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6548 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6549 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6550 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6551 } 6552 undefinedList.add(info); 6553 } 6554 } 6555 } 6556 6557 // We'll want to include browser possibilities in a few cases 6558 boolean includeBrowser = false; 6559 6560 // First try to add the "always" resolution(s) for the current user, if any 6561 if (alwaysList.size() > 0) { 6562 result.addAll(alwaysList); 6563 } else { 6564 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6565 result.addAll(undefinedList); 6566 // Maybe add one for the other profile. 6567 if (xpDomainInfo != null && ( 6568 xpDomainInfo.bestDomainVerificationStatus 6569 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6570 result.add(xpDomainInfo.resolveInfo); 6571 } 6572 includeBrowser = true; 6573 } 6574 6575 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6576 // If there were 'always' entries their preferred order has been set, so we also 6577 // back that off to make the alternatives equivalent 6578 if (alwaysAskList.size() > 0) { 6579 for (ResolveInfo i : result) { 6580 i.preferredOrder = 0; 6581 } 6582 result.addAll(alwaysAskList); 6583 includeBrowser = true; 6584 } 6585 6586 if (includeBrowser) { 6587 // Also add browsers (all of them or only the default one) 6588 if (DEBUG_DOMAIN_VERIFICATION) { 6589 Slog.v(TAG, " ...including browsers in candidate set"); 6590 } 6591 if ((matchFlags & MATCH_ALL) != 0) { 6592 result.addAll(matchAllList); 6593 } else { 6594 // Browser/generic handling case. If there's a default browser, go straight 6595 // to that (but only if there is no other higher-priority match). 6596 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6597 int maxMatchPrio = 0; 6598 ResolveInfo defaultBrowserMatch = null; 6599 final int numCandidates = matchAllList.size(); 6600 for (int n = 0; n < numCandidates; n++) { 6601 ResolveInfo info = matchAllList.get(n); 6602 // track the highest overall match priority... 6603 if (info.priority > maxMatchPrio) { 6604 maxMatchPrio = info.priority; 6605 } 6606 // ...and the highest-priority default browser match 6607 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6608 if (defaultBrowserMatch == null 6609 || (defaultBrowserMatch.priority < info.priority)) { 6610 if (debug) { 6611 Slog.v(TAG, "Considering default browser match " + info); 6612 } 6613 defaultBrowserMatch = info; 6614 } 6615 } 6616 } 6617 if (defaultBrowserMatch != null 6618 && defaultBrowserMatch.priority >= maxMatchPrio 6619 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6620 { 6621 if (debug) { 6622 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6623 } 6624 result.add(defaultBrowserMatch); 6625 } else { 6626 result.addAll(matchAllList); 6627 } 6628 } 6629 6630 // If there is nothing selected, add all candidates and remove the ones that the user 6631 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6632 if (result.size() == 0) { 6633 result.addAll(candidates); 6634 result.removeAll(neverList); 6635 } 6636 } 6637 } 6638 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6639 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6640 result.size()); 6641 for (ResolveInfo info : result) { 6642 Slog.v(TAG, " + " + info.activityInfo); 6643 } 6644 } 6645 return result; 6646 } 6647 6648 // Returns a packed value as a long: 6649 // 6650 // high 'int'-sized word: link status: undefined/ask/never/always. 6651 // low 'int'-sized word: relative priority among 'always' results. 6652 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6653 long result = ps.getDomainVerificationStatusForUser(userId); 6654 // if none available, get the master status 6655 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6656 if (ps.getIntentFilterVerificationInfo() != null) { 6657 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6658 } 6659 } 6660 return result; 6661 } 6662 6663 private ResolveInfo querySkipCurrentProfileIntents( 6664 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6665 int flags, int sourceUserId) { 6666 if (matchingFilters != null) { 6667 int size = matchingFilters.size(); 6668 for (int i = 0; i < size; i ++) { 6669 CrossProfileIntentFilter filter = matchingFilters.get(i); 6670 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6671 // Checking if there are activities in the target user that can handle the 6672 // intent. 6673 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6674 resolvedType, flags, sourceUserId); 6675 if (resolveInfo != null) { 6676 return resolveInfo; 6677 } 6678 } 6679 } 6680 } 6681 return null; 6682 } 6683 6684 // Return matching ResolveInfo in target user if any. 6685 private ResolveInfo queryCrossProfileIntents( 6686 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6687 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6688 if (matchingFilters != null) { 6689 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6690 // match the same intent. For performance reasons, it is better not to 6691 // run queryIntent twice for the same userId 6692 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6693 int size = matchingFilters.size(); 6694 for (int i = 0; i < size; i++) { 6695 CrossProfileIntentFilter filter = matchingFilters.get(i); 6696 int targetUserId = filter.getTargetUserId(); 6697 boolean skipCurrentProfile = 6698 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6699 boolean skipCurrentProfileIfNoMatchFound = 6700 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6701 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6702 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6703 // Checking if there are activities in the target user that can handle the 6704 // intent. 6705 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6706 resolvedType, flags, sourceUserId); 6707 if (resolveInfo != null) return resolveInfo; 6708 alreadyTriedUserIds.put(targetUserId, true); 6709 } 6710 } 6711 } 6712 return null; 6713 } 6714 6715 /** 6716 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6717 * will forward the intent to the filter's target user. 6718 * Otherwise, returns null. 6719 */ 6720 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6721 String resolvedType, int flags, int sourceUserId) { 6722 int targetUserId = filter.getTargetUserId(); 6723 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6724 resolvedType, flags, targetUserId); 6725 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6726 // If all the matches in the target profile are suspended, return null. 6727 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6728 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6729 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6730 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6731 targetUserId); 6732 } 6733 } 6734 } 6735 return null; 6736 } 6737 6738 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6739 int sourceUserId, int targetUserId) { 6740 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6741 long ident = Binder.clearCallingIdentity(); 6742 boolean targetIsProfile; 6743 try { 6744 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6745 } finally { 6746 Binder.restoreCallingIdentity(ident); 6747 } 6748 String className; 6749 if (targetIsProfile) { 6750 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6751 } else { 6752 className = FORWARD_INTENT_TO_PARENT; 6753 } 6754 ComponentName forwardingActivityComponentName = new ComponentName( 6755 mAndroidApplication.packageName, className); 6756 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6757 sourceUserId); 6758 if (!targetIsProfile) { 6759 forwardingActivityInfo.showUserIcon = targetUserId; 6760 forwardingResolveInfo.noResourceId = true; 6761 } 6762 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6763 forwardingResolveInfo.priority = 0; 6764 forwardingResolveInfo.preferredOrder = 0; 6765 forwardingResolveInfo.match = 0; 6766 forwardingResolveInfo.isDefault = true; 6767 forwardingResolveInfo.filter = filter; 6768 forwardingResolveInfo.targetUserId = targetUserId; 6769 return forwardingResolveInfo; 6770 } 6771 6772 @Override 6773 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6774 Intent[] specifics, String[] specificTypes, Intent intent, 6775 String resolvedType, int flags, int userId) { 6776 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6777 specificTypes, intent, resolvedType, flags, userId)); 6778 } 6779 6780 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6781 Intent[] specifics, String[] specificTypes, Intent intent, 6782 String resolvedType, int flags, int userId) { 6783 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6784 final int callingUid = Binder.getCallingUid(); 6785 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6786 false /*includeInstantApps*/); 6787 enforceCrossUserPermission(callingUid, userId, 6788 false /*requireFullPermission*/, false /*checkShell*/, 6789 "query intent activity options"); 6790 final String resultsAction = intent.getAction(); 6791 6792 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6793 | PackageManager.GET_RESOLVED_FILTER, userId); 6794 6795 if (DEBUG_INTENT_MATCHING) { 6796 Log.v(TAG, "Query " + intent + ": " + results); 6797 } 6798 6799 int specificsPos = 0; 6800 int N; 6801 6802 // todo: note that the algorithm used here is O(N^2). This 6803 // isn't a problem in our current environment, but if we start running 6804 // into situations where we have more than 5 or 10 matches then this 6805 // should probably be changed to something smarter... 6806 6807 // First we go through and resolve each of the specific items 6808 // that were supplied, taking care of removing any corresponding 6809 // duplicate items in the generic resolve list. 6810 if (specifics != null) { 6811 for (int i=0; i<specifics.length; i++) { 6812 final Intent sintent = specifics[i]; 6813 if (sintent == null) { 6814 continue; 6815 } 6816 6817 if (DEBUG_INTENT_MATCHING) { 6818 Log.v(TAG, "Specific #" + i + ": " + sintent); 6819 } 6820 6821 String action = sintent.getAction(); 6822 if (resultsAction != null && resultsAction.equals(action)) { 6823 // If this action was explicitly requested, then don't 6824 // remove things that have it. 6825 action = null; 6826 } 6827 6828 ResolveInfo ri = null; 6829 ActivityInfo ai = null; 6830 6831 ComponentName comp = sintent.getComponent(); 6832 if (comp == null) { 6833 ri = resolveIntent( 6834 sintent, 6835 specificTypes != null ? specificTypes[i] : null, 6836 flags, userId); 6837 if (ri == null) { 6838 continue; 6839 } 6840 if (ri == mResolveInfo) { 6841 // ACK! Must do something better with this. 6842 } 6843 ai = ri.activityInfo; 6844 comp = new ComponentName(ai.applicationInfo.packageName, 6845 ai.name); 6846 } else { 6847 ai = getActivityInfo(comp, flags, userId); 6848 if (ai == null) { 6849 continue; 6850 } 6851 } 6852 6853 // Look for any generic query activities that are duplicates 6854 // of this specific one, and remove them from the results. 6855 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6856 N = results.size(); 6857 int j; 6858 for (j=specificsPos; j<N; j++) { 6859 ResolveInfo sri = results.get(j); 6860 if ((sri.activityInfo.name.equals(comp.getClassName()) 6861 && sri.activityInfo.applicationInfo.packageName.equals( 6862 comp.getPackageName())) 6863 || (action != null && sri.filter.matchAction(action))) { 6864 results.remove(j); 6865 if (DEBUG_INTENT_MATCHING) Log.v( 6866 TAG, "Removing duplicate item from " + j 6867 + " due to specific " + specificsPos); 6868 if (ri == null) { 6869 ri = sri; 6870 } 6871 j--; 6872 N--; 6873 } 6874 } 6875 6876 // Add this specific item to its proper place. 6877 if (ri == null) { 6878 ri = new ResolveInfo(); 6879 ri.activityInfo = ai; 6880 } 6881 results.add(specificsPos, ri); 6882 ri.specificIndex = i; 6883 specificsPos++; 6884 } 6885 } 6886 6887 // Now we go through the remaining generic results and remove any 6888 // duplicate actions that are found here. 6889 N = results.size(); 6890 for (int i=specificsPos; i<N-1; i++) { 6891 final ResolveInfo rii = results.get(i); 6892 if (rii.filter == null) { 6893 continue; 6894 } 6895 6896 // Iterate over all of the actions of this result's intent 6897 // filter... typically this should be just one. 6898 final Iterator<String> it = rii.filter.actionsIterator(); 6899 if (it == null) { 6900 continue; 6901 } 6902 while (it.hasNext()) { 6903 final String action = it.next(); 6904 if (resultsAction != null && resultsAction.equals(action)) { 6905 // If this action was explicitly requested, then don't 6906 // remove things that have it. 6907 continue; 6908 } 6909 for (int j=i+1; j<N; j++) { 6910 final ResolveInfo rij = results.get(j); 6911 if (rij.filter != null && rij.filter.hasAction(action)) { 6912 results.remove(j); 6913 if (DEBUG_INTENT_MATCHING) Log.v( 6914 TAG, "Removing duplicate item from " + j 6915 + " due to action " + action + " at " + i); 6916 j--; 6917 N--; 6918 } 6919 } 6920 } 6921 6922 // If the caller didn't request filter information, drop it now 6923 // so we don't have to marshall/unmarshall it. 6924 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6925 rii.filter = null; 6926 } 6927 } 6928 6929 // Filter out the caller activity if so requested. 6930 if (caller != null) { 6931 N = results.size(); 6932 for (int i=0; i<N; i++) { 6933 ActivityInfo ainfo = results.get(i).activityInfo; 6934 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6935 && caller.getClassName().equals(ainfo.name)) { 6936 results.remove(i); 6937 break; 6938 } 6939 } 6940 } 6941 6942 // If the caller didn't request filter information, 6943 // drop them now so we don't have to 6944 // marshall/unmarshall it. 6945 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6946 N = results.size(); 6947 for (int i=0; i<N; i++) { 6948 results.get(i).filter = null; 6949 } 6950 } 6951 6952 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6953 return results; 6954 } 6955 6956 @Override 6957 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6958 String resolvedType, int flags, int userId) { 6959 return new ParceledListSlice<>( 6960 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6961 } 6962 6963 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6964 String resolvedType, int flags, int userId) { 6965 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6966 final int callingUid = Binder.getCallingUid(); 6967 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6968 false /*includeInstantApps*/); 6969 ComponentName comp = intent.getComponent(); 6970 if (comp == null) { 6971 if (intent.getSelector() != null) { 6972 intent = intent.getSelector(); 6973 comp = intent.getComponent(); 6974 } 6975 } 6976 if (comp != null) { 6977 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6978 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6979 if (ai != null) { 6980 ResolveInfo ri = new ResolveInfo(); 6981 ri.activityInfo = ai; 6982 list.add(ri); 6983 } 6984 return list; 6985 } 6986 6987 // reader 6988 synchronized (mPackages) { 6989 String pkgName = intent.getPackage(); 6990 if (pkgName == null) { 6991 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6992 } 6993 final PackageParser.Package pkg = mPackages.get(pkgName); 6994 if (pkg != null) { 6995 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6996 userId); 6997 } 6998 return Collections.emptyList(); 6999 } 7000 } 7001 7002 @Override 7003 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7004 final int callingUid = Binder.getCallingUid(); 7005 return resolveServiceInternal( 7006 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7007 } 7008 7009 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7010 int userId, int callingUid, boolean includeInstantApps) { 7011 if (!sUserManager.exists(userId)) return null; 7012 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7013 List<ResolveInfo> query = queryIntentServicesInternal( 7014 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7015 if (query != null) { 7016 if (query.size() >= 1) { 7017 // If there is more than one service with the same priority, 7018 // just arbitrarily pick the first one. 7019 return query.get(0); 7020 } 7021 } 7022 return null; 7023 } 7024 7025 @Override 7026 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7027 String resolvedType, int flags, int userId) { 7028 final int callingUid = Binder.getCallingUid(); 7029 return new ParceledListSlice<>(queryIntentServicesInternal( 7030 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7031 } 7032 7033 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7034 String resolvedType, int flags, int userId, int callingUid, 7035 boolean includeInstantApps) { 7036 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7037 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7038 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7039 ComponentName comp = intent.getComponent(); 7040 if (comp == null) { 7041 if (intent.getSelector() != null) { 7042 intent = intent.getSelector(); 7043 comp = intent.getComponent(); 7044 } 7045 } 7046 if (comp != null) { 7047 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7048 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7049 if (si != null) { 7050 // When specifying an explicit component, we prevent the service from being 7051 // used when either 1) the service is in an instant application and the 7052 // caller is not the same instant application or 2) the calling package is 7053 // ephemeral and the activity is not visible to ephemeral applications. 7054 final boolean matchVisibleToInstantAppOnly = 7055 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7056 final boolean isCallerInstantApp = 7057 instantAppPkgName != null; 7058 final boolean isTargetSameInstantApp = 7059 comp.getPackageName().equals(instantAppPkgName); 7060 final boolean isTargetHiddenFromInstantApp = 7061 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7062 final boolean blockResolution = 7063 !isTargetSameInstantApp 7064 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7065 && isTargetHiddenFromInstantApp)); 7066 if (!blockResolution) { 7067 final ResolveInfo ri = new ResolveInfo(); 7068 ri.serviceInfo = si; 7069 list.add(ri); 7070 } 7071 } 7072 return list; 7073 } 7074 7075 // reader 7076 synchronized (mPackages) { 7077 String pkgName = intent.getPackage(); 7078 if (pkgName == null) { 7079 return applyPostServiceResolutionFilter( 7080 mServices.queryIntent(intent, resolvedType, flags, userId), 7081 instantAppPkgName); 7082 } 7083 final PackageParser.Package pkg = mPackages.get(pkgName); 7084 if (pkg != null) { 7085 return applyPostServiceResolutionFilter( 7086 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7087 userId), 7088 instantAppPkgName); 7089 } 7090 return Collections.emptyList(); 7091 } 7092 } 7093 7094 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7095 String instantAppPkgName) { 7096 // TODO: When adding on-demand split support for non-instant apps, remove this check 7097 // and always apply post filtering 7098 if (instantAppPkgName == null) { 7099 return resolveInfos; 7100 } 7101 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7102 final ResolveInfo info = resolveInfos.get(i); 7103 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7104 // allow services that are defined in the provided package 7105 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7106 if (info.serviceInfo.splitName != null 7107 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7108 info.serviceInfo.splitName)) { 7109 // requested service is defined in a split that hasn't been installed yet. 7110 // add the installer to the resolve list 7111 if (DEBUG_EPHEMERAL) { 7112 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7113 } 7114 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7115 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7116 info.serviceInfo.packageName, info.serviceInfo.splitName, 7117 info.serviceInfo.applicationInfo.versionCode); 7118 // make sure this resolver is the default 7119 installerInfo.isDefault = true; 7120 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7121 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7122 // add a non-generic filter 7123 installerInfo.filter = new IntentFilter(); 7124 // load resources from the correct package 7125 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7126 resolveInfos.set(i, installerInfo); 7127 } 7128 continue; 7129 } 7130 // allow services that have been explicitly exposed to ephemeral apps 7131 if (!isEphemeralApp 7132 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7133 continue; 7134 } 7135 resolveInfos.remove(i); 7136 } 7137 return resolveInfos; 7138 } 7139 7140 @Override 7141 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7142 String resolvedType, int flags, int userId) { 7143 return new ParceledListSlice<>( 7144 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7145 } 7146 7147 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7148 Intent intent, String resolvedType, int flags, int userId) { 7149 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7150 final int callingUid = Binder.getCallingUid(); 7151 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7152 false /*includeInstantApps*/); 7153 ComponentName comp = intent.getComponent(); 7154 if (comp == null) { 7155 if (intent.getSelector() != null) { 7156 intent = intent.getSelector(); 7157 comp = intent.getComponent(); 7158 } 7159 } 7160 if (comp != null) { 7161 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7162 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7163 if (pi != null) { 7164 final ResolveInfo ri = new ResolveInfo(); 7165 ri.providerInfo = pi; 7166 list.add(ri); 7167 } 7168 return list; 7169 } 7170 7171 // reader 7172 synchronized (mPackages) { 7173 String pkgName = intent.getPackage(); 7174 if (pkgName == null) { 7175 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7176 } 7177 final PackageParser.Package pkg = mPackages.get(pkgName); 7178 if (pkg != null) { 7179 return mProviders.queryIntentForPackage( 7180 intent, resolvedType, flags, pkg.providers, userId); 7181 } 7182 return Collections.emptyList(); 7183 } 7184 } 7185 7186 @Override 7187 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7188 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7189 flags = updateFlagsForPackage(flags, userId, null); 7190 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7191 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7192 true /* requireFullPermission */, false /* checkShell */, 7193 "get installed packages"); 7194 7195 // writer 7196 synchronized (mPackages) { 7197 ArrayList<PackageInfo> list; 7198 if (listUninstalled) { 7199 list = new ArrayList<>(mSettings.mPackages.size()); 7200 for (PackageSetting ps : mSettings.mPackages.values()) { 7201 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7202 continue; 7203 } 7204 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7205 if (pi != null) { 7206 list.add(pi); 7207 } 7208 } 7209 } else { 7210 list = new ArrayList<>(mPackages.size()); 7211 for (PackageParser.Package p : mPackages.values()) { 7212 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7213 Binder.getCallingUid(), userId)) { 7214 continue; 7215 } 7216 final PackageInfo pi = generatePackageInfo((PackageSetting) 7217 p.mExtras, flags, userId); 7218 if (pi != null) { 7219 list.add(pi); 7220 } 7221 } 7222 } 7223 7224 return new ParceledListSlice<>(list); 7225 } 7226 } 7227 7228 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7229 String[] permissions, boolean[] tmp, int flags, int userId) { 7230 int numMatch = 0; 7231 final PermissionsState permissionsState = ps.getPermissionsState(); 7232 for (int i=0; i<permissions.length; i++) { 7233 final String permission = permissions[i]; 7234 if (permissionsState.hasPermission(permission, userId)) { 7235 tmp[i] = true; 7236 numMatch++; 7237 } else { 7238 tmp[i] = false; 7239 } 7240 } 7241 if (numMatch == 0) { 7242 return; 7243 } 7244 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7245 7246 // The above might return null in cases of uninstalled apps or install-state 7247 // skew across users/profiles. 7248 if (pi != null) { 7249 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7250 if (numMatch == permissions.length) { 7251 pi.requestedPermissions = permissions; 7252 } else { 7253 pi.requestedPermissions = new String[numMatch]; 7254 numMatch = 0; 7255 for (int i=0; i<permissions.length; i++) { 7256 if (tmp[i]) { 7257 pi.requestedPermissions[numMatch] = permissions[i]; 7258 numMatch++; 7259 } 7260 } 7261 } 7262 } 7263 list.add(pi); 7264 } 7265 } 7266 7267 @Override 7268 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7269 String[] permissions, int flags, int userId) { 7270 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7271 flags = updateFlagsForPackage(flags, userId, permissions); 7272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7273 true /* requireFullPermission */, false /* checkShell */, 7274 "get packages holding permissions"); 7275 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7276 7277 // writer 7278 synchronized (mPackages) { 7279 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7280 boolean[] tmpBools = new boolean[permissions.length]; 7281 if (listUninstalled) { 7282 for (PackageSetting ps : mSettings.mPackages.values()) { 7283 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7284 userId); 7285 } 7286 } else { 7287 for (PackageParser.Package pkg : mPackages.values()) { 7288 PackageSetting ps = (PackageSetting)pkg.mExtras; 7289 if (ps != null) { 7290 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7291 userId); 7292 } 7293 } 7294 } 7295 7296 return new ParceledListSlice<PackageInfo>(list); 7297 } 7298 } 7299 7300 @Override 7301 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7302 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7303 flags = updateFlagsForApplication(flags, userId, null); 7304 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7305 7306 // writer 7307 synchronized (mPackages) { 7308 ArrayList<ApplicationInfo> list; 7309 if (listUninstalled) { 7310 list = new ArrayList<>(mSettings.mPackages.size()); 7311 for (PackageSetting ps : mSettings.mPackages.values()) { 7312 ApplicationInfo ai; 7313 int effectiveFlags = flags; 7314 if (ps.isSystem()) { 7315 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7316 } 7317 if (ps.pkg != null) { 7318 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7319 continue; 7320 } 7321 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7322 ps.readUserState(userId), userId); 7323 if (ai != null) { 7324 rebaseEnabledOverlays(ai, userId); 7325 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7326 } 7327 } else { 7328 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7329 // and already converts to externally visible package name 7330 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7331 Binder.getCallingUid(), effectiveFlags, userId); 7332 } 7333 if (ai != null) { 7334 list.add(ai); 7335 } 7336 } 7337 } else { 7338 list = new ArrayList<>(mPackages.size()); 7339 for (PackageParser.Package p : mPackages.values()) { 7340 if (p.mExtras != null) { 7341 PackageSetting ps = (PackageSetting) p.mExtras; 7342 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7343 continue; 7344 } 7345 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7346 ps.readUserState(userId), userId); 7347 if (ai != null) { 7348 rebaseEnabledOverlays(ai, userId); 7349 ai.packageName = resolveExternalPackageNameLPr(p); 7350 list.add(ai); 7351 } 7352 } 7353 } 7354 } 7355 7356 return new ParceledListSlice<>(list); 7357 } 7358 } 7359 7360 @Override 7361 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7362 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7363 return null; 7364 } 7365 7366 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7367 "getEphemeralApplications"); 7368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7369 true /* requireFullPermission */, false /* checkShell */, 7370 "getEphemeralApplications"); 7371 synchronized (mPackages) { 7372 List<InstantAppInfo> instantApps = mInstantAppRegistry 7373 .getInstantAppsLPr(userId); 7374 if (instantApps != null) { 7375 return new ParceledListSlice<>(instantApps); 7376 } 7377 } 7378 return null; 7379 } 7380 7381 @Override 7382 public boolean isInstantApp(String packageName, int userId) { 7383 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7384 true /* requireFullPermission */, false /* checkShell */, 7385 "isInstantApp"); 7386 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7387 return false; 7388 } 7389 int uid = Binder.getCallingUid(); 7390 if (Process.isIsolated(uid)) { 7391 uid = mIsolatedOwners.get(uid); 7392 } 7393 7394 synchronized (mPackages) { 7395 final PackageSetting ps = mSettings.mPackages.get(packageName); 7396 PackageParser.Package pkg = mPackages.get(packageName); 7397 final boolean returnAllowed = 7398 ps != null 7399 && (isCallerSameApp(packageName, uid) 7400 || mContext.checkCallingOrSelfPermission( 7401 android.Manifest.permission.ACCESS_INSTANT_APPS) 7402 == PERMISSION_GRANTED 7403 || mInstantAppRegistry.isInstantAccessGranted( 7404 userId, UserHandle.getAppId(uid), ps.appId)); 7405 if (returnAllowed) { 7406 return ps.getInstantApp(userId); 7407 } 7408 } 7409 return false; 7410 } 7411 7412 @Override 7413 public byte[] getInstantAppCookie(String packageName, int userId) { 7414 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7415 return null; 7416 } 7417 7418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7419 true /* requireFullPermission */, false /* checkShell */, 7420 "getInstantAppCookie"); 7421 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7422 return null; 7423 } 7424 synchronized (mPackages) { 7425 return mInstantAppRegistry.getInstantAppCookieLPw( 7426 packageName, userId); 7427 } 7428 } 7429 7430 @Override 7431 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7432 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7433 return true; 7434 } 7435 7436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7437 true /* requireFullPermission */, true /* checkShell */, 7438 "setInstantAppCookie"); 7439 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7440 return false; 7441 } 7442 synchronized (mPackages) { 7443 return mInstantAppRegistry.setInstantAppCookieLPw( 7444 packageName, cookie, userId); 7445 } 7446 } 7447 7448 @Override 7449 public Bitmap getInstantAppIcon(String packageName, int userId) { 7450 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7451 return null; 7452 } 7453 7454 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7455 "getInstantAppIcon"); 7456 7457 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7458 true /* requireFullPermission */, false /* checkShell */, 7459 "getInstantAppIcon"); 7460 7461 synchronized (mPackages) { 7462 return mInstantAppRegistry.getInstantAppIconLPw( 7463 packageName, userId); 7464 } 7465 } 7466 7467 private boolean isCallerSameApp(String packageName, int uid) { 7468 PackageParser.Package pkg = mPackages.get(packageName); 7469 return pkg != null 7470 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7471 } 7472 7473 @Override 7474 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7475 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7476 } 7477 7478 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7479 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7480 7481 // reader 7482 synchronized (mPackages) { 7483 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7484 final int userId = UserHandle.getCallingUserId(); 7485 while (i.hasNext()) { 7486 final PackageParser.Package p = i.next(); 7487 if (p.applicationInfo == null) continue; 7488 7489 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7490 && !p.applicationInfo.isDirectBootAware(); 7491 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7492 && p.applicationInfo.isDirectBootAware(); 7493 7494 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7495 && (!mSafeMode || isSystemApp(p)) 7496 && (matchesUnaware || matchesAware)) { 7497 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7498 if (ps != null) { 7499 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7500 ps.readUserState(userId), userId); 7501 if (ai != null) { 7502 rebaseEnabledOverlays(ai, userId); 7503 finalList.add(ai); 7504 } 7505 } 7506 } 7507 } 7508 } 7509 7510 return finalList; 7511 } 7512 7513 @Override 7514 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7515 if (!sUserManager.exists(userId)) return null; 7516 flags = updateFlagsForComponent(flags, userId, name); 7517 // reader 7518 synchronized (mPackages) { 7519 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7520 PackageSetting ps = provider != null 7521 ? mSettings.mPackages.get(provider.owner.packageName) 7522 : null; 7523 return ps != null 7524 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7525 ? PackageParser.generateProviderInfo(provider, flags, 7526 ps.readUserState(userId), userId) 7527 : null; 7528 } 7529 } 7530 7531 /** 7532 * @deprecated 7533 */ 7534 @Deprecated 7535 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7536 // reader 7537 synchronized (mPackages) { 7538 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7539 .entrySet().iterator(); 7540 final int userId = UserHandle.getCallingUserId(); 7541 while (i.hasNext()) { 7542 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7543 PackageParser.Provider p = entry.getValue(); 7544 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7545 7546 if (ps != null && p.syncable 7547 && (!mSafeMode || (p.info.applicationInfo.flags 7548 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7549 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7550 ps.readUserState(userId), userId); 7551 if (info != null) { 7552 outNames.add(entry.getKey()); 7553 outInfo.add(info); 7554 } 7555 } 7556 } 7557 } 7558 } 7559 7560 @Override 7561 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7562 int uid, int flags, String metaDataKey) { 7563 final int userId = processName != null ? UserHandle.getUserId(uid) 7564 : UserHandle.getCallingUserId(); 7565 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7566 flags = updateFlagsForComponent(flags, userId, processName); 7567 7568 ArrayList<ProviderInfo> finalList = null; 7569 // reader 7570 synchronized (mPackages) { 7571 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7572 while (i.hasNext()) { 7573 final PackageParser.Provider p = i.next(); 7574 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7575 if (ps != null && p.info.authority != null 7576 && (processName == null 7577 || (p.info.processName.equals(processName) 7578 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7579 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7580 7581 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7582 // parameter. 7583 if (metaDataKey != null 7584 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7585 continue; 7586 } 7587 7588 if (finalList == null) { 7589 finalList = new ArrayList<ProviderInfo>(3); 7590 } 7591 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7592 ps.readUserState(userId), userId); 7593 if (info != null) { 7594 finalList.add(info); 7595 } 7596 } 7597 } 7598 } 7599 7600 if (finalList != null) { 7601 Collections.sort(finalList, mProviderInitOrderSorter); 7602 return new ParceledListSlice<ProviderInfo>(finalList); 7603 } 7604 7605 return ParceledListSlice.emptyList(); 7606 } 7607 7608 @Override 7609 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7610 // reader 7611 synchronized (mPackages) { 7612 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7613 return PackageParser.generateInstrumentationInfo(i, flags); 7614 } 7615 } 7616 7617 @Override 7618 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7619 String targetPackage, int flags) { 7620 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7621 } 7622 7623 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7624 int flags) { 7625 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7626 7627 // reader 7628 synchronized (mPackages) { 7629 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7630 while (i.hasNext()) { 7631 final PackageParser.Instrumentation p = i.next(); 7632 if (targetPackage == null 7633 || targetPackage.equals(p.info.targetPackage)) { 7634 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7635 flags); 7636 if (ii != null) { 7637 finalList.add(ii); 7638 } 7639 } 7640 } 7641 } 7642 7643 return finalList; 7644 } 7645 7646 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7648 try { 7649 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7650 } finally { 7651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7652 } 7653 } 7654 7655 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7656 final File[] files = dir.listFiles(); 7657 if (ArrayUtils.isEmpty(files)) { 7658 Log.d(TAG, "No files in app dir " + dir); 7659 return; 7660 } 7661 7662 if (DEBUG_PACKAGE_SCANNING) { 7663 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7664 + " flags=0x" + Integer.toHexString(parseFlags)); 7665 } 7666 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7667 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7668 7669 // Submit files for parsing in parallel 7670 int fileCount = 0; 7671 for (File file : files) { 7672 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7673 && !PackageInstallerService.isStageName(file.getName()); 7674 if (!isPackage) { 7675 // Ignore entries which are not packages 7676 continue; 7677 } 7678 parallelPackageParser.submit(file, parseFlags); 7679 fileCount++; 7680 } 7681 7682 // Process results one by one 7683 for (; fileCount > 0; fileCount--) { 7684 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7685 Throwable throwable = parseResult.throwable; 7686 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7687 7688 if (throwable == null) { 7689 // Static shared libraries have synthetic package names 7690 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7691 renameStaticSharedLibraryPackage(parseResult.pkg); 7692 } 7693 try { 7694 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7695 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7696 currentTime, null); 7697 } 7698 } catch (PackageManagerException e) { 7699 errorCode = e.error; 7700 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7701 } 7702 } else if (throwable instanceof PackageParser.PackageParserException) { 7703 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7704 throwable; 7705 errorCode = e.error; 7706 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7707 } else { 7708 throw new IllegalStateException("Unexpected exception occurred while parsing " 7709 + parseResult.scanFile, throwable); 7710 } 7711 7712 // Delete invalid userdata apps 7713 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7714 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7715 logCriticalInfo(Log.WARN, 7716 "Deleting invalid package at " + parseResult.scanFile); 7717 removeCodePathLI(parseResult.scanFile); 7718 } 7719 } 7720 parallelPackageParser.close(); 7721 } 7722 7723 private static File getSettingsProblemFile() { 7724 File dataDir = Environment.getDataDirectory(); 7725 File systemDir = new File(dataDir, "system"); 7726 File fname = new File(systemDir, "uiderrors.txt"); 7727 return fname; 7728 } 7729 7730 static void reportSettingsProblem(int priority, String msg) { 7731 logCriticalInfo(priority, msg); 7732 } 7733 7734 public static void logCriticalInfo(int priority, String msg) { 7735 Slog.println(priority, TAG, msg); 7736 EventLogTags.writePmCriticalInfo(msg); 7737 try { 7738 File fname = getSettingsProblemFile(); 7739 FileOutputStream out = new FileOutputStream(fname, true); 7740 PrintWriter pw = new FastPrintWriter(out); 7741 SimpleDateFormat formatter = new SimpleDateFormat(); 7742 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7743 pw.println(dateString + ": " + msg); 7744 pw.close(); 7745 FileUtils.setPermissions( 7746 fname.toString(), 7747 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7748 -1, -1); 7749 } catch (java.io.IOException e) { 7750 } 7751 } 7752 7753 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7754 if (srcFile.isDirectory()) { 7755 final File baseFile = new File(pkg.baseCodePath); 7756 long maxModifiedTime = baseFile.lastModified(); 7757 if (pkg.splitCodePaths != null) { 7758 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7759 final File splitFile = new File(pkg.splitCodePaths[i]); 7760 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7761 } 7762 } 7763 return maxModifiedTime; 7764 } 7765 return srcFile.lastModified(); 7766 } 7767 7768 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7769 final int policyFlags) throws PackageManagerException { 7770 // When upgrading from pre-N MR1, verify the package time stamp using the package 7771 // directory and not the APK file. 7772 final long lastModifiedTime = mIsPreNMR1Upgrade 7773 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7774 if (ps != null 7775 && ps.codePath.equals(srcFile) 7776 && ps.timeStamp == lastModifiedTime 7777 && !isCompatSignatureUpdateNeeded(pkg) 7778 && !isRecoverSignatureUpdateNeeded(pkg)) { 7779 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7780 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7781 ArraySet<PublicKey> signingKs; 7782 synchronized (mPackages) { 7783 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7784 } 7785 if (ps.signatures.mSignatures != null 7786 && ps.signatures.mSignatures.length != 0 7787 && signingKs != null) { 7788 // Optimization: reuse the existing cached certificates 7789 // if the package appears to be unchanged. 7790 pkg.mSignatures = ps.signatures.mSignatures; 7791 pkg.mSigningKeys = signingKs; 7792 return; 7793 } 7794 7795 Slog.w(TAG, "PackageSetting for " + ps.name 7796 + " is missing signatures. Collecting certs again to recover them."); 7797 } else { 7798 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7799 } 7800 7801 try { 7802 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7803 PackageParser.collectCertificates(pkg, policyFlags); 7804 } catch (PackageParserException e) { 7805 throw PackageManagerException.from(e); 7806 } finally { 7807 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7808 } 7809 } 7810 7811 /** 7812 * Traces a package scan. 7813 * @see #scanPackageLI(File, int, int, long, UserHandle) 7814 */ 7815 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7816 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7818 try { 7819 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7820 } finally { 7821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7822 } 7823 } 7824 7825 /** 7826 * Scans a package and returns the newly parsed package. 7827 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7828 */ 7829 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7830 long currentTime, UserHandle user) throws PackageManagerException { 7831 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7832 PackageParser pp = new PackageParser(); 7833 pp.setSeparateProcesses(mSeparateProcesses); 7834 pp.setOnlyCoreApps(mOnlyCore); 7835 pp.setDisplayMetrics(mMetrics); 7836 pp.setCallback(mPackageParserCallback); 7837 7838 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7839 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7840 } 7841 7842 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7843 final PackageParser.Package pkg; 7844 try { 7845 pkg = pp.parsePackage(scanFile, parseFlags); 7846 } catch (PackageParserException e) { 7847 throw PackageManagerException.from(e); 7848 } finally { 7849 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7850 } 7851 7852 // Static shared libraries have synthetic package names 7853 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7854 renameStaticSharedLibraryPackage(pkg); 7855 } 7856 7857 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7858 } 7859 7860 /** 7861 * Scans a package and returns the newly parsed package. 7862 * @throws PackageManagerException on a parse error. 7863 */ 7864 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7865 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7866 throws PackageManagerException { 7867 // If the package has children and this is the first dive in the function 7868 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7869 // packages (parent and children) would be successfully scanned before the 7870 // actual scan since scanning mutates internal state and we want to atomically 7871 // install the package and its children. 7872 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7873 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7874 scanFlags |= SCAN_CHECK_ONLY; 7875 } 7876 } else { 7877 scanFlags &= ~SCAN_CHECK_ONLY; 7878 } 7879 7880 // Scan the parent 7881 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7882 scanFlags, currentTime, user); 7883 7884 // Scan the children 7885 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7886 for (int i = 0; i < childCount; i++) { 7887 PackageParser.Package childPackage = pkg.childPackages.get(i); 7888 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7889 currentTime, user); 7890 } 7891 7892 7893 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7894 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7895 } 7896 7897 return scannedPkg; 7898 } 7899 7900 /** 7901 * Scans a package and returns the newly parsed package. 7902 * @throws PackageManagerException on a parse error. 7903 */ 7904 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7905 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7906 throws PackageManagerException { 7907 PackageSetting ps = null; 7908 PackageSetting updatedPkg; 7909 // reader 7910 synchronized (mPackages) { 7911 // Look to see if we already know about this package. 7912 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7913 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7914 // This package has been renamed to its original name. Let's 7915 // use that. 7916 ps = mSettings.getPackageLPr(oldName); 7917 } 7918 // If there was no original package, see one for the real package name. 7919 if (ps == null) { 7920 ps = mSettings.getPackageLPr(pkg.packageName); 7921 } 7922 // Check to see if this package could be hiding/updating a system 7923 // package. Must look for it either under the original or real 7924 // package name depending on our state. 7925 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7926 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7927 7928 // If this is a package we don't know about on the system partition, we 7929 // may need to remove disabled child packages on the system partition 7930 // or may need to not add child packages if the parent apk is updated 7931 // on the data partition and no longer defines this child package. 7932 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7933 // If this is a parent package for an updated system app and this system 7934 // app got an OTA update which no longer defines some of the child packages 7935 // we have to prune them from the disabled system packages. 7936 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7937 if (disabledPs != null) { 7938 final int scannedChildCount = (pkg.childPackages != null) 7939 ? pkg.childPackages.size() : 0; 7940 final int disabledChildCount = disabledPs.childPackageNames != null 7941 ? disabledPs.childPackageNames.size() : 0; 7942 for (int i = 0; i < disabledChildCount; i++) { 7943 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7944 boolean disabledPackageAvailable = false; 7945 for (int j = 0; j < scannedChildCount; j++) { 7946 PackageParser.Package childPkg = pkg.childPackages.get(j); 7947 if (childPkg.packageName.equals(disabledChildPackageName)) { 7948 disabledPackageAvailable = true; 7949 break; 7950 } 7951 } 7952 if (!disabledPackageAvailable) { 7953 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7954 } 7955 } 7956 } 7957 } 7958 } 7959 7960 boolean updatedPkgBetter = false; 7961 // First check if this is a system package that may involve an update 7962 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7963 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7964 // it needs to drop FLAG_PRIVILEGED. 7965 if (locationIsPrivileged(scanFile)) { 7966 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7967 } else { 7968 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7969 } 7970 7971 if (ps != null && !ps.codePath.equals(scanFile)) { 7972 // The path has changed from what was last scanned... check the 7973 // version of the new path against what we have stored to determine 7974 // what to do. 7975 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7976 if (pkg.mVersionCode <= ps.versionCode) { 7977 // The system package has been updated and the code path does not match 7978 // Ignore entry. Skip it. 7979 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7980 + " ignored: updated version " + ps.versionCode 7981 + " better than this " + pkg.mVersionCode); 7982 if (!updatedPkg.codePath.equals(scanFile)) { 7983 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7984 + ps.name + " changing from " + updatedPkg.codePathString 7985 + " to " + scanFile); 7986 updatedPkg.codePath = scanFile; 7987 updatedPkg.codePathString = scanFile.toString(); 7988 updatedPkg.resourcePath = scanFile; 7989 updatedPkg.resourcePathString = scanFile.toString(); 7990 } 7991 updatedPkg.pkg = pkg; 7992 updatedPkg.versionCode = pkg.mVersionCode; 7993 7994 // Update the disabled system child packages to point to the package too. 7995 final int childCount = updatedPkg.childPackageNames != null 7996 ? updatedPkg.childPackageNames.size() : 0; 7997 for (int i = 0; i < childCount; i++) { 7998 String childPackageName = updatedPkg.childPackageNames.get(i); 7999 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8000 childPackageName); 8001 if (updatedChildPkg != null) { 8002 updatedChildPkg.pkg = pkg; 8003 updatedChildPkg.versionCode = pkg.mVersionCode; 8004 } 8005 } 8006 8007 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8008 + scanFile + " ignored: updated version " + ps.versionCode 8009 + " better than this " + pkg.mVersionCode); 8010 } else { 8011 // The current app on the system partition is better than 8012 // what we have updated to on the data partition; switch 8013 // back to the system partition version. 8014 // At this point, its safely assumed that package installation for 8015 // apps in system partition will go through. If not there won't be a working 8016 // version of the app 8017 // writer 8018 synchronized (mPackages) { 8019 // Just remove the loaded entries from package lists. 8020 mPackages.remove(ps.name); 8021 } 8022 8023 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8024 + " reverting from " + ps.codePathString 8025 + ": new version " + pkg.mVersionCode 8026 + " better than installed " + ps.versionCode); 8027 8028 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8029 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8030 synchronized (mInstallLock) { 8031 args.cleanUpResourcesLI(); 8032 } 8033 synchronized (mPackages) { 8034 mSettings.enableSystemPackageLPw(ps.name); 8035 } 8036 updatedPkgBetter = true; 8037 } 8038 } 8039 } 8040 8041 if (updatedPkg != null) { 8042 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8043 // initially 8044 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8045 8046 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8047 // flag set initially 8048 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8049 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8050 } 8051 } 8052 8053 // Verify certificates against what was last scanned 8054 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8055 8056 /* 8057 * A new system app appeared, but we already had a non-system one of the 8058 * same name installed earlier. 8059 */ 8060 boolean shouldHideSystemApp = false; 8061 if (updatedPkg == null && ps != null 8062 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8063 /* 8064 * Check to make sure the signatures match first. If they don't, 8065 * wipe the installed application and its data. 8066 */ 8067 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8068 != PackageManager.SIGNATURE_MATCH) { 8069 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8070 + " signatures don't match existing userdata copy; removing"); 8071 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8072 "scanPackageInternalLI")) { 8073 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8074 } 8075 ps = null; 8076 } else { 8077 /* 8078 * If the newly-added system app is an older version than the 8079 * already installed version, hide it. It will be scanned later 8080 * and re-added like an update. 8081 */ 8082 if (pkg.mVersionCode <= ps.versionCode) { 8083 shouldHideSystemApp = true; 8084 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8085 + " but new version " + pkg.mVersionCode + " better than installed " 8086 + ps.versionCode + "; hiding system"); 8087 } else { 8088 /* 8089 * The newly found system app is a newer version that the 8090 * one previously installed. Simply remove the 8091 * already-installed application and replace it with our own 8092 * while keeping the application data. 8093 */ 8094 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8095 + " reverting from " + ps.codePathString + ": new version " 8096 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8097 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8098 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8099 synchronized (mInstallLock) { 8100 args.cleanUpResourcesLI(); 8101 } 8102 } 8103 } 8104 } 8105 8106 // The apk is forward locked (not public) if its code and resources 8107 // are kept in different files. (except for app in either system or 8108 // vendor path). 8109 // TODO grab this value from PackageSettings 8110 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8111 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8112 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8113 } 8114 } 8115 8116 // TODO: extend to support forward-locked splits 8117 String resourcePath = null; 8118 String baseResourcePath = null; 8119 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8120 if (ps != null && ps.resourcePathString != null) { 8121 resourcePath = ps.resourcePathString; 8122 baseResourcePath = ps.resourcePathString; 8123 } else { 8124 // Should not happen at all. Just log an error. 8125 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8126 } 8127 } else { 8128 resourcePath = pkg.codePath; 8129 baseResourcePath = pkg.baseCodePath; 8130 } 8131 8132 // Set application objects path explicitly. 8133 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8134 pkg.setApplicationInfoCodePath(pkg.codePath); 8135 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8136 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8137 pkg.setApplicationInfoResourcePath(resourcePath); 8138 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8139 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8140 8141 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8142 if (ps != null && ps.getInstantApp(userId)) { 8143 scanFlags |= SCAN_AS_INSTANT_APP; 8144 } 8145 8146 // Note that we invoke the following method only if we are about to unpack an application 8147 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8148 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8149 8150 /* 8151 * If the system app should be overridden by a previously installed 8152 * data, hide the system app now and let the /data/app scan pick it up 8153 * again. 8154 */ 8155 if (shouldHideSystemApp) { 8156 synchronized (mPackages) { 8157 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8158 } 8159 } 8160 8161 return scannedPkg; 8162 } 8163 8164 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8165 // Derive the new package synthetic package name 8166 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8167 + pkg.staticSharedLibVersion); 8168 } 8169 8170 private static String fixProcessName(String defProcessName, 8171 String processName) { 8172 if (processName == null) { 8173 return defProcessName; 8174 } 8175 return processName; 8176 } 8177 8178 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8179 throws PackageManagerException { 8180 if (pkgSetting.signatures.mSignatures != null) { 8181 // Already existing package. Make sure signatures match 8182 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8183 == PackageManager.SIGNATURE_MATCH; 8184 if (!match) { 8185 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8186 == PackageManager.SIGNATURE_MATCH; 8187 } 8188 if (!match) { 8189 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8190 == PackageManager.SIGNATURE_MATCH; 8191 } 8192 if (!match) { 8193 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8194 + pkg.packageName + " signatures do not match the " 8195 + "previously installed version; ignoring!"); 8196 } 8197 } 8198 8199 // Check for shared user signatures 8200 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8201 // Already existing package. Make sure signatures match 8202 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8203 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8204 if (!match) { 8205 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8206 == PackageManager.SIGNATURE_MATCH; 8207 } 8208 if (!match) { 8209 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8210 == PackageManager.SIGNATURE_MATCH; 8211 } 8212 if (!match) { 8213 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8214 "Package " + pkg.packageName 8215 + " has no signatures that match those in shared user " 8216 + pkgSetting.sharedUser.name + "; ignoring!"); 8217 } 8218 } 8219 } 8220 8221 /** 8222 * Enforces that only the system UID or root's UID can call a method exposed 8223 * via Binder. 8224 * 8225 * @param message used as message if SecurityException is thrown 8226 * @throws SecurityException if the caller is not system or root 8227 */ 8228 private static final void enforceSystemOrRoot(String message) { 8229 final int uid = Binder.getCallingUid(); 8230 if (uid != Process.SYSTEM_UID && uid != 0) { 8231 throw new SecurityException(message); 8232 } 8233 } 8234 8235 @Override 8236 public void performFstrimIfNeeded() { 8237 enforceSystemOrRoot("Only the system can request fstrim"); 8238 8239 // Before everything else, see whether we need to fstrim. 8240 try { 8241 IStorageManager sm = PackageHelper.getStorageManager(); 8242 if (sm != null) { 8243 boolean doTrim = false; 8244 final long interval = android.provider.Settings.Global.getLong( 8245 mContext.getContentResolver(), 8246 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8247 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8248 if (interval > 0) { 8249 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8250 if (timeSinceLast > interval) { 8251 doTrim = true; 8252 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8253 + "; running immediately"); 8254 } 8255 } 8256 if (doTrim) { 8257 final boolean dexOptDialogShown; 8258 synchronized (mPackages) { 8259 dexOptDialogShown = mDexOptDialogShown; 8260 } 8261 if (!isFirstBoot() && dexOptDialogShown) { 8262 try { 8263 ActivityManager.getService().showBootMessage( 8264 mContext.getResources().getString( 8265 R.string.android_upgrading_fstrim), true); 8266 } catch (RemoteException e) { 8267 } 8268 } 8269 sm.runMaintenance(); 8270 } 8271 } else { 8272 Slog.e(TAG, "storageManager service unavailable!"); 8273 } 8274 } catch (RemoteException e) { 8275 // Can't happen; StorageManagerService is local 8276 } 8277 } 8278 8279 @Override 8280 public void updatePackagesIfNeeded() { 8281 enforceSystemOrRoot("Only the system can request package update"); 8282 8283 // We need to re-extract after an OTA. 8284 boolean causeUpgrade = isUpgrade(); 8285 8286 // First boot or factory reset. 8287 // Note: we also handle devices that are upgrading to N right now as if it is their 8288 // first boot, as they do not have profile data. 8289 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8290 8291 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8292 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8293 8294 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8295 return; 8296 } 8297 8298 List<PackageParser.Package> pkgs; 8299 synchronized (mPackages) { 8300 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8301 } 8302 8303 final long startTime = System.nanoTime(); 8304 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8305 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8306 8307 final int elapsedTimeSeconds = 8308 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8309 8310 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8311 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8312 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8313 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8314 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8315 } 8316 8317 /** 8318 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8319 * containing statistics about the invocation. The array consists of three elements, 8320 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8321 * and {@code numberOfPackagesFailed}. 8322 */ 8323 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8324 String compilerFilter) { 8325 8326 int numberOfPackagesVisited = 0; 8327 int numberOfPackagesOptimized = 0; 8328 int numberOfPackagesSkipped = 0; 8329 int numberOfPackagesFailed = 0; 8330 final int numberOfPackagesToDexopt = pkgs.size(); 8331 8332 for (PackageParser.Package pkg : pkgs) { 8333 numberOfPackagesVisited++; 8334 8335 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8336 if (DEBUG_DEXOPT) { 8337 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8338 } 8339 numberOfPackagesSkipped++; 8340 continue; 8341 } 8342 8343 if (DEBUG_DEXOPT) { 8344 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8345 numberOfPackagesToDexopt + ": " + pkg.packageName); 8346 } 8347 8348 if (showDialog) { 8349 try { 8350 ActivityManager.getService().showBootMessage( 8351 mContext.getResources().getString(R.string.android_upgrading_apk, 8352 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8353 } catch (RemoteException e) { 8354 } 8355 synchronized (mPackages) { 8356 mDexOptDialogShown = true; 8357 } 8358 } 8359 8360 // If the OTA updates a system app which was previously preopted to a non-preopted state 8361 // the app might end up being verified at runtime. That's because by default the apps 8362 // are verify-profile but for preopted apps there's no profile. 8363 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8364 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8365 // filter (by default interpret-only). 8366 // Note that at this stage unused apps are already filtered. 8367 if (isSystemApp(pkg) && 8368 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8369 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8370 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8371 } 8372 8373 // checkProfiles is false to avoid merging profiles during boot which 8374 // might interfere with background compilation (b/28612421). 8375 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8376 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8377 // trade-off worth doing to save boot time work. 8378 int dexOptStatus = performDexOptTraced(pkg.packageName, 8379 false /* checkProfiles */, 8380 compilerFilter, 8381 false /* force */); 8382 switch (dexOptStatus) { 8383 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8384 numberOfPackagesOptimized++; 8385 break; 8386 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8387 numberOfPackagesSkipped++; 8388 break; 8389 case PackageDexOptimizer.DEX_OPT_FAILED: 8390 numberOfPackagesFailed++; 8391 break; 8392 default: 8393 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8394 break; 8395 } 8396 } 8397 8398 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8399 numberOfPackagesFailed }; 8400 } 8401 8402 @Override 8403 public void notifyPackageUse(String packageName, int reason) { 8404 synchronized (mPackages) { 8405 PackageParser.Package p = mPackages.get(packageName); 8406 if (p == null) { 8407 return; 8408 } 8409 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8410 } 8411 } 8412 8413 @Override 8414 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8415 int userId = UserHandle.getCallingUserId(); 8416 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8417 if (ai == null) { 8418 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8419 + loadingPackageName + ", user=" + userId); 8420 return; 8421 } 8422 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8423 } 8424 8425 // TODO: this is not used nor needed. Delete it. 8426 @Override 8427 public boolean performDexOptIfNeeded(String packageName) { 8428 int dexOptStatus = performDexOptTraced(packageName, 8429 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8430 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8431 } 8432 8433 @Override 8434 public boolean performDexOpt(String packageName, 8435 boolean checkProfiles, int compileReason, boolean force) { 8436 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8437 getCompilerFilterForReason(compileReason), force); 8438 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8439 } 8440 8441 @Override 8442 public boolean performDexOptMode(String packageName, 8443 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8444 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8445 targetCompilerFilter, force); 8446 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8447 } 8448 8449 private int performDexOptTraced(String packageName, 8450 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8451 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8452 try { 8453 return performDexOptInternal(packageName, checkProfiles, 8454 targetCompilerFilter, force); 8455 } finally { 8456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8457 } 8458 } 8459 8460 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8461 // if the package can now be considered up to date for the given filter. 8462 private int performDexOptInternal(String packageName, 8463 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8464 PackageParser.Package p; 8465 synchronized (mPackages) { 8466 p = mPackages.get(packageName); 8467 if (p == null) { 8468 // Package could not be found. Report failure. 8469 return PackageDexOptimizer.DEX_OPT_FAILED; 8470 } 8471 mPackageUsage.maybeWriteAsync(mPackages); 8472 mCompilerStats.maybeWriteAsync(); 8473 } 8474 long callingId = Binder.clearCallingIdentity(); 8475 try { 8476 synchronized (mInstallLock) { 8477 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8478 targetCompilerFilter, force); 8479 } 8480 } finally { 8481 Binder.restoreCallingIdentity(callingId); 8482 } 8483 } 8484 8485 public ArraySet<String> getOptimizablePackages() { 8486 ArraySet<String> pkgs = new ArraySet<String>(); 8487 synchronized (mPackages) { 8488 for (PackageParser.Package p : mPackages.values()) { 8489 if (PackageDexOptimizer.canOptimizePackage(p)) { 8490 pkgs.add(p.packageName); 8491 } 8492 } 8493 } 8494 return pkgs; 8495 } 8496 8497 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8498 boolean checkProfiles, String targetCompilerFilter, 8499 boolean force) { 8500 // Select the dex optimizer based on the force parameter. 8501 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8502 // allocate an object here. 8503 PackageDexOptimizer pdo = force 8504 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8505 : mPackageDexOptimizer; 8506 8507 // Dexopt all dependencies first. Note: we ignore the return value and march on 8508 // on errors. 8509 // Note that we are going to call performDexOpt on those libraries as many times as 8510 // they are referenced in packages. When we do a batch of performDexOpt (for example 8511 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8512 // and the first package that uses the library will dexopt it. The 8513 // others will see that the compiled code for the library is up to date. 8514 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8515 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8516 if (!deps.isEmpty()) { 8517 for (PackageParser.Package depPackage : deps) { 8518 // TODO: Analyze and investigate if we (should) profile libraries. 8519 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8520 false /* checkProfiles */, 8521 targetCompilerFilter, 8522 getOrCreateCompilerPackageStats(depPackage), 8523 true /* isUsedByOtherApps */); 8524 } 8525 } 8526 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8527 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8528 mDexManager.isUsedByOtherApps(p.packageName)); 8529 } 8530 8531 // Performs dexopt on the used secondary dex files belonging to the given package. 8532 // Returns true if all dex files were process successfully (which could mean either dexopt or 8533 // skip). Returns false if any of the files caused errors. 8534 @Override 8535 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8536 boolean force) { 8537 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8538 } 8539 8540 public boolean performDexOptSecondary(String packageName, int compileReason, 8541 boolean force) { 8542 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8543 } 8544 8545 /** 8546 * Reconcile the information we have about the secondary dex files belonging to 8547 * {@code packagName} and the actual dex files. For all dex files that were 8548 * deleted, update the internal records and delete the generated oat files. 8549 */ 8550 @Override 8551 public void reconcileSecondaryDexFiles(String packageName) { 8552 mDexManager.reconcileSecondaryDexFiles(packageName); 8553 } 8554 8555 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8556 // a reference there. 8557 /*package*/ DexManager getDexManager() { 8558 return mDexManager; 8559 } 8560 8561 /** 8562 * Execute the background dexopt job immediately. 8563 */ 8564 @Override 8565 public boolean runBackgroundDexoptJob() { 8566 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8567 } 8568 8569 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8570 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8571 || p.usesStaticLibraries != null) { 8572 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8573 Set<String> collectedNames = new HashSet<>(); 8574 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8575 8576 retValue.remove(p); 8577 8578 return retValue; 8579 } else { 8580 return Collections.emptyList(); 8581 } 8582 } 8583 8584 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8585 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8586 if (!collectedNames.contains(p.packageName)) { 8587 collectedNames.add(p.packageName); 8588 collected.add(p); 8589 8590 if (p.usesLibraries != null) { 8591 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8592 null, collected, collectedNames); 8593 } 8594 if (p.usesOptionalLibraries != null) { 8595 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8596 null, collected, collectedNames); 8597 } 8598 if (p.usesStaticLibraries != null) { 8599 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8600 p.usesStaticLibrariesVersions, collected, collectedNames); 8601 } 8602 } 8603 } 8604 8605 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8606 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8607 final int libNameCount = libs.size(); 8608 for (int i = 0; i < libNameCount; i++) { 8609 String libName = libs.get(i); 8610 int version = (versions != null && versions.length == libNameCount) 8611 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8612 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8613 if (libPkg != null) { 8614 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8615 } 8616 } 8617 } 8618 8619 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8620 synchronized (mPackages) { 8621 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8622 if (libEntry != null) { 8623 return mPackages.get(libEntry.apk); 8624 } 8625 return null; 8626 } 8627 } 8628 8629 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8630 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8631 if (versionedLib == null) { 8632 return null; 8633 } 8634 return versionedLib.get(version); 8635 } 8636 8637 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8638 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8639 pkg.staticSharedLibName); 8640 if (versionedLib == null) { 8641 return null; 8642 } 8643 int previousLibVersion = -1; 8644 final int versionCount = versionedLib.size(); 8645 for (int i = 0; i < versionCount; i++) { 8646 final int libVersion = versionedLib.keyAt(i); 8647 if (libVersion < pkg.staticSharedLibVersion) { 8648 previousLibVersion = Math.max(previousLibVersion, libVersion); 8649 } 8650 } 8651 if (previousLibVersion >= 0) { 8652 return versionedLib.get(previousLibVersion); 8653 } 8654 return null; 8655 } 8656 8657 public void shutdown() { 8658 mPackageUsage.writeNow(mPackages); 8659 mCompilerStats.writeNow(); 8660 } 8661 8662 @Override 8663 public void dumpProfiles(String packageName) { 8664 PackageParser.Package pkg; 8665 synchronized (mPackages) { 8666 pkg = mPackages.get(packageName); 8667 if (pkg == null) { 8668 throw new IllegalArgumentException("Unknown package: " + packageName); 8669 } 8670 } 8671 /* Only the shell, root, or the app user should be able to dump profiles. */ 8672 int callingUid = Binder.getCallingUid(); 8673 if (callingUid != Process.SHELL_UID && 8674 callingUid != Process.ROOT_UID && 8675 callingUid != pkg.applicationInfo.uid) { 8676 throw new SecurityException("dumpProfiles"); 8677 } 8678 8679 synchronized (mInstallLock) { 8680 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8681 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8682 try { 8683 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8684 String codePaths = TextUtils.join(";", allCodePaths); 8685 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8686 } catch (InstallerException e) { 8687 Slog.w(TAG, "Failed to dump profiles", e); 8688 } 8689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8690 } 8691 } 8692 8693 @Override 8694 public void forceDexOpt(String packageName) { 8695 enforceSystemOrRoot("forceDexOpt"); 8696 8697 PackageParser.Package pkg; 8698 synchronized (mPackages) { 8699 pkg = mPackages.get(packageName); 8700 if (pkg == null) { 8701 throw new IllegalArgumentException("Unknown package: " + packageName); 8702 } 8703 } 8704 8705 synchronized (mInstallLock) { 8706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8707 8708 // Whoever is calling forceDexOpt wants a fully compiled package. 8709 // Don't use profiles since that may cause compilation to be skipped. 8710 final int res = performDexOptInternalWithDependenciesLI(pkg, 8711 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8712 true /* force */); 8713 8714 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8715 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8716 throw new IllegalStateException("Failed to dexopt: " + res); 8717 } 8718 } 8719 } 8720 8721 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8722 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8723 Slog.w(TAG, "Unable to update from " + oldPkg.name 8724 + " to " + newPkg.packageName 8725 + ": old package not in system partition"); 8726 return false; 8727 } else if (mPackages.get(oldPkg.name) != null) { 8728 Slog.w(TAG, "Unable to update from " + oldPkg.name 8729 + " to " + newPkg.packageName 8730 + ": old package still exists"); 8731 return false; 8732 } 8733 return true; 8734 } 8735 8736 void removeCodePathLI(File codePath) { 8737 if (codePath.isDirectory()) { 8738 try { 8739 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8740 } catch (InstallerException e) { 8741 Slog.w(TAG, "Failed to remove code path", e); 8742 } 8743 } else { 8744 codePath.delete(); 8745 } 8746 } 8747 8748 private int[] resolveUserIds(int userId) { 8749 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8750 } 8751 8752 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8753 if (pkg == null) { 8754 Slog.wtf(TAG, "Package was null!", new Throwable()); 8755 return; 8756 } 8757 clearAppDataLeafLIF(pkg, userId, flags); 8758 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8759 for (int i = 0; i < childCount; i++) { 8760 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8761 } 8762 } 8763 8764 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8765 final PackageSetting ps; 8766 synchronized (mPackages) { 8767 ps = mSettings.mPackages.get(pkg.packageName); 8768 } 8769 for (int realUserId : resolveUserIds(userId)) { 8770 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8771 try { 8772 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8773 ceDataInode); 8774 } catch (InstallerException e) { 8775 Slog.w(TAG, String.valueOf(e)); 8776 } 8777 } 8778 } 8779 8780 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8781 if (pkg == null) { 8782 Slog.wtf(TAG, "Package was null!", new Throwable()); 8783 return; 8784 } 8785 destroyAppDataLeafLIF(pkg, userId, flags); 8786 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8787 for (int i = 0; i < childCount; i++) { 8788 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8789 } 8790 } 8791 8792 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8793 final PackageSetting ps; 8794 synchronized (mPackages) { 8795 ps = mSettings.mPackages.get(pkg.packageName); 8796 } 8797 for (int realUserId : resolveUserIds(userId)) { 8798 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8799 try { 8800 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8801 ceDataInode); 8802 } catch (InstallerException e) { 8803 Slog.w(TAG, String.valueOf(e)); 8804 } 8805 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8806 } 8807 } 8808 8809 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8810 if (pkg == null) { 8811 Slog.wtf(TAG, "Package was null!", new Throwable()); 8812 return; 8813 } 8814 destroyAppProfilesLeafLIF(pkg); 8815 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8816 for (int i = 0; i < childCount; i++) { 8817 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8818 } 8819 } 8820 8821 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8822 try { 8823 mInstaller.destroyAppProfiles(pkg.packageName); 8824 } catch (InstallerException e) { 8825 Slog.w(TAG, String.valueOf(e)); 8826 } 8827 } 8828 8829 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8830 if (pkg == null) { 8831 Slog.wtf(TAG, "Package was null!", new Throwable()); 8832 return; 8833 } 8834 clearAppProfilesLeafLIF(pkg); 8835 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8836 for (int i = 0; i < childCount; i++) { 8837 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8838 } 8839 } 8840 8841 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8842 try { 8843 mInstaller.clearAppProfiles(pkg.packageName); 8844 } catch (InstallerException e) { 8845 Slog.w(TAG, String.valueOf(e)); 8846 } 8847 } 8848 8849 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8850 long lastUpdateTime) { 8851 // Set parent install/update time 8852 PackageSetting ps = (PackageSetting) pkg.mExtras; 8853 if (ps != null) { 8854 ps.firstInstallTime = firstInstallTime; 8855 ps.lastUpdateTime = lastUpdateTime; 8856 } 8857 // Set children install/update time 8858 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8859 for (int i = 0; i < childCount; i++) { 8860 PackageParser.Package childPkg = pkg.childPackages.get(i); 8861 ps = (PackageSetting) childPkg.mExtras; 8862 if (ps != null) { 8863 ps.firstInstallTime = firstInstallTime; 8864 ps.lastUpdateTime = lastUpdateTime; 8865 } 8866 } 8867 } 8868 8869 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8870 PackageParser.Package changingLib) { 8871 if (file.path != null) { 8872 usesLibraryFiles.add(file.path); 8873 return; 8874 } 8875 PackageParser.Package p = mPackages.get(file.apk); 8876 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8877 // If we are doing this while in the middle of updating a library apk, 8878 // then we need to make sure to use that new apk for determining the 8879 // dependencies here. (We haven't yet finished committing the new apk 8880 // to the package manager state.) 8881 if (p == null || p.packageName.equals(changingLib.packageName)) { 8882 p = changingLib; 8883 } 8884 } 8885 if (p != null) { 8886 usesLibraryFiles.addAll(p.getAllCodePaths()); 8887 } 8888 } 8889 8890 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8891 PackageParser.Package changingLib) throws PackageManagerException { 8892 if (pkg == null) { 8893 return; 8894 } 8895 ArraySet<String> usesLibraryFiles = null; 8896 if (pkg.usesLibraries != null) { 8897 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8898 null, null, pkg.packageName, changingLib, true, null); 8899 } 8900 if (pkg.usesStaticLibraries != null) { 8901 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8902 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8903 pkg.packageName, changingLib, true, usesLibraryFiles); 8904 } 8905 if (pkg.usesOptionalLibraries != null) { 8906 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8907 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8908 } 8909 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8910 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8911 } else { 8912 pkg.usesLibraryFiles = null; 8913 } 8914 } 8915 8916 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8917 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8918 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8919 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8920 throws PackageManagerException { 8921 final int libCount = requestedLibraries.size(); 8922 for (int i = 0; i < libCount; i++) { 8923 final String libName = requestedLibraries.get(i); 8924 final int libVersion = requiredVersions != null ? requiredVersions[i] 8925 : SharedLibraryInfo.VERSION_UNDEFINED; 8926 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8927 if (libEntry == null) { 8928 if (required) { 8929 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8930 "Package " + packageName + " requires unavailable shared library " 8931 + libName + "; failing!"); 8932 } else { 8933 Slog.w(TAG, "Package " + packageName 8934 + " desires unavailable shared library " 8935 + libName + "; ignoring!"); 8936 } 8937 } else { 8938 if (requiredVersions != null && requiredCertDigests != null) { 8939 if (libEntry.info.getVersion() != requiredVersions[i]) { 8940 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8941 "Package " + packageName + " requires unavailable static shared" 8942 + " library " + libName + " version " 8943 + libEntry.info.getVersion() + "; failing!"); 8944 } 8945 8946 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8947 if (libPkg == null) { 8948 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8949 "Package " + packageName + " requires unavailable static shared" 8950 + " library; failing!"); 8951 } 8952 8953 String expectedCertDigest = requiredCertDigests[i]; 8954 String libCertDigest = PackageUtils.computeCertSha256Digest( 8955 libPkg.mSignatures[0]); 8956 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8957 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8958 "Package " + packageName + " requires differently signed" + 8959 " static shared library; failing!"); 8960 } 8961 } 8962 8963 if (outUsedLibraries == null) { 8964 outUsedLibraries = new ArraySet<>(); 8965 } 8966 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8967 } 8968 } 8969 return outUsedLibraries; 8970 } 8971 8972 private static boolean hasString(List<String> list, List<String> which) { 8973 if (list == null) { 8974 return false; 8975 } 8976 for (int i=list.size()-1; i>=0; i--) { 8977 for (int j=which.size()-1; j>=0; j--) { 8978 if (which.get(j).equals(list.get(i))) { 8979 return true; 8980 } 8981 } 8982 } 8983 return false; 8984 } 8985 8986 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8987 PackageParser.Package changingPkg) { 8988 ArrayList<PackageParser.Package> res = null; 8989 for (PackageParser.Package pkg : mPackages.values()) { 8990 if (changingPkg != null 8991 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8992 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8993 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8994 changingPkg.staticSharedLibName)) { 8995 return null; 8996 } 8997 if (res == null) { 8998 res = new ArrayList<>(); 8999 } 9000 res.add(pkg); 9001 try { 9002 updateSharedLibrariesLPr(pkg, changingPkg); 9003 } catch (PackageManagerException e) { 9004 // If a system app update or an app and a required lib missing we 9005 // delete the package and for updated system apps keep the data as 9006 // it is better for the user to reinstall than to be in an limbo 9007 // state. Also libs disappearing under an app should never happen 9008 // - just in case. 9009 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9010 final int flags = pkg.isUpdatedSystemApp() 9011 ? PackageManager.DELETE_KEEP_DATA : 0; 9012 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9013 flags , null, true, null); 9014 } 9015 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9016 } 9017 } 9018 return res; 9019 } 9020 9021 /** 9022 * Derive the value of the {@code cpuAbiOverride} based on the provided 9023 * value and an optional stored value from the package settings. 9024 */ 9025 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9026 String cpuAbiOverride = null; 9027 9028 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9029 cpuAbiOverride = null; 9030 } else if (abiOverride != null) { 9031 cpuAbiOverride = abiOverride; 9032 } else if (settings != null) { 9033 cpuAbiOverride = settings.cpuAbiOverrideString; 9034 } 9035 9036 return cpuAbiOverride; 9037 } 9038 9039 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9040 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9041 throws PackageManagerException { 9042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9043 // If the package has children and this is the first dive in the function 9044 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9045 // whether all packages (parent and children) would be successfully scanned 9046 // before the actual scan since scanning mutates internal state and we want 9047 // to atomically install the package and its children. 9048 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9049 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9050 scanFlags |= SCAN_CHECK_ONLY; 9051 } 9052 } else { 9053 scanFlags &= ~SCAN_CHECK_ONLY; 9054 } 9055 9056 final PackageParser.Package scannedPkg; 9057 try { 9058 // Scan the parent 9059 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9060 // Scan the children 9061 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9062 for (int i = 0; i < childCount; i++) { 9063 PackageParser.Package childPkg = pkg.childPackages.get(i); 9064 scanPackageLI(childPkg, policyFlags, 9065 scanFlags, currentTime, user); 9066 } 9067 } finally { 9068 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9069 } 9070 9071 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9072 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9073 } 9074 9075 return scannedPkg; 9076 } 9077 9078 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9079 int scanFlags, long currentTime, @Nullable UserHandle user) 9080 throws PackageManagerException { 9081 boolean success = false; 9082 try { 9083 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9084 currentTime, user); 9085 success = true; 9086 return res; 9087 } finally { 9088 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9089 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9090 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9091 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9092 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9093 } 9094 } 9095 } 9096 9097 /** 9098 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9099 */ 9100 private static boolean apkHasCode(String fileName) { 9101 StrictJarFile jarFile = null; 9102 try { 9103 jarFile = new StrictJarFile(fileName, 9104 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9105 return jarFile.findEntry("classes.dex") != null; 9106 } catch (IOException ignore) { 9107 } finally { 9108 try { 9109 if (jarFile != null) { 9110 jarFile.close(); 9111 } 9112 } catch (IOException ignore) {} 9113 } 9114 return false; 9115 } 9116 9117 /** 9118 * Enforces code policy for the package. This ensures that if an APK has 9119 * declared hasCode="true" in its manifest that the APK actually contains 9120 * code. 9121 * 9122 * @throws PackageManagerException If bytecode could not be found when it should exist 9123 */ 9124 private static void assertCodePolicy(PackageParser.Package pkg) 9125 throws PackageManagerException { 9126 final boolean shouldHaveCode = 9127 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9128 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9129 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9130 "Package " + pkg.baseCodePath + " code is missing"); 9131 } 9132 9133 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9134 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9135 final boolean splitShouldHaveCode = 9136 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9137 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9138 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9139 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9140 } 9141 } 9142 } 9143 } 9144 9145 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9146 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9147 throws PackageManagerException { 9148 if (DEBUG_PACKAGE_SCANNING) { 9149 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9150 Log.d(TAG, "Scanning package " + pkg.packageName); 9151 } 9152 9153 applyPolicy(pkg, policyFlags); 9154 9155 assertPackageIsValid(pkg, policyFlags, scanFlags); 9156 9157 // Initialize package source and resource directories 9158 final File scanFile = new File(pkg.codePath); 9159 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9160 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9161 9162 SharedUserSetting suid = null; 9163 PackageSetting pkgSetting = null; 9164 9165 // Getting the package setting may have a side-effect, so if we 9166 // are only checking if scan would succeed, stash a copy of the 9167 // old setting to restore at the end. 9168 PackageSetting nonMutatedPs = null; 9169 9170 // We keep references to the derived CPU Abis from settings in oder to reuse 9171 // them in the case where we're not upgrading or booting for the first time. 9172 String primaryCpuAbiFromSettings = null; 9173 String secondaryCpuAbiFromSettings = null; 9174 9175 // writer 9176 synchronized (mPackages) { 9177 if (pkg.mSharedUserId != null) { 9178 // SIDE EFFECTS; may potentially allocate a new shared user 9179 suid = mSettings.getSharedUserLPw( 9180 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9181 if (DEBUG_PACKAGE_SCANNING) { 9182 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9183 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9184 + "): packages=" + suid.packages); 9185 } 9186 } 9187 9188 // Check if we are renaming from an original package name. 9189 PackageSetting origPackage = null; 9190 String realName = null; 9191 if (pkg.mOriginalPackages != null) { 9192 // This package may need to be renamed to a previously 9193 // installed name. Let's check on that... 9194 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9195 if (pkg.mOriginalPackages.contains(renamed)) { 9196 // This package had originally been installed as the 9197 // original name, and we have already taken care of 9198 // transitioning to the new one. Just update the new 9199 // one to continue using the old name. 9200 realName = pkg.mRealPackage; 9201 if (!pkg.packageName.equals(renamed)) { 9202 // Callers into this function may have already taken 9203 // care of renaming the package; only do it here if 9204 // it is not already done. 9205 pkg.setPackageName(renamed); 9206 } 9207 } else { 9208 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9209 if ((origPackage = mSettings.getPackageLPr( 9210 pkg.mOriginalPackages.get(i))) != null) { 9211 // We do have the package already installed under its 9212 // original name... should we use it? 9213 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9214 // New package is not compatible with original. 9215 origPackage = null; 9216 continue; 9217 } else if (origPackage.sharedUser != null) { 9218 // Make sure uid is compatible between packages. 9219 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9220 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9221 + " to " + pkg.packageName + ": old uid " 9222 + origPackage.sharedUser.name 9223 + " differs from " + pkg.mSharedUserId); 9224 origPackage = null; 9225 continue; 9226 } 9227 // TODO: Add case when shared user id is added [b/28144775] 9228 } else { 9229 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9230 + pkg.packageName + " to old name " + origPackage.name); 9231 } 9232 break; 9233 } 9234 } 9235 } 9236 } 9237 9238 if (mTransferedPackages.contains(pkg.packageName)) { 9239 Slog.w(TAG, "Package " + pkg.packageName 9240 + " was transferred to another, but its .apk remains"); 9241 } 9242 9243 // See comments in nonMutatedPs declaration 9244 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9245 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9246 if (foundPs != null) { 9247 nonMutatedPs = new PackageSetting(foundPs); 9248 } 9249 } 9250 9251 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9252 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9253 if (foundPs != null) { 9254 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9255 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9256 } 9257 } 9258 9259 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9260 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9261 PackageManagerService.reportSettingsProblem(Log.WARN, 9262 "Package " + pkg.packageName + " shared user changed from " 9263 + (pkgSetting.sharedUser != null 9264 ? pkgSetting.sharedUser.name : "<nothing>") 9265 + " to " 9266 + (suid != null ? suid.name : "<nothing>") 9267 + "; replacing with new"); 9268 pkgSetting = null; 9269 } 9270 final PackageSetting oldPkgSetting = 9271 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9272 final PackageSetting disabledPkgSetting = 9273 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9274 9275 String[] usesStaticLibraries = null; 9276 if (pkg.usesStaticLibraries != null) { 9277 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9278 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9279 } 9280 9281 if (pkgSetting == null) { 9282 final String parentPackageName = (pkg.parentPackage != null) 9283 ? pkg.parentPackage.packageName : null; 9284 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9285 // REMOVE SharedUserSetting from method; update in a separate call 9286 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9287 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9288 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9289 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9290 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9291 true /*allowInstall*/, instantApp, parentPackageName, 9292 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9293 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9294 // SIDE EFFECTS; updates system state; move elsewhere 9295 if (origPackage != null) { 9296 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9297 } 9298 mSettings.addUserToSettingLPw(pkgSetting); 9299 } else { 9300 // REMOVE SharedUserSetting from method; update in a separate call. 9301 // 9302 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9303 // secondaryCpuAbi are not known at this point so we always update them 9304 // to null here, only to reset them at a later point. 9305 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9306 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9307 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9308 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9309 UserManagerService.getInstance(), usesStaticLibraries, 9310 pkg.usesStaticLibrariesVersions); 9311 } 9312 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9313 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9314 9315 // SIDE EFFECTS; modifies system state; move elsewhere 9316 if (pkgSetting.origPackage != null) { 9317 // If we are first transitioning from an original package, 9318 // fix up the new package's name now. We need to do this after 9319 // looking up the package under its new name, so getPackageLP 9320 // can take care of fiddling things correctly. 9321 pkg.setPackageName(origPackage.name); 9322 9323 // File a report about this. 9324 String msg = "New package " + pkgSetting.realName 9325 + " renamed to replace old package " + pkgSetting.name; 9326 reportSettingsProblem(Log.WARN, msg); 9327 9328 // Make a note of it. 9329 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9330 mTransferedPackages.add(origPackage.name); 9331 } 9332 9333 // No longer need to retain this. 9334 pkgSetting.origPackage = null; 9335 } 9336 9337 // SIDE EFFECTS; modifies system state; move elsewhere 9338 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9339 // Make a note of it. 9340 mTransferedPackages.add(pkg.packageName); 9341 } 9342 9343 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9344 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9345 } 9346 9347 if ((scanFlags & SCAN_BOOTING) == 0 9348 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9349 // Check all shared libraries and map to their actual file path. 9350 // We only do this here for apps not on a system dir, because those 9351 // are the only ones that can fail an install due to this. We 9352 // will take care of the system apps by updating all of their 9353 // library paths after the scan is done. Also during the initial 9354 // scan don't update any libs as we do this wholesale after all 9355 // apps are scanned to avoid dependency based scanning. 9356 updateSharedLibrariesLPr(pkg, null); 9357 } 9358 9359 if (mFoundPolicyFile) { 9360 SELinuxMMAC.assignSeInfoValue(pkg); 9361 } 9362 pkg.applicationInfo.uid = pkgSetting.appId; 9363 pkg.mExtras = pkgSetting; 9364 9365 9366 // Static shared libs have same package with different versions where 9367 // we internally use a synthetic package name to allow multiple versions 9368 // of the same package, therefore we need to compare signatures against 9369 // the package setting for the latest library version. 9370 PackageSetting signatureCheckPs = pkgSetting; 9371 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9372 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9373 if (libraryEntry != null) { 9374 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9375 } 9376 } 9377 9378 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9379 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9380 // We just determined the app is signed correctly, so bring 9381 // over the latest parsed certs. 9382 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9383 } else { 9384 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9385 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9386 "Package " + pkg.packageName + " upgrade keys do not match the " 9387 + "previously installed version"); 9388 } else { 9389 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9390 String msg = "System package " + pkg.packageName 9391 + " signature changed; retaining data."; 9392 reportSettingsProblem(Log.WARN, msg); 9393 } 9394 } 9395 } else { 9396 try { 9397 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9398 verifySignaturesLP(signatureCheckPs, pkg); 9399 // We just determined the app is signed correctly, so bring 9400 // over the latest parsed certs. 9401 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9402 } catch (PackageManagerException e) { 9403 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9404 throw e; 9405 } 9406 // The signature has changed, but this package is in the system 9407 // image... let's recover! 9408 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9409 // However... if this package is part of a shared user, but it 9410 // doesn't match the signature of the shared user, let's fail. 9411 // What this means is that you can't change the signatures 9412 // associated with an overall shared user, which doesn't seem all 9413 // that unreasonable. 9414 if (signatureCheckPs.sharedUser != null) { 9415 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9416 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9417 throw new PackageManagerException( 9418 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9419 "Signature mismatch for shared user: " 9420 + pkgSetting.sharedUser); 9421 } 9422 } 9423 // File a report about this. 9424 String msg = "System package " + pkg.packageName 9425 + " signature changed; retaining data."; 9426 reportSettingsProblem(Log.WARN, msg); 9427 } 9428 } 9429 9430 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9431 // This package wants to adopt ownership of permissions from 9432 // another package. 9433 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9434 final String origName = pkg.mAdoptPermissions.get(i); 9435 final PackageSetting orig = mSettings.getPackageLPr(origName); 9436 if (orig != null) { 9437 if (verifyPackageUpdateLPr(orig, pkg)) { 9438 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9439 + pkg.packageName); 9440 // SIDE EFFECTS; updates permissions system state; move elsewhere 9441 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9442 } 9443 } 9444 } 9445 } 9446 } 9447 9448 pkg.applicationInfo.processName = fixProcessName( 9449 pkg.applicationInfo.packageName, 9450 pkg.applicationInfo.processName); 9451 9452 if (pkg != mPlatformPackage) { 9453 // Get all of our default paths setup 9454 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9455 } 9456 9457 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9458 9459 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9460 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9461 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9462 derivePackageAbi( 9463 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9464 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9465 9466 // Some system apps still use directory structure for native libraries 9467 // in which case we might end up not detecting abi solely based on apk 9468 // structure. Try to detect abi based on directory structure. 9469 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9470 pkg.applicationInfo.primaryCpuAbi == null) { 9471 setBundledAppAbisAndRoots(pkg, pkgSetting); 9472 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9473 } 9474 } else { 9475 // This is not a first boot or an upgrade, don't bother deriving the 9476 // ABI during the scan. Instead, trust the value that was stored in the 9477 // package setting. 9478 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9479 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9480 9481 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9482 9483 if (DEBUG_ABI_SELECTION) { 9484 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9485 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9486 pkg.applicationInfo.secondaryCpuAbi); 9487 } 9488 } 9489 } else { 9490 if ((scanFlags & SCAN_MOVE) != 0) { 9491 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9492 // but we already have this packages package info in the PackageSetting. We just 9493 // use that and derive the native library path based on the new codepath. 9494 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9495 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9496 } 9497 9498 // Set native library paths again. For moves, the path will be updated based on the 9499 // ABIs we've determined above. For non-moves, the path will be updated based on the 9500 // ABIs we determined during compilation, but the path will depend on the final 9501 // package path (after the rename away from the stage path). 9502 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9503 } 9504 9505 // This is a special case for the "system" package, where the ABI is 9506 // dictated by the zygote configuration (and init.rc). We should keep track 9507 // of this ABI so that we can deal with "normal" applications that run under 9508 // the same UID correctly. 9509 if (mPlatformPackage == pkg) { 9510 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9511 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9512 } 9513 9514 // If there's a mismatch between the abi-override in the package setting 9515 // and the abiOverride specified for the install. Warn about this because we 9516 // would've already compiled the app without taking the package setting into 9517 // account. 9518 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9519 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9520 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9521 " for package " + pkg.packageName); 9522 } 9523 } 9524 9525 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9526 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9527 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9528 9529 // Copy the derived override back to the parsed package, so that we can 9530 // update the package settings accordingly. 9531 pkg.cpuAbiOverride = cpuAbiOverride; 9532 9533 if (DEBUG_ABI_SELECTION) { 9534 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9535 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9536 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9537 } 9538 9539 // Push the derived path down into PackageSettings so we know what to 9540 // clean up at uninstall time. 9541 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9542 9543 if (DEBUG_ABI_SELECTION) { 9544 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9545 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9546 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9547 } 9548 9549 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9550 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9551 // We don't do this here during boot because we can do it all 9552 // at once after scanning all existing packages. 9553 // 9554 // We also do this *before* we perform dexopt on this package, so that 9555 // we can avoid redundant dexopts, and also to make sure we've got the 9556 // code and package path correct. 9557 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9558 } 9559 9560 if (mFactoryTest && pkg.requestedPermissions.contains( 9561 android.Manifest.permission.FACTORY_TEST)) { 9562 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9563 } 9564 9565 if (isSystemApp(pkg)) { 9566 pkgSetting.isOrphaned = true; 9567 } 9568 9569 // Take care of first install / last update times. 9570 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9571 if (currentTime != 0) { 9572 if (pkgSetting.firstInstallTime == 0) { 9573 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9574 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9575 pkgSetting.lastUpdateTime = currentTime; 9576 } 9577 } else if (pkgSetting.firstInstallTime == 0) { 9578 // We need *something*. Take time time stamp of the file. 9579 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9580 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9581 if (scanFileTime != pkgSetting.timeStamp) { 9582 // A package on the system image has changed; consider this 9583 // to be an update. 9584 pkgSetting.lastUpdateTime = scanFileTime; 9585 } 9586 } 9587 pkgSetting.setTimeStamp(scanFileTime); 9588 9589 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9590 if (nonMutatedPs != null) { 9591 synchronized (mPackages) { 9592 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9593 } 9594 } 9595 } else { 9596 final int userId = user == null ? 0 : user.getIdentifier(); 9597 // Modify state for the given package setting 9598 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9599 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9600 if (pkgSetting.getInstantApp(userId)) { 9601 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9602 } 9603 } 9604 return pkg; 9605 } 9606 9607 /** 9608 * Applies policy to the parsed package based upon the given policy flags. 9609 * Ensures the package is in a good state. 9610 * <p> 9611 * Implementation detail: This method must NOT have any side effect. It would 9612 * ideally be static, but, it requires locks to read system state. 9613 */ 9614 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9615 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9616 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9617 if (pkg.applicationInfo.isDirectBootAware()) { 9618 // we're direct boot aware; set for all components 9619 for (PackageParser.Service s : pkg.services) { 9620 s.info.encryptionAware = s.info.directBootAware = true; 9621 } 9622 for (PackageParser.Provider p : pkg.providers) { 9623 p.info.encryptionAware = p.info.directBootAware = true; 9624 } 9625 for (PackageParser.Activity a : pkg.activities) { 9626 a.info.encryptionAware = a.info.directBootAware = true; 9627 } 9628 for (PackageParser.Activity r : pkg.receivers) { 9629 r.info.encryptionAware = r.info.directBootAware = true; 9630 } 9631 } 9632 } else { 9633 // Only allow system apps to be flagged as core apps. 9634 pkg.coreApp = false; 9635 // clear flags not applicable to regular apps 9636 pkg.applicationInfo.privateFlags &= 9637 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9638 pkg.applicationInfo.privateFlags &= 9639 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9640 } 9641 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9642 9643 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9644 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9645 } 9646 9647 if (!isSystemApp(pkg)) { 9648 // Only system apps can use these features. 9649 pkg.mOriginalPackages = null; 9650 pkg.mRealPackage = null; 9651 pkg.mAdoptPermissions = null; 9652 } 9653 } 9654 9655 /** 9656 * Asserts the parsed package is valid according to the given policy. If the 9657 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9658 * <p> 9659 * Implementation detail: This method must NOT have any side effects. It would 9660 * ideally be static, but, it requires locks to read system state. 9661 * 9662 * @throws PackageManagerException If the package fails any of the validation checks 9663 */ 9664 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9665 throws PackageManagerException { 9666 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9667 assertCodePolicy(pkg); 9668 } 9669 9670 if (pkg.applicationInfo.getCodePath() == null || 9671 pkg.applicationInfo.getResourcePath() == null) { 9672 // Bail out. The resource and code paths haven't been set. 9673 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9674 "Code and resource paths haven't been set correctly"); 9675 } 9676 9677 // Make sure we're not adding any bogus keyset info 9678 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9679 ksms.assertScannedPackageValid(pkg); 9680 9681 synchronized (mPackages) { 9682 // The special "android" package can only be defined once 9683 if (pkg.packageName.equals("android")) { 9684 if (mAndroidApplication != null) { 9685 Slog.w(TAG, "*************************************************"); 9686 Slog.w(TAG, "Core android package being redefined. Skipping."); 9687 Slog.w(TAG, " codePath=" + pkg.codePath); 9688 Slog.w(TAG, "*************************************************"); 9689 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9690 "Core android package being redefined. Skipping."); 9691 } 9692 } 9693 9694 // A package name must be unique; don't allow duplicates 9695 if (mPackages.containsKey(pkg.packageName)) { 9696 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9697 "Application package " + pkg.packageName 9698 + " already installed. Skipping duplicate."); 9699 } 9700 9701 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9702 // Static libs have a synthetic package name containing the version 9703 // but we still want the base name to be unique. 9704 if (mPackages.containsKey(pkg.manifestPackageName)) { 9705 throw new PackageManagerException( 9706 "Duplicate static shared lib provider package"); 9707 } 9708 9709 // Static shared libraries should have at least O target SDK 9710 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9711 throw new PackageManagerException( 9712 "Packages declaring static-shared libs must target O SDK or higher"); 9713 } 9714 9715 // Package declaring static a shared lib cannot be instant apps 9716 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9717 throw new PackageManagerException( 9718 "Packages declaring static-shared libs cannot be instant apps"); 9719 } 9720 9721 // Package declaring static a shared lib cannot be renamed since the package 9722 // name is synthetic and apps can't code around package manager internals. 9723 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9724 throw new PackageManagerException( 9725 "Packages declaring static-shared libs cannot be renamed"); 9726 } 9727 9728 // Package declaring static a shared lib cannot declare child packages 9729 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9730 throw new PackageManagerException( 9731 "Packages declaring static-shared libs cannot have child packages"); 9732 } 9733 9734 // Package declaring static a shared lib cannot declare dynamic libs 9735 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9736 throw new PackageManagerException( 9737 "Packages declaring static-shared libs cannot declare dynamic libs"); 9738 } 9739 9740 // Package declaring static a shared lib cannot declare shared users 9741 if (pkg.mSharedUserId != null) { 9742 throw new PackageManagerException( 9743 "Packages declaring static-shared libs cannot declare shared users"); 9744 } 9745 9746 // Static shared libs cannot declare activities 9747 if (!pkg.activities.isEmpty()) { 9748 throw new PackageManagerException( 9749 "Static shared libs cannot declare activities"); 9750 } 9751 9752 // Static shared libs cannot declare services 9753 if (!pkg.services.isEmpty()) { 9754 throw new PackageManagerException( 9755 "Static shared libs cannot declare services"); 9756 } 9757 9758 // Static shared libs cannot declare providers 9759 if (!pkg.providers.isEmpty()) { 9760 throw new PackageManagerException( 9761 "Static shared libs cannot declare content providers"); 9762 } 9763 9764 // Static shared libs cannot declare receivers 9765 if (!pkg.receivers.isEmpty()) { 9766 throw new PackageManagerException( 9767 "Static shared libs cannot declare broadcast receivers"); 9768 } 9769 9770 // Static shared libs cannot declare permission groups 9771 if (!pkg.permissionGroups.isEmpty()) { 9772 throw new PackageManagerException( 9773 "Static shared libs cannot declare permission groups"); 9774 } 9775 9776 // Static shared libs cannot declare permissions 9777 if (!pkg.permissions.isEmpty()) { 9778 throw new PackageManagerException( 9779 "Static shared libs cannot declare permissions"); 9780 } 9781 9782 // Static shared libs cannot declare protected broadcasts 9783 if (pkg.protectedBroadcasts != null) { 9784 throw new PackageManagerException( 9785 "Static shared libs cannot declare protected broadcasts"); 9786 } 9787 9788 // Static shared libs cannot be overlay targets 9789 if (pkg.mOverlayTarget != null) { 9790 throw new PackageManagerException( 9791 "Static shared libs cannot be overlay targets"); 9792 } 9793 9794 // The version codes must be ordered as lib versions 9795 int minVersionCode = Integer.MIN_VALUE; 9796 int maxVersionCode = Integer.MAX_VALUE; 9797 9798 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9799 pkg.staticSharedLibName); 9800 if (versionedLib != null) { 9801 final int versionCount = versionedLib.size(); 9802 for (int i = 0; i < versionCount; i++) { 9803 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9804 // TODO: We will change version code to long, so in the new API it is long 9805 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9806 .getVersionCode(); 9807 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9808 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9809 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9810 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9811 } else { 9812 minVersionCode = maxVersionCode = libVersionCode; 9813 break; 9814 } 9815 } 9816 } 9817 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9818 throw new PackageManagerException("Static shared" 9819 + " lib version codes must be ordered as lib versions"); 9820 } 9821 } 9822 9823 // Only privileged apps and updated privileged apps can add child packages. 9824 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9825 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9826 throw new PackageManagerException("Only privileged apps can add child " 9827 + "packages. Ignoring package " + pkg.packageName); 9828 } 9829 final int childCount = pkg.childPackages.size(); 9830 for (int i = 0; i < childCount; i++) { 9831 PackageParser.Package childPkg = pkg.childPackages.get(i); 9832 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9833 childPkg.packageName)) { 9834 throw new PackageManagerException("Can't override child of " 9835 + "another disabled app. Ignoring package " + pkg.packageName); 9836 } 9837 } 9838 } 9839 9840 // If we're only installing presumed-existing packages, require that the 9841 // scanned APK is both already known and at the path previously established 9842 // for it. Previously unknown packages we pick up normally, but if we have an 9843 // a priori expectation about this package's install presence, enforce it. 9844 // With a singular exception for new system packages. When an OTA contains 9845 // a new system package, we allow the codepath to change from a system location 9846 // to the user-installed location. If we don't allow this change, any newer, 9847 // user-installed version of the application will be ignored. 9848 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9849 if (mExpectingBetter.containsKey(pkg.packageName)) { 9850 logCriticalInfo(Log.WARN, 9851 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9852 } else { 9853 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9854 if (known != null) { 9855 if (DEBUG_PACKAGE_SCANNING) { 9856 Log.d(TAG, "Examining " + pkg.codePath 9857 + " and requiring known paths " + known.codePathString 9858 + " & " + known.resourcePathString); 9859 } 9860 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9861 || !pkg.applicationInfo.getResourcePath().equals( 9862 known.resourcePathString)) { 9863 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9864 "Application package " + pkg.packageName 9865 + " found at " + pkg.applicationInfo.getCodePath() 9866 + " but expected at " + known.codePathString 9867 + "; ignoring."); 9868 } 9869 } 9870 } 9871 } 9872 9873 // Verify that this new package doesn't have any content providers 9874 // that conflict with existing packages. Only do this if the 9875 // package isn't already installed, since we don't want to break 9876 // things that are installed. 9877 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9878 final int N = pkg.providers.size(); 9879 int i; 9880 for (i=0; i<N; i++) { 9881 PackageParser.Provider p = pkg.providers.get(i); 9882 if (p.info.authority != null) { 9883 String names[] = p.info.authority.split(";"); 9884 for (int j = 0; j < names.length; j++) { 9885 if (mProvidersByAuthority.containsKey(names[j])) { 9886 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9887 final String otherPackageName = 9888 ((other != null && other.getComponentName() != null) ? 9889 other.getComponentName().getPackageName() : "?"); 9890 throw new PackageManagerException( 9891 INSTALL_FAILED_CONFLICTING_PROVIDER, 9892 "Can't install because provider name " + names[j] 9893 + " (in package " + pkg.applicationInfo.packageName 9894 + ") is already used by " + otherPackageName); 9895 } 9896 } 9897 } 9898 } 9899 } 9900 } 9901 } 9902 9903 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9904 int type, String declaringPackageName, int declaringVersionCode) { 9905 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9906 if (versionedLib == null) { 9907 versionedLib = new SparseArray<>(); 9908 mSharedLibraries.put(name, versionedLib); 9909 if (type == SharedLibraryInfo.TYPE_STATIC) { 9910 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9911 } 9912 } else if (versionedLib.indexOfKey(version) >= 0) { 9913 return false; 9914 } 9915 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9916 version, type, declaringPackageName, declaringVersionCode); 9917 versionedLib.put(version, libEntry); 9918 return true; 9919 } 9920 9921 private boolean removeSharedLibraryLPw(String name, int version) { 9922 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9923 if (versionedLib == null) { 9924 return false; 9925 } 9926 final int libIdx = versionedLib.indexOfKey(version); 9927 if (libIdx < 0) { 9928 return false; 9929 } 9930 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9931 versionedLib.remove(version); 9932 if (versionedLib.size() <= 0) { 9933 mSharedLibraries.remove(name); 9934 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9935 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9936 .getPackageName()); 9937 } 9938 } 9939 return true; 9940 } 9941 9942 /** 9943 * Adds a scanned package to the system. When this method is finished, the package will 9944 * be available for query, resolution, etc... 9945 */ 9946 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9947 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9948 final String pkgName = pkg.packageName; 9949 if (mCustomResolverComponentName != null && 9950 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9951 setUpCustomResolverActivity(pkg); 9952 } 9953 9954 if (pkg.packageName.equals("android")) { 9955 synchronized (mPackages) { 9956 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9957 // Set up information for our fall-back user intent resolution activity. 9958 mPlatformPackage = pkg; 9959 pkg.mVersionCode = mSdkVersion; 9960 mAndroidApplication = pkg.applicationInfo; 9961 if (!mResolverReplaced) { 9962 mResolveActivity.applicationInfo = mAndroidApplication; 9963 mResolveActivity.name = ResolverActivity.class.getName(); 9964 mResolveActivity.packageName = mAndroidApplication.packageName; 9965 mResolveActivity.processName = "system:ui"; 9966 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9967 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9968 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9969 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9970 mResolveActivity.exported = true; 9971 mResolveActivity.enabled = true; 9972 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9973 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9974 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9975 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9976 | ActivityInfo.CONFIG_ORIENTATION 9977 | ActivityInfo.CONFIG_KEYBOARD 9978 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9979 mResolveInfo.activityInfo = mResolveActivity; 9980 mResolveInfo.priority = 0; 9981 mResolveInfo.preferredOrder = 0; 9982 mResolveInfo.match = 0; 9983 mResolveComponentName = new ComponentName( 9984 mAndroidApplication.packageName, mResolveActivity.name); 9985 } 9986 } 9987 } 9988 } 9989 9990 ArrayList<PackageParser.Package> clientLibPkgs = null; 9991 // writer 9992 synchronized (mPackages) { 9993 boolean hasStaticSharedLibs = false; 9994 9995 // Any app can add new static shared libraries 9996 if (pkg.staticSharedLibName != null) { 9997 // Static shared libs don't allow renaming as they have synthetic package 9998 // names to allow install of multiple versions, so use name from manifest. 9999 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10000 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10001 pkg.manifestPackageName, pkg.mVersionCode)) { 10002 hasStaticSharedLibs = true; 10003 } else { 10004 Slog.w(TAG, "Package " + pkg.packageName + " library " 10005 + pkg.staticSharedLibName + " already exists; skipping"); 10006 } 10007 // Static shared libs cannot be updated once installed since they 10008 // use synthetic package name which includes the version code, so 10009 // not need to update other packages's shared lib dependencies. 10010 } 10011 10012 if (!hasStaticSharedLibs 10013 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10014 // Only system apps can add new dynamic shared libraries. 10015 if (pkg.libraryNames != null) { 10016 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10017 String name = pkg.libraryNames.get(i); 10018 boolean allowed = false; 10019 if (pkg.isUpdatedSystemApp()) { 10020 // New library entries can only be added through the 10021 // system image. This is important to get rid of a lot 10022 // of nasty edge cases: for example if we allowed a non- 10023 // system update of the app to add a library, then uninstalling 10024 // the update would make the library go away, and assumptions 10025 // we made such as through app install filtering would now 10026 // have allowed apps on the device which aren't compatible 10027 // with it. Better to just have the restriction here, be 10028 // conservative, and create many fewer cases that can negatively 10029 // impact the user experience. 10030 final PackageSetting sysPs = mSettings 10031 .getDisabledSystemPkgLPr(pkg.packageName); 10032 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10033 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10034 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10035 allowed = true; 10036 break; 10037 } 10038 } 10039 } 10040 } else { 10041 allowed = true; 10042 } 10043 if (allowed) { 10044 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10045 SharedLibraryInfo.VERSION_UNDEFINED, 10046 SharedLibraryInfo.TYPE_DYNAMIC, 10047 pkg.packageName, pkg.mVersionCode)) { 10048 Slog.w(TAG, "Package " + pkg.packageName + " library " 10049 + name + " already exists; skipping"); 10050 } 10051 } else { 10052 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10053 + name + " that is not declared on system image; skipping"); 10054 } 10055 } 10056 10057 if ((scanFlags & SCAN_BOOTING) == 0) { 10058 // If we are not booting, we need to update any applications 10059 // that are clients of our shared library. If we are booting, 10060 // this will all be done once the scan is complete. 10061 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10062 } 10063 } 10064 } 10065 } 10066 10067 if ((scanFlags & SCAN_BOOTING) != 0) { 10068 // No apps can run during boot scan, so they don't need to be frozen 10069 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10070 // Caller asked to not kill app, so it's probably not frozen 10071 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10072 // Caller asked us to ignore frozen check for some reason; they 10073 // probably didn't know the package name 10074 } else { 10075 // We're doing major surgery on this package, so it better be frozen 10076 // right now to keep it from launching 10077 checkPackageFrozen(pkgName); 10078 } 10079 10080 // Also need to kill any apps that are dependent on the library. 10081 if (clientLibPkgs != null) { 10082 for (int i=0; i<clientLibPkgs.size(); i++) { 10083 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10084 killApplication(clientPkg.applicationInfo.packageName, 10085 clientPkg.applicationInfo.uid, "update lib"); 10086 } 10087 } 10088 10089 // writer 10090 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10091 10092 synchronized (mPackages) { 10093 // We don't expect installation to fail beyond this point 10094 10095 // Add the new setting to mSettings 10096 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10097 // Add the new setting to mPackages 10098 mPackages.put(pkg.applicationInfo.packageName, pkg); 10099 // Make sure we don't accidentally delete its data. 10100 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10101 while (iter.hasNext()) { 10102 PackageCleanItem item = iter.next(); 10103 if (pkgName.equals(item.packageName)) { 10104 iter.remove(); 10105 } 10106 } 10107 10108 // Add the package's KeySets to the global KeySetManagerService 10109 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10110 ksms.addScannedPackageLPw(pkg); 10111 10112 int N = pkg.providers.size(); 10113 StringBuilder r = null; 10114 int i; 10115 for (i=0; i<N; i++) { 10116 PackageParser.Provider p = pkg.providers.get(i); 10117 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10118 p.info.processName); 10119 mProviders.addProvider(p); 10120 p.syncable = p.info.isSyncable; 10121 if (p.info.authority != null) { 10122 String names[] = p.info.authority.split(";"); 10123 p.info.authority = null; 10124 for (int j = 0; j < names.length; j++) { 10125 if (j == 1 && p.syncable) { 10126 // We only want the first authority for a provider to possibly be 10127 // syncable, so if we already added this provider using a different 10128 // authority clear the syncable flag. We copy the provider before 10129 // changing it because the mProviders object contains a reference 10130 // to a provider that we don't want to change. 10131 // Only do this for the second authority since the resulting provider 10132 // object can be the same for all future authorities for this provider. 10133 p = new PackageParser.Provider(p); 10134 p.syncable = false; 10135 } 10136 if (!mProvidersByAuthority.containsKey(names[j])) { 10137 mProvidersByAuthority.put(names[j], p); 10138 if (p.info.authority == null) { 10139 p.info.authority = names[j]; 10140 } else { 10141 p.info.authority = p.info.authority + ";" + names[j]; 10142 } 10143 if (DEBUG_PACKAGE_SCANNING) { 10144 if (chatty) 10145 Log.d(TAG, "Registered content provider: " + names[j] 10146 + ", className = " + p.info.name + ", isSyncable = " 10147 + p.info.isSyncable); 10148 } 10149 } else { 10150 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10151 Slog.w(TAG, "Skipping provider name " + names[j] + 10152 " (in package " + pkg.applicationInfo.packageName + 10153 "): name already used by " 10154 + ((other != null && other.getComponentName() != null) 10155 ? other.getComponentName().getPackageName() : "?")); 10156 } 10157 } 10158 } 10159 if (chatty) { 10160 if (r == null) { 10161 r = new StringBuilder(256); 10162 } else { 10163 r.append(' '); 10164 } 10165 r.append(p.info.name); 10166 } 10167 } 10168 if (r != null) { 10169 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10170 } 10171 10172 N = pkg.services.size(); 10173 r = null; 10174 for (i=0; i<N; i++) { 10175 PackageParser.Service s = pkg.services.get(i); 10176 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10177 s.info.processName); 10178 mServices.addService(s); 10179 if (chatty) { 10180 if (r == null) { 10181 r = new StringBuilder(256); 10182 } else { 10183 r.append(' '); 10184 } 10185 r.append(s.info.name); 10186 } 10187 } 10188 if (r != null) { 10189 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10190 } 10191 10192 N = pkg.receivers.size(); 10193 r = null; 10194 for (i=0; i<N; i++) { 10195 PackageParser.Activity a = pkg.receivers.get(i); 10196 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10197 a.info.processName); 10198 mReceivers.addActivity(a, "receiver"); 10199 if (chatty) { 10200 if (r == null) { 10201 r = new StringBuilder(256); 10202 } else { 10203 r.append(' '); 10204 } 10205 r.append(a.info.name); 10206 } 10207 } 10208 if (r != null) { 10209 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10210 } 10211 10212 N = pkg.activities.size(); 10213 r = null; 10214 for (i=0; i<N; i++) { 10215 PackageParser.Activity a = pkg.activities.get(i); 10216 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10217 a.info.processName); 10218 mActivities.addActivity(a, "activity"); 10219 if (chatty) { 10220 if (r == null) { 10221 r = new StringBuilder(256); 10222 } else { 10223 r.append(' '); 10224 } 10225 r.append(a.info.name); 10226 } 10227 } 10228 if (r != null) { 10229 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10230 } 10231 10232 N = pkg.permissionGroups.size(); 10233 r = null; 10234 for (i=0; i<N; i++) { 10235 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10236 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10237 final String curPackageName = cur == null ? null : cur.info.packageName; 10238 // Dont allow ephemeral apps to define new permission groups. 10239 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10240 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10241 + pg.info.packageName 10242 + " ignored: instant apps cannot define new permission groups."); 10243 continue; 10244 } 10245 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10246 if (cur == null || isPackageUpdate) { 10247 mPermissionGroups.put(pg.info.name, pg); 10248 if (chatty) { 10249 if (r == null) { 10250 r = new StringBuilder(256); 10251 } else { 10252 r.append(' '); 10253 } 10254 if (isPackageUpdate) { 10255 r.append("UPD:"); 10256 } 10257 r.append(pg.info.name); 10258 } 10259 } else { 10260 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10261 + pg.info.packageName + " ignored: original from " 10262 + cur.info.packageName); 10263 if (chatty) { 10264 if (r == null) { 10265 r = new StringBuilder(256); 10266 } else { 10267 r.append(' '); 10268 } 10269 r.append("DUP:"); 10270 r.append(pg.info.name); 10271 } 10272 } 10273 } 10274 if (r != null) { 10275 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10276 } 10277 10278 N = pkg.permissions.size(); 10279 r = null; 10280 for (i=0; i<N; i++) { 10281 PackageParser.Permission p = pkg.permissions.get(i); 10282 10283 // Dont allow ephemeral apps to define new permissions. 10284 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10285 Slog.w(TAG, "Permission " + p.info.name + " from package " 10286 + p.info.packageName 10287 + " ignored: instant apps cannot define new permissions."); 10288 continue; 10289 } 10290 10291 // Assume by default that we did not install this permission into the system. 10292 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10293 10294 // Now that permission groups have a special meaning, we ignore permission 10295 // groups for legacy apps to prevent unexpected behavior. In particular, 10296 // permissions for one app being granted to someone just becase they happen 10297 // to be in a group defined by another app (before this had no implications). 10298 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10299 p.group = mPermissionGroups.get(p.info.group); 10300 // Warn for a permission in an unknown group. 10301 if (p.info.group != null && p.group == null) { 10302 Slog.w(TAG, "Permission " + p.info.name + " from package " 10303 + p.info.packageName + " in an unknown group " + p.info.group); 10304 } 10305 } 10306 10307 ArrayMap<String, BasePermission> permissionMap = 10308 p.tree ? mSettings.mPermissionTrees 10309 : mSettings.mPermissions; 10310 BasePermission bp = permissionMap.get(p.info.name); 10311 10312 // Allow system apps to redefine non-system permissions 10313 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10314 final boolean currentOwnerIsSystem = (bp.perm != null 10315 && isSystemApp(bp.perm.owner)); 10316 if (isSystemApp(p.owner)) { 10317 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10318 // It's a built-in permission and no owner, take ownership now 10319 bp.packageSetting = pkgSetting; 10320 bp.perm = p; 10321 bp.uid = pkg.applicationInfo.uid; 10322 bp.sourcePackage = p.info.packageName; 10323 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10324 } else if (!currentOwnerIsSystem) { 10325 String msg = "New decl " + p.owner + " of permission " 10326 + p.info.name + " is system; overriding " + bp.sourcePackage; 10327 reportSettingsProblem(Log.WARN, msg); 10328 bp = null; 10329 } 10330 } 10331 } 10332 10333 if (bp == null) { 10334 bp = new BasePermission(p.info.name, p.info.packageName, 10335 BasePermission.TYPE_NORMAL); 10336 permissionMap.put(p.info.name, bp); 10337 } 10338 10339 if (bp.perm == null) { 10340 if (bp.sourcePackage == null 10341 || bp.sourcePackage.equals(p.info.packageName)) { 10342 BasePermission tree = findPermissionTreeLP(p.info.name); 10343 if (tree == null 10344 || tree.sourcePackage.equals(p.info.packageName)) { 10345 bp.packageSetting = pkgSetting; 10346 bp.perm = p; 10347 bp.uid = pkg.applicationInfo.uid; 10348 bp.sourcePackage = p.info.packageName; 10349 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10350 if (chatty) { 10351 if (r == null) { 10352 r = new StringBuilder(256); 10353 } else { 10354 r.append(' '); 10355 } 10356 r.append(p.info.name); 10357 } 10358 } else { 10359 Slog.w(TAG, "Permission " + p.info.name + " from package " 10360 + p.info.packageName + " ignored: base tree " 10361 + tree.name + " is from package " 10362 + tree.sourcePackage); 10363 } 10364 } else { 10365 Slog.w(TAG, "Permission " + p.info.name + " from package " 10366 + p.info.packageName + " ignored: original from " 10367 + bp.sourcePackage); 10368 } 10369 } else if (chatty) { 10370 if (r == null) { 10371 r = new StringBuilder(256); 10372 } else { 10373 r.append(' '); 10374 } 10375 r.append("DUP:"); 10376 r.append(p.info.name); 10377 } 10378 if (bp.perm == p) { 10379 bp.protectionLevel = p.info.protectionLevel; 10380 } 10381 } 10382 10383 if (r != null) { 10384 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10385 } 10386 10387 N = pkg.instrumentation.size(); 10388 r = null; 10389 for (i=0; i<N; i++) { 10390 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10391 a.info.packageName = pkg.applicationInfo.packageName; 10392 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10393 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10394 a.info.splitNames = pkg.splitNames; 10395 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10396 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10397 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10398 a.info.dataDir = pkg.applicationInfo.dataDir; 10399 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10400 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10401 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10402 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10403 mInstrumentation.put(a.getComponentName(), a); 10404 if (chatty) { 10405 if (r == null) { 10406 r = new StringBuilder(256); 10407 } else { 10408 r.append(' '); 10409 } 10410 r.append(a.info.name); 10411 } 10412 } 10413 if (r != null) { 10414 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10415 } 10416 10417 if (pkg.protectedBroadcasts != null) { 10418 N = pkg.protectedBroadcasts.size(); 10419 for (i=0; i<N; i++) { 10420 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10421 } 10422 } 10423 } 10424 10425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10426 } 10427 10428 /** 10429 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10430 * is derived purely on the basis of the contents of {@code scanFile} and 10431 * {@code cpuAbiOverride}. 10432 * 10433 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10434 */ 10435 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10436 String cpuAbiOverride, boolean extractLibs, 10437 File appLib32InstallDir) 10438 throws PackageManagerException { 10439 // Give ourselves some initial paths; we'll come back for another 10440 // pass once we've determined ABI below. 10441 setNativeLibraryPaths(pkg, appLib32InstallDir); 10442 10443 // We would never need to extract libs for forward-locked and external packages, 10444 // since the container service will do it for us. We shouldn't attempt to 10445 // extract libs from system app when it was not updated. 10446 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10447 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10448 extractLibs = false; 10449 } 10450 10451 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10452 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10453 10454 NativeLibraryHelper.Handle handle = null; 10455 try { 10456 handle = NativeLibraryHelper.Handle.create(pkg); 10457 // TODO(multiArch): This can be null for apps that didn't go through the 10458 // usual installation process. We can calculate it again, like we 10459 // do during install time. 10460 // 10461 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10462 // unnecessary. 10463 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10464 10465 // Null out the abis so that they can be recalculated. 10466 pkg.applicationInfo.primaryCpuAbi = null; 10467 pkg.applicationInfo.secondaryCpuAbi = null; 10468 if (isMultiArch(pkg.applicationInfo)) { 10469 // Warn if we've set an abiOverride for multi-lib packages.. 10470 // By definition, we need to copy both 32 and 64 bit libraries for 10471 // such packages. 10472 if (pkg.cpuAbiOverride != null 10473 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10474 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10475 } 10476 10477 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10478 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10479 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10480 if (extractLibs) { 10481 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10482 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10483 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10484 useIsaSpecificSubdirs); 10485 } else { 10486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10487 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10488 } 10489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10490 } 10491 10492 maybeThrowExceptionForMultiArchCopy( 10493 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10494 10495 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10496 if (extractLibs) { 10497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10498 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10499 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10500 useIsaSpecificSubdirs); 10501 } else { 10502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10503 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10504 } 10505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10506 } 10507 10508 maybeThrowExceptionForMultiArchCopy( 10509 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10510 10511 if (abi64 >= 0) { 10512 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10513 } 10514 10515 if (abi32 >= 0) { 10516 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10517 if (abi64 >= 0) { 10518 if (pkg.use32bitAbi) { 10519 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10520 pkg.applicationInfo.primaryCpuAbi = abi; 10521 } else { 10522 pkg.applicationInfo.secondaryCpuAbi = abi; 10523 } 10524 } else { 10525 pkg.applicationInfo.primaryCpuAbi = abi; 10526 } 10527 } 10528 10529 } else { 10530 String[] abiList = (cpuAbiOverride != null) ? 10531 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10532 10533 // Enable gross and lame hacks for apps that are built with old 10534 // SDK tools. We must scan their APKs for renderscript bitcode and 10535 // not launch them if it's present. Don't bother checking on devices 10536 // that don't have 64 bit support. 10537 boolean needsRenderScriptOverride = false; 10538 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10539 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10540 abiList = Build.SUPPORTED_32_BIT_ABIS; 10541 needsRenderScriptOverride = true; 10542 } 10543 10544 final int copyRet; 10545 if (extractLibs) { 10546 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10547 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10548 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10549 } else { 10550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10551 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10552 } 10553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10554 10555 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10556 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10557 "Error unpackaging native libs for app, errorCode=" + copyRet); 10558 } 10559 10560 if (copyRet >= 0) { 10561 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10562 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10563 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10564 } else if (needsRenderScriptOverride) { 10565 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10566 } 10567 } 10568 } catch (IOException ioe) { 10569 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10570 } finally { 10571 IoUtils.closeQuietly(handle); 10572 } 10573 10574 // Now that we've calculated the ABIs and determined if it's an internal app, 10575 // we will go ahead and populate the nativeLibraryPath. 10576 setNativeLibraryPaths(pkg, appLib32InstallDir); 10577 } 10578 10579 /** 10580 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10581 * i.e, so that all packages can be run inside a single process if required. 10582 * 10583 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10584 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10585 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10586 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10587 * updating a package that belongs to a shared user. 10588 * 10589 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10590 * adds unnecessary complexity. 10591 */ 10592 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10593 PackageParser.Package scannedPackage) { 10594 String requiredInstructionSet = null; 10595 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10596 requiredInstructionSet = VMRuntime.getInstructionSet( 10597 scannedPackage.applicationInfo.primaryCpuAbi); 10598 } 10599 10600 PackageSetting requirer = null; 10601 for (PackageSetting ps : packagesForUser) { 10602 // If packagesForUser contains scannedPackage, we skip it. This will happen 10603 // when scannedPackage is an update of an existing package. Without this check, 10604 // we will never be able to change the ABI of any package belonging to a shared 10605 // user, even if it's compatible with other packages. 10606 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10607 if (ps.primaryCpuAbiString == null) { 10608 continue; 10609 } 10610 10611 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10612 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10613 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10614 // this but there's not much we can do. 10615 String errorMessage = "Instruction set mismatch, " 10616 + ((requirer == null) ? "[caller]" : requirer) 10617 + " requires " + requiredInstructionSet + " whereas " + ps 10618 + " requires " + instructionSet; 10619 Slog.w(TAG, errorMessage); 10620 } 10621 10622 if (requiredInstructionSet == null) { 10623 requiredInstructionSet = instructionSet; 10624 requirer = ps; 10625 } 10626 } 10627 } 10628 10629 if (requiredInstructionSet != null) { 10630 String adjustedAbi; 10631 if (requirer != null) { 10632 // requirer != null implies that either scannedPackage was null or that scannedPackage 10633 // did not require an ABI, in which case we have to adjust scannedPackage to match 10634 // the ABI of the set (which is the same as requirer's ABI) 10635 adjustedAbi = requirer.primaryCpuAbiString; 10636 if (scannedPackage != null) { 10637 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10638 } 10639 } else { 10640 // requirer == null implies that we're updating all ABIs in the set to 10641 // match scannedPackage. 10642 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10643 } 10644 10645 for (PackageSetting ps : packagesForUser) { 10646 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10647 if (ps.primaryCpuAbiString != null) { 10648 continue; 10649 } 10650 10651 ps.primaryCpuAbiString = adjustedAbi; 10652 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10653 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10654 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10655 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10656 + " (requirer=" 10657 + (requirer != null ? requirer.pkg : "null") 10658 + ", scannedPackage=" 10659 + (scannedPackage != null ? scannedPackage : "null") 10660 + ")"); 10661 try { 10662 mInstaller.rmdex(ps.codePathString, 10663 getDexCodeInstructionSet(getPreferredInstructionSet())); 10664 } catch (InstallerException ignored) { 10665 } 10666 } 10667 } 10668 } 10669 } 10670 } 10671 10672 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10673 synchronized (mPackages) { 10674 mResolverReplaced = true; 10675 // Set up information for custom user intent resolution activity. 10676 mResolveActivity.applicationInfo = pkg.applicationInfo; 10677 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10678 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10679 mResolveActivity.processName = pkg.applicationInfo.packageName; 10680 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10681 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10682 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10683 mResolveActivity.theme = 0; 10684 mResolveActivity.exported = true; 10685 mResolveActivity.enabled = true; 10686 mResolveInfo.activityInfo = mResolveActivity; 10687 mResolveInfo.priority = 0; 10688 mResolveInfo.preferredOrder = 0; 10689 mResolveInfo.match = 0; 10690 mResolveComponentName = mCustomResolverComponentName; 10691 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10692 mResolveComponentName); 10693 } 10694 } 10695 10696 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10697 if (installerActivity == null) { 10698 if (DEBUG_EPHEMERAL) { 10699 Slog.d(TAG, "Clear ephemeral installer activity"); 10700 } 10701 mInstantAppInstallerActivity = null; 10702 return; 10703 } 10704 10705 if (DEBUG_EPHEMERAL) { 10706 Slog.d(TAG, "Set ephemeral installer activity: " 10707 + installerActivity.getComponentName()); 10708 } 10709 // Set up information for ephemeral installer activity 10710 mInstantAppInstallerActivity = installerActivity; 10711 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10712 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10713 mInstantAppInstallerActivity.exported = true; 10714 mInstantAppInstallerActivity.enabled = true; 10715 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10716 mInstantAppInstallerInfo.priority = 0; 10717 mInstantAppInstallerInfo.preferredOrder = 1; 10718 mInstantAppInstallerInfo.isDefault = true; 10719 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10720 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10721 } 10722 10723 private static String calculateBundledApkRoot(final String codePathString) { 10724 final File codePath = new File(codePathString); 10725 final File codeRoot; 10726 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10727 codeRoot = Environment.getRootDirectory(); 10728 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10729 codeRoot = Environment.getOemDirectory(); 10730 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10731 codeRoot = Environment.getVendorDirectory(); 10732 } else { 10733 // Unrecognized code path; take its top real segment as the apk root: 10734 // e.g. /something/app/blah.apk => /something 10735 try { 10736 File f = codePath.getCanonicalFile(); 10737 File parent = f.getParentFile(); // non-null because codePath is a file 10738 File tmp; 10739 while ((tmp = parent.getParentFile()) != null) { 10740 f = parent; 10741 parent = tmp; 10742 } 10743 codeRoot = f; 10744 Slog.w(TAG, "Unrecognized code path " 10745 + codePath + " - using " + codeRoot); 10746 } catch (IOException e) { 10747 // Can't canonicalize the code path -- shenanigans? 10748 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10749 return Environment.getRootDirectory().getPath(); 10750 } 10751 } 10752 return codeRoot.getPath(); 10753 } 10754 10755 /** 10756 * Derive and set the location of native libraries for the given package, 10757 * which varies depending on where and how the package was installed. 10758 */ 10759 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10760 final ApplicationInfo info = pkg.applicationInfo; 10761 final String codePath = pkg.codePath; 10762 final File codeFile = new File(codePath); 10763 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10764 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10765 10766 info.nativeLibraryRootDir = null; 10767 info.nativeLibraryRootRequiresIsa = false; 10768 info.nativeLibraryDir = null; 10769 info.secondaryNativeLibraryDir = null; 10770 10771 if (isApkFile(codeFile)) { 10772 // Monolithic install 10773 if (bundledApp) { 10774 // If "/system/lib64/apkname" exists, assume that is the per-package 10775 // native library directory to use; otherwise use "/system/lib/apkname". 10776 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10777 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10778 getPrimaryInstructionSet(info)); 10779 10780 // This is a bundled system app so choose the path based on the ABI. 10781 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10782 // is just the default path. 10783 final String apkName = deriveCodePathName(codePath); 10784 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10785 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10786 apkName).getAbsolutePath(); 10787 10788 if (info.secondaryCpuAbi != null) { 10789 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10790 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10791 secondaryLibDir, apkName).getAbsolutePath(); 10792 } 10793 } else if (asecApp) { 10794 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10795 .getAbsolutePath(); 10796 } else { 10797 final String apkName = deriveCodePathName(codePath); 10798 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10799 .getAbsolutePath(); 10800 } 10801 10802 info.nativeLibraryRootRequiresIsa = false; 10803 info.nativeLibraryDir = info.nativeLibraryRootDir; 10804 } else { 10805 // Cluster install 10806 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10807 info.nativeLibraryRootRequiresIsa = true; 10808 10809 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10810 getPrimaryInstructionSet(info)).getAbsolutePath(); 10811 10812 if (info.secondaryCpuAbi != null) { 10813 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10814 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10815 } 10816 } 10817 } 10818 10819 /** 10820 * Calculate the abis and roots for a bundled app. These can uniquely 10821 * be determined from the contents of the system partition, i.e whether 10822 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10823 * of this information, and instead assume that the system was built 10824 * sensibly. 10825 */ 10826 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10827 PackageSetting pkgSetting) { 10828 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10829 10830 // If "/system/lib64/apkname" exists, assume that is the per-package 10831 // native library directory to use; otherwise use "/system/lib/apkname". 10832 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10833 setBundledAppAbi(pkg, apkRoot, apkName); 10834 // pkgSetting might be null during rescan following uninstall of updates 10835 // to a bundled app, so accommodate that possibility. The settings in 10836 // that case will be established later from the parsed package. 10837 // 10838 // If the settings aren't null, sync them up with what we've just derived. 10839 // note that apkRoot isn't stored in the package settings. 10840 if (pkgSetting != null) { 10841 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10842 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10843 } 10844 } 10845 10846 /** 10847 * Deduces the ABI of a bundled app and sets the relevant fields on the 10848 * parsed pkg object. 10849 * 10850 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10851 * under which system libraries are installed. 10852 * @param apkName the name of the installed package. 10853 */ 10854 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10855 final File codeFile = new File(pkg.codePath); 10856 10857 final boolean has64BitLibs; 10858 final boolean has32BitLibs; 10859 if (isApkFile(codeFile)) { 10860 // Monolithic install 10861 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10862 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10863 } else { 10864 // Cluster install 10865 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10866 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10867 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10868 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10869 has64BitLibs = (new File(rootDir, isa)).exists(); 10870 } else { 10871 has64BitLibs = false; 10872 } 10873 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10874 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10875 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10876 has32BitLibs = (new File(rootDir, isa)).exists(); 10877 } else { 10878 has32BitLibs = false; 10879 } 10880 } 10881 10882 if (has64BitLibs && !has32BitLibs) { 10883 // The package has 64 bit libs, but not 32 bit libs. Its primary 10884 // ABI should be 64 bit. We can safely assume here that the bundled 10885 // native libraries correspond to the most preferred ABI in the list. 10886 10887 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10888 pkg.applicationInfo.secondaryCpuAbi = null; 10889 } else if (has32BitLibs && !has64BitLibs) { 10890 // The package has 32 bit libs but not 64 bit libs. Its primary 10891 // ABI should be 32 bit. 10892 10893 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10894 pkg.applicationInfo.secondaryCpuAbi = null; 10895 } else if (has32BitLibs && has64BitLibs) { 10896 // The application has both 64 and 32 bit bundled libraries. We check 10897 // here that the app declares multiArch support, and warn if it doesn't. 10898 // 10899 // We will be lenient here and record both ABIs. The primary will be the 10900 // ABI that's higher on the list, i.e, a device that's configured to prefer 10901 // 64 bit apps will see a 64 bit primary ABI, 10902 10903 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10904 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10905 } 10906 10907 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10908 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10909 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10910 } else { 10911 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10912 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10913 } 10914 } else { 10915 pkg.applicationInfo.primaryCpuAbi = null; 10916 pkg.applicationInfo.secondaryCpuAbi = null; 10917 } 10918 } 10919 10920 private void killApplication(String pkgName, int appId, String reason) { 10921 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10922 } 10923 10924 private void killApplication(String pkgName, int appId, int userId, String reason) { 10925 // Request the ActivityManager to kill the process(only for existing packages) 10926 // so that we do not end up in a confused state while the user is still using the older 10927 // version of the application while the new one gets installed. 10928 final long token = Binder.clearCallingIdentity(); 10929 try { 10930 IActivityManager am = ActivityManager.getService(); 10931 if (am != null) { 10932 try { 10933 am.killApplication(pkgName, appId, userId, reason); 10934 } catch (RemoteException e) { 10935 } 10936 } 10937 } finally { 10938 Binder.restoreCallingIdentity(token); 10939 } 10940 } 10941 10942 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10943 // Remove the parent package setting 10944 PackageSetting ps = (PackageSetting) pkg.mExtras; 10945 if (ps != null) { 10946 removePackageLI(ps, chatty); 10947 } 10948 // Remove the child package setting 10949 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10950 for (int i = 0; i < childCount; i++) { 10951 PackageParser.Package childPkg = pkg.childPackages.get(i); 10952 ps = (PackageSetting) childPkg.mExtras; 10953 if (ps != null) { 10954 removePackageLI(ps, chatty); 10955 } 10956 } 10957 } 10958 10959 void removePackageLI(PackageSetting ps, boolean chatty) { 10960 if (DEBUG_INSTALL) { 10961 if (chatty) 10962 Log.d(TAG, "Removing package " + ps.name); 10963 } 10964 10965 // writer 10966 synchronized (mPackages) { 10967 mPackages.remove(ps.name); 10968 final PackageParser.Package pkg = ps.pkg; 10969 if (pkg != null) { 10970 cleanPackageDataStructuresLILPw(pkg, chatty); 10971 } 10972 } 10973 } 10974 10975 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10976 if (DEBUG_INSTALL) { 10977 if (chatty) 10978 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10979 } 10980 10981 // writer 10982 synchronized (mPackages) { 10983 // Remove the parent package 10984 mPackages.remove(pkg.applicationInfo.packageName); 10985 cleanPackageDataStructuresLILPw(pkg, chatty); 10986 10987 // Remove the child packages 10988 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10989 for (int i = 0; i < childCount; i++) { 10990 PackageParser.Package childPkg = pkg.childPackages.get(i); 10991 mPackages.remove(childPkg.applicationInfo.packageName); 10992 cleanPackageDataStructuresLILPw(childPkg, chatty); 10993 } 10994 } 10995 } 10996 10997 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10998 int N = pkg.providers.size(); 10999 StringBuilder r = null; 11000 int i; 11001 for (i=0; i<N; i++) { 11002 PackageParser.Provider p = pkg.providers.get(i); 11003 mProviders.removeProvider(p); 11004 if (p.info.authority == null) { 11005 11006 /* There was another ContentProvider with this authority when 11007 * this app was installed so this authority is null, 11008 * Ignore it as we don't have to unregister the provider. 11009 */ 11010 continue; 11011 } 11012 String names[] = p.info.authority.split(";"); 11013 for (int j = 0; j < names.length; j++) { 11014 if (mProvidersByAuthority.get(names[j]) == p) { 11015 mProvidersByAuthority.remove(names[j]); 11016 if (DEBUG_REMOVE) { 11017 if (chatty) 11018 Log.d(TAG, "Unregistered content provider: " + names[j] 11019 + ", className = " + p.info.name + ", isSyncable = " 11020 + p.info.isSyncable); 11021 } 11022 } 11023 } 11024 if (DEBUG_REMOVE && chatty) { 11025 if (r == null) { 11026 r = new StringBuilder(256); 11027 } else { 11028 r.append(' '); 11029 } 11030 r.append(p.info.name); 11031 } 11032 } 11033 if (r != null) { 11034 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11035 } 11036 11037 N = pkg.services.size(); 11038 r = null; 11039 for (i=0; i<N; i++) { 11040 PackageParser.Service s = pkg.services.get(i); 11041 mServices.removeService(s); 11042 if (chatty) { 11043 if (r == null) { 11044 r = new StringBuilder(256); 11045 } else { 11046 r.append(' '); 11047 } 11048 r.append(s.info.name); 11049 } 11050 } 11051 if (r != null) { 11052 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11053 } 11054 11055 N = pkg.receivers.size(); 11056 r = null; 11057 for (i=0; i<N; i++) { 11058 PackageParser.Activity a = pkg.receivers.get(i); 11059 mReceivers.removeActivity(a, "receiver"); 11060 if (DEBUG_REMOVE && chatty) { 11061 if (r == null) { 11062 r = new StringBuilder(256); 11063 } else { 11064 r.append(' '); 11065 } 11066 r.append(a.info.name); 11067 } 11068 } 11069 if (r != null) { 11070 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11071 } 11072 11073 N = pkg.activities.size(); 11074 r = null; 11075 for (i=0; i<N; i++) { 11076 PackageParser.Activity a = pkg.activities.get(i); 11077 mActivities.removeActivity(a, "activity"); 11078 if (DEBUG_REMOVE && chatty) { 11079 if (r == null) { 11080 r = new StringBuilder(256); 11081 } else { 11082 r.append(' '); 11083 } 11084 r.append(a.info.name); 11085 } 11086 } 11087 if (r != null) { 11088 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11089 } 11090 11091 N = pkg.permissions.size(); 11092 r = null; 11093 for (i=0; i<N; i++) { 11094 PackageParser.Permission p = pkg.permissions.get(i); 11095 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11096 if (bp == null) { 11097 bp = mSettings.mPermissionTrees.get(p.info.name); 11098 } 11099 if (bp != null && bp.perm == p) { 11100 bp.perm = null; 11101 if (DEBUG_REMOVE && chatty) { 11102 if (r == null) { 11103 r = new StringBuilder(256); 11104 } else { 11105 r.append(' '); 11106 } 11107 r.append(p.info.name); 11108 } 11109 } 11110 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11111 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11112 if (appOpPkgs != null) { 11113 appOpPkgs.remove(pkg.packageName); 11114 } 11115 } 11116 } 11117 if (r != null) { 11118 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11119 } 11120 11121 N = pkg.requestedPermissions.size(); 11122 r = null; 11123 for (i=0; i<N; i++) { 11124 String perm = pkg.requestedPermissions.get(i); 11125 BasePermission bp = mSettings.mPermissions.get(perm); 11126 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11127 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11128 if (appOpPkgs != null) { 11129 appOpPkgs.remove(pkg.packageName); 11130 if (appOpPkgs.isEmpty()) { 11131 mAppOpPermissionPackages.remove(perm); 11132 } 11133 } 11134 } 11135 } 11136 if (r != null) { 11137 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11138 } 11139 11140 N = pkg.instrumentation.size(); 11141 r = null; 11142 for (i=0; i<N; i++) { 11143 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11144 mInstrumentation.remove(a.getComponentName()); 11145 if (DEBUG_REMOVE && chatty) { 11146 if (r == null) { 11147 r = new StringBuilder(256); 11148 } else { 11149 r.append(' '); 11150 } 11151 r.append(a.info.name); 11152 } 11153 } 11154 if (r != null) { 11155 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11156 } 11157 11158 r = null; 11159 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11160 // Only system apps can hold shared libraries. 11161 if (pkg.libraryNames != null) { 11162 for (i = 0; i < pkg.libraryNames.size(); i++) { 11163 String name = pkg.libraryNames.get(i); 11164 if (removeSharedLibraryLPw(name, 0)) { 11165 if (DEBUG_REMOVE && chatty) { 11166 if (r == null) { 11167 r = new StringBuilder(256); 11168 } else { 11169 r.append(' '); 11170 } 11171 r.append(name); 11172 } 11173 } 11174 } 11175 } 11176 } 11177 11178 r = null; 11179 11180 // Any package can hold static shared libraries. 11181 if (pkg.staticSharedLibName != null) { 11182 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11183 if (DEBUG_REMOVE && chatty) { 11184 if (r == null) { 11185 r = new StringBuilder(256); 11186 } else { 11187 r.append(' '); 11188 } 11189 r.append(pkg.staticSharedLibName); 11190 } 11191 } 11192 } 11193 11194 if (r != null) { 11195 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11196 } 11197 } 11198 11199 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11200 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11201 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11202 return true; 11203 } 11204 } 11205 return false; 11206 } 11207 11208 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11209 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11210 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11211 11212 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11213 // Update the parent permissions 11214 updatePermissionsLPw(pkg.packageName, pkg, flags); 11215 // Update the child permissions 11216 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11217 for (int i = 0; i < childCount; i++) { 11218 PackageParser.Package childPkg = pkg.childPackages.get(i); 11219 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11220 } 11221 } 11222 11223 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11224 int flags) { 11225 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11226 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11227 } 11228 11229 private void updatePermissionsLPw(String changingPkg, 11230 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11231 // Make sure there are no dangling permission trees. 11232 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11233 while (it.hasNext()) { 11234 final BasePermission bp = it.next(); 11235 if (bp.packageSetting == null) { 11236 // We may not yet have parsed the package, so just see if 11237 // we still know about its settings. 11238 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11239 } 11240 if (bp.packageSetting == null) { 11241 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11242 + " from package " + bp.sourcePackage); 11243 it.remove(); 11244 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11245 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11246 Slog.i(TAG, "Removing old permission tree: " + bp.name 11247 + " from package " + bp.sourcePackage); 11248 flags |= UPDATE_PERMISSIONS_ALL; 11249 it.remove(); 11250 } 11251 } 11252 } 11253 11254 // Make sure all dynamic permissions have been assigned to a package, 11255 // and make sure there are no dangling permissions. 11256 it = mSettings.mPermissions.values().iterator(); 11257 while (it.hasNext()) { 11258 final BasePermission bp = it.next(); 11259 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11260 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11261 + bp.name + " pkg=" + bp.sourcePackage 11262 + " info=" + bp.pendingInfo); 11263 if (bp.packageSetting == null && bp.pendingInfo != null) { 11264 final BasePermission tree = findPermissionTreeLP(bp.name); 11265 if (tree != null && tree.perm != null) { 11266 bp.packageSetting = tree.packageSetting; 11267 bp.perm = new PackageParser.Permission(tree.perm.owner, 11268 new PermissionInfo(bp.pendingInfo)); 11269 bp.perm.info.packageName = tree.perm.info.packageName; 11270 bp.perm.info.name = bp.name; 11271 bp.uid = tree.uid; 11272 } 11273 } 11274 } 11275 if (bp.packageSetting == null) { 11276 // We may not yet have parsed the package, so just see if 11277 // we still know about its settings. 11278 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11279 } 11280 if (bp.packageSetting == null) { 11281 Slog.w(TAG, "Removing dangling permission: " + bp.name 11282 + " from package " + bp.sourcePackage); 11283 it.remove(); 11284 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11285 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11286 Slog.i(TAG, "Removing old permission: " + bp.name 11287 + " from package " + bp.sourcePackage); 11288 flags |= UPDATE_PERMISSIONS_ALL; 11289 it.remove(); 11290 } 11291 } 11292 } 11293 11294 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11295 // Now update the permissions for all packages, in particular 11296 // replace the granted permissions of the system packages. 11297 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11298 for (PackageParser.Package pkg : mPackages.values()) { 11299 if (pkg != pkgInfo) { 11300 // Only replace for packages on requested volume 11301 final String volumeUuid = getVolumeUuidForPackage(pkg); 11302 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11303 && Objects.equals(replaceVolumeUuid, volumeUuid); 11304 grantPermissionsLPw(pkg, replace, changingPkg); 11305 } 11306 } 11307 } 11308 11309 if (pkgInfo != null) { 11310 // Only replace for packages on requested volume 11311 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11312 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11313 && Objects.equals(replaceVolumeUuid, volumeUuid); 11314 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11315 } 11316 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11317 } 11318 11319 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11320 String packageOfInterest) { 11321 // IMPORTANT: There are two types of permissions: install and runtime. 11322 // Install time permissions are granted when the app is installed to 11323 // all device users and users added in the future. Runtime permissions 11324 // are granted at runtime explicitly to specific users. Normal and signature 11325 // protected permissions are install time permissions. Dangerous permissions 11326 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11327 // otherwise they are runtime permissions. This function does not manage 11328 // runtime permissions except for the case an app targeting Lollipop MR1 11329 // being upgraded to target a newer SDK, in which case dangerous permissions 11330 // are transformed from install time to runtime ones. 11331 11332 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11333 if (ps == null) { 11334 return; 11335 } 11336 11337 PermissionsState permissionsState = ps.getPermissionsState(); 11338 PermissionsState origPermissions = permissionsState; 11339 11340 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11341 11342 boolean runtimePermissionsRevoked = false; 11343 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11344 11345 boolean changedInstallPermission = false; 11346 11347 if (replace) { 11348 ps.installPermissionsFixed = false; 11349 if (!ps.isSharedUser()) { 11350 origPermissions = new PermissionsState(permissionsState); 11351 permissionsState.reset(); 11352 } else { 11353 // We need to know only about runtime permission changes since the 11354 // calling code always writes the install permissions state but 11355 // the runtime ones are written only if changed. The only cases of 11356 // changed runtime permissions here are promotion of an install to 11357 // runtime and revocation of a runtime from a shared user. 11358 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11359 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11360 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11361 runtimePermissionsRevoked = true; 11362 } 11363 } 11364 } 11365 11366 permissionsState.setGlobalGids(mGlobalGids); 11367 11368 final int N = pkg.requestedPermissions.size(); 11369 for (int i=0; i<N; i++) { 11370 final String name = pkg.requestedPermissions.get(i); 11371 final BasePermission bp = mSettings.mPermissions.get(name); 11372 11373 if (DEBUG_INSTALL) { 11374 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11375 } 11376 11377 if (bp == null || bp.packageSetting == null) { 11378 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11379 Slog.w(TAG, "Unknown permission " + name 11380 + " in package " + pkg.packageName); 11381 } 11382 continue; 11383 } 11384 11385 11386 // Limit ephemeral apps to ephemeral allowed permissions. 11387 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11388 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11389 + pkg.packageName); 11390 continue; 11391 } 11392 11393 final String perm = bp.name; 11394 boolean allowedSig = false; 11395 int grant = GRANT_DENIED; 11396 11397 // Keep track of app op permissions. 11398 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11399 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11400 if (pkgs == null) { 11401 pkgs = new ArraySet<>(); 11402 mAppOpPermissionPackages.put(bp.name, pkgs); 11403 } 11404 pkgs.add(pkg.packageName); 11405 } 11406 11407 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11408 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11409 >= Build.VERSION_CODES.M; 11410 switch (level) { 11411 case PermissionInfo.PROTECTION_NORMAL: { 11412 // For all apps normal permissions are install time ones. 11413 grant = GRANT_INSTALL; 11414 } break; 11415 11416 case PermissionInfo.PROTECTION_DANGEROUS: { 11417 // If a permission review is required for legacy apps we represent 11418 // their permissions as always granted runtime ones since we need 11419 // to keep the review required permission flag per user while an 11420 // install permission's state is shared across all users. 11421 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11422 // For legacy apps dangerous permissions are install time ones. 11423 grant = GRANT_INSTALL; 11424 } else if (origPermissions.hasInstallPermission(bp.name)) { 11425 // For legacy apps that became modern, install becomes runtime. 11426 grant = GRANT_UPGRADE; 11427 } else if (mPromoteSystemApps 11428 && isSystemApp(ps) 11429 && mExistingSystemPackages.contains(ps.name)) { 11430 // For legacy system apps, install becomes runtime. 11431 // We cannot check hasInstallPermission() for system apps since those 11432 // permissions were granted implicitly and not persisted pre-M. 11433 grant = GRANT_UPGRADE; 11434 } else { 11435 // For modern apps keep runtime permissions unchanged. 11436 grant = GRANT_RUNTIME; 11437 } 11438 } break; 11439 11440 case PermissionInfo.PROTECTION_SIGNATURE: { 11441 // For all apps signature permissions are install time ones. 11442 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11443 if (allowedSig) { 11444 grant = GRANT_INSTALL; 11445 } 11446 } break; 11447 } 11448 11449 if (DEBUG_INSTALL) { 11450 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11451 } 11452 11453 if (grant != GRANT_DENIED) { 11454 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11455 // If this is an existing, non-system package, then 11456 // we can't add any new permissions to it. 11457 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11458 // Except... if this is a permission that was added 11459 // to the platform (note: need to only do this when 11460 // updating the platform). 11461 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11462 grant = GRANT_DENIED; 11463 } 11464 } 11465 } 11466 11467 switch (grant) { 11468 case GRANT_INSTALL: { 11469 // Revoke this as runtime permission to handle the case of 11470 // a runtime permission being downgraded to an install one. 11471 // Also in permission review mode we keep dangerous permissions 11472 // for legacy apps 11473 for (int userId : UserManagerService.getInstance().getUserIds()) { 11474 if (origPermissions.getRuntimePermissionState( 11475 bp.name, userId) != null) { 11476 // Revoke the runtime permission and clear the flags. 11477 origPermissions.revokeRuntimePermission(bp, userId); 11478 origPermissions.updatePermissionFlags(bp, userId, 11479 PackageManager.MASK_PERMISSION_FLAGS, 0); 11480 // If we revoked a permission permission, we have to write. 11481 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11482 changedRuntimePermissionUserIds, userId); 11483 } 11484 } 11485 // Grant an install permission. 11486 if (permissionsState.grantInstallPermission(bp) != 11487 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11488 changedInstallPermission = true; 11489 } 11490 } break; 11491 11492 case GRANT_RUNTIME: { 11493 // Grant previously granted runtime permissions. 11494 for (int userId : UserManagerService.getInstance().getUserIds()) { 11495 PermissionState permissionState = origPermissions 11496 .getRuntimePermissionState(bp.name, userId); 11497 int flags = permissionState != null 11498 ? permissionState.getFlags() : 0; 11499 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11500 // Don't propagate the permission in a permission review mode if 11501 // the former was revoked, i.e. marked to not propagate on upgrade. 11502 // Note that in a permission review mode install permissions are 11503 // represented as constantly granted runtime ones since we need to 11504 // keep a per user state associated with the permission. Also the 11505 // revoke on upgrade flag is no longer applicable and is reset. 11506 final boolean revokeOnUpgrade = (flags & PackageManager 11507 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11508 if (revokeOnUpgrade) { 11509 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11510 // Since we changed the flags, we have to write. 11511 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11512 changedRuntimePermissionUserIds, userId); 11513 } 11514 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11515 if (permissionsState.grantRuntimePermission(bp, userId) == 11516 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11517 // If we cannot put the permission as it was, 11518 // we have to write. 11519 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11520 changedRuntimePermissionUserIds, userId); 11521 } 11522 } 11523 11524 // If the app supports runtime permissions no need for a review. 11525 if (mPermissionReviewRequired 11526 && appSupportsRuntimePermissions 11527 && (flags & PackageManager 11528 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11529 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11530 // Since we changed the flags, we have to write. 11531 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11532 changedRuntimePermissionUserIds, userId); 11533 } 11534 } else if (mPermissionReviewRequired 11535 && !appSupportsRuntimePermissions) { 11536 // For legacy apps that need a permission review, every new 11537 // runtime permission is granted but it is pending a review. 11538 // We also need to review only platform defined runtime 11539 // permissions as these are the only ones the platform knows 11540 // how to disable the API to simulate revocation as legacy 11541 // apps don't expect to run with revoked permissions. 11542 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11543 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11544 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11545 // We changed the flags, hence have to write. 11546 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11547 changedRuntimePermissionUserIds, userId); 11548 } 11549 } 11550 if (permissionsState.grantRuntimePermission(bp, userId) 11551 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11552 // We changed the permission, hence have to write. 11553 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11554 changedRuntimePermissionUserIds, userId); 11555 } 11556 } 11557 // Propagate the permission flags. 11558 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11559 } 11560 } break; 11561 11562 case GRANT_UPGRADE: { 11563 // Grant runtime permissions for a previously held install permission. 11564 PermissionState permissionState = origPermissions 11565 .getInstallPermissionState(bp.name); 11566 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11567 11568 if (origPermissions.revokeInstallPermission(bp) 11569 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11570 // We will be transferring the permission flags, so clear them. 11571 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11572 PackageManager.MASK_PERMISSION_FLAGS, 0); 11573 changedInstallPermission = true; 11574 } 11575 11576 // If the permission is not to be promoted to runtime we ignore it and 11577 // also its other flags as they are not applicable to install permissions. 11578 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11579 for (int userId : currentUserIds) { 11580 if (permissionsState.grantRuntimePermission(bp, userId) != 11581 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11582 // Transfer the permission flags. 11583 permissionsState.updatePermissionFlags(bp, userId, 11584 flags, flags); 11585 // If we granted the permission, we have to write. 11586 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11587 changedRuntimePermissionUserIds, userId); 11588 } 11589 } 11590 } 11591 } break; 11592 11593 default: { 11594 if (packageOfInterest == null 11595 || packageOfInterest.equals(pkg.packageName)) { 11596 Slog.w(TAG, "Not granting permission " + perm 11597 + " to package " + pkg.packageName 11598 + " because it was previously installed without"); 11599 } 11600 } break; 11601 } 11602 } else { 11603 if (permissionsState.revokeInstallPermission(bp) != 11604 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11605 // Also drop the permission flags. 11606 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11607 PackageManager.MASK_PERMISSION_FLAGS, 0); 11608 changedInstallPermission = true; 11609 Slog.i(TAG, "Un-granting permission " + perm 11610 + " from package " + pkg.packageName 11611 + " (protectionLevel=" + bp.protectionLevel 11612 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11613 + ")"); 11614 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11615 // Don't print warning for app op permissions, since it is fine for them 11616 // not to be granted, there is a UI for the user to decide. 11617 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11618 Slog.w(TAG, "Not granting permission " + perm 11619 + " to package " + pkg.packageName 11620 + " (protectionLevel=" + bp.protectionLevel 11621 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11622 + ")"); 11623 } 11624 } 11625 } 11626 } 11627 11628 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11629 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11630 // This is the first that we have heard about this package, so the 11631 // permissions we have now selected are fixed until explicitly 11632 // changed. 11633 ps.installPermissionsFixed = true; 11634 } 11635 11636 // Persist the runtime permissions state for users with changes. If permissions 11637 // were revoked because no app in the shared user declares them we have to 11638 // write synchronously to avoid losing runtime permissions state. 11639 for (int userId : changedRuntimePermissionUserIds) { 11640 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11641 } 11642 } 11643 11644 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11645 boolean allowed = false; 11646 final int NP = PackageParser.NEW_PERMISSIONS.length; 11647 for (int ip=0; ip<NP; ip++) { 11648 final PackageParser.NewPermissionInfo npi 11649 = PackageParser.NEW_PERMISSIONS[ip]; 11650 if (npi.name.equals(perm) 11651 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11652 allowed = true; 11653 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11654 + pkg.packageName); 11655 break; 11656 } 11657 } 11658 return allowed; 11659 } 11660 11661 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11662 BasePermission bp, PermissionsState origPermissions) { 11663 boolean privilegedPermission = (bp.protectionLevel 11664 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11665 boolean privappPermissionsDisable = 11666 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11667 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11668 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11669 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11670 && !platformPackage && platformPermission) { 11671 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11672 .getPrivAppPermissions(pkg.packageName); 11673 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11674 if (!whitelisted) { 11675 Slog.w(TAG, "Privileged permission " + perm + " for package " 11676 + pkg.packageName + " - not in privapp-permissions whitelist"); 11677 // Only report violations for apps on system image 11678 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11679 if (mPrivappPermissionsViolations == null) { 11680 mPrivappPermissionsViolations = new ArraySet<>(); 11681 } 11682 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11683 } 11684 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11685 return false; 11686 } 11687 } 11688 } 11689 boolean allowed = (compareSignatures( 11690 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11691 == PackageManager.SIGNATURE_MATCH) 11692 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11693 == PackageManager.SIGNATURE_MATCH); 11694 if (!allowed && privilegedPermission) { 11695 if (isSystemApp(pkg)) { 11696 // For updated system applications, a system permission 11697 // is granted only if it had been defined by the original application. 11698 if (pkg.isUpdatedSystemApp()) { 11699 final PackageSetting sysPs = mSettings 11700 .getDisabledSystemPkgLPr(pkg.packageName); 11701 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11702 // If the original was granted this permission, we take 11703 // that grant decision as read and propagate it to the 11704 // update. 11705 if (sysPs.isPrivileged()) { 11706 allowed = true; 11707 } 11708 } else { 11709 // The system apk may have been updated with an older 11710 // version of the one on the data partition, but which 11711 // granted a new system permission that it didn't have 11712 // before. In this case we do want to allow the app to 11713 // now get the new permission if the ancestral apk is 11714 // privileged to get it. 11715 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11716 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11717 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11718 allowed = true; 11719 break; 11720 } 11721 } 11722 } 11723 // Also if a privileged parent package on the system image or any of 11724 // its children requested a privileged permission, the updated child 11725 // packages can also get the permission. 11726 if (pkg.parentPackage != null) { 11727 final PackageSetting disabledSysParentPs = mSettings 11728 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11729 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11730 && disabledSysParentPs.isPrivileged()) { 11731 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11732 allowed = true; 11733 } else if (disabledSysParentPs.pkg.childPackages != null) { 11734 final int count = disabledSysParentPs.pkg.childPackages.size(); 11735 for (int i = 0; i < count; i++) { 11736 PackageParser.Package disabledSysChildPkg = 11737 disabledSysParentPs.pkg.childPackages.get(i); 11738 if (isPackageRequestingPermission(disabledSysChildPkg, 11739 perm)) { 11740 allowed = true; 11741 break; 11742 } 11743 } 11744 } 11745 } 11746 } 11747 } 11748 } else { 11749 allowed = isPrivilegedApp(pkg); 11750 } 11751 } 11752 } 11753 if (!allowed) { 11754 if (!allowed && (bp.protectionLevel 11755 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11756 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11757 // If this was a previously normal/dangerous permission that got moved 11758 // to a system permission as part of the runtime permission redesign, then 11759 // we still want to blindly grant it to old apps. 11760 allowed = true; 11761 } 11762 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11763 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11764 // If this permission is to be granted to the system installer and 11765 // this app is an installer, then it gets the permission. 11766 allowed = true; 11767 } 11768 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11769 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11770 // If this permission is to be granted to the system verifier and 11771 // this app is a verifier, then it gets the permission. 11772 allowed = true; 11773 } 11774 if (!allowed && (bp.protectionLevel 11775 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11776 && isSystemApp(pkg)) { 11777 // Any pre-installed system app is allowed to get this permission. 11778 allowed = true; 11779 } 11780 if (!allowed && (bp.protectionLevel 11781 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11782 // For development permissions, a development permission 11783 // is granted only if it was already granted. 11784 allowed = origPermissions.hasInstallPermission(perm); 11785 } 11786 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11787 && pkg.packageName.equals(mSetupWizardPackage)) { 11788 // If this permission is to be granted to the system setup wizard and 11789 // this app is a setup wizard, then it gets the permission. 11790 allowed = true; 11791 } 11792 } 11793 return allowed; 11794 } 11795 11796 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11797 final int permCount = pkg.requestedPermissions.size(); 11798 for (int j = 0; j < permCount; j++) { 11799 String requestedPermission = pkg.requestedPermissions.get(j); 11800 if (permission.equals(requestedPermission)) { 11801 return true; 11802 } 11803 } 11804 return false; 11805 } 11806 11807 final class ActivityIntentResolver 11808 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11809 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11810 boolean defaultOnly, int userId) { 11811 if (!sUserManager.exists(userId)) return null; 11812 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11813 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11814 } 11815 11816 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11817 int userId) { 11818 if (!sUserManager.exists(userId)) return null; 11819 mFlags = flags; 11820 return super.queryIntent(intent, resolvedType, 11821 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11822 userId); 11823 } 11824 11825 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11826 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11827 if (!sUserManager.exists(userId)) return null; 11828 if (packageActivities == null) { 11829 return null; 11830 } 11831 mFlags = flags; 11832 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11833 final int N = packageActivities.size(); 11834 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11835 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11836 11837 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11838 for (int i = 0; i < N; ++i) { 11839 intentFilters = packageActivities.get(i).intents; 11840 if (intentFilters != null && intentFilters.size() > 0) { 11841 PackageParser.ActivityIntentInfo[] array = 11842 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11843 intentFilters.toArray(array); 11844 listCut.add(array); 11845 } 11846 } 11847 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11848 } 11849 11850 /** 11851 * Finds a privileged activity that matches the specified activity names. 11852 */ 11853 private PackageParser.Activity findMatchingActivity( 11854 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11855 for (PackageParser.Activity sysActivity : activityList) { 11856 if (sysActivity.info.name.equals(activityInfo.name)) { 11857 return sysActivity; 11858 } 11859 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11860 return sysActivity; 11861 } 11862 if (sysActivity.info.targetActivity != null) { 11863 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11864 return sysActivity; 11865 } 11866 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11867 return sysActivity; 11868 } 11869 } 11870 } 11871 return null; 11872 } 11873 11874 public class IterGenerator<E> { 11875 public Iterator<E> generate(ActivityIntentInfo info) { 11876 return null; 11877 } 11878 } 11879 11880 public class ActionIterGenerator extends IterGenerator<String> { 11881 @Override 11882 public Iterator<String> generate(ActivityIntentInfo info) { 11883 return info.actionsIterator(); 11884 } 11885 } 11886 11887 public class CategoriesIterGenerator extends IterGenerator<String> { 11888 @Override 11889 public Iterator<String> generate(ActivityIntentInfo info) { 11890 return info.categoriesIterator(); 11891 } 11892 } 11893 11894 public class SchemesIterGenerator extends IterGenerator<String> { 11895 @Override 11896 public Iterator<String> generate(ActivityIntentInfo info) { 11897 return info.schemesIterator(); 11898 } 11899 } 11900 11901 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11902 @Override 11903 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11904 return info.authoritiesIterator(); 11905 } 11906 } 11907 11908 /** 11909 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11910 * MODIFIED. Do not pass in a list that should not be changed. 11911 */ 11912 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11913 IterGenerator<T> generator, Iterator<T> searchIterator) { 11914 // loop through the set of actions; every one must be found in the intent filter 11915 while (searchIterator.hasNext()) { 11916 // we must have at least one filter in the list to consider a match 11917 if (intentList.size() == 0) { 11918 break; 11919 } 11920 11921 final T searchAction = searchIterator.next(); 11922 11923 // loop through the set of intent filters 11924 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11925 while (intentIter.hasNext()) { 11926 final ActivityIntentInfo intentInfo = intentIter.next(); 11927 boolean selectionFound = false; 11928 11929 // loop through the intent filter's selection criteria; at least one 11930 // of them must match the searched criteria 11931 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11932 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11933 final T intentSelection = intentSelectionIter.next(); 11934 if (intentSelection != null && intentSelection.equals(searchAction)) { 11935 selectionFound = true; 11936 break; 11937 } 11938 } 11939 11940 // the selection criteria wasn't found in this filter's set; this filter 11941 // is not a potential match 11942 if (!selectionFound) { 11943 intentIter.remove(); 11944 } 11945 } 11946 } 11947 } 11948 11949 private boolean isProtectedAction(ActivityIntentInfo filter) { 11950 final Iterator<String> actionsIter = filter.actionsIterator(); 11951 while (actionsIter != null && actionsIter.hasNext()) { 11952 final String filterAction = actionsIter.next(); 11953 if (PROTECTED_ACTIONS.contains(filterAction)) { 11954 return true; 11955 } 11956 } 11957 return false; 11958 } 11959 11960 /** 11961 * Adjusts the priority of the given intent filter according to policy. 11962 * <p> 11963 * <ul> 11964 * <li>The priority for non privileged applications is capped to '0'</li> 11965 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11966 * <li>The priority for unbundled updates to privileged applications is capped to the 11967 * priority defined on the system partition</li> 11968 * </ul> 11969 * <p> 11970 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11971 * allowed to obtain any priority on any action. 11972 */ 11973 private void adjustPriority( 11974 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11975 // nothing to do; priority is fine as-is 11976 if (intent.getPriority() <= 0) { 11977 return; 11978 } 11979 11980 final ActivityInfo activityInfo = intent.activity.info; 11981 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11982 11983 final boolean privilegedApp = 11984 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11985 if (!privilegedApp) { 11986 // non-privileged applications can never define a priority >0 11987 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11988 + " package: " + applicationInfo.packageName 11989 + " activity: " + intent.activity.className 11990 + " origPrio: " + intent.getPriority()); 11991 intent.setPriority(0); 11992 return; 11993 } 11994 11995 if (systemActivities == null) { 11996 // the system package is not disabled; we're parsing the system partition 11997 if (isProtectedAction(intent)) { 11998 if (mDeferProtectedFilters) { 11999 // We can't deal with these just yet. No component should ever obtain a 12000 // >0 priority for a protected actions, with ONE exception -- the setup 12001 // wizard. The setup wizard, however, cannot be known until we're able to 12002 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12003 // until all intent filters have been processed. Chicken, meet egg. 12004 // Let the filter temporarily have a high priority and rectify the 12005 // priorities after all system packages have been scanned. 12006 mProtectedFilters.add(intent); 12007 if (DEBUG_FILTERS) { 12008 Slog.i(TAG, "Protected action; save for later;" 12009 + " package: " + applicationInfo.packageName 12010 + " activity: " + intent.activity.className 12011 + " origPrio: " + intent.getPriority()); 12012 } 12013 return; 12014 } else { 12015 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12016 Slog.i(TAG, "No setup wizard;" 12017 + " All protected intents capped to priority 0"); 12018 } 12019 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12020 if (DEBUG_FILTERS) { 12021 Slog.i(TAG, "Found setup wizard;" 12022 + " allow priority " + intent.getPriority() + ";" 12023 + " package: " + intent.activity.info.packageName 12024 + " activity: " + intent.activity.className 12025 + " priority: " + intent.getPriority()); 12026 } 12027 // setup wizard gets whatever it wants 12028 return; 12029 } 12030 Slog.w(TAG, "Protected action; cap priority to 0;" 12031 + " package: " + intent.activity.info.packageName 12032 + " activity: " + intent.activity.className 12033 + " origPrio: " + intent.getPriority()); 12034 intent.setPriority(0); 12035 return; 12036 } 12037 } 12038 // privileged apps on the system image get whatever priority they request 12039 return; 12040 } 12041 12042 // privileged app unbundled update ... try to find the same activity 12043 final PackageParser.Activity foundActivity = 12044 findMatchingActivity(systemActivities, activityInfo); 12045 if (foundActivity == null) { 12046 // this is a new activity; it cannot obtain >0 priority 12047 if (DEBUG_FILTERS) { 12048 Slog.i(TAG, "New activity; cap priority to 0;" 12049 + " package: " + applicationInfo.packageName 12050 + " activity: " + intent.activity.className 12051 + " origPrio: " + intent.getPriority()); 12052 } 12053 intent.setPriority(0); 12054 return; 12055 } 12056 12057 // found activity, now check for filter equivalence 12058 12059 // a shallow copy is enough; we modify the list, not its contents 12060 final List<ActivityIntentInfo> intentListCopy = 12061 new ArrayList<>(foundActivity.intents); 12062 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12063 12064 // find matching action subsets 12065 final Iterator<String> actionsIterator = intent.actionsIterator(); 12066 if (actionsIterator != null) { 12067 getIntentListSubset( 12068 intentListCopy, new ActionIterGenerator(), actionsIterator); 12069 if (intentListCopy.size() == 0) { 12070 // no more intents to match; we're not equivalent 12071 if (DEBUG_FILTERS) { 12072 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12073 + " package: " + applicationInfo.packageName 12074 + " activity: " + intent.activity.className 12075 + " origPrio: " + intent.getPriority()); 12076 } 12077 intent.setPriority(0); 12078 return; 12079 } 12080 } 12081 12082 // find matching category subsets 12083 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12084 if (categoriesIterator != null) { 12085 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12086 categoriesIterator); 12087 if (intentListCopy.size() == 0) { 12088 // no more intents to match; we're not equivalent 12089 if (DEBUG_FILTERS) { 12090 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12091 + " package: " + applicationInfo.packageName 12092 + " activity: " + intent.activity.className 12093 + " origPrio: " + intent.getPriority()); 12094 } 12095 intent.setPriority(0); 12096 return; 12097 } 12098 } 12099 12100 // find matching schemes subsets 12101 final Iterator<String> schemesIterator = intent.schemesIterator(); 12102 if (schemesIterator != null) { 12103 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12104 schemesIterator); 12105 if (intentListCopy.size() == 0) { 12106 // no more intents to match; we're not equivalent 12107 if (DEBUG_FILTERS) { 12108 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12109 + " package: " + applicationInfo.packageName 12110 + " activity: " + intent.activity.className 12111 + " origPrio: " + intent.getPriority()); 12112 } 12113 intent.setPriority(0); 12114 return; 12115 } 12116 } 12117 12118 // find matching authorities subsets 12119 final Iterator<IntentFilter.AuthorityEntry> 12120 authoritiesIterator = intent.authoritiesIterator(); 12121 if (authoritiesIterator != null) { 12122 getIntentListSubset(intentListCopy, 12123 new AuthoritiesIterGenerator(), 12124 authoritiesIterator); 12125 if (intentListCopy.size() == 0) { 12126 // no more intents to match; we're not equivalent 12127 if (DEBUG_FILTERS) { 12128 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12129 + " package: " + applicationInfo.packageName 12130 + " activity: " + intent.activity.className 12131 + " origPrio: " + intent.getPriority()); 12132 } 12133 intent.setPriority(0); 12134 return; 12135 } 12136 } 12137 12138 // we found matching filter(s); app gets the max priority of all intents 12139 int cappedPriority = 0; 12140 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12141 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12142 } 12143 if (intent.getPriority() > cappedPriority) { 12144 if (DEBUG_FILTERS) { 12145 Slog.i(TAG, "Found matching filter(s);" 12146 + " cap priority to " + cappedPriority + ";" 12147 + " package: " + applicationInfo.packageName 12148 + " activity: " + intent.activity.className 12149 + " origPrio: " + intent.getPriority()); 12150 } 12151 intent.setPriority(cappedPriority); 12152 return; 12153 } 12154 // all this for nothing; the requested priority was <= what was on the system 12155 } 12156 12157 public final void addActivity(PackageParser.Activity a, String type) { 12158 mActivities.put(a.getComponentName(), a); 12159 if (DEBUG_SHOW_INFO) 12160 Log.v( 12161 TAG, " " + type + " " + 12162 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12163 if (DEBUG_SHOW_INFO) 12164 Log.v(TAG, " Class=" + a.info.name); 12165 final int NI = a.intents.size(); 12166 for (int j=0; j<NI; j++) { 12167 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12168 if ("activity".equals(type)) { 12169 final PackageSetting ps = 12170 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12171 final List<PackageParser.Activity> systemActivities = 12172 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12173 adjustPriority(systemActivities, intent); 12174 } 12175 if (DEBUG_SHOW_INFO) { 12176 Log.v(TAG, " IntentFilter:"); 12177 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12178 } 12179 if (!intent.debugCheck()) { 12180 Log.w(TAG, "==> For Activity " + a.info.name); 12181 } 12182 addFilter(intent); 12183 } 12184 } 12185 12186 public final void removeActivity(PackageParser.Activity a, String type) { 12187 mActivities.remove(a.getComponentName()); 12188 if (DEBUG_SHOW_INFO) { 12189 Log.v(TAG, " " + type + " " 12190 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12191 : a.info.name) + ":"); 12192 Log.v(TAG, " Class=" + a.info.name); 12193 } 12194 final int NI = a.intents.size(); 12195 for (int j=0; j<NI; j++) { 12196 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12197 if (DEBUG_SHOW_INFO) { 12198 Log.v(TAG, " IntentFilter:"); 12199 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12200 } 12201 removeFilter(intent); 12202 } 12203 } 12204 12205 @Override 12206 protected boolean allowFilterResult( 12207 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12208 ActivityInfo filterAi = filter.activity.info; 12209 for (int i=dest.size()-1; i>=0; i--) { 12210 ActivityInfo destAi = dest.get(i).activityInfo; 12211 if (destAi.name == filterAi.name 12212 && destAi.packageName == filterAi.packageName) { 12213 return false; 12214 } 12215 } 12216 return true; 12217 } 12218 12219 @Override 12220 protected ActivityIntentInfo[] newArray(int size) { 12221 return new ActivityIntentInfo[size]; 12222 } 12223 12224 @Override 12225 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12226 if (!sUserManager.exists(userId)) return true; 12227 PackageParser.Package p = filter.activity.owner; 12228 if (p != null) { 12229 PackageSetting ps = (PackageSetting)p.mExtras; 12230 if (ps != null) { 12231 // System apps are never considered stopped for purposes of 12232 // filtering, because there may be no way for the user to 12233 // actually re-launch them. 12234 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12235 && ps.getStopped(userId); 12236 } 12237 } 12238 return false; 12239 } 12240 12241 @Override 12242 protected boolean isPackageForFilter(String packageName, 12243 PackageParser.ActivityIntentInfo info) { 12244 return packageName.equals(info.activity.owner.packageName); 12245 } 12246 12247 @Override 12248 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12249 int match, int userId) { 12250 if (!sUserManager.exists(userId)) return null; 12251 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12252 return null; 12253 } 12254 final PackageParser.Activity activity = info.activity; 12255 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12256 if (ps == null) { 12257 return null; 12258 } 12259 final PackageUserState userState = ps.readUserState(userId); 12260 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12261 userState, userId); 12262 if (ai == null) { 12263 return null; 12264 } 12265 final boolean matchVisibleToInstantApp = 12266 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12267 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12268 // throw out filters that aren't visible to ephemeral apps 12269 if (matchVisibleToInstantApp 12270 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12271 return null; 12272 } 12273 // throw out ephemeral filters if we're not explicitly requesting them 12274 if (!isInstantApp && userState.instantApp) { 12275 return null; 12276 } 12277 // throw out instant app filters if updates are available; will trigger 12278 // instant app resolution 12279 if (userState.instantApp && ps.isUpdateAvailable()) { 12280 return null; 12281 } 12282 final ResolveInfo res = new ResolveInfo(); 12283 res.activityInfo = ai; 12284 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12285 res.filter = info; 12286 } 12287 if (info != null) { 12288 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12289 } 12290 res.priority = info.getPriority(); 12291 res.preferredOrder = activity.owner.mPreferredOrder; 12292 //System.out.println("Result: " + res.activityInfo.className + 12293 // " = " + res.priority); 12294 res.match = match; 12295 res.isDefault = info.hasDefault; 12296 res.labelRes = info.labelRes; 12297 res.nonLocalizedLabel = info.nonLocalizedLabel; 12298 if (userNeedsBadging(userId)) { 12299 res.noResourceId = true; 12300 } else { 12301 res.icon = info.icon; 12302 } 12303 res.iconResourceId = info.icon; 12304 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12305 res.instantAppAvailable = userState.instantApp; 12306 return res; 12307 } 12308 12309 @Override 12310 protected void sortResults(List<ResolveInfo> results) { 12311 Collections.sort(results, mResolvePrioritySorter); 12312 } 12313 12314 @Override 12315 protected void dumpFilter(PrintWriter out, String prefix, 12316 PackageParser.ActivityIntentInfo filter) { 12317 out.print(prefix); out.print( 12318 Integer.toHexString(System.identityHashCode(filter.activity))); 12319 out.print(' '); 12320 filter.activity.printComponentShortName(out); 12321 out.print(" filter "); 12322 out.println(Integer.toHexString(System.identityHashCode(filter))); 12323 } 12324 12325 @Override 12326 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12327 return filter.activity; 12328 } 12329 12330 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12331 PackageParser.Activity activity = (PackageParser.Activity)label; 12332 out.print(prefix); out.print( 12333 Integer.toHexString(System.identityHashCode(activity))); 12334 out.print(' '); 12335 activity.printComponentShortName(out); 12336 if (count > 1) { 12337 out.print(" ("); out.print(count); out.print(" filters)"); 12338 } 12339 out.println(); 12340 } 12341 12342 // Keys are String (activity class name), values are Activity. 12343 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12344 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12345 private int mFlags; 12346 } 12347 12348 private final class ServiceIntentResolver 12349 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12350 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12351 boolean defaultOnly, int userId) { 12352 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12353 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12354 } 12355 12356 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12357 int userId) { 12358 if (!sUserManager.exists(userId)) return null; 12359 mFlags = flags; 12360 return super.queryIntent(intent, resolvedType, 12361 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12362 userId); 12363 } 12364 12365 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12366 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12367 if (!sUserManager.exists(userId)) return null; 12368 if (packageServices == null) { 12369 return null; 12370 } 12371 mFlags = flags; 12372 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12373 final int N = packageServices.size(); 12374 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12375 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12376 12377 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12378 for (int i = 0; i < N; ++i) { 12379 intentFilters = packageServices.get(i).intents; 12380 if (intentFilters != null && intentFilters.size() > 0) { 12381 PackageParser.ServiceIntentInfo[] array = 12382 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12383 intentFilters.toArray(array); 12384 listCut.add(array); 12385 } 12386 } 12387 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12388 } 12389 12390 public final void addService(PackageParser.Service s) { 12391 mServices.put(s.getComponentName(), s); 12392 if (DEBUG_SHOW_INFO) { 12393 Log.v(TAG, " " 12394 + (s.info.nonLocalizedLabel != null 12395 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12396 Log.v(TAG, " Class=" + s.info.name); 12397 } 12398 final int NI = s.intents.size(); 12399 int j; 12400 for (j=0; j<NI; j++) { 12401 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12402 if (DEBUG_SHOW_INFO) { 12403 Log.v(TAG, " IntentFilter:"); 12404 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12405 } 12406 if (!intent.debugCheck()) { 12407 Log.w(TAG, "==> For Service " + s.info.name); 12408 } 12409 addFilter(intent); 12410 } 12411 } 12412 12413 public final void removeService(PackageParser.Service s) { 12414 mServices.remove(s.getComponentName()); 12415 if (DEBUG_SHOW_INFO) { 12416 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12417 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12418 Log.v(TAG, " Class=" + s.info.name); 12419 } 12420 final int NI = s.intents.size(); 12421 int j; 12422 for (j=0; j<NI; j++) { 12423 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12424 if (DEBUG_SHOW_INFO) { 12425 Log.v(TAG, " IntentFilter:"); 12426 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12427 } 12428 removeFilter(intent); 12429 } 12430 } 12431 12432 @Override 12433 protected boolean allowFilterResult( 12434 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12435 ServiceInfo filterSi = filter.service.info; 12436 for (int i=dest.size()-1; i>=0; i--) { 12437 ServiceInfo destAi = dest.get(i).serviceInfo; 12438 if (destAi.name == filterSi.name 12439 && destAi.packageName == filterSi.packageName) { 12440 return false; 12441 } 12442 } 12443 return true; 12444 } 12445 12446 @Override 12447 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12448 return new PackageParser.ServiceIntentInfo[size]; 12449 } 12450 12451 @Override 12452 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12453 if (!sUserManager.exists(userId)) return true; 12454 PackageParser.Package p = filter.service.owner; 12455 if (p != null) { 12456 PackageSetting ps = (PackageSetting)p.mExtras; 12457 if (ps != null) { 12458 // System apps are never considered stopped for purposes of 12459 // filtering, because there may be no way for the user to 12460 // actually re-launch them. 12461 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12462 && ps.getStopped(userId); 12463 } 12464 } 12465 return false; 12466 } 12467 12468 @Override 12469 protected boolean isPackageForFilter(String packageName, 12470 PackageParser.ServiceIntentInfo info) { 12471 return packageName.equals(info.service.owner.packageName); 12472 } 12473 12474 @Override 12475 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12476 int match, int userId) { 12477 if (!sUserManager.exists(userId)) return null; 12478 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12479 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12480 return null; 12481 } 12482 final PackageParser.Service service = info.service; 12483 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12484 if (ps == null) { 12485 return null; 12486 } 12487 final PackageUserState userState = ps.readUserState(userId); 12488 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12489 userState, userId); 12490 if (si == null) { 12491 return null; 12492 } 12493 final boolean matchVisibleToInstantApp = 12494 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12495 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12496 // throw out filters that aren't visible to ephemeral apps 12497 if (matchVisibleToInstantApp 12498 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12499 return null; 12500 } 12501 // throw out ephemeral filters if we're not explicitly requesting them 12502 if (!isInstantApp && userState.instantApp) { 12503 return null; 12504 } 12505 // throw out instant app filters if updates are available; will trigger 12506 // instant app resolution 12507 if (userState.instantApp && ps.isUpdateAvailable()) { 12508 return null; 12509 } 12510 final ResolveInfo res = new ResolveInfo(); 12511 res.serviceInfo = si; 12512 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12513 res.filter = filter; 12514 } 12515 res.priority = info.getPriority(); 12516 res.preferredOrder = service.owner.mPreferredOrder; 12517 res.match = match; 12518 res.isDefault = info.hasDefault; 12519 res.labelRes = info.labelRes; 12520 res.nonLocalizedLabel = info.nonLocalizedLabel; 12521 res.icon = info.icon; 12522 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12523 return res; 12524 } 12525 12526 @Override 12527 protected void sortResults(List<ResolveInfo> results) { 12528 Collections.sort(results, mResolvePrioritySorter); 12529 } 12530 12531 @Override 12532 protected void dumpFilter(PrintWriter out, String prefix, 12533 PackageParser.ServiceIntentInfo filter) { 12534 out.print(prefix); out.print( 12535 Integer.toHexString(System.identityHashCode(filter.service))); 12536 out.print(' '); 12537 filter.service.printComponentShortName(out); 12538 out.print(" filter "); 12539 out.println(Integer.toHexString(System.identityHashCode(filter))); 12540 } 12541 12542 @Override 12543 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12544 return filter.service; 12545 } 12546 12547 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12548 PackageParser.Service service = (PackageParser.Service)label; 12549 out.print(prefix); out.print( 12550 Integer.toHexString(System.identityHashCode(service))); 12551 out.print(' '); 12552 service.printComponentShortName(out); 12553 if (count > 1) { 12554 out.print(" ("); out.print(count); out.print(" filters)"); 12555 } 12556 out.println(); 12557 } 12558 12559// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12560// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12561// final List<ResolveInfo> retList = Lists.newArrayList(); 12562// while (i.hasNext()) { 12563// final ResolveInfo resolveInfo = (ResolveInfo) i; 12564// if (isEnabledLP(resolveInfo.serviceInfo)) { 12565// retList.add(resolveInfo); 12566// } 12567// } 12568// return retList; 12569// } 12570 12571 // Keys are String (activity class name), values are Activity. 12572 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12573 = new ArrayMap<ComponentName, PackageParser.Service>(); 12574 private int mFlags; 12575 } 12576 12577 private final class ProviderIntentResolver 12578 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12579 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12580 boolean defaultOnly, int userId) { 12581 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12582 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12583 } 12584 12585 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12586 int userId) { 12587 if (!sUserManager.exists(userId)) 12588 return null; 12589 mFlags = flags; 12590 return super.queryIntent(intent, resolvedType, 12591 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12592 userId); 12593 } 12594 12595 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12596 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12597 if (!sUserManager.exists(userId)) 12598 return null; 12599 if (packageProviders == null) { 12600 return null; 12601 } 12602 mFlags = flags; 12603 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12604 final int N = packageProviders.size(); 12605 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12606 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12607 12608 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12609 for (int i = 0; i < N; ++i) { 12610 intentFilters = packageProviders.get(i).intents; 12611 if (intentFilters != null && intentFilters.size() > 0) { 12612 PackageParser.ProviderIntentInfo[] array = 12613 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12614 intentFilters.toArray(array); 12615 listCut.add(array); 12616 } 12617 } 12618 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12619 } 12620 12621 public final void addProvider(PackageParser.Provider p) { 12622 if (mProviders.containsKey(p.getComponentName())) { 12623 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12624 return; 12625 } 12626 12627 mProviders.put(p.getComponentName(), p); 12628 if (DEBUG_SHOW_INFO) { 12629 Log.v(TAG, " " 12630 + (p.info.nonLocalizedLabel != null 12631 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12632 Log.v(TAG, " Class=" + p.info.name); 12633 } 12634 final int NI = p.intents.size(); 12635 int j; 12636 for (j = 0; j < NI; j++) { 12637 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12638 if (DEBUG_SHOW_INFO) { 12639 Log.v(TAG, " IntentFilter:"); 12640 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12641 } 12642 if (!intent.debugCheck()) { 12643 Log.w(TAG, "==> For Provider " + p.info.name); 12644 } 12645 addFilter(intent); 12646 } 12647 } 12648 12649 public final void removeProvider(PackageParser.Provider p) { 12650 mProviders.remove(p.getComponentName()); 12651 if (DEBUG_SHOW_INFO) { 12652 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12653 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12654 Log.v(TAG, " Class=" + p.info.name); 12655 } 12656 final int NI = p.intents.size(); 12657 int j; 12658 for (j = 0; j < NI; j++) { 12659 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12660 if (DEBUG_SHOW_INFO) { 12661 Log.v(TAG, " IntentFilter:"); 12662 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12663 } 12664 removeFilter(intent); 12665 } 12666 } 12667 12668 @Override 12669 protected boolean allowFilterResult( 12670 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12671 ProviderInfo filterPi = filter.provider.info; 12672 for (int i = dest.size() - 1; i >= 0; i--) { 12673 ProviderInfo destPi = dest.get(i).providerInfo; 12674 if (destPi.name == filterPi.name 12675 && destPi.packageName == filterPi.packageName) { 12676 return false; 12677 } 12678 } 12679 return true; 12680 } 12681 12682 @Override 12683 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12684 return new PackageParser.ProviderIntentInfo[size]; 12685 } 12686 12687 @Override 12688 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12689 if (!sUserManager.exists(userId)) 12690 return true; 12691 PackageParser.Package p = filter.provider.owner; 12692 if (p != null) { 12693 PackageSetting ps = (PackageSetting) p.mExtras; 12694 if (ps != null) { 12695 // System apps are never considered stopped for purposes of 12696 // filtering, because there may be no way for the user to 12697 // actually re-launch them. 12698 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12699 && ps.getStopped(userId); 12700 } 12701 } 12702 return false; 12703 } 12704 12705 @Override 12706 protected boolean isPackageForFilter(String packageName, 12707 PackageParser.ProviderIntentInfo info) { 12708 return packageName.equals(info.provider.owner.packageName); 12709 } 12710 12711 @Override 12712 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12713 int match, int userId) { 12714 if (!sUserManager.exists(userId)) 12715 return null; 12716 final PackageParser.ProviderIntentInfo info = filter; 12717 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12718 return null; 12719 } 12720 final PackageParser.Provider provider = info.provider; 12721 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12722 if (ps == null) { 12723 return null; 12724 } 12725 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12726 ps.readUserState(userId), userId); 12727 if (pi == null) { 12728 return null; 12729 } 12730 final ResolveInfo res = new ResolveInfo(); 12731 res.providerInfo = pi; 12732 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12733 res.filter = filter; 12734 } 12735 res.priority = info.getPriority(); 12736 res.preferredOrder = provider.owner.mPreferredOrder; 12737 res.match = match; 12738 res.isDefault = info.hasDefault; 12739 res.labelRes = info.labelRes; 12740 res.nonLocalizedLabel = info.nonLocalizedLabel; 12741 res.icon = info.icon; 12742 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12743 return res; 12744 } 12745 12746 @Override 12747 protected void sortResults(List<ResolveInfo> results) { 12748 Collections.sort(results, mResolvePrioritySorter); 12749 } 12750 12751 @Override 12752 protected void dumpFilter(PrintWriter out, String prefix, 12753 PackageParser.ProviderIntentInfo filter) { 12754 out.print(prefix); 12755 out.print( 12756 Integer.toHexString(System.identityHashCode(filter.provider))); 12757 out.print(' '); 12758 filter.provider.printComponentShortName(out); 12759 out.print(" filter "); 12760 out.println(Integer.toHexString(System.identityHashCode(filter))); 12761 } 12762 12763 @Override 12764 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12765 return filter.provider; 12766 } 12767 12768 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12769 PackageParser.Provider provider = (PackageParser.Provider)label; 12770 out.print(prefix); out.print( 12771 Integer.toHexString(System.identityHashCode(provider))); 12772 out.print(' '); 12773 provider.printComponentShortName(out); 12774 if (count > 1) { 12775 out.print(" ("); out.print(count); out.print(" filters)"); 12776 } 12777 out.println(); 12778 } 12779 12780 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12781 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12782 private int mFlags; 12783 } 12784 12785 static final class EphemeralIntentResolver 12786 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12787 /** 12788 * The result that has the highest defined order. Ordering applies on a 12789 * per-package basis. Mapping is from package name to Pair of order and 12790 * EphemeralResolveInfo. 12791 * <p> 12792 * NOTE: This is implemented as a field variable for convenience and efficiency. 12793 * By having a field variable, we're able to track filter ordering as soon as 12794 * a non-zero order is defined. Otherwise, multiple loops across the result set 12795 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12796 * this needs to be contained entirely within {@link #filterResults}. 12797 */ 12798 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12799 12800 @Override 12801 protected AuxiliaryResolveInfo[] newArray(int size) { 12802 return new AuxiliaryResolveInfo[size]; 12803 } 12804 12805 @Override 12806 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12807 return true; 12808 } 12809 12810 @Override 12811 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12812 int userId) { 12813 if (!sUserManager.exists(userId)) { 12814 return null; 12815 } 12816 final String packageName = responseObj.resolveInfo.getPackageName(); 12817 final Integer order = responseObj.getOrder(); 12818 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12819 mOrderResult.get(packageName); 12820 // ordering is enabled and this item's order isn't high enough 12821 if (lastOrderResult != null && lastOrderResult.first >= order) { 12822 return null; 12823 } 12824 final InstantAppResolveInfo res = responseObj.resolveInfo; 12825 if (order > 0) { 12826 // non-zero order, enable ordering 12827 mOrderResult.put(packageName, new Pair<>(order, res)); 12828 } 12829 return responseObj; 12830 } 12831 12832 @Override 12833 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12834 // only do work if ordering is enabled [most of the time it won't be] 12835 if (mOrderResult.size() == 0) { 12836 return; 12837 } 12838 int resultSize = results.size(); 12839 for (int i = 0; i < resultSize; i++) { 12840 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12841 final String packageName = info.getPackageName(); 12842 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12843 if (savedInfo == null) { 12844 // package doesn't having ordering 12845 continue; 12846 } 12847 if (savedInfo.second == info) { 12848 // circled back to the highest ordered item; remove from order list 12849 mOrderResult.remove(savedInfo); 12850 if (mOrderResult.size() == 0) { 12851 // no more ordered items 12852 break; 12853 } 12854 continue; 12855 } 12856 // item has a worse order, remove it from the result list 12857 results.remove(i); 12858 resultSize--; 12859 i--; 12860 } 12861 } 12862 } 12863 12864 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12865 new Comparator<ResolveInfo>() { 12866 public int compare(ResolveInfo r1, ResolveInfo r2) { 12867 int v1 = r1.priority; 12868 int v2 = r2.priority; 12869 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12870 if (v1 != v2) { 12871 return (v1 > v2) ? -1 : 1; 12872 } 12873 v1 = r1.preferredOrder; 12874 v2 = r2.preferredOrder; 12875 if (v1 != v2) { 12876 return (v1 > v2) ? -1 : 1; 12877 } 12878 if (r1.isDefault != r2.isDefault) { 12879 return r1.isDefault ? -1 : 1; 12880 } 12881 v1 = r1.match; 12882 v2 = r2.match; 12883 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12884 if (v1 != v2) { 12885 return (v1 > v2) ? -1 : 1; 12886 } 12887 if (r1.system != r2.system) { 12888 return r1.system ? -1 : 1; 12889 } 12890 if (r1.activityInfo != null) { 12891 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12892 } 12893 if (r1.serviceInfo != null) { 12894 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12895 } 12896 if (r1.providerInfo != null) { 12897 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12898 } 12899 return 0; 12900 } 12901 }; 12902 12903 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12904 new Comparator<ProviderInfo>() { 12905 public int compare(ProviderInfo p1, ProviderInfo p2) { 12906 final int v1 = p1.initOrder; 12907 final int v2 = p2.initOrder; 12908 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12909 } 12910 }; 12911 12912 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12913 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12914 final int[] userIds) { 12915 mHandler.post(new Runnable() { 12916 @Override 12917 public void run() { 12918 try { 12919 final IActivityManager am = ActivityManager.getService(); 12920 if (am == null) return; 12921 final int[] resolvedUserIds; 12922 if (userIds == null) { 12923 resolvedUserIds = am.getRunningUserIds(); 12924 } else { 12925 resolvedUserIds = userIds; 12926 } 12927 for (int id : resolvedUserIds) { 12928 final Intent intent = new Intent(action, 12929 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12930 if (extras != null) { 12931 intent.putExtras(extras); 12932 } 12933 if (targetPkg != null) { 12934 intent.setPackage(targetPkg); 12935 } 12936 // Modify the UID when posting to other users 12937 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12938 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12939 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12940 intent.putExtra(Intent.EXTRA_UID, uid); 12941 } 12942 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12943 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12944 if (DEBUG_BROADCASTS) { 12945 RuntimeException here = new RuntimeException("here"); 12946 here.fillInStackTrace(); 12947 Slog.d(TAG, "Sending to user " + id + ": " 12948 + intent.toShortString(false, true, false, false) 12949 + " " + intent.getExtras(), here); 12950 } 12951 am.broadcastIntent(null, intent, null, finishedReceiver, 12952 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12953 null, finishedReceiver != null, false, id); 12954 } 12955 } catch (RemoteException ex) { 12956 } 12957 } 12958 }); 12959 } 12960 12961 /** 12962 * Check if the external storage media is available. This is true if there 12963 * is a mounted external storage medium or if the external storage is 12964 * emulated. 12965 */ 12966 private boolean isExternalMediaAvailable() { 12967 return mMediaMounted || Environment.isExternalStorageEmulated(); 12968 } 12969 12970 @Override 12971 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12972 // writer 12973 synchronized (mPackages) { 12974 if (!isExternalMediaAvailable()) { 12975 // If the external storage is no longer mounted at this point, 12976 // the caller may not have been able to delete all of this 12977 // packages files and can not delete any more. Bail. 12978 return null; 12979 } 12980 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12981 if (lastPackage != null) { 12982 pkgs.remove(lastPackage); 12983 } 12984 if (pkgs.size() > 0) { 12985 return pkgs.get(0); 12986 } 12987 } 12988 return null; 12989 } 12990 12991 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12992 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12993 userId, andCode ? 1 : 0, packageName); 12994 if (mSystemReady) { 12995 msg.sendToTarget(); 12996 } else { 12997 if (mPostSystemReadyMessages == null) { 12998 mPostSystemReadyMessages = new ArrayList<>(); 12999 } 13000 mPostSystemReadyMessages.add(msg); 13001 } 13002 } 13003 13004 void startCleaningPackages() { 13005 // reader 13006 if (!isExternalMediaAvailable()) { 13007 return; 13008 } 13009 synchronized (mPackages) { 13010 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13011 return; 13012 } 13013 } 13014 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13015 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13016 IActivityManager am = ActivityManager.getService(); 13017 if (am != null) { 13018 try { 13019 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13020 UserHandle.USER_SYSTEM); 13021 } catch (RemoteException e) { 13022 } 13023 } 13024 } 13025 13026 @Override 13027 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13028 int installFlags, String installerPackageName, int userId) { 13029 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13030 13031 final int callingUid = Binder.getCallingUid(); 13032 enforceCrossUserPermission(callingUid, userId, 13033 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13034 13035 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13036 try { 13037 if (observer != null) { 13038 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13039 } 13040 } catch (RemoteException re) { 13041 } 13042 return; 13043 } 13044 13045 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13046 installFlags |= PackageManager.INSTALL_FROM_ADB; 13047 13048 } else { 13049 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13050 // about installerPackageName. 13051 13052 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13053 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13054 } 13055 13056 UserHandle user; 13057 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13058 user = UserHandle.ALL; 13059 } else { 13060 user = new UserHandle(userId); 13061 } 13062 13063 // Only system components can circumvent runtime permissions when installing. 13064 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13065 && mContext.checkCallingOrSelfPermission(Manifest.permission 13066 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13067 throw new SecurityException("You need the " 13068 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13069 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13070 } 13071 13072 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13073 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13074 throw new IllegalArgumentException( 13075 "New installs into ASEC containers no longer supported"); 13076 } 13077 13078 final File originFile = new File(originPath); 13079 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13080 13081 final Message msg = mHandler.obtainMessage(INIT_COPY); 13082 final VerificationInfo verificationInfo = new VerificationInfo( 13083 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13084 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13085 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13086 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13087 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13088 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13089 msg.obj = params; 13090 13091 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13092 System.identityHashCode(msg.obj)); 13093 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13094 System.identityHashCode(msg.obj)); 13095 13096 mHandler.sendMessage(msg); 13097 } 13098 13099 13100 /** 13101 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13102 * it is acting on behalf on an enterprise or the user). 13103 * 13104 * Note that the ordering of the conditionals in this method is important. The checks we perform 13105 * are as follows, in this order: 13106 * 13107 * 1) If the install is being performed by a system app, we can trust the app to have set the 13108 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13109 * what it is. 13110 * 2) If the install is being performed by a device or profile owner app, the install reason 13111 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13112 * set the install reason correctly. If the app targets an older SDK version where install 13113 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13114 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13115 * 3) In all other cases, the install is being performed by a regular app that is neither part 13116 * of the system nor a device or profile owner. We have no reason to believe that this app is 13117 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13118 * set to enterprise policy and if so, change it to unknown instead. 13119 */ 13120 private int fixUpInstallReason(String installerPackageName, int installerUid, 13121 int installReason) { 13122 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13123 == PERMISSION_GRANTED) { 13124 // If the install is being performed by a system app, we trust that app to have set the 13125 // install reason correctly. 13126 return installReason; 13127 } 13128 13129 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13130 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13131 if (dpm != null) { 13132 ComponentName owner = null; 13133 try { 13134 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13135 if (owner == null) { 13136 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13137 } 13138 } catch (RemoteException e) { 13139 } 13140 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13141 // If the install is being performed by a device or profile owner, the install 13142 // reason should be enterprise policy. 13143 return PackageManager.INSTALL_REASON_POLICY; 13144 } 13145 } 13146 13147 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13148 // If the install is being performed by a regular app (i.e. neither system app nor 13149 // device or profile owner), we have no reason to believe that the app is acting on 13150 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13151 // change it to unknown instead. 13152 return PackageManager.INSTALL_REASON_UNKNOWN; 13153 } 13154 13155 // If the install is being performed by a regular app and the install reason was set to any 13156 // value but enterprise policy, leave the install reason unchanged. 13157 return installReason; 13158 } 13159 13160 void installStage(String packageName, File stagedDir, String stagedCid, 13161 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13162 String installerPackageName, int installerUid, UserHandle user, 13163 Certificate[][] certificates) { 13164 if (DEBUG_EPHEMERAL) { 13165 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13166 Slog.d(TAG, "Ephemeral install of " + packageName); 13167 } 13168 } 13169 final VerificationInfo verificationInfo = new VerificationInfo( 13170 sessionParams.originatingUri, sessionParams.referrerUri, 13171 sessionParams.originatingUid, installerUid); 13172 13173 final OriginInfo origin; 13174 if (stagedDir != null) { 13175 origin = OriginInfo.fromStagedFile(stagedDir); 13176 } else { 13177 origin = OriginInfo.fromStagedContainer(stagedCid); 13178 } 13179 13180 final Message msg = mHandler.obtainMessage(INIT_COPY); 13181 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13182 sessionParams.installReason); 13183 final InstallParams params = new InstallParams(origin, null, observer, 13184 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13185 verificationInfo, user, sessionParams.abiOverride, 13186 sessionParams.grantedRuntimePermissions, certificates, installReason); 13187 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13188 msg.obj = params; 13189 13190 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13191 System.identityHashCode(msg.obj)); 13192 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13193 System.identityHashCode(msg.obj)); 13194 13195 mHandler.sendMessage(msg); 13196 } 13197 13198 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13199 int userId) { 13200 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13201 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13202 } 13203 13204 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13205 int appId, int... userIds) { 13206 if (ArrayUtils.isEmpty(userIds)) { 13207 return; 13208 } 13209 Bundle extras = new Bundle(1); 13210 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13211 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13212 13213 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13214 packageName, extras, 0, null, null, userIds); 13215 if (isSystem) { 13216 mHandler.post(() -> { 13217 for (int userId : userIds) { 13218 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13219 } 13220 } 13221 ); 13222 } 13223 } 13224 13225 /** 13226 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13227 * automatically without needing an explicit launch. 13228 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13229 */ 13230 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13231 // If user is not running, the app didn't miss any broadcast 13232 if (!mUserManagerInternal.isUserRunning(userId)) { 13233 return; 13234 } 13235 final IActivityManager am = ActivityManager.getService(); 13236 try { 13237 // Deliver LOCKED_BOOT_COMPLETED first 13238 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13239 .setPackage(packageName); 13240 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13241 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13242 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13243 13244 // Deliver BOOT_COMPLETED only if user is unlocked 13245 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13246 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13247 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13248 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13249 } 13250 } catch (RemoteException e) { 13251 throw e.rethrowFromSystemServer(); 13252 } 13253 } 13254 13255 @Override 13256 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13257 int userId) { 13258 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13259 PackageSetting pkgSetting; 13260 final int uid = Binder.getCallingUid(); 13261 enforceCrossUserPermission(uid, userId, 13262 true /* requireFullPermission */, true /* checkShell */, 13263 "setApplicationHiddenSetting for user " + userId); 13264 13265 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13266 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13267 return false; 13268 } 13269 13270 long callingId = Binder.clearCallingIdentity(); 13271 try { 13272 boolean sendAdded = false; 13273 boolean sendRemoved = false; 13274 // writer 13275 synchronized (mPackages) { 13276 pkgSetting = mSettings.mPackages.get(packageName); 13277 if (pkgSetting == null) { 13278 return false; 13279 } 13280 // Do not allow "android" is being disabled 13281 if ("android".equals(packageName)) { 13282 Slog.w(TAG, "Cannot hide package: android"); 13283 return false; 13284 } 13285 // Cannot hide static shared libs as they are considered 13286 // a part of the using app (emulating static linking). Also 13287 // static libs are installed always on internal storage. 13288 PackageParser.Package pkg = mPackages.get(packageName); 13289 if (pkg != null && pkg.staticSharedLibName != null) { 13290 Slog.w(TAG, "Cannot hide package: " + packageName 13291 + " providing static shared library: " 13292 + pkg.staticSharedLibName); 13293 return false; 13294 } 13295 // Only allow protected packages to hide themselves. 13296 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13297 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13298 Slog.w(TAG, "Not hiding protected package: " + packageName); 13299 return false; 13300 } 13301 13302 if (pkgSetting.getHidden(userId) != hidden) { 13303 pkgSetting.setHidden(hidden, userId); 13304 mSettings.writePackageRestrictionsLPr(userId); 13305 if (hidden) { 13306 sendRemoved = true; 13307 } else { 13308 sendAdded = true; 13309 } 13310 } 13311 } 13312 if (sendAdded) { 13313 sendPackageAddedForUser(packageName, pkgSetting, userId); 13314 return true; 13315 } 13316 if (sendRemoved) { 13317 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13318 "hiding pkg"); 13319 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13320 return true; 13321 } 13322 } finally { 13323 Binder.restoreCallingIdentity(callingId); 13324 } 13325 return false; 13326 } 13327 13328 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13329 int userId) { 13330 final PackageRemovedInfo info = new PackageRemovedInfo(); 13331 info.removedPackage = packageName; 13332 info.removedUsers = new int[] {userId}; 13333 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13334 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13335 } 13336 13337 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13338 if (pkgList.length > 0) { 13339 Bundle extras = new Bundle(1); 13340 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13341 13342 sendPackageBroadcast( 13343 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13344 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13345 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13346 new int[] {userId}); 13347 } 13348 } 13349 13350 /** 13351 * Returns true if application is not found or there was an error. Otherwise it returns 13352 * the hidden state of the package for the given user. 13353 */ 13354 @Override 13355 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13358 true /* requireFullPermission */, false /* checkShell */, 13359 "getApplicationHidden for user " + userId); 13360 PackageSetting pkgSetting; 13361 long callingId = Binder.clearCallingIdentity(); 13362 try { 13363 // writer 13364 synchronized (mPackages) { 13365 pkgSetting = mSettings.mPackages.get(packageName); 13366 if (pkgSetting == null) { 13367 return true; 13368 } 13369 return pkgSetting.getHidden(userId); 13370 } 13371 } finally { 13372 Binder.restoreCallingIdentity(callingId); 13373 } 13374 } 13375 13376 /** 13377 * @hide 13378 */ 13379 @Override 13380 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13381 int installReason) { 13382 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13383 null); 13384 PackageSetting pkgSetting; 13385 final int uid = Binder.getCallingUid(); 13386 enforceCrossUserPermission(uid, userId, 13387 true /* requireFullPermission */, true /* checkShell */, 13388 "installExistingPackage for user " + userId); 13389 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13390 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13391 } 13392 13393 long callingId = Binder.clearCallingIdentity(); 13394 try { 13395 boolean installed = false; 13396 final boolean instantApp = 13397 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13398 final boolean fullApp = 13399 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13400 13401 // writer 13402 synchronized (mPackages) { 13403 pkgSetting = mSettings.mPackages.get(packageName); 13404 if (pkgSetting == null) { 13405 return PackageManager.INSTALL_FAILED_INVALID_URI; 13406 } 13407 if (!pkgSetting.getInstalled(userId)) { 13408 pkgSetting.setInstalled(true, userId); 13409 pkgSetting.setHidden(false, userId); 13410 pkgSetting.setInstallReason(installReason, userId); 13411 mSettings.writePackageRestrictionsLPr(userId); 13412 mSettings.writeKernelMappingLPr(pkgSetting); 13413 installed = true; 13414 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13415 // upgrade app from instant to full; we don't allow app downgrade 13416 installed = true; 13417 } 13418 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13419 } 13420 13421 if (installed) { 13422 if (pkgSetting.pkg != null) { 13423 synchronized (mInstallLock) { 13424 // We don't need to freeze for a brand new install 13425 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13426 } 13427 } 13428 sendPackageAddedForUser(packageName, pkgSetting, userId); 13429 synchronized (mPackages) { 13430 updateSequenceNumberLP(packageName, new int[]{ userId }); 13431 } 13432 } 13433 } finally { 13434 Binder.restoreCallingIdentity(callingId); 13435 } 13436 13437 return PackageManager.INSTALL_SUCCEEDED; 13438 } 13439 13440 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13441 boolean instantApp, boolean fullApp) { 13442 // no state specified; do nothing 13443 if (!instantApp && !fullApp) { 13444 return; 13445 } 13446 if (userId != UserHandle.USER_ALL) { 13447 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13448 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13449 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13450 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13451 } 13452 } else { 13453 for (int currentUserId : sUserManager.getUserIds()) { 13454 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13455 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13456 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13457 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13458 } 13459 } 13460 } 13461 } 13462 13463 boolean isUserRestricted(int userId, String restrictionKey) { 13464 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13465 if (restrictions.getBoolean(restrictionKey, false)) { 13466 Log.w(TAG, "User is restricted: " + restrictionKey); 13467 return true; 13468 } 13469 return false; 13470 } 13471 13472 @Override 13473 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13474 int userId) { 13475 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13476 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13477 true /* requireFullPermission */, true /* checkShell */, 13478 "setPackagesSuspended for user " + userId); 13479 13480 if (ArrayUtils.isEmpty(packageNames)) { 13481 return packageNames; 13482 } 13483 13484 // List of package names for whom the suspended state has changed. 13485 List<String> changedPackages = new ArrayList<>(packageNames.length); 13486 // List of package names for whom the suspended state is not set as requested in this 13487 // method. 13488 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13489 long callingId = Binder.clearCallingIdentity(); 13490 try { 13491 for (int i = 0; i < packageNames.length; i++) { 13492 String packageName = packageNames[i]; 13493 boolean changed = false; 13494 final int appId; 13495 synchronized (mPackages) { 13496 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13497 if (pkgSetting == null) { 13498 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13499 + "\". Skipping suspending/un-suspending."); 13500 unactionedPackages.add(packageName); 13501 continue; 13502 } 13503 appId = pkgSetting.appId; 13504 if (pkgSetting.getSuspended(userId) != suspended) { 13505 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13506 unactionedPackages.add(packageName); 13507 continue; 13508 } 13509 pkgSetting.setSuspended(suspended, userId); 13510 mSettings.writePackageRestrictionsLPr(userId); 13511 changed = true; 13512 changedPackages.add(packageName); 13513 } 13514 } 13515 13516 if (changed && suspended) { 13517 killApplication(packageName, UserHandle.getUid(userId, appId), 13518 "suspending package"); 13519 } 13520 } 13521 } finally { 13522 Binder.restoreCallingIdentity(callingId); 13523 } 13524 13525 if (!changedPackages.isEmpty()) { 13526 sendPackagesSuspendedForUser(changedPackages.toArray( 13527 new String[changedPackages.size()]), userId, suspended); 13528 } 13529 13530 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13531 } 13532 13533 @Override 13534 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13535 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13536 true /* requireFullPermission */, false /* checkShell */, 13537 "isPackageSuspendedForUser for user " + userId); 13538 synchronized (mPackages) { 13539 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13540 if (pkgSetting == null) { 13541 throw new IllegalArgumentException("Unknown target package: " + packageName); 13542 } 13543 return pkgSetting.getSuspended(userId); 13544 } 13545 } 13546 13547 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13548 if (isPackageDeviceAdmin(packageName, userId)) { 13549 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13550 + "\": has an active device admin"); 13551 return false; 13552 } 13553 13554 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13555 if (packageName.equals(activeLauncherPackageName)) { 13556 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13557 + "\": contains the active launcher"); 13558 return false; 13559 } 13560 13561 if (packageName.equals(mRequiredInstallerPackage)) { 13562 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13563 + "\": required for package installation"); 13564 return false; 13565 } 13566 13567 if (packageName.equals(mRequiredUninstallerPackage)) { 13568 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13569 + "\": required for package uninstallation"); 13570 return false; 13571 } 13572 13573 if (packageName.equals(mRequiredVerifierPackage)) { 13574 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13575 + "\": required for package verification"); 13576 return false; 13577 } 13578 13579 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13580 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13581 + "\": is the default dialer"); 13582 return false; 13583 } 13584 13585 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13586 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13587 + "\": protected package"); 13588 return false; 13589 } 13590 13591 // Cannot suspend static shared libs as they are considered 13592 // a part of the using app (emulating static linking). Also 13593 // static libs are installed always on internal storage. 13594 PackageParser.Package pkg = mPackages.get(packageName); 13595 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13596 Slog.w(TAG, "Cannot suspend package: " + packageName 13597 + " providing static shared library: " 13598 + pkg.staticSharedLibName); 13599 return false; 13600 } 13601 13602 return true; 13603 } 13604 13605 private String getActiveLauncherPackageName(int userId) { 13606 Intent intent = new Intent(Intent.ACTION_MAIN); 13607 intent.addCategory(Intent.CATEGORY_HOME); 13608 ResolveInfo resolveInfo = resolveIntent( 13609 intent, 13610 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13611 PackageManager.MATCH_DEFAULT_ONLY, 13612 userId); 13613 13614 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13615 } 13616 13617 private String getDefaultDialerPackageName(int userId) { 13618 synchronized (mPackages) { 13619 return mSettings.getDefaultDialerPackageNameLPw(userId); 13620 } 13621 } 13622 13623 @Override 13624 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13625 mContext.enforceCallingOrSelfPermission( 13626 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13627 "Only package verification agents can verify applications"); 13628 13629 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13630 final PackageVerificationResponse response = new PackageVerificationResponse( 13631 verificationCode, Binder.getCallingUid()); 13632 msg.arg1 = id; 13633 msg.obj = response; 13634 mHandler.sendMessage(msg); 13635 } 13636 13637 @Override 13638 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13639 long millisecondsToDelay) { 13640 mContext.enforceCallingOrSelfPermission( 13641 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13642 "Only package verification agents can extend verification timeouts"); 13643 13644 final PackageVerificationState state = mPendingVerification.get(id); 13645 final PackageVerificationResponse response = new PackageVerificationResponse( 13646 verificationCodeAtTimeout, Binder.getCallingUid()); 13647 13648 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13649 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13650 } 13651 if (millisecondsToDelay < 0) { 13652 millisecondsToDelay = 0; 13653 } 13654 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13655 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13656 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13657 } 13658 13659 if ((state != null) && !state.timeoutExtended()) { 13660 state.extendTimeout(); 13661 13662 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13663 msg.arg1 = id; 13664 msg.obj = response; 13665 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13666 } 13667 } 13668 13669 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13670 int verificationCode, UserHandle user) { 13671 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13672 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13673 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13674 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13675 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13676 13677 mContext.sendBroadcastAsUser(intent, user, 13678 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13679 } 13680 13681 private ComponentName matchComponentForVerifier(String packageName, 13682 List<ResolveInfo> receivers) { 13683 ActivityInfo targetReceiver = null; 13684 13685 final int NR = receivers.size(); 13686 for (int i = 0; i < NR; i++) { 13687 final ResolveInfo info = receivers.get(i); 13688 if (info.activityInfo == null) { 13689 continue; 13690 } 13691 13692 if (packageName.equals(info.activityInfo.packageName)) { 13693 targetReceiver = info.activityInfo; 13694 break; 13695 } 13696 } 13697 13698 if (targetReceiver == null) { 13699 return null; 13700 } 13701 13702 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13703 } 13704 13705 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13706 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13707 if (pkgInfo.verifiers.length == 0) { 13708 return null; 13709 } 13710 13711 final int N = pkgInfo.verifiers.length; 13712 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13713 for (int i = 0; i < N; i++) { 13714 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13715 13716 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13717 receivers); 13718 if (comp == null) { 13719 continue; 13720 } 13721 13722 final int verifierUid = getUidForVerifier(verifierInfo); 13723 if (verifierUid == -1) { 13724 continue; 13725 } 13726 13727 if (DEBUG_VERIFY) { 13728 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13729 + " with the correct signature"); 13730 } 13731 sufficientVerifiers.add(comp); 13732 verificationState.addSufficientVerifier(verifierUid); 13733 } 13734 13735 return sufficientVerifiers; 13736 } 13737 13738 private int getUidForVerifier(VerifierInfo verifierInfo) { 13739 synchronized (mPackages) { 13740 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13741 if (pkg == null) { 13742 return -1; 13743 } else if (pkg.mSignatures.length != 1) { 13744 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13745 + " has more than one signature; ignoring"); 13746 return -1; 13747 } 13748 13749 /* 13750 * If the public key of the package's signature does not match 13751 * our expected public key, then this is a different package and 13752 * we should skip. 13753 */ 13754 13755 final byte[] expectedPublicKey; 13756 try { 13757 final Signature verifierSig = pkg.mSignatures[0]; 13758 final PublicKey publicKey = verifierSig.getPublicKey(); 13759 expectedPublicKey = publicKey.getEncoded(); 13760 } catch (CertificateException e) { 13761 return -1; 13762 } 13763 13764 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13765 13766 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13767 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13768 + " does not have the expected public key; ignoring"); 13769 return -1; 13770 } 13771 13772 return pkg.applicationInfo.uid; 13773 } 13774 } 13775 13776 @Override 13777 public void finishPackageInstall(int token, boolean didLaunch) { 13778 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13779 13780 if (DEBUG_INSTALL) { 13781 Slog.v(TAG, "BM finishing package install for " + token); 13782 } 13783 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13784 13785 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13786 mHandler.sendMessage(msg); 13787 } 13788 13789 /** 13790 * Get the verification agent timeout. 13791 * 13792 * @return verification timeout in milliseconds 13793 */ 13794 private long getVerificationTimeout() { 13795 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13796 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13797 DEFAULT_VERIFICATION_TIMEOUT); 13798 } 13799 13800 /** 13801 * Get the default verification agent response code. 13802 * 13803 * @return default verification response code 13804 */ 13805 private int getDefaultVerificationResponse() { 13806 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13807 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13808 DEFAULT_VERIFICATION_RESPONSE); 13809 } 13810 13811 /** 13812 * Check whether or not package verification has been enabled. 13813 * 13814 * @return true if verification should be performed 13815 */ 13816 private boolean isVerificationEnabled(int userId, int installFlags) { 13817 if (!DEFAULT_VERIFY_ENABLE) { 13818 return false; 13819 } 13820 13821 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13822 13823 // Check if installing from ADB 13824 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13825 // Do not run verification in a test harness environment 13826 if (ActivityManager.isRunningInTestHarness()) { 13827 return false; 13828 } 13829 if (ensureVerifyAppsEnabled) { 13830 return true; 13831 } 13832 // Check if the developer does not want package verification for ADB installs 13833 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13834 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13835 return false; 13836 } 13837 } 13838 13839 if (ensureVerifyAppsEnabled) { 13840 return true; 13841 } 13842 13843 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13844 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13845 } 13846 13847 @Override 13848 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13849 throws RemoteException { 13850 mContext.enforceCallingOrSelfPermission( 13851 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13852 "Only intentfilter verification agents can verify applications"); 13853 13854 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13855 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13856 Binder.getCallingUid(), verificationCode, failedDomains); 13857 msg.arg1 = id; 13858 msg.obj = response; 13859 mHandler.sendMessage(msg); 13860 } 13861 13862 @Override 13863 public int getIntentVerificationStatus(String packageName, int userId) { 13864 synchronized (mPackages) { 13865 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13866 } 13867 } 13868 13869 @Override 13870 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13871 mContext.enforceCallingOrSelfPermission( 13872 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13873 13874 boolean result = false; 13875 synchronized (mPackages) { 13876 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13877 } 13878 if (result) { 13879 scheduleWritePackageRestrictionsLocked(userId); 13880 } 13881 return result; 13882 } 13883 13884 @Override 13885 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13886 String packageName) { 13887 synchronized (mPackages) { 13888 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13889 } 13890 } 13891 13892 @Override 13893 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13894 if (TextUtils.isEmpty(packageName)) { 13895 return ParceledListSlice.emptyList(); 13896 } 13897 synchronized (mPackages) { 13898 PackageParser.Package pkg = mPackages.get(packageName); 13899 if (pkg == null || pkg.activities == null) { 13900 return ParceledListSlice.emptyList(); 13901 } 13902 final int count = pkg.activities.size(); 13903 ArrayList<IntentFilter> result = new ArrayList<>(); 13904 for (int n=0; n<count; n++) { 13905 PackageParser.Activity activity = pkg.activities.get(n); 13906 if (activity.intents != null && activity.intents.size() > 0) { 13907 result.addAll(activity.intents); 13908 } 13909 } 13910 return new ParceledListSlice<>(result); 13911 } 13912 } 13913 13914 @Override 13915 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13916 mContext.enforceCallingOrSelfPermission( 13917 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13918 13919 synchronized (mPackages) { 13920 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13921 if (packageName != null) { 13922 result |= updateIntentVerificationStatus(packageName, 13923 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13924 userId); 13925 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13926 packageName, userId); 13927 } 13928 return result; 13929 } 13930 } 13931 13932 @Override 13933 public String getDefaultBrowserPackageName(int userId) { 13934 synchronized (mPackages) { 13935 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13936 } 13937 } 13938 13939 /** 13940 * Get the "allow unknown sources" setting. 13941 * 13942 * @return the current "allow unknown sources" setting 13943 */ 13944 private int getUnknownSourcesSettings() { 13945 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13946 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13947 -1); 13948 } 13949 13950 @Override 13951 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13952 final int uid = Binder.getCallingUid(); 13953 // writer 13954 synchronized (mPackages) { 13955 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13956 if (targetPackageSetting == null) { 13957 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13958 } 13959 13960 PackageSetting installerPackageSetting; 13961 if (installerPackageName != null) { 13962 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13963 if (installerPackageSetting == null) { 13964 throw new IllegalArgumentException("Unknown installer package: " 13965 + installerPackageName); 13966 } 13967 } else { 13968 installerPackageSetting = null; 13969 } 13970 13971 Signature[] callerSignature; 13972 Object obj = mSettings.getUserIdLPr(uid); 13973 if (obj != null) { 13974 if (obj instanceof SharedUserSetting) { 13975 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13976 } else if (obj instanceof PackageSetting) { 13977 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13978 } else { 13979 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13980 } 13981 } else { 13982 throw new SecurityException("Unknown calling UID: " + uid); 13983 } 13984 13985 // Verify: can't set installerPackageName to a package that is 13986 // not signed with the same cert as the caller. 13987 if (installerPackageSetting != null) { 13988 if (compareSignatures(callerSignature, 13989 installerPackageSetting.signatures.mSignatures) 13990 != PackageManager.SIGNATURE_MATCH) { 13991 throw new SecurityException( 13992 "Caller does not have same cert as new installer package " 13993 + installerPackageName); 13994 } 13995 } 13996 13997 // Verify: if target already has an installer package, it must 13998 // be signed with the same cert as the caller. 13999 if (targetPackageSetting.installerPackageName != null) { 14000 PackageSetting setting = mSettings.mPackages.get( 14001 targetPackageSetting.installerPackageName); 14002 // If the currently set package isn't valid, then it's always 14003 // okay to change it. 14004 if (setting != null) { 14005 if (compareSignatures(callerSignature, 14006 setting.signatures.mSignatures) 14007 != PackageManager.SIGNATURE_MATCH) { 14008 throw new SecurityException( 14009 "Caller does not have same cert as old installer package " 14010 + targetPackageSetting.installerPackageName); 14011 } 14012 } 14013 } 14014 14015 // Okay! 14016 targetPackageSetting.installerPackageName = installerPackageName; 14017 if (installerPackageName != null) { 14018 mSettings.mInstallerPackages.add(installerPackageName); 14019 } 14020 scheduleWriteSettingsLocked(); 14021 } 14022 } 14023 14024 @Override 14025 public void setApplicationCategoryHint(String packageName, int categoryHint, 14026 String callerPackageName) { 14027 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14028 callerPackageName); 14029 synchronized (mPackages) { 14030 PackageSetting ps = mSettings.mPackages.get(packageName); 14031 if (ps == null) { 14032 throw new IllegalArgumentException("Unknown target package " + packageName); 14033 } 14034 14035 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14036 throw new IllegalArgumentException("Calling package " + callerPackageName 14037 + " is not installer for " + packageName); 14038 } 14039 14040 if (ps.categoryHint != categoryHint) { 14041 ps.categoryHint = categoryHint; 14042 scheduleWriteSettingsLocked(); 14043 } 14044 } 14045 } 14046 14047 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14048 // Queue up an async operation since the package installation may take a little while. 14049 mHandler.post(new Runnable() { 14050 public void run() { 14051 mHandler.removeCallbacks(this); 14052 // Result object to be returned 14053 PackageInstalledInfo res = new PackageInstalledInfo(); 14054 res.setReturnCode(currentStatus); 14055 res.uid = -1; 14056 res.pkg = null; 14057 res.removedInfo = null; 14058 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14059 args.doPreInstall(res.returnCode); 14060 synchronized (mInstallLock) { 14061 installPackageTracedLI(args, res); 14062 } 14063 args.doPostInstall(res.returnCode, res.uid); 14064 } 14065 14066 // A restore should be performed at this point if (a) the install 14067 // succeeded, (b) the operation is not an update, and (c) the new 14068 // package has not opted out of backup participation. 14069 final boolean update = res.removedInfo != null 14070 && res.removedInfo.removedPackage != null; 14071 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14072 boolean doRestore = !update 14073 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14074 14075 // Set up the post-install work request bookkeeping. This will be used 14076 // and cleaned up by the post-install event handling regardless of whether 14077 // there's a restore pass performed. Token values are >= 1. 14078 int token; 14079 if (mNextInstallToken < 0) mNextInstallToken = 1; 14080 token = mNextInstallToken++; 14081 14082 PostInstallData data = new PostInstallData(args, res); 14083 mRunningInstalls.put(token, data); 14084 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14085 14086 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14087 // Pass responsibility to the Backup Manager. It will perform a 14088 // restore if appropriate, then pass responsibility back to the 14089 // Package Manager to run the post-install observer callbacks 14090 // and broadcasts. 14091 IBackupManager bm = IBackupManager.Stub.asInterface( 14092 ServiceManager.getService(Context.BACKUP_SERVICE)); 14093 if (bm != null) { 14094 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14095 + " to BM for possible restore"); 14096 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14097 try { 14098 // TODO: http://b/22388012 14099 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14100 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14101 } else { 14102 doRestore = false; 14103 } 14104 } catch (RemoteException e) { 14105 // can't happen; the backup manager is local 14106 } catch (Exception e) { 14107 Slog.e(TAG, "Exception trying to enqueue restore", e); 14108 doRestore = false; 14109 } 14110 } else { 14111 Slog.e(TAG, "Backup Manager not found!"); 14112 doRestore = false; 14113 } 14114 } 14115 14116 if (!doRestore) { 14117 // No restore possible, or the Backup Manager was mysteriously not 14118 // available -- just fire the post-install work request directly. 14119 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14120 14121 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14122 14123 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14124 mHandler.sendMessage(msg); 14125 } 14126 } 14127 }); 14128 } 14129 14130 /** 14131 * Callback from PackageSettings whenever an app is first transitioned out of the 14132 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14133 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14134 * here whether the app is the target of an ongoing install, and only send the 14135 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14136 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14137 * handling. 14138 */ 14139 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14140 // Serialize this with the rest of the install-process message chain. In the 14141 // restore-at-install case, this Runnable will necessarily run before the 14142 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14143 // are coherent. In the non-restore case, the app has already completed install 14144 // and been launched through some other means, so it is not in a problematic 14145 // state for observers to see the FIRST_LAUNCH signal. 14146 mHandler.post(new Runnable() { 14147 @Override 14148 public void run() { 14149 for (int i = 0; i < mRunningInstalls.size(); i++) { 14150 final PostInstallData data = mRunningInstalls.valueAt(i); 14151 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14152 continue; 14153 } 14154 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14155 // right package; but is it for the right user? 14156 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14157 if (userId == data.res.newUsers[uIndex]) { 14158 if (DEBUG_BACKUP) { 14159 Slog.i(TAG, "Package " + pkgName 14160 + " being restored so deferring FIRST_LAUNCH"); 14161 } 14162 return; 14163 } 14164 } 14165 } 14166 } 14167 // didn't find it, so not being restored 14168 if (DEBUG_BACKUP) { 14169 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14170 } 14171 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14172 } 14173 }); 14174 } 14175 14176 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14177 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14178 installerPkg, null, userIds); 14179 } 14180 14181 private abstract class HandlerParams { 14182 private static final int MAX_RETRIES = 4; 14183 14184 /** 14185 * Number of times startCopy() has been attempted and had a non-fatal 14186 * error. 14187 */ 14188 private int mRetries = 0; 14189 14190 /** User handle for the user requesting the information or installation. */ 14191 private final UserHandle mUser; 14192 String traceMethod; 14193 int traceCookie; 14194 14195 HandlerParams(UserHandle user) { 14196 mUser = user; 14197 } 14198 14199 UserHandle getUser() { 14200 return mUser; 14201 } 14202 14203 HandlerParams setTraceMethod(String traceMethod) { 14204 this.traceMethod = traceMethod; 14205 return this; 14206 } 14207 14208 HandlerParams setTraceCookie(int traceCookie) { 14209 this.traceCookie = traceCookie; 14210 return this; 14211 } 14212 14213 final boolean startCopy() { 14214 boolean res; 14215 try { 14216 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14217 14218 if (++mRetries > MAX_RETRIES) { 14219 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14220 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14221 handleServiceError(); 14222 return false; 14223 } else { 14224 handleStartCopy(); 14225 res = true; 14226 } 14227 } catch (RemoteException e) { 14228 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14229 mHandler.sendEmptyMessage(MCS_RECONNECT); 14230 res = false; 14231 } 14232 handleReturnCode(); 14233 return res; 14234 } 14235 14236 final void serviceError() { 14237 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14238 handleServiceError(); 14239 handleReturnCode(); 14240 } 14241 14242 abstract void handleStartCopy() throws RemoteException; 14243 abstract void handleServiceError(); 14244 abstract void handleReturnCode(); 14245 } 14246 14247 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14248 for (File path : paths) { 14249 try { 14250 mcs.clearDirectory(path.getAbsolutePath()); 14251 } catch (RemoteException e) { 14252 } 14253 } 14254 } 14255 14256 static class OriginInfo { 14257 /** 14258 * Location where install is coming from, before it has been 14259 * copied/renamed into place. This could be a single monolithic APK 14260 * file, or a cluster directory. This location may be untrusted. 14261 */ 14262 final File file; 14263 final String cid; 14264 14265 /** 14266 * Flag indicating that {@link #file} or {@link #cid} has already been 14267 * staged, meaning downstream users don't need to defensively copy the 14268 * contents. 14269 */ 14270 final boolean staged; 14271 14272 /** 14273 * Flag indicating that {@link #file} or {@link #cid} is an already 14274 * installed app that is being moved. 14275 */ 14276 final boolean existing; 14277 14278 final String resolvedPath; 14279 final File resolvedFile; 14280 14281 static OriginInfo fromNothing() { 14282 return new OriginInfo(null, null, false, false); 14283 } 14284 14285 static OriginInfo fromUntrustedFile(File file) { 14286 return new OriginInfo(file, null, false, false); 14287 } 14288 14289 static OriginInfo fromExistingFile(File file) { 14290 return new OriginInfo(file, null, false, true); 14291 } 14292 14293 static OriginInfo fromStagedFile(File file) { 14294 return new OriginInfo(file, null, true, false); 14295 } 14296 14297 static OriginInfo fromStagedContainer(String cid) { 14298 return new OriginInfo(null, cid, true, false); 14299 } 14300 14301 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14302 this.file = file; 14303 this.cid = cid; 14304 this.staged = staged; 14305 this.existing = existing; 14306 14307 if (cid != null) { 14308 resolvedPath = PackageHelper.getSdDir(cid); 14309 resolvedFile = new File(resolvedPath); 14310 } else if (file != null) { 14311 resolvedPath = file.getAbsolutePath(); 14312 resolvedFile = file; 14313 } else { 14314 resolvedPath = null; 14315 resolvedFile = null; 14316 } 14317 } 14318 } 14319 14320 static class MoveInfo { 14321 final int moveId; 14322 final String fromUuid; 14323 final String toUuid; 14324 final String packageName; 14325 final String dataAppName; 14326 final int appId; 14327 final String seinfo; 14328 final int targetSdkVersion; 14329 14330 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14331 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14332 this.moveId = moveId; 14333 this.fromUuid = fromUuid; 14334 this.toUuid = toUuid; 14335 this.packageName = packageName; 14336 this.dataAppName = dataAppName; 14337 this.appId = appId; 14338 this.seinfo = seinfo; 14339 this.targetSdkVersion = targetSdkVersion; 14340 } 14341 } 14342 14343 static class VerificationInfo { 14344 /** A constant used to indicate that a uid value is not present. */ 14345 public static final int NO_UID = -1; 14346 14347 /** URI referencing where the package was downloaded from. */ 14348 final Uri originatingUri; 14349 14350 /** HTTP referrer URI associated with the originatingURI. */ 14351 final Uri referrer; 14352 14353 /** UID of the application that the install request originated from. */ 14354 final int originatingUid; 14355 14356 /** UID of application requesting the install */ 14357 final int installerUid; 14358 14359 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14360 this.originatingUri = originatingUri; 14361 this.referrer = referrer; 14362 this.originatingUid = originatingUid; 14363 this.installerUid = installerUid; 14364 } 14365 } 14366 14367 class InstallParams extends HandlerParams { 14368 final OriginInfo origin; 14369 final MoveInfo move; 14370 final IPackageInstallObserver2 observer; 14371 int installFlags; 14372 final String installerPackageName; 14373 final String volumeUuid; 14374 private InstallArgs mArgs; 14375 private int mRet; 14376 final String packageAbiOverride; 14377 final String[] grantedRuntimePermissions; 14378 final VerificationInfo verificationInfo; 14379 final Certificate[][] certificates; 14380 final int installReason; 14381 14382 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14383 int installFlags, String installerPackageName, String volumeUuid, 14384 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14385 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14386 super(user); 14387 this.origin = origin; 14388 this.move = move; 14389 this.observer = observer; 14390 this.installFlags = installFlags; 14391 this.installerPackageName = installerPackageName; 14392 this.volumeUuid = volumeUuid; 14393 this.verificationInfo = verificationInfo; 14394 this.packageAbiOverride = packageAbiOverride; 14395 this.grantedRuntimePermissions = grantedPermissions; 14396 this.certificates = certificates; 14397 this.installReason = installReason; 14398 } 14399 14400 @Override 14401 public String toString() { 14402 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14403 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14404 } 14405 14406 private int installLocationPolicy(PackageInfoLite pkgLite) { 14407 String packageName = pkgLite.packageName; 14408 int installLocation = pkgLite.installLocation; 14409 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14410 // reader 14411 synchronized (mPackages) { 14412 // Currently installed package which the new package is attempting to replace or 14413 // null if no such package is installed. 14414 PackageParser.Package installedPkg = mPackages.get(packageName); 14415 // Package which currently owns the data which the new package will own if installed. 14416 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14417 // will be null whereas dataOwnerPkg will contain information about the package 14418 // which was uninstalled while keeping its data. 14419 PackageParser.Package dataOwnerPkg = installedPkg; 14420 if (dataOwnerPkg == null) { 14421 PackageSetting ps = mSettings.mPackages.get(packageName); 14422 if (ps != null) { 14423 dataOwnerPkg = ps.pkg; 14424 } 14425 } 14426 14427 if (dataOwnerPkg != null) { 14428 // If installed, the package will get access to data left on the device by its 14429 // predecessor. As a security measure, this is permited only if this is not a 14430 // version downgrade or if the predecessor package is marked as debuggable and 14431 // a downgrade is explicitly requested. 14432 // 14433 // On debuggable platform builds, downgrades are permitted even for 14434 // non-debuggable packages to make testing easier. Debuggable platform builds do 14435 // not offer security guarantees and thus it's OK to disable some security 14436 // mechanisms to make debugging/testing easier on those builds. However, even on 14437 // debuggable builds downgrades of packages are permitted only if requested via 14438 // installFlags. This is because we aim to keep the behavior of debuggable 14439 // platform builds as close as possible to the behavior of non-debuggable 14440 // platform builds. 14441 final boolean downgradeRequested = 14442 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14443 final boolean packageDebuggable = 14444 (dataOwnerPkg.applicationInfo.flags 14445 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14446 final boolean downgradePermitted = 14447 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14448 if (!downgradePermitted) { 14449 try { 14450 checkDowngrade(dataOwnerPkg, pkgLite); 14451 } catch (PackageManagerException e) { 14452 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14453 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14454 } 14455 } 14456 } 14457 14458 if (installedPkg != null) { 14459 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14460 // Check for updated system application. 14461 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14462 if (onSd) { 14463 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14464 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14465 } 14466 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14467 } else { 14468 if (onSd) { 14469 // Install flag overrides everything. 14470 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14471 } 14472 // If current upgrade specifies particular preference 14473 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14474 // Application explicitly specified internal. 14475 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14476 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14477 // App explictly prefers external. Let policy decide 14478 } else { 14479 // Prefer previous location 14480 if (isExternal(installedPkg)) { 14481 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14482 } 14483 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14484 } 14485 } 14486 } else { 14487 // Invalid install. Return error code 14488 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14489 } 14490 } 14491 } 14492 // All the special cases have been taken care of. 14493 // Return result based on recommended install location. 14494 if (onSd) { 14495 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14496 } 14497 return pkgLite.recommendedInstallLocation; 14498 } 14499 14500 /* 14501 * Invoke remote method to get package information and install 14502 * location values. Override install location based on default 14503 * policy if needed and then create install arguments based 14504 * on the install location. 14505 */ 14506 public void handleStartCopy() throws RemoteException { 14507 int ret = PackageManager.INSTALL_SUCCEEDED; 14508 14509 // If we're already staged, we've firmly committed to an install location 14510 if (origin.staged) { 14511 if (origin.file != null) { 14512 installFlags |= PackageManager.INSTALL_INTERNAL; 14513 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14514 } else if (origin.cid != null) { 14515 installFlags |= PackageManager.INSTALL_EXTERNAL; 14516 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14517 } else { 14518 throw new IllegalStateException("Invalid stage location"); 14519 } 14520 } 14521 14522 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14523 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14524 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14525 PackageInfoLite pkgLite = null; 14526 14527 if (onInt && onSd) { 14528 // Check if both bits are set. 14529 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14530 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14531 } else if (onSd && ephemeral) { 14532 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14533 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14534 } else { 14535 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14536 packageAbiOverride); 14537 14538 if (DEBUG_EPHEMERAL && ephemeral) { 14539 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14540 } 14541 14542 /* 14543 * If we have too little free space, try to free cache 14544 * before giving up. 14545 */ 14546 if (!origin.staged && pkgLite.recommendedInstallLocation 14547 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14548 // TODO: focus freeing disk space on the target device 14549 final StorageManager storage = StorageManager.from(mContext); 14550 final long lowThreshold = storage.getStorageLowBytes( 14551 Environment.getDataDirectory()); 14552 14553 final long sizeBytes = mContainerService.calculateInstalledSize( 14554 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14555 14556 try { 14557 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14558 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14559 installFlags, packageAbiOverride); 14560 } catch (InstallerException e) { 14561 Slog.w(TAG, "Failed to free cache", e); 14562 } 14563 14564 /* 14565 * The cache free must have deleted the file we 14566 * downloaded to install. 14567 * 14568 * TODO: fix the "freeCache" call to not delete 14569 * the file we care about. 14570 */ 14571 if (pkgLite.recommendedInstallLocation 14572 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14573 pkgLite.recommendedInstallLocation 14574 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14575 } 14576 } 14577 } 14578 14579 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14580 int loc = pkgLite.recommendedInstallLocation; 14581 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14582 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14583 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14584 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14585 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14586 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14587 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14588 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14589 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14590 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14591 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14592 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14593 } else { 14594 // Override with defaults if needed. 14595 loc = installLocationPolicy(pkgLite); 14596 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14597 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14598 } else if (!onSd && !onInt) { 14599 // Override install location with flags 14600 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14601 // Set the flag to install on external media. 14602 installFlags |= PackageManager.INSTALL_EXTERNAL; 14603 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14604 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14605 if (DEBUG_EPHEMERAL) { 14606 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14607 } 14608 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14609 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14610 |PackageManager.INSTALL_INTERNAL); 14611 } else { 14612 // Make sure the flag for installing on external 14613 // media is unset 14614 installFlags |= PackageManager.INSTALL_INTERNAL; 14615 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14616 } 14617 } 14618 } 14619 } 14620 14621 final InstallArgs args = createInstallArgs(this); 14622 mArgs = args; 14623 14624 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14625 // TODO: http://b/22976637 14626 // Apps installed for "all" users use the device owner to verify the app 14627 UserHandle verifierUser = getUser(); 14628 if (verifierUser == UserHandle.ALL) { 14629 verifierUser = UserHandle.SYSTEM; 14630 } 14631 14632 /* 14633 * Determine if we have any installed package verifiers. If we 14634 * do, then we'll defer to them to verify the packages. 14635 */ 14636 final int requiredUid = mRequiredVerifierPackage == null ? -1 14637 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14638 verifierUser.getIdentifier()); 14639 if (!origin.existing && requiredUid != -1 14640 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14641 final Intent verification = new Intent( 14642 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14643 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14644 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14645 PACKAGE_MIME_TYPE); 14646 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14647 14648 // Query all live verifiers based on current user state 14649 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14650 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14651 14652 if (DEBUG_VERIFY) { 14653 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14654 + verification.toString() + " with " + pkgLite.verifiers.length 14655 + " optional verifiers"); 14656 } 14657 14658 final int verificationId = mPendingVerificationToken++; 14659 14660 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14661 14662 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14663 installerPackageName); 14664 14665 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14666 installFlags); 14667 14668 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14669 pkgLite.packageName); 14670 14671 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14672 pkgLite.versionCode); 14673 14674 if (verificationInfo != null) { 14675 if (verificationInfo.originatingUri != null) { 14676 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14677 verificationInfo.originatingUri); 14678 } 14679 if (verificationInfo.referrer != null) { 14680 verification.putExtra(Intent.EXTRA_REFERRER, 14681 verificationInfo.referrer); 14682 } 14683 if (verificationInfo.originatingUid >= 0) { 14684 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14685 verificationInfo.originatingUid); 14686 } 14687 if (verificationInfo.installerUid >= 0) { 14688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14689 verificationInfo.installerUid); 14690 } 14691 } 14692 14693 final PackageVerificationState verificationState = new PackageVerificationState( 14694 requiredUid, args); 14695 14696 mPendingVerification.append(verificationId, verificationState); 14697 14698 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14699 receivers, verificationState); 14700 14701 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14702 final long idleDuration = getVerificationTimeout(); 14703 14704 /* 14705 * If any sufficient verifiers were listed in the package 14706 * manifest, attempt to ask them. 14707 */ 14708 if (sufficientVerifiers != null) { 14709 final int N = sufficientVerifiers.size(); 14710 if (N == 0) { 14711 Slog.i(TAG, "Additional verifiers required, but none installed."); 14712 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14713 } else { 14714 for (int i = 0; i < N; i++) { 14715 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14716 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14717 verifierComponent.getPackageName(), idleDuration, 14718 verifierUser.getIdentifier(), false, "package verifier"); 14719 14720 final Intent sufficientIntent = new Intent(verification); 14721 sufficientIntent.setComponent(verifierComponent); 14722 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14723 } 14724 } 14725 } 14726 14727 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14728 mRequiredVerifierPackage, receivers); 14729 if (ret == PackageManager.INSTALL_SUCCEEDED 14730 && mRequiredVerifierPackage != null) { 14731 Trace.asyncTraceBegin( 14732 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14733 /* 14734 * Send the intent to the required verification agent, 14735 * but only start the verification timeout after the 14736 * target BroadcastReceivers have run. 14737 */ 14738 verification.setComponent(requiredVerifierComponent); 14739 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14740 mRequiredVerifierPackage, idleDuration, 14741 verifierUser.getIdentifier(), false, "package verifier"); 14742 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14743 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14744 new BroadcastReceiver() { 14745 @Override 14746 public void onReceive(Context context, Intent intent) { 14747 final Message msg = mHandler 14748 .obtainMessage(CHECK_PENDING_VERIFICATION); 14749 msg.arg1 = verificationId; 14750 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14751 } 14752 }, null, 0, null, null); 14753 14754 /* 14755 * We don't want the copy to proceed until verification 14756 * succeeds, so null out this field. 14757 */ 14758 mArgs = null; 14759 } 14760 } else { 14761 /* 14762 * No package verification is enabled, so immediately start 14763 * the remote call to initiate copy using temporary file. 14764 */ 14765 ret = args.copyApk(mContainerService, true); 14766 } 14767 } 14768 14769 mRet = ret; 14770 } 14771 14772 @Override 14773 void handleReturnCode() { 14774 // If mArgs is null, then MCS couldn't be reached. When it 14775 // reconnects, it will try again to install. At that point, this 14776 // will succeed. 14777 if (mArgs != null) { 14778 processPendingInstall(mArgs, mRet); 14779 } 14780 } 14781 14782 @Override 14783 void handleServiceError() { 14784 mArgs = createInstallArgs(this); 14785 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14786 } 14787 14788 public boolean isForwardLocked() { 14789 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14790 } 14791 } 14792 14793 /** 14794 * Used during creation of InstallArgs 14795 * 14796 * @param installFlags package installation flags 14797 * @return true if should be installed on external storage 14798 */ 14799 private static boolean installOnExternalAsec(int installFlags) { 14800 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14801 return false; 14802 } 14803 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14804 return true; 14805 } 14806 return false; 14807 } 14808 14809 /** 14810 * Used during creation of InstallArgs 14811 * 14812 * @param installFlags package installation flags 14813 * @return true if should be installed as forward locked 14814 */ 14815 private static boolean installForwardLocked(int installFlags) { 14816 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14817 } 14818 14819 private InstallArgs createInstallArgs(InstallParams params) { 14820 if (params.move != null) { 14821 return new MoveInstallArgs(params); 14822 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14823 return new AsecInstallArgs(params); 14824 } else { 14825 return new FileInstallArgs(params); 14826 } 14827 } 14828 14829 /** 14830 * Create args that describe an existing installed package. Typically used 14831 * when cleaning up old installs, or used as a move source. 14832 */ 14833 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14834 String resourcePath, String[] instructionSets) { 14835 final boolean isInAsec; 14836 if (installOnExternalAsec(installFlags)) { 14837 /* Apps on SD card are always in ASEC containers. */ 14838 isInAsec = true; 14839 } else if (installForwardLocked(installFlags) 14840 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14841 /* 14842 * Forward-locked apps are only in ASEC containers if they're the 14843 * new style 14844 */ 14845 isInAsec = true; 14846 } else { 14847 isInAsec = false; 14848 } 14849 14850 if (isInAsec) { 14851 return new AsecInstallArgs(codePath, instructionSets, 14852 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14853 } else { 14854 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14855 } 14856 } 14857 14858 static abstract class InstallArgs { 14859 /** @see InstallParams#origin */ 14860 final OriginInfo origin; 14861 /** @see InstallParams#move */ 14862 final MoveInfo move; 14863 14864 final IPackageInstallObserver2 observer; 14865 // Always refers to PackageManager flags only 14866 final int installFlags; 14867 final String installerPackageName; 14868 final String volumeUuid; 14869 final UserHandle user; 14870 final String abiOverride; 14871 final String[] installGrantPermissions; 14872 /** If non-null, drop an async trace when the install completes */ 14873 final String traceMethod; 14874 final int traceCookie; 14875 final Certificate[][] certificates; 14876 final int installReason; 14877 14878 // The list of instruction sets supported by this app. This is currently 14879 // only used during the rmdex() phase to clean up resources. We can get rid of this 14880 // if we move dex files under the common app path. 14881 /* nullable */ String[] instructionSets; 14882 14883 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14884 int installFlags, String installerPackageName, String volumeUuid, 14885 UserHandle user, String[] instructionSets, 14886 String abiOverride, String[] installGrantPermissions, 14887 String traceMethod, int traceCookie, Certificate[][] certificates, 14888 int installReason) { 14889 this.origin = origin; 14890 this.move = move; 14891 this.installFlags = installFlags; 14892 this.observer = observer; 14893 this.installerPackageName = installerPackageName; 14894 this.volumeUuid = volumeUuid; 14895 this.user = user; 14896 this.instructionSets = instructionSets; 14897 this.abiOverride = abiOverride; 14898 this.installGrantPermissions = installGrantPermissions; 14899 this.traceMethod = traceMethod; 14900 this.traceCookie = traceCookie; 14901 this.certificates = certificates; 14902 this.installReason = installReason; 14903 } 14904 14905 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14906 abstract int doPreInstall(int status); 14907 14908 /** 14909 * Rename package into final resting place. All paths on the given 14910 * scanned package should be updated to reflect the rename. 14911 */ 14912 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14913 abstract int doPostInstall(int status, int uid); 14914 14915 /** @see PackageSettingBase#codePathString */ 14916 abstract String getCodePath(); 14917 /** @see PackageSettingBase#resourcePathString */ 14918 abstract String getResourcePath(); 14919 14920 // Need installer lock especially for dex file removal. 14921 abstract void cleanUpResourcesLI(); 14922 abstract boolean doPostDeleteLI(boolean delete); 14923 14924 /** 14925 * Called before the source arguments are copied. This is used mostly 14926 * for MoveParams when it needs to read the source file to put it in the 14927 * destination. 14928 */ 14929 int doPreCopy() { 14930 return PackageManager.INSTALL_SUCCEEDED; 14931 } 14932 14933 /** 14934 * Called after the source arguments are copied. This is used mostly for 14935 * MoveParams when it needs to read the source file to put it in the 14936 * destination. 14937 */ 14938 int doPostCopy(int uid) { 14939 return PackageManager.INSTALL_SUCCEEDED; 14940 } 14941 14942 protected boolean isFwdLocked() { 14943 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14944 } 14945 14946 protected boolean isExternalAsec() { 14947 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14948 } 14949 14950 protected boolean isEphemeral() { 14951 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14952 } 14953 14954 UserHandle getUser() { 14955 return user; 14956 } 14957 } 14958 14959 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14960 if (!allCodePaths.isEmpty()) { 14961 if (instructionSets == null) { 14962 throw new IllegalStateException("instructionSet == null"); 14963 } 14964 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14965 for (String codePath : allCodePaths) { 14966 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14967 try { 14968 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14969 } catch (InstallerException ignored) { 14970 } 14971 } 14972 } 14973 } 14974 } 14975 14976 /** 14977 * Logic to handle installation of non-ASEC applications, including copying 14978 * and renaming logic. 14979 */ 14980 class FileInstallArgs extends InstallArgs { 14981 private File codeFile; 14982 private File resourceFile; 14983 14984 // Example topology: 14985 // /data/app/com.example/base.apk 14986 // /data/app/com.example/split_foo.apk 14987 // /data/app/com.example/lib/arm/libfoo.so 14988 // /data/app/com.example/lib/arm64/libfoo.so 14989 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14990 14991 /** New install */ 14992 FileInstallArgs(InstallParams params) { 14993 super(params.origin, params.move, params.observer, params.installFlags, 14994 params.installerPackageName, params.volumeUuid, 14995 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14996 params.grantedRuntimePermissions, 14997 params.traceMethod, params.traceCookie, params.certificates, 14998 params.installReason); 14999 if (isFwdLocked()) { 15000 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15001 } 15002 } 15003 15004 /** Existing install */ 15005 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15006 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15007 null, null, null, 0, null /*certificates*/, 15008 PackageManager.INSTALL_REASON_UNKNOWN); 15009 this.codeFile = (codePath != null) ? new File(codePath) : null; 15010 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15011 } 15012 15013 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15014 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15015 try { 15016 return doCopyApk(imcs, temp); 15017 } finally { 15018 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15019 } 15020 } 15021 15022 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15023 if (origin.staged) { 15024 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15025 codeFile = origin.file; 15026 resourceFile = origin.file; 15027 return PackageManager.INSTALL_SUCCEEDED; 15028 } 15029 15030 try { 15031 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15032 final File tempDir = 15033 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15034 codeFile = tempDir; 15035 resourceFile = tempDir; 15036 } catch (IOException e) { 15037 Slog.w(TAG, "Failed to create copy file: " + e); 15038 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15039 } 15040 15041 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15042 @Override 15043 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15044 if (!FileUtils.isValidExtFilename(name)) { 15045 throw new IllegalArgumentException("Invalid filename: " + name); 15046 } 15047 try { 15048 final File file = new File(codeFile, name); 15049 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15050 O_RDWR | O_CREAT, 0644); 15051 Os.chmod(file.getAbsolutePath(), 0644); 15052 return new ParcelFileDescriptor(fd); 15053 } catch (ErrnoException e) { 15054 throw new RemoteException("Failed to open: " + e.getMessage()); 15055 } 15056 } 15057 }; 15058 15059 int ret = PackageManager.INSTALL_SUCCEEDED; 15060 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15061 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15062 Slog.e(TAG, "Failed to copy package"); 15063 return ret; 15064 } 15065 15066 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15067 NativeLibraryHelper.Handle handle = null; 15068 try { 15069 handle = NativeLibraryHelper.Handle.create(codeFile); 15070 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15071 abiOverride); 15072 } catch (IOException e) { 15073 Slog.e(TAG, "Copying native libraries failed", e); 15074 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15075 } finally { 15076 IoUtils.closeQuietly(handle); 15077 } 15078 15079 return ret; 15080 } 15081 15082 int doPreInstall(int status) { 15083 if (status != PackageManager.INSTALL_SUCCEEDED) { 15084 cleanUp(); 15085 } 15086 return status; 15087 } 15088 15089 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15090 if (status != PackageManager.INSTALL_SUCCEEDED) { 15091 cleanUp(); 15092 return false; 15093 } 15094 15095 final File targetDir = codeFile.getParentFile(); 15096 final File beforeCodeFile = codeFile; 15097 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15098 15099 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15100 try { 15101 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15102 } catch (ErrnoException e) { 15103 Slog.w(TAG, "Failed to rename", e); 15104 return false; 15105 } 15106 15107 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15108 Slog.w(TAG, "Failed to restorecon"); 15109 return false; 15110 } 15111 15112 // Reflect the rename internally 15113 codeFile = afterCodeFile; 15114 resourceFile = afterCodeFile; 15115 15116 // Reflect the rename in scanned details 15117 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15118 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15119 afterCodeFile, pkg.baseCodePath)); 15120 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15121 afterCodeFile, pkg.splitCodePaths)); 15122 15123 // Reflect the rename in app info 15124 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15125 pkg.setApplicationInfoCodePath(pkg.codePath); 15126 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15127 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15128 pkg.setApplicationInfoResourcePath(pkg.codePath); 15129 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15130 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15131 15132 return true; 15133 } 15134 15135 int doPostInstall(int status, int uid) { 15136 if (status != PackageManager.INSTALL_SUCCEEDED) { 15137 cleanUp(); 15138 } 15139 return status; 15140 } 15141 15142 @Override 15143 String getCodePath() { 15144 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15145 } 15146 15147 @Override 15148 String getResourcePath() { 15149 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15150 } 15151 15152 private boolean cleanUp() { 15153 if (codeFile == null || !codeFile.exists()) { 15154 return false; 15155 } 15156 15157 removeCodePathLI(codeFile); 15158 15159 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15160 resourceFile.delete(); 15161 } 15162 15163 return true; 15164 } 15165 15166 void cleanUpResourcesLI() { 15167 // Try enumerating all code paths before deleting 15168 List<String> allCodePaths = Collections.EMPTY_LIST; 15169 if (codeFile != null && codeFile.exists()) { 15170 try { 15171 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15172 allCodePaths = pkg.getAllCodePaths(); 15173 } catch (PackageParserException e) { 15174 // Ignored; we tried our best 15175 } 15176 } 15177 15178 cleanUp(); 15179 removeDexFiles(allCodePaths, instructionSets); 15180 } 15181 15182 boolean doPostDeleteLI(boolean delete) { 15183 // XXX err, shouldn't we respect the delete flag? 15184 cleanUpResourcesLI(); 15185 return true; 15186 } 15187 } 15188 15189 private boolean isAsecExternal(String cid) { 15190 final String asecPath = PackageHelper.getSdFilesystem(cid); 15191 return !asecPath.startsWith(mAsecInternalPath); 15192 } 15193 15194 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15195 PackageManagerException { 15196 if (copyRet < 0) { 15197 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15198 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15199 throw new PackageManagerException(copyRet, message); 15200 } 15201 } 15202 } 15203 15204 /** 15205 * Extract the StorageManagerService "container ID" from the full code path of an 15206 * .apk. 15207 */ 15208 static String cidFromCodePath(String fullCodePath) { 15209 int eidx = fullCodePath.lastIndexOf("/"); 15210 String subStr1 = fullCodePath.substring(0, eidx); 15211 int sidx = subStr1.lastIndexOf("/"); 15212 return subStr1.substring(sidx+1, eidx); 15213 } 15214 15215 /** 15216 * Logic to handle installation of ASEC applications, including copying and 15217 * renaming logic. 15218 */ 15219 class AsecInstallArgs extends InstallArgs { 15220 static final String RES_FILE_NAME = "pkg.apk"; 15221 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15222 15223 String cid; 15224 String packagePath; 15225 String resourcePath; 15226 15227 /** New install */ 15228 AsecInstallArgs(InstallParams params) { 15229 super(params.origin, params.move, params.observer, params.installFlags, 15230 params.installerPackageName, params.volumeUuid, 15231 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15232 params.grantedRuntimePermissions, 15233 params.traceMethod, params.traceCookie, params.certificates, 15234 params.installReason); 15235 } 15236 15237 /** Existing install */ 15238 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15239 boolean isExternal, boolean isForwardLocked) { 15240 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15241 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15242 instructionSets, null, null, null, 0, null /*certificates*/, 15243 PackageManager.INSTALL_REASON_UNKNOWN); 15244 // Hackily pretend we're still looking at a full code path 15245 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15246 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15247 } 15248 15249 // Extract cid from fullCodePath 15250 int eidx = fullCodePath.lastIndexOf("/"); 15251 String subStr1 = fullCodePath.substring(0, eidx); 15252 int sidx = subStr1.lastIndexOf("/"); 15253 cid = subStr1.substring(sidx+1, eidx); 15254 setMountPath(subStr1); 15255 } 15256 15257 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15258 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15259 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15260 instructionSets, null, null, null, 0, null /*certificates*/, 15261 PackageManager.INSTALL_REASON_UNKNOWN); 15262 this.cid = cid; 15263 setMountPath(PackageHelper.getSdDir(cid)); 15264 } 15265 15266 void createCopyFile() { 15267 cid = mInstallerService.allocateExternalStageCidLegacy(); 15268 } 15269 15270 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15271 if (origin.staged && origin.cid != null) { 15272 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15273 cid = origin.cid; 15274 setMountPath(PackageHelper.getSdDir(cid)); 15275 return PackageManager.INSTALL_SUCCEEDED; 15276 } 15277 15278 if (temp) { 15279 createCopyFile(); 15280 } else { 15281 /* 15282 * Pre-emptively destroy the container since it's destroyed if 15283 * copying fails due to it existing anyway. 15284 */ 15285 PackageHelper.destroySdDir(cid); 15286 } 15287 15288 final String newMountPath = imcs.copyPackageToContainer( 15289 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15290 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15291 15292 if (newMountPath != null) { 15293 setMountPath(newMountPath); 15294 return PackageManager.INSTALL_SUCCEEDED; 15295 } else { 15296 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15297 } 15298 } 15299 15300 @Override 15301 String getCodePath() { 15302 return packagePath; 15303 } 15304 15305 @Override 15306 String getResourcePath() { 15307 return resourcePath; 15308 } 15309 15310 int doPreInstall(int status) { 15311 if (status != PackageManager.INSTALL_SUCCEEDED) { 15312 // Destroy container 15313 PackageHelper.destroySdDir(cid); 15314 } else { 15315 boolean mounted = PackageHelper.isContainerMounted(cid); 15316 if (!mounted) { 15317 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15318 Process.SYSTEM_UID); 15319 if (newMountPath != null) { 15320 setMountPath(newMountPath); 15321 } else { 15322 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15323 } 15324 } 15325 } 15326 return status; 15327 } 15328 15329 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15330 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15331 String newMountPath = null; 15332 if (PackageHelper.isContainerMounted(cid)) { 15333 // Unmount the container 15334 if (!PackageHelper.unMountSdDir(cid)) { 15335 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15336 return false; 15337 } 15338 } 15339 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15340 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15341 " which might be stale. Will try to clean up."); 15342 // Clean up the stale container and proceed to recreate. 15343 if (!PackageHelper.destroySdDir(newCacheId)) { 15344 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15345 return false; 15346 } 15347 // Successfully cleaned up stale container. Try to rename again. 15348 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15349 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15350 + " inspite of cleaning it up."); 15351 return false; 15352 } 15353 } 15354 if (!PackageHelper.isContainerMounted(newCacheId)) { 15355 Slog.w(TAG, "Mounting container " + newCacheId); 15356 newMountPath = PackageHelper.mountSdDir(newCacheId, 15357 getEncryptKey(), Process.SYSTEM_UID); 15358 } else { 15359 newMountPath = PackageHelper.getSdDir(newCacheId); 15360 } 15361 if (newMountPath == null) { 15362 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15363 return false; 15364 } 15365 Log.i(TAG, "Succesfully renamed " + cid + 15366 " to " + newCacheId + 15367 " at new path: " + newMountPath); 15368 cid = newCacheId; 15369 15370 final File beforeCodeFile = new File(packagePath); 15371 setMountPath(newMountPath); 15372 final File afterCodeFile = new File(packagePath); 15373 15374 // Reflect the rename in scanned details 15375 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15376 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15377 afterCodeFile, pkg.baseCodePath)); 15378 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15379 afterCodeFile, pkg.splitCodePaths)); 15380 15381 // Reflect the rename in app info 15382 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15383 pkg.setApplicationInfoCodePath(pkg.codePath); 15384 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15385 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15386 pkg.setApplicationInfoResourcePath(pkg.codePath); 15387 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15388 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15389 15390 return true; 15391 } 15392 15393 private void setMountPath(String mountPath) { 15394 final File mountFile = new File(mountPath); 15395 15396 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15397 if (monolithicFile.exists()) { 15398 packagePath = monolithicFile.getAbsolutePath(); 15399 if (isFwdLocked()) { 15400 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15401 } else { 15402 resourcePath = packagePath; 15403 } 15404 } else { 15405 packagePath = mountFile.getAbsolutePath(); 15406 resourcePath = packagePath; 15407 } 15408 } 15409 15410 int doPostInstall(int status, int uid) { 15411 if (status != PackageManager.INSTALL_SUCCEEDED) { 15412 cleanUp(); 15413 } else { 15414 final int groupOwner; 15415 final String protectedFile; 15416 if (isFwdLocked()) { 15417 groupOwner = UserHandle.getSharedAppGid(uid); 15418 protectedFile = RES_FILE_NAME; 15419 } else { 15420 groupOwner = -1; 15421 protectedFile = null; 15422 } 15423 15424 if (uid < Process.FIRST_APPLICATION_UID 15425 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15426 Slog.e(TAG, "Failed to finalize " + cid); 15427 PackageHelper.destroySdDir(cid); 15428 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15429 } 15430 15431 boolean mounted = PackageHelper.isContainerMounted(cid); 15432 if (!mounted) { 15433 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15434 } 15435 } 15436 return status; 15437 } 15438 15439 private void cleanUp() { 15440 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15441 15442 // Destroy secure container 15443 PackageHelper.destroySdDir(cid); 15444 } 15445 15446 private List<String> getAllCodePaths() { 15447 final File codeFile = new File(getCodePath()); 15448 if (codeFile != null && codeFile.exists()) { 15449 try { 15450 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15451 return pkg.getAllCodePaths(); 15452 } catch (PackageParserException e) { 15453 // Ignored; we tried our best 15454 } 15455 } 15456 return Collections.EMPTY_LIST; 15457 } 15458 15459 void cleanUpResourcesLI() { 15460 // Enumerate all code paths before deleting 15461 cleanUpResourcesLI(getAllCodePaths()); 15462 } 15463 15464 private void cleanUpResourcesLI(List<String> allCodePaths) { 15465 cleanUp(); 15466 removeDexFiles(allCodePaths, instructionSets); 15467 } 15468 15469 String getPackageName() { 15470 return getAsecPackageName(cid); 15471 } 15472 15473 boolean doPostDeleteLI(boolean delete) { 15474 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15475 final List<String> allCodePaths = getAllCodePaths(); 15476 boolean mounted = PackageHelper.isContainerMounted(cid); 15477 if (mounted) { 15478 // Unmount first 15479 if (PackageHelper.unMountSdDir(cid)) { 15480 mounted = false; 15481 } 15482 } 15483 if (!mounted && delete) { 15484 cleanUpResourcesLI(allCodePaths); 15485 } 15486 return !mounted; 15487 } 15488 15489 @Override 15490 int doPreCopy() { 15491 if (isFwdLocked()) { 15492 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15493 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15494 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15495 } 15496 } 15497 15498 return PackageManager.INSTALL_SUCCEEDED; 15499 } 15500 15501 @Override 15502 int doPostCopy(int uid) { 15503 if (isFwdLocked()) { 15504 if (uid < Process.FIRST_APPLICATION_UID 15505 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15506 RES_FILE_NAME)) { 15507 Slog.e(TAG, "Failed to finalize " + cid); 15508 PackageHelper.destroySdDir(cid); 15509 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15510 } 15511 } 15512 15513 return PackageManager.INSTALL_SUCCEEDED; 15514 } 15515 } 15516 15517 /** 15518 * Logic to handle movement of existing installed applications. 15519 */ 15520 class MoveInstallArgs extends InstallArgs { 15521 private File codeFile; 15522 private File resourceFile; 15523 15524 /** New install */ 15525 MoveInstallArgs(InstallParams params) { 15526 super(params.origin, params.move, params.observer, params.installFlags, 15527 params.installerPackageName, params.volumeUuid, 15528 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15529 params.grantedRuntimePermissions, 15530 params.traceMethod, params.traceCookie, params.certificates, 15531 params.installReason); 15532 } 15533 15534 int copyApk(IMediaContainerService imcs, boolean temp) { 15535 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15536 + move.fromUuid + " to " + move.toUuid); 15537 synchronized (mInstaller) { 15538 try { 15539 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15540 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15541 } catch (InstallerException e) { 15542 Slog.w(TAG, "Failed to move app", e); 15543 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15544 } 15545 } 15546 15547 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15548 resourceFile = codeFile; 15549 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15550 15551 return PackageManager.INSTALL_SUCCEEDED; 15552 } 15553 15554 int doPreInstall(int status) { 15555 if (status != PackageManager.INSTALL_SUCCEEDED) { 15556 cleanUp(move.toUuid); 15557 } 15558 return status; 15559 } 15560 15561 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15562 if (status != PackageManager.INSTALL_SUCCEEDED) { 15563 cleanUp(move.toUuid); 15564 return false; 15565 } 15566 15567 // Reflect the move in app info 15568 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15569 pkg.setApplicationInfoCodePath(pkg.codePath); 15570 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15571 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15572 pkg.setApplicationInfoResourcePath(pkg.codePath); 15573 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15574 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15575 15576 return true; 15577 } 15578 15579 int doPostInstall(int status, int uid) { 15580 if (status == PackageManager.INSTALL_SUCCEEDED) { 15581 cleanUp(move.fromUuid); 15582 } else { 15583 cleanUp(move.toUuid); 15584 } 15585 return status; 15586 } 15587 15588 @Override 15589 String getCodePath() { 15590 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15591 } 15592 15593 @Override 15594 String getResourcePath() { 15595 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15596 } 15597 15598 private boolean cleanUp(String volumeUuid) { 15599 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15600 move.dataAppName); 15601 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15602 final int[] userIds = sUserManager.getUserIds(); 15603 synchronized (mInstallLock) { 15604 // Clean up both app data and code 15605 // All package moves are frozen until finished 15606 for (int userId : userIds) { 15607 try { 15608 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15609 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15610 } catch (InstallerException e) { 15611 Slog.w(TAG, String.valueOf(e)); 15612 } 15613 } 15614 removeCodePathLI(codeFile); 15615 } 15616 return true; 15617 } 15618 15619 void cleanUpResourcesLI() { 15620 throw new UnsupportedOperationException(); 15621 } 15622 15623 boolean doPostDeleteLI(boolean delete) { 15624 throw new UnsupportedOperationException(); 15625 } 15626 } 15627 15628 static String getAsecPackageName(String packageCid) { 15629 int idx = packageCid.lastIndexOf("-"); 15630 if (idx == -1) { 15631 return packageCid; 15632 } 15633 return packageCid.substring(0, idx); 15634 } 15635 15636 // Utility method used to create code paths based on package name and available index. 15637 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15638 String idxStr = ""; 15639 int idx = 1; 15640 // Fall back to default value of idx=1 if prefix is not 15641 // part of oldCodePath 15642 if (oldCodePath != null) { 15643 String subStr = oldCodePath; 15644 // Drop the suffix right away 15645 if (suffix != null && subStr.endsWith(suffix)) { 15646 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15647 } 15648 // If oldCodePath already contains prefix find out the 15649 // ending index to either increment or decrement. 15650 int sidx = subStr.lastIndexOf(prefix); 15651 if (sidx != -1) { 15652 subStr = subStr.substring(sidx + prefix.length()); 15653 if (subStr != null) { 15654 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15655 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15656 } 15657 try { 15658 idx = Integer.parseInt(subStr); 15659 if (idx <= 1) { 15660 idx++; 15661 } else { 15662 idx--; 15663 } 15664 } catch(NumberFormatException e) { 15665 } 15666 } 15667 } 15668 } 15669 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15670 return prefix + idxStr; 15671 } 15672 15673 private File getNextCodePath(File targetDir, String packageName) { 15674 File result; 15675 SecureRandom random = new SecureRandom(); 15676 byte[] bytes = new byte[16]; 15677 do { 15678 random.nextBytes(bytes); 15679 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15680 result = new File(targetDir, packageName + "-" + suffix); 15681 } while (result.exists()); 15682 return result; 15683 } 15684 15685 // Utility method that returns the relative package path with respect 15686 // to the installation directory. Like say for /data/data/com.test-1.apk 15687 // string com.test-1 is returned. 15688 static String deriveCodePathName(String codePath) { 15689 if (codePath == null) { 15690 return null; 15691 } 15692 final File codeFile = new File(codePath); 15693 final String name = codeFile.getName(); 15694 if (codeFile.isDirectory()) { 15695 return name; 15696 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15697 final int lastDot = name.lastIndexOf('.'); 15698 return name.substring(0, lastDot); 15699 } else { 15700 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15701 return null; 15702 } 15703 } 15704 15705 static class PackageInstalledInfo { 15706 String name; 15707 int uid; 15708 // The set of users that originally had this package installed. 15709 int[] origUsers; 15710 // The set of users that now have this package installed. 15711 int[] newUsers; 15712 PackageParser.Package pkg; 15713 int returnCode; 15714 String returnMsg; 15715 PackageRemovedInfo removedInfo; 15716 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15717 15718 public void setError(int code, String msg) { 15719 setReturnCode(code); 15720 setReturnMessage(msg); 15721 Slog.w(TAG, msg); 15722 } 15723 15724 public void setError(String msg, PackageParserException e) { 15725 setReturnCode(e.error); 15726 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15727 Slog.w(TAG, msg, e); 15728 } 15729 15730 public void setError(String msg, PackageManagerException e) { 15731 returnCode = e.error; 15732 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15733 Slog.w(TAG, msg, e); 15734 } 15735 15736 public void setReturnCode(int returnCode) { 15737 this.returnCode = returnCode; 15738 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15739 for (int i = 0; i < childCount; i++) { 15740 addedChildPackages.valueAt(i).returnCode = returnCode; 15741 } 15742 } 15743 15744 private void setReturnMessage(String returnMsg) { 15745 this.returnMsg = returnMsg; 15746 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15747 for (int i = 0; i < childCount; i++) { 15748 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15749 } 15750 } 15751 15752 // In some error cases we want to convey more info back to the observer 15753 String origPackage; 15754 String origPermission; 15755 } 15756 15757 /* 15758 * Install a non-existing package. 15759 */ 15760 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15761 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15762 PackageInstalledInfo res, int installReason) { 15763 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15764 15765 // Remember this for later, in case we need to rollback this install 15766 String pkgName = pkg.packageName; 15767 15768 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15769 15770 synchronized(mPackages) { 15771 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15772 if (renamedPackage != null) { 15773 // A package with the same name is already installed, though 15774 // it has been renamed to an older name. The package we 15775 // are trying to install should be installed as an update to 15776 // the existing one, but that has not been requested, so bail. 15777 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15778 + " without first uninstalling package running as " 15779 + renamedPackage); 15780 return; 15781 } 15782 if (mPackages.containsKey(pkgName)) { 15783 // Don't allow installation over an existing package with the same name. 15784 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15785 + " without first uninstalling."); 15786 return; 15787 } 15788 } 15789 15790 try { 15791 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15792 System.currentTimeMillis(), user); 15793 15794 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15795 15796 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15797 prepareAppDataAfterInstallLIF(newPackage); 15798 15799 } else { 15800 // Remove package from internal structures, but keep around any 15801 // data that might have already existed 15802 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15803 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15804 } 15805 } catch (PackageManagerException e) { 15806 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15807 } 15808 15809 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15810 } 15811 15812 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15813 // Can't rotate keys during boot or if sharedUser. 15814 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15815 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15816 return false; 15817 } 15818 // app is using upgradeKeySets; make sure all are valid 15819 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15820 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15821 for (int i = 0; i < upgradeKeySets.length; i++) { 15822 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15823 Slog.wtf(TAG, "Package " 15824 + (oldPs.name != null ? oldPs.name : "<null>") 15825 + " contains upgrade-key-set reference to unknown key-set: " 15826 + upgradeKeySets[i] 15827 + " reverting to signatures check."); 15828 return false; 15829 } 15830 } 15831 return true; 15832 } 15833 15834 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15835 // Upgrade keysets are being used. Determine if new package has a superset of the 15836 // required keys. 15837 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15838 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15839 for (int i = 0; i < upgradeKeySets.length; i++) { 15840 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15841 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15842 return true; 15843 } 15844 } 15845 return false; 15846 } 15847 15848 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15849 try (DigestInputStream digestStream = 15850 new DigestInputStream(new FileInputStream(file), digest)) { 15851 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15852 } 15853 } 15854 15855 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15856 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15857 int installReason) { 15858 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15859 15860 final PackageParser.Package oldPackage; 15861 final String pkgName = pkg.packageName; 15862 final int[] allUsers; 15863 final int[] installedUsers; 15864 15865 synchronized(mPackages) { 15866 oldPackage = mPackages.get(pkgName); 15867 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15868 15869 // don't allow upgrade to target a release SDK from a pre-release SDK 15870 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15871 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15872 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15873 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15874 if (oldTargetsPreRelease 15875 && !newTargetsPreRelease 15876 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15877 Slog.w(TAG, "Can't install package targeting released sdk"); 15878 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15879 return; 15880 } 15881 15882 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15883 15884 // verify signatures are valid 15885 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15886 if (!checkUpgradeKeySetLP(ps, pkg)) { 15887 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15888 "New package not signed by keys specified by upgrade-keysets: " 15889 + pkgName); 15890 return; 15891 } 15892 } else { 15893 // default to original signature matching 15894 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15895 != PackageManager.SIGNATURE_MATCH) { 15896 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15897 "New package has a different signature: " + pkgName); 15898 return; 15899 } 15900 } 15901 15902 // don't allow a system upgrade unless the upgrade hash matches 15903 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15904 byte[] digestBytes = null; 15905 try { 15906 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15907 updateDigest(digest, new File(pkg.baseCodePath)); 15908 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15909 for (String path : pkg.splitCodePaths) { 15910 updateDigest(digest, new File(path)); 15911 } 15912 } 15913 digestBytes = digest.digest(); 15914 } catch (NoSuchAlgorithmException | IOException e) { 15915 res.setError(INSTALL_FAILED_INVALID_APK, 15916 "Could not compute hash: " + pkgName); 15917 return; 15918 } 15919 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15920 res.setError(INSTALL_FAILED_INVALID_APK, 15921 "New package fails restrict-update check: " + pkgName); 15922 return; 15923 } 15924 // retain upgrade restriction 15925 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15926 } 15927 15928 // Check for shared user id changes 15929 String invalidPackageName = 15930 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15931 if (invalidPackageName != null) { 15932 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15933 "Package " + invalidPackageName + " tried to change user " 15934 + oldPackage.mSharedUserId); 15935 return; 15936 } 15937 15938 // In case of rollback, remember per-user/profile install state 15939 allUsers = sUserManager.getUserIds(); 15940 installedUsers = ps.queryInstalledUsers(allUsers, true); 15941 15942 // don't allow an upgrade from full to ephemeral 15943 if (isInstantApp) { 15944 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15945 for (int currentUser : allUsers) { 15946 if (!ps.getInstantApp(currentUser)) { 15947 // can't downgrade from full to instant 15948 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15949 + " for user: " + currentUser); 15950 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15951 return; 15952 } 15953 } 15954 } else if (!ps.getInstantApp(user.getIdentifier())) { 15955 // can't downgrade from full to instant 15956 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15957 + " for user: " + user.getIdentifier()); 15958 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15959 return; 15960 } 15961 } 15962 } 15963 15964 // Update what is removed 15965 res.removedInfo = new PackageRemovedInfo(); 15966 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15967 res.removedInfo.removedPackage = oldPackage.packageName; 15968 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15969 res.removedInfo.isUpdate = true; 15970 res.removedInfo.origUsers = installedUsers; 15971 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15972 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15973 for (int i = 0; i < installedUsers.length; i++) { 15974 final int userId = installedUsers[i]; 15975 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15976 } 15977 15978 final int childCount = (oldPackage.childPackages != null) 15979 ? oldPackage.childPackages.size() : 0; 15980 for (int i = 0; i < childCount; i++) { 15981 boolean childPackageUpdated = false; 15982 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15983 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15984 if (res.addedChildPackages != null) { 15985 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15986 if (childRes != null) { 15987 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15988 childRes.removedInfo.removedPackage = childPkg.packageName; 15989 childRes.removedInfo.isUpdate = true; 15990 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15991 childPackageUpdated = true; 15992 } 15993 } 15994 if (!childPackageUpdated) { 15995 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15996 childRemovedRes.removedPackage = childPkg.packageName; 15997 childRemovedRes.isUpdate = false; 15998 childRemovedRes.dataRemoved = true; 15999 synchronized (mPackages) { 16000 if (childPs != null) { 16001 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16002 } 16003 } 16004 if (res.removedInfo.removedChildPackages == null) { 16005 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16006 } 16007 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16008 } 16009 } 16010 16011 boolean sysPkg = (isSystemApp(oldPackage)); 16012 if (sysPkg) { 16013 // Set the system/privileged flags as needed 16014 final boolean privileged = 16015 (oldPackage.applicationInfo.privateFlags 16016 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16017 final int systemPolicyFlags = policyFlags 16018 | PackageParser.PARSE_IS_SYSTEM 16019 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16020 16021 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16022 user, allUsers, installerPackageName, res, installReason); 16023 } else { 16024 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16025 user, allUsers, installerPackageName, res, installReason); 16026 } 16027 } 16028 16029 public List<String> getPreviousCodePaths(String packageName) { 16030 final PackageSetting ps = mSettings.mPackages.get(packageName); 16031 final List<String> result = new ArrayList<String>(); 16032 if (ps != null && ps.oldCodePaths != null) { 16033 result.addAll(ps.oldCodePaths); 16034 } 16035 return result; 16036 } 16037 16038 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16039 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16040 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16041 int installReason) { 16042 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16043 + deletedPackage); 16044 16045 String pkgName = deletedPackage.packageName; 16046 boolean deletedPkg = true; 16047 boolean addedPkg = false; 16048 boolean updatedSettings = false; 16049 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16050 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16051 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16052 16053 final long origUpdateTime = (pkg.mExtras != null) 16054 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16055 16056 // First delete the existing package while retaining the data directory 16057 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16058 res.removedInfo, true, pkg)) { 16059 // If the existing package wasn't successfully deleted 16060 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16061 deletedPkg = false; 16062 } else { 16063 // Successfully deleted the old package; proceed with replace. 16064 16065 // If deleted package lived in a container, give users a chance to 16066 // relinquish resources before killing. 16067 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16068 if (DEBUG_INSTALL) { 16069 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16070 } 16071 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16072 final ArrayList<String> pkgList = new ArrayList<String>(1); 16073 pkgList.add(deletedPackage.applicationInfo.packageName); 16074 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16075 } 16076 16077 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16078 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16079 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16080 16081 try { 16082 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16083 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16084 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16085 installReason); 16086 16087 // Update the in-memory copy of the previous code paths. 16088 PackageSetting ps = mSettings.mPackages.get(pkgName); 16089 if (!killApp) { 16090 if (ps.oldCodePaths == null) { 16091 ps.oldCodePaths = new ArraySet<>(); 16092 } 16093 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16094 if (deletedPackage.splitCodePaths != null) { 16095 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16096 } 16097 } else { 16098 ps.oldCodePaths = null; 16099 } 16100 if (ps.childPackageNames != null) { 16101 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16102 final String childPkgName = ps.childPackageNames.get(i); 16103 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16104 childPs.oldCodePaths = ps.oldCodePaths; 16105 } 16106 } 16107 // set instant app status, but, only if it's explicitly specified 16108 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16109 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16110 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16111 prepareAppDataAfterInstallLIF(newPackage); 16112 addedPkg = true; 16113 mDexManager.notifyPackageUpdated(newPackage.packageName, 16114 newPackage.baseCodePath, newPackage.splitCodePaths); 16115 } catch (PackageManagerException e) { 16116 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16117 } 16118 } 16119 16120 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16121 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16122 16123 // Revert all internal state mutations and added folders for the failed install 16124 if (addedPkg) { 16125 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16126 res.removedInfo, true, null); 16127 } 16128 16129 // Restore the old package 16130 if (deletedPkg) { 16131 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16132 File restoreFile = new File(deletedPackage.codePath); 16133 // Parse old package 16134 boolean oldExternal = isExternal(deletedPackage); 16135 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16136 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16137 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16138 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16139 try { 16140 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16141 null); 16142 } catch (PackageManagerException e) { 16143 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16144 + e.getMessage()); 16145 return; 16146 } 16147 16148 synchronized (mPackages) { 16149 // Ensure the installer package name up to date 16150 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16151 16152 // Update permissions for restored package 16153 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16154 16155 mSettings.writeLPr(); 16156 } 16157 16158 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16159 } 16160 } else { 16161 synchronized (mPackages) { 16162 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16163 if (ps != null) { 16164 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16165 if (res.removedInfo.removedChildPackages != null) { 16166 final int childCount = res.removedInfo.removedChildPackages.size(); 16167 // Iterate in reverse as we may modify the collection 16168 for (int i = childCount - 1; i >= 0; i--) { 16169 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16170 if (res.addedChildPackages.containsKey(childPackageName)) { 16171 res.removedInfo.removedChildPackages.removeAt(i); 16172 } else { 16173 PackageRemovedInfo childInfo = res.removedInfo 16174 .removedChildPackages.valueAt(i); 16175 childInfo.removedForAllUsers = mPackages.get( 16176 childInfo.removedPackage) == null; 16177 } 16178 } 16179 } 16180 } 16181 } 16182 } 16183 } 16184 16185 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16186 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16187 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16188 int installReason) { 16189 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16190 + ", old=" + deletedPackage); 16191 16192 final boolean disabledSystem; 16193 16194 // Remove existing system package 16195 removePackageLI(deletedPackage, true); 16196 16197 synchronized (mPackages) { 16198 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16199 } 16200 if (!disabledSystem) { 16201 // We didn't need to disable the .apk as a current system package, 16202 // which means we are replacing another update that is already 16203 // installed. We need to make sure to delete the older one's .apk. 16204 res.removedInfo.args = createInstallArgsForExisting(0, 16205 deletedPackage.applicationInfo.getCodePath(), 16206 deletedPackage.applicationInfo.getResourcePath(), 16207 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16208 } else { 16209 res.removedInfo.args = null; 16210 } 16211 16212 // Successfully disabled the old package. Now proceed with re-installation 16213 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16214 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16215 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16216 16217 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16218 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16219 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16220 16221 PackageParser.Package newPackage = null; 16222 try { 16223 // Add the package to the internal data structures 16224 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16225 16226 // Set the update and install times 16227 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16228 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16229 System.currentTimeMillis()); 16230 16231 // Update the package dynamic state if succeeded 16232 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16233 // Now that the install succeeded make sure we remove data 16234 // directories for any child package the update removed. 16235 final int deletedChildCount = (deletedPackage.childPackages != null) 16236 ? deletedPackage.childPackages.size() : 0; 16237 final int newChildCount = (newPackage.childPackages != null) 16238 ? newPackage.childPackages.size() : 0; 16239 for (int i = 0; i < deletedChildCount; i++) { 16240 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16241 boolean childPackageDeleted = true; 16242 for (int j = 0; j < newChildCount; j++) { 16243 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16244 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16245 childPackageDeleted = false; 16246 break; 16247 } 16248 } 16249 if (childPackageDeleted) { 16250 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16251 deletedChildPkg.packageName); 16252 if (ps != null && res.removedInfo.removedChildPackages != null) { 16253 PackageRemovedInfo removedChildRes = res.removedInfo 16254 .removedChildPackages.get(deletedChildPkg.packageName); 16255 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16256 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16257 } 16258 } 16259 } 16260 16261 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16262 installReason); 16263 prepareAppDataAfterInstallLIF(newPackage); 16264 16265 mDexManager.notifyPackageUpdated(newPackage.packageName, 16266 newPackage.baseCodePath, newPackage.splitCodePaths); 16267 } 16268 } catch (PackageManagerException e) { 16269 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16270 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16271 } 16272 16273 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16274 // Re installation failed. Restore old information 16275 // Remove new pkg information 16276 if (newPackage != null) { 16277 removeInstalledPackageLI(newPackage, true); 16278 } 16279 // Add back the old system package 16280 try { 16281 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16282 } catch (PackageManagerException e) { 16283 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16284 } 16285 16286 synchronized (mPackages) { 16287 if (disabledSystem) { 16288 enableSystemPackageLPw(deletedPackage); 16289 } 16290 16291 // Ensure the installer package name up to date 16292 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16293 16294 // Update permissions for restored package 16295 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16296 16297 mSettings.writeLPr(); 16298 } 16299 16300 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16301 + " after failed upgrade"); 16302 } 16303 } 16304 16305 /** 16306 * Checks whether the parent or any of the child packages have a change shared 16307 * user. For a package to be a valid update the shred users of the parent and 16308 * the children should match. We may later support changing child shared users. 16309 * @param oldPkg The updated package. 16310 * @param newPkg The update package. 16311 * @return The shared user that change between the versions. 16312 */ 16313 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16314 PackageParser.Package newPkg) { 16315 // Check parent shared user 16316 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16317 return newPkg.packageName; 16318 } 16319 // Check child shared users 16320 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16321 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16322 for (int i = 0; i < newChildCount; i++) { 16323 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16324 // If this child was present, did it have the same shared user? 16325 for (int j = 0; j < oldChildCount; j++) { 16326 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16327 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16328 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16329 return newChildPkg.packageName; 16330 } 16331 } 16332 } 16333 return null; 16334 } 16335 16336 private void removeNativeBinariesLI(PackageSetting ps) { 16337 // Remove the lib path for the parent package 16338 if (ps != null) { 16339 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16340 // Remove the lib path for the child packages 16341 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16342 for (int i = 0; i < childCount; i++) { 16343 PackageSetting childPs = null; 16344 synchronized (mPackages) { 16345 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16346 } 16347 if (childPs != null) { 16348 NativeLibraryHelper.removeNativeBinariesLI(childPs 16349 .legacyNativeLibraryPathString); 16350 } 16351 } 16352 } 16353 } 16354 16355 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16356 // Enable the parent package 16357 mSettings.enableSystemPackageLPw(pkg.packageName); 16358 // Enable the child packages 16359 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16360 for (int i = 0; i < childCount; i++) { 16361 PackageParser.Package childPkg = pkg.childPackages.get(i); 16362 mSettings.enableSystemPackageLPw(childPkg.packageName); 16363 } 16364 } 16365 16366 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16367 PackageParser.Package newPkg) { 16368 // Disable the parent package (parent always replaced) 16369 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16370 // Disable the child packages 16371 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16372 for (int i = 0; i < childCount; i++) { 16373 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16374 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16375 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16376 } 16377 return disabled; 16378 } 16379 16380 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16381 String installerPackageName) { 16382 // Enable the parent package 16383 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16384 // Enable the child packages 16385 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16386 for (int i = 0; i < childCount; i++) { 16387 PackageParser.Package childPkg = pkg.childPackages.get(i); 16388 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16389 } 16390 } 16391 16392 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16393 // Collect all used permissions in the UID 16394 ArraySet<String> usedPermissions = new ArraySet<>(); 16395 final int packageCount = su.packages.size(); 16396 for (int i = 0; i < packageCount; i++) { 16397 PackageSetting ps = su.packages.valueAt(i); 16398 if (ps.pkg == null) { 16399 continue; 16400 } 16401 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16402 for (int j = 0; j < requestedPermCount; j++) { 16403 String permission = ps.pkg.requestedPermissions.get(j); 16404 BasePermission bp = mSettings.mPermissions.get(permission); 16405 if (bp != null) { 16406 usedPermissions.add(permission); 16407 } 16408 } 16409 } 16410 16411 PermissionsState permissionsState = su.getPermissionsState(); 16412 // Prune install permissions 16413 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16414 final int installPermCount = installPermStates.size(); 16415 for (int i = installPermCount - 1; i >= 0; i--) { 16416 PermissionState permissionState = installPermStates.get(i); 16417 if (!usedPermissions.contains(permissionState.getName())) { 16418 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16419 if (bp != null) { 16420 permissionsState.revokeInstallPermission(bp); 16421 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16422 PackageManager.MASK_PERMISSION_FLAGS, 0); 16423 } 16424 } 16425 } 16426 16427 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16428 16429 // Prune runtime permissions 16430 for (int userId : allUserIds) { 16431 List<PermissionState> runtimePermStates = permissionsState 16432 .getRuntimePermissionStates(userId); 16433 final int runtimePermCount = runtimePermStates.size(); 16434 for (int i = runtimePermCount - 1; i >= 0; i--) { 16435 PermissionState permissionState = runtimePermStates.get(i); 16436 if (!usedPermissions.contains(permissionState.getName())) { 16437 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16438 if (bp != null) { 16439 permissionsState.revokeRuntimePermission(bp, userId); 16440 permissionsState.updatePermissionFlags(bp, userId, 16441 PackageManager.MASK_PERMISSION_FLAGS, 0); 16442 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16443 runtimePermissionChangedUserIds, userId); 16444 } 16445 } 16446 } 16447 } 16448 16449 return runtimePermissionChangedUserIds; 16450 } 16451 16452 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16453 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16454 // Update the parent package setting 16455 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16456 res, user, installReason); 16457 // Update the child packages setting 16458 final int childCount = (newPackage.childPackages != null) 16459 ? newPackage.childPackages.size() : 0; 16460 for (int i = 0; i < childCount; i++) { 16461 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16462 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16463 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16464 childRes.origUsers, childRes, user, installReason); 16465 } 16466 } 16467 16468 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16469 String installerPackageName, int[] allUsers, int[] installedForUsers, 16470 PackageInstalledInfo res, UserHandle user, int installReason) { 16471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16472 16473 String pkgName = newPackage.packageName; 16474 synchronized (mPackages) { 16475 //write settings. the installStatus will be incomplete at this stage. 16476 //note that the new package setting would have already been 16477 //added to mPackages. It hasn't been persisted yet. 16478 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16479 // TODO: Remove this write? It's also written at the end of this method 16480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16481 mSettings.writeLPr(); 16482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16483 } 16484 16485 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16486 synchronized (mPackages) { 16487 updatePermissionsLPw(newPackage.packageName, newPackage, 16488 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16489 ? UPDATE_PERMISSIONS_ALL : 0)); 16490 // For system-bundled packages, we assume that installing an upgraded version 16491 // of the package implies that the user actually wants to run that new code, 16492 // so we enable the package. 16493 PackageSetting ps = mSettings.mPackages.get(pkgName); 16494 final int userId = user.getIdentifier(); 16495 if (ps != null) { 16496 if (isSystemApp(newPackage)) { 16497 if (DEBUG_INSTALL) { 16498 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16499 } 16500 // Enable system package for requested users 16501 if (res.origUsers != null) { 16502 for (int origUserId : res.origUsers) { 16503 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16504 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16505 origUserId, installerPackageName); 16506 } 16507 } 16508 } 16509 // Also convey the prior install/uninstall state 16510 if (allUsers != null && installedForUsers != null) { 16511 for (int currentUserId : allUsers) { 16512 final boolean installed = ArrayUtils.contains( 16513 installedForUsers, currentUserId); 16514 if (DEBUG_INSTALL) { 16515 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16516 } 16517 ps.setInstalled(installed, currentUserId); 16518 } 16519 // these install state changes will be persisted in the 16520 // upcoming call to mSettings.writeLPr(). 16521 } 16522 } 16523 // It's implied that when a user requests installation, they want the app to be 16524 // installed and enabled. 16525 if (userId != UserHandle.USER_ALL) { 16526 ps.setInstalled(true, userId); 16527 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16528 } 16529 16530 // When replacing an existing package, preserve the original install reason for all 16531 // users that had the package installed before. 16532 final Set<Integer> previousUserIds = new ArraySet<>(); 16533 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16534 final int installReasonCount = res.removedInfo.installReasons.size(); 16535 for (int i = 0; i < installReasonCount; i++) { 16536 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16537 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16538 ps.setInstallReason(previousInstallReason, previousUserId); 16539 previousUserIds.add(previousUserId); 16540 } 16541 } 16542 16543 // Set install reason for users that are having the package newly installed. 16544 if (userId == UserHandle.USER_ALL) { 16545 for (int currentUserId : sUserManager.getUserIds()) { 16546 if (!previousUserIds.contains(currentUserId)) { 16547 ps.setInstallReason(installReason, currentUserId); 16548 } 16549 } 16550 } else if (!previousUserIds.contains(userId)) { 16551 ps.setInstallReason(installReason, userId); 16552 } 16553 mSettings.writeKernelMappingLPr(ps); 16554 } 16555 res.name = pkgName; 16556 res.uid = newPackage.applicationInfo.uid; 16557 res.pkg = newPackage; 16558 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16559 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16560 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16561 //to update install status 16562 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16563 mSettings.writeLPr(); 16564 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16565 } 16566 16567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16568 } 16569 16570 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16571 try { 16572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16573 installPackageLI(args, res); 16574 } finally { 16575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16576 } 16577 } 16578 16579 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16580 final int installFlags = args.installFlags; 16581 final String installerPackageName = args.installerPackageName; 16582 final String volumeUuid = args.volumeUuid; 16583 final File tmpPackageFile = new File(args.getCodePath()); 16584 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16585 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16586 || (args.volumeUuid != null)); 16587 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16588 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16589 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16590 boolean replace = false; 16591 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16592 if (args.move != null) { 16593 // moving a complete application; perform an initial scan on the new install location 16594 scanFlags |= SCAN_INITIAL; 16595 } 16596 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16597 scanFlags |= SCAN_DONT_KILL_APP; 16598 } 16599 if (instantApp) { 16600 scanFlags |= SCAN_AS_INSTANT_APP; 16601 } 16602 if (fullApp) { 16603 scanFlags |= SCAN_AS_FULL_APP; 16604 } 16605 16606 // Result object to be returned 16607 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16608 16609 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16610 16611 // Sanity check 16612 if (instantApp && (forwardLocked || onExternal)) { 16613 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16614 + " external=" + onExternal); 16615 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16616 return; 16617 } 16618 16619 // Retrieve PackageSettings and parse package 16620 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16621 | PackageParser.PARSE_ENFORCE_CODE 16622 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16623 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16624 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16625 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16626 PackageParser pp = new PackageParser(); 16627 pp.setSeparateProcesses(mSeparateProcesses); 16628 pp.setDisplayMetrics(mMetrics); 16629 pp.setCallback(mPackageParserCallback); 16630 16631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16632 final PackageParser.Package pkg; 16633 try { 16634 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16635 } catch (PackageParserException e) { 16636 res.setError("Failed parse during installPackageLI", e); 16637 return; 16638 } finally { 16639 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16640 } 16641 16642 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16643 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16644 Slog.w(TAG, "Instant app package " + pkg.packageName 16645 + " does not target O, this will be a fatal error."); 16646 // STOPSHIP: Make this a fatal error 16647 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16648 } 16649 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16650 Slog.w(TAG, "Instant app package " + pkg.packageName 16651 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16652 // STOPSHIP: Make this a fatal error 16653 pkg.applicationInfo.targetSandboxVersion = 2; 16654 } 16655 16656 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16657 // Static shared libraries have synthetic package names 16658 renameStaticSharedLibraryPackage(pkg); 16659 16660 // No static shared libs on external storage 16661 if (onExternal) { 16662 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16663 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16664 "Packages declaring static-shared libs cannot be updated"); 16665 return; 16666 } 16667 } 16668 16669 // If we are installing a clustered package add results for the children 16670 if (pkg.childPackages != null) { 16671 synchronized (mPackages) { 16672 final int childCount = pkg.childPackages.size(); 16673 for (int i = 0; i < childCount; i++) { 16674 PackageParser.Package childPkg = pkg.childPackages.get(i); 16675 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16676 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16677 childRes.pkg = childPkg; 16678 childRes.name = childPkg.packageName; 16679 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16680 if (childPs != null) { 16681 childRes.origUsers = childPs.queryInstalledUsers( 16682 sUserManager.getUserIds(), true); 16683 } 16684 if ((mPackages.containsKey(childPkg.packageName))) { 16685 childRes.removedInfo = new PackageRemovedInfo(); 16686 childRes.removedInfo.removedPackage = childPkg.packageName; 16687 } 16688 if (res.addedChildPackages == null) { 16689 res.addedChildPackages = new ArrayMap<>(); 16690 } 16691 res.addedChildPackages.put(childPkg.packageName, childRes); 16692 } 16693 } 16694 } 16695 16696 // If package doesn't declare API override, mark that we have an install 16697 // time CPU ABI override. 16698 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16699 pkg.cpuAbiOverride = args.abiOverride; 16700 } 16701 16702 String pkgName = res.name = pkg.packageName; 16703 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16704 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16705 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16706 return; 16707 } 16708 } 16709 16710 try { 16711 // either use what we've been given or parse directly from the APK 16712 if (args.certificates != null) { 16713 try { 16714 PackageParser.populateCertificates(pkg, args.certificates); 16715 } catch (PackageParserException e) { 16716 // there was something wrong with the certificates we were given; 16717 // try to pull them from the APK 16718 PackageParser.collectCertificates(pkg, parseFlags); 16719 } 16720 } else { 16721 PackageParser.collectCertificates(pkg, parseFlags); 16722 } 16723 } catch (PackageParserException e) { 16724 res.setError("Failed collect during installPackageLI", e); 16725 return; 16726 } 16727 16728 // Get rid of all references to package scan path via parser. 16729 pp = null; 16730 String oldCodePath = null; 16731 boolean systemApp = false; 16732 synchronized (mPackages) { 16733 // Check if installing already existing package 16734 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16735 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16736 if (pkg.mOriginalPackages != null 16737 && pkg.mOriginalPackages.contains(oldName) 16738 && mPackages.containsKey(oldName)) { 16739 // This package is derived from an original package, 16740 // and this device has been updating from that original 16741 // name. We must continue using the original name, so 16742 // rename the new package here. 16743 pkg.setPackageName(oldName); 16744 pkgName = pkg.packageName; 16745 replace = true; 16746 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16747 + oldName + " pkgName=" + pkgName); 16748 } else if (mPackages.containsKey(pkgName)) { 16749 // This package, under its official name, already exists 16750 // on the device; we should replace it. 16751 replace = true; 16752 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16753 } 16754 16755 // Child packages are installed through the parent package 16756 if (pkg.parentPackage != null) { 16757 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16758 "Package " + pkg.packageName + " is child of package " 16759 + pkg.parentPackage.parentPackage + ". Child packages " 16760 + "can be updated only through the parent package."); 16761 return; 16762 } 16763 16764 if (replace) { 16765 // Prevent apps opting out from runtime permissions 16766 PackageParser.Package oldPackage = mPackages.get(pkgName); 16767 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16768 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16769 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16770 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16771 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16772 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16773 + " doesn't support runtime permissions but the old" 16774 + " target SDK " + oldTargetSdk + " does."); 16775 return; 16776 } 16777 // Prevent apps from downgrading their targetSandbox. 16778 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16779 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16780 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16781 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16782 "Package " + pkg.packageName + " new target sandbox " 16783 + newTargetSandbox + " is incompatible with the previous value of" 16784 + oldTargetSandbox + "."); 16785 return; 16786 } 16787 16788 // Prevent installing of child packages 16789 if (oldPackage.parentPackage != null) { 16790 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16791 "Package " + pkg.packageName + " is child of package " 16792 + oldPackage.parentPackage + ". Child packages " 16793 + "can be updated only through the parent package."); 16794 return; 16795 } 16796 } 16797 } 16798 16799 PackageSetting ps = mSettings.mPackages.get(pkgName); 16800 if (ps != null) { 16801 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16802 16803 // Static shared libs have same package with different versions where 16804 // we internally use a synthetic package name to allow multiple versions 16805 // of the same package, therefore we need to compare signatures against 16806 // the package setting for the latest library version. 16807 PackageSetting signatureCheckPs = ps; 16808 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16809 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16810 if (libraryEntry != null) { 16811 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16812 } 16813 } 16814 16815 // Quick sanity check that we're signed correctly if updating; 16816 // we'll check this again later when scanning, but we want to 16817 // bail early here before tripping over redefined permissions. 16818 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16819 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16820 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16821 + pkg.packageName + " upgrade keys do not match the " 16822 + "previously installed version"); 16823 return; 16824 } 16825 } else { 16826 try { 16827 verifySignaturesLP(signatureCheckPs, pkg); 16828 } catch (PackageManagerException e) { 16829 res.setError(e.error, e.getMessage()); 16830 return; 16831 } 16832 } 16833 16834 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16835 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16836 systemApp = (ps.pkg.applicationInfo.flags & 16837 ApplicationInfo.FLAG_SYSTEM) != 0; 16838 } 16839 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16840 } 16841 16842 int N = pkg.permissions.size(); 16843 for (int i = N-1; i >= 0; i--) { 16844 PackageParser.Permission perm = pkg.permissions.get(i); 16845 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16846 16847 // Don't allow anyone but the platform to define ephemeral permissions. 16848 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16849 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16850 Slog.w(TAG, "Package " + pkg.packageName 16851 + " attempting to delcare ephemeral permission " 16852 + perm.info.name + "; Removing ephemeral."); 16853 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16854 } 16855 // Check whether the newly-scanned package wants to define an already-defined perm 16856 if (bp != null) { 16857 // If the defining package is signed with our cert, it's okay. This 16858 // also includes the "updating the same package" case, of course. 16859 // "updating same package" could also involve key-rotation. 16860 final boolean sigsOk; 16861 if (bp.sourcePackage.equals(pkg.packageName) 16862 && (bp.packageSetting instanceof PackageSetting) 16863 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16864 scanFlags))) { 16865 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16866 } else { 16867 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16868 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16869 } 16870 if (!sigsOk) { 16871 // If the owning package is the system itself, we log but allow 16872 // install to proceed; we fail the install on all other permission 16873 // redefinitions. 16874 if (!bp.sourcePackage.equals("android")) { 16875 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16876 + pkg.packageName + " attempting to redeclare permission " 16877 + perm.info.name + " already owned by " + bp.sourcePackage); 16878 res.origPermission = perm.info.name; 16879 res.origPackage = bp.sourcePackage; 16880 return; 16881 } else { 16882 Slog.w(TAG, "Package " + pkg.packageName 16883 + " attempting to redeclare system permission " 16884 + perm.info.name + "; ignoring new declaration"); 16885 pkg.permissions.remove(i); 16886 } 16887 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16888 // Prevent apps to change protection level to dangerous from any other 16889 // type as this would allow a privilege escalation where an app adds a 16890 // normal/signature permission in other app's group and later redefines 16891 // it as dangerous leading to the group auto-grant. 16892 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16893 == PermissionInfo.PROTECTION_DANGEROUS) { 16894 if (bp != null && !bp.isRuntime()) { 16895 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16896 + "non-runtime permission " + perm.info.name 16897 + " to runtime; keeping old protection level"); 16898 perm.info.protectionLevel = bp.protectionLevel; 16899 } 16900 } 16901 } 16902 } 16903 } 16904 } 16905 16906 if (systemApp) { 16907 if (onExternal) { 16908 // Abort update; system app can't be replaced with app on sdcard 16909 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16910 "Cannot install updates to system apps on sdcard"); 16911 return; 16912 } else if (instantApp) { 16913 // Abort update; system app can't be replaced with an instant app 16914 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16915 "Cannot update a system app with an instant app"); 16916 return; 16917 } 16918 } 16919 16920 if (args.move != null) { 16921 // We did an in-place move, so dex is ready to roll 16922 scanFlags |= SCAN_NO_DEX; 16923 scanFlags |= SCAN_MOVE; 16924 16925 synchronized (mPackages) { 16926 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16927 if (ps == null) { 16928 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16929 "Missing settings for moved package " + pkgName); 16930 } 16931 16932 // We moved the entire application as-is, so bring over the 16933 // previously derived ABI information. 16934 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16935 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16936 } 16937 16938 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16939 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16940 scanFlags |= SCAN_NO_DEX; 16941 16942 try { 16943 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16944 args.abiOverride : pkg.cpuAbiOverride); 16945 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16946 true /*extractLibs*/, mAppLib32InstallDir); 16947 } catch (PackageManagerException pme) { 16948 Slog.e(TAG, "Error deriving application ABI", pme); 16949 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16950 return; 16951 } 16952 16953 // Shared libraries for the package need to be updated. 16954 synchronized (mPackages) { 16955 try { 16956 updateSharedLibrariesLPr(pkg, null); 16957 } catch (PackageManagerException e) { 16958 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16959 } 16960 } 16961 16962 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16963 // Do not run PackageDexOptimizer through the local performDexOpt 16964 // method because `pkg` may not be in `mPackages` yet. 16965 // 16966 // Also, don't fail application installs if the dexopt step fails. 16967 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16968 null /* instructionSets */, false /* checkProfiles */, 16969 getCompilerFilterForReason(REASON_INSTALL), 16970 getOrCreateCompilerPackageStats(pkg), 16971 mDexManager.isUsedByOtherApps(pkg.packageName)); 16972 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16973 16974 // Notify BackgroundDexOptService that the package has been changed. 16975 // If this is an update of a package which used to fail to compile, 16976 // BDOS will remove it from its blacklist. 16977 // TODO: Layering violation 16978 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16979 } 16980 16981 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16982 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16983 return; 16984 } 16985 16986 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16987 16988 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16989 "installPackageLI")) { 16990 if (replace) { 16991 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16992 // Static libs have a synthetic package name containing the version 16993 // and cannot be updated as an update would get a new package name, 16994 // unless this is the exact same version code which is useful for 16995 // development. 16996 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16997 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16998 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16999 + "static-shared libs cannot be updated"); 17000 return; 17001 } 17002 } 17003 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17004 installerPackageName, res, args.installReason); 17005 } else { 17006 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17007 args.user, installerPackageName, volumeUuid, res, args.installReason); 17008 } 17009 } 17010 17011 synchronized (mPackages) { 17012 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17013 if (ps != null) { 17014 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17015 ps.setUpdateAvailable(false /*updateAvailable*/); 17016 } 17017 17018 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17019 for (int i = 0; i < childCount; i++) { 17020 PackageParser.Package childPkg = pkg.childPackages.get(i); 17021 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17022 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17023 if (childPs != null) { 17024 childRes.newUsers = childPs.queryInstalledUsers( 17025 sUserManager.getUserIds(), true); 17026 } 17027 } 17028 17029 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17030 updateSequenceNumberLP(pkgName, res.newUsers); 17031 updateInstantAppInstallerLocked(); 17032 } 17033 } 17034 } 17035 17036 private void startIntentFilterVerifications(int userId, boolean replacing, 17037 PackageParser.Package pkg) { 17038 if (mIntentFilterVerifierComponent == null) { 17039 Slog.w(TAG, "No IntentFilter verification will not be done as " 17040 + "there is no IntentFilterVerifier available!"); 17041 return; 17042 } 17043 17044 final int verifierUid = getPackageUid( 17045 mIntentFilterVerifierComponent.getPackageName(), 17046 MATCH_DEBUG_TRIAGED_MISSING, 17047 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17048 17049 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17050 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17051 mHandler.sendMessage(msg); 17052 17053 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17054 for (int i = 0; i < childCount; i++) { 17055 PackageParser.Package childPkg = pkg.childPackages.get(i); 17056 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17057 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17058 mHandler.sendMessage(msg); 17059 } 17060 } 17061 17062 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17063 PackageParser.Package pkg) { 17064 int size = pkg.activities.size(); 17065 if (size == 0) { 17066 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17067 "No activity, so no need to verify any IntentFilter!"); 17068 return; 17069 } 17070 17071 final boolean hasDomainURLs = hasDomainURLs(pkg); 17072 if (!hasDomainURLs) { 17073 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17074 "No domain URLs, so no need to verify any IntentFilter!"); 17075 return; 17076 } 17077 17078 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17079 + " if any IntentFilter from the " + size 17080 + " Activities needs verification ..."); 17081 17082 int count = 0; 17083 final String packageName = pkg.packageName; 17084 17085 synchronized (mPackages) { 17086 // If this is a new install and we see that we've already run verification for this 17087 // package, we have nothing to do: it means the state was restored from backup. 17088 if (!replacing) { 17089 IntentFilterVerificationInfo ivi = 17090 mSettings.getIntentFilterVerificationLPr(packageName); 17091 if (ivi != null) { 17092 if (DEBUG_DOMAIN_VERIFICATION) { 17093 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17094 + ivi.getStatusString()); 17095 } 17096 return; 17097 } 17098 } 17099 17100 // If any filters need to be verified, then all need to be. 17101 boolean needToVerify = false; 17102 for (PackageParser.Activity a : pkg.activities) { 17103 for (ActivityIntentInfo filter : a.intents) { 17104 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17105 if (DEBUG_DOMAIN_VERIFICATION) { 17106 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17107 } 17108 needToVerify = true; 17109 break; 17110 } 17111 } 17112 } 17113 17114 if (needToVerify) { 17115 final int verificationId = mIntentFilterVerificationToken++; 17116 for (PackageParser.Activity a : pkg.activities) { 17117 for (ActivityIntentInfo filter : a.intents) { 17118 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17119 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17120 "Verification needed for IntentFilter:" + filter.toString()); 17121 mIntentFilterVerifier.addOneIntentFilterVerification( 17122 verifierUid, userId, verificationId, filter, packageName); 17123 count++; 17124 } 17125 } 17126 } 17127 } 17128 } 17129 17130 if (count > 0) { 17131 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17132 + " IntentFilter verification" + (count > 1 ? "s" : "") 17133 + " for userId:" + userId); 17134 mIntentFilterVerifier.startVerifications(userId); 17135 } else { 17136 if (DEBUG_DOMAIN_VERIFICATION) { 17137 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17138 } 17139 } 17140 } 17141 17142 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17143 final ComponentName cn = filter.activity.getComponentName(); 17144 final String packageName = cn.getPackageName(); 17145 17146 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17147 packageName); 17148 if (ivi == null) { 17149 return true; 17150 } 17151 int status = ivi.getStatus(); 17152 switch (status) { 17153 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17154 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17155 return true; 17156 17157 default: 17158 // Nothing to do 17159 return false; 17160 } 17161 } 17162 17163 private static boolean isMultiArch(ApplicationInfo info) { 17164 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17165 } 17166 17167 private static boolean isExternal(PackageParser.Package pkg) { 17168 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17169 } 17170 17171 private static boolean isExternal(PackageSetting ps) { 17172 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17173 } 17174 17175 private static boolean isSystemApp(PackageParser.Package pkg) { 17176 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17177 } 17178 17179 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17180 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17181 } 17182 17183 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17184 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17185 } 17186 17187 private static boolean isSystemApp(PackageSetting ps) { 17188 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17189 } 17190 17191 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17192 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17193 } 17194 17195 private int packageFlagsToInstallFlags(PackageSetting ps) { 17196 int installFlags = 0; 17197 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17198 // This existing package was an external ASEC install when we have 17199 // the external flag without a UUID 17200 installFlags |= PackageManager.INSTALL_EXTERNAL; 17201 } 17202 if (ps.isForwardLocked()) { 17203 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17204 } 17205 return installFlags; 17206 } 17207 17208 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17209 if (isExternal(pkg)) { 17210 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17211 return StorageManager.UUID_PRIMARY_PHYSICAL; 17212 } else { 17213 return pkg.volumeUuid; 17214 } 17215 } else { 17216 return StorageManager.UUID_PRIVATE_INTERNAL; 17217 } 17218 } 17219 17220 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17221 if (isExternal(pkg)) { 17222 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17223 return mSettings.getExternalVersion(); 17224 } else { 17225 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17226 } 17227 } else { 17228 return mSettings.getInternalVersion(); 17229 } 17230 } 17231 17232 private void deleteTempPackageFiles() { 17233 final FilenameFilter filter = new FilenameFilter() { 17234 public boolean accept(File dir, String name) { 17235 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17236 } 17237 }; 17238 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17239 file.delete(); 17240 } 17241 } 17242 17243 @Override 17244 public void deletePackageAsUser(String packageName, int versionCode, 17245 IPackageDeleteObserver observer, int userId, int flags) { 17246 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17247 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17248 } 17249 17250 @Override 17251 public void deletePackageVersioned(VersionedPackage versionedPackage, 17252 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17253 mContext.enforceCallingOrSelfPermission( 17254 android.Manifest.permission.DELETE_PACKAGES, null); 17255 Preconditions.checkNotNull(versionedPackage); 17256 Preconditions.checkNotNull(observer); 17257 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17258 PackageManager.VERSION_CODE_HIGHEST, 17259 Integer.MAX_VALUE, "versionCode must be >= -1"); 17260 17261 final String packageName = versionedPackage.getPackageName(); 17262 // TODO: We will change version code to long, so in the new API it is long 17263 final int versionCode = (int) versionedPackage.getVersionCode(); 17264 final String internalPackageName; 17265 synchronized (mPackages) { 17266 // Normalize package name to handle renamed packages and static libs 17267 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17268 // TODO: We will change version code to long, so in the new API it is long 17269 (int) versionedPackage.getVersionCode()); 17270 } 17271 17272 final int uid = Binder.getCallingUid(); 17273 if (!isOrphaned(internalPackageName) 17274 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17275 try { 17276 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17277 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17278 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17279 observer.onUserActionRequired(intent); 17280 } catch (RemoteException re) { 17281 } 17282 return; 17283 } 17284 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17285 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17286 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17287 mContext.enforceCallingOrSelfPermission( 17288 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17289 "deletePackage for user " + userId); 17290 } 17291 17292 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17293 try { 17294 observer.onPackageDeleted(packageName, 17295 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17296 } catch (RemoteException re) { 17297 } 17298 return; 17299 } 17300 17301 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17302 try { 17303 observer.onPackageDeleted(packageName, 17304 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17305 } catch (RemoteException re) { 17306 } 17307 return; 17308 } 17309 17310 if (DEBUG_REMOVE) { 17311 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17312 + " deleteAllUsers: " + deleteAllUsers + " version=" 17313 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17314 ? "VERSION_CODE_HIGHEST" : versionCode)); 17315 } 17316 // Queue up an async operation since the package deletion may take a little while. 17317 mHandler.post(new Runnable() { 17318 public void run() { 17319 mHandler.removeCallbacks(this); 17320 int returnCode; 17321 if (!deleteAllUsers) { 17322 returnCode = deletePackageX(internalPackageName, versionCode, 17323 userId, deleteFlags); 17324 } else { 17325 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17326 internalPackageName, users); 17327 // If nobody is blocking uninstall, proceed with delete for all users 17328 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17329 returnCode = deletePackageX(internalPackageName, versionCode, 17330 userId, deleteFlags); 17331 } else { 17332 // Otherwise uninstall individually for users with blockUninstalls=false 17333 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17334 for (int userId : users) { 17335 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17336 returnCode = deletePackageX(internalPackageName, versionCode, 17337 userId, userFlags); 17338 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17339 Slog.w(TAG, "Package delete failed for user " + userId 17340 + ", returnCode " + returnCode); 17341 } 17342 } 17343 } 17344 // The app has only been marked uninstalled for certain users. 17345 // We still need to report that delete was blocked 17346 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17347 } 17348 } 17349 try { 17350 observer.onPackageDeleted(packageName, returnCode, null); 17351 } catch (RemoteException e) { 17352 Log.i(TAG, "Observer no longer exists."); 17353 } //end catch 17354 } //end run 17355 }); 17356 } 17357 17358 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17359 if (pkg.staticSharedLibName != null) { 17360 return pkg.manifestPackageName; 17361 } 17362 return pkg.packageName; 17363 } 17364 17365 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17366 // Handle renamed packages 17367 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17368 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17369 17370 // Is this a static library? 17371 SparseArray<SharedLibraryEntry> versionedLib = 17372 mStaticLibsByDeclaringPackage.get(packageName); 17373 if (versionedLib == null || versionedLib.size() <= 0) { 17374 return packageName; 17375 } 17376 17377 // Figure out which lib versions the caller can see 17378 SparseIntArray versionsCallerCanSee = null; 17379 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17380 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17381 && callingAppId != Process.ROOT_UID) { 17382 versionsCallerCanSee = new SparseIntArray(); 17383 String libName = versionedLib.valueAt(0).info.getName(); 17384 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17385 if (uidPackages != null) { 17386 for (String uidPackage : uidPackages) { 17387 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17388 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17389 if (libIdx >= 0) { 17390 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17391 versionsCallerCanSee.append(libVersion, libVersion); 17392 } 17393 } 17394 } 17395 } 17396 17397 // Caller can see nothing - done 17398 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17399 return packageName; 17400 } 17401 17402 // Find the version the caller can see and the app version code 17403 SharedLibraryEntry highestVersion = null; 17404 final int versionCount = versionedLib.size(); 17405 for (int i = 0; i < versionCount; i++) { 17406 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17407 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17408 libEntry.info.getVersion()) < 0) { 17409 continue; 17410 } 17411 // TODO: We will change version code to long, so in the new API it is long 17412 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17413 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17414 if (libVersionCode == versionCode) { 17415 return libEntry.apk; 17416 } 17417 } else if (highestVersion == null) { 17418 highestVersion = libEntry; 17419 } else if (libVersionCode > highestVersion.info 17420 .getDeclaringPackage().getVersionCode()) { 17421 highestVersion = libEntry; 17422 } 17423 } 17424 17425 if (highestVersion != null) { 17426 return highestVersion.apk; 17427 } 17428 17429 return packageName; 17430 } 17431 17432 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17433 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17434 || callingUid == Process.SYSTEM_UID) { 17435 return true; 17436 } 17437 final int callingUserId = UserHandle.getUserId(callingUid); 17438 // If the caller installed the pkgName, then allow it to silently uninstall. 17439 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17440 return true; 17441 } 17442 17443 // Allow package verifier to silently uninstall. 17444 if (mRequiredVerifierPackage != null && 17445 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17446 return true; 17447 } 17448 17449 // Allow package uninstaller to silently uninstall. 17450 if (mRequiredUninstallerPackage != null && 17451 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17452 return true; 17453 } 17454 17455 // Allow storage manager to silently uninstall. 17456 if (mStorageManagerPackage != null && 17457 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17458 return true; 17459 } 17460 return false; 17461 } 17462 17463 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17464 int[] result = EMPTY_INT_ARRAY; 17465 for (int userId : userIds) { 17466 if (getBlockUninstallForUser(packageName, userId)) { 17467 result = ArrayUtils.appendInt(result, userId); 17468 } 17469 } 17470 return result; 17471 } 17472 17473 @Override 17474 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17475 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17476 } 17477 17478 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17479 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17480 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17481 try { 17482 if (dpm != null) { 17483 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17484 /* callingUserOnly =*/ false); 17485 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17486 : deviceOwnerComponentName.getPackageName(); 17487 // Does the package contains the device owner? 17488 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17489 // this check is probably not needed, since DO should be registered as a device 17490 // admin on some user too. (Original bug for this: b/17657954) 17491 if (packageName.equals(deviceOwnerPackageName)) { 17492 return true; 17493 } 17494 // Does it contain a device admin for any user? 17495 int[] users; 17496 if (userId == UserHandle.USER_ALL) { 17497 users = sUserManager.getUserIds(); 17498 } else { 17499 users = new int[]{userId}; 17500 } 17501 for (int i = 0; i < users.length; ++i) { 17502 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17503 return true; 17504 } 17505 } 17506 } 17507 } catch (RemoteException e) { 17508 } 17509 return false; 17510 } 17511 17512 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17513 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17514 } 17515 17516 /** 17517 * This method is an internal method that could be get invoked either 17518 * to delete an installed package or to clean up a failed installation. 17519 * After deleting an installed package, a broadcast is sent to notify any 17520 * listeners that the package has been removed. For cleaning up a failed 17521 * installation, the broadcast is not necessary since the package's 17522 * installation wouldn't have sent the initial broadcast either 17523 * The key steps in deleting a package are 17524 * deleting the package information in internal structures like mPackages, 17525 * deleting the packages base directories through installd 17526 * updating mSettings to reflect current status 17527 * persisting settings for later use 17528 * sending a broadcast if necessary 17529 */ 17530 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17531 final PackageRemovedInfo info = new PackageRemovedInfo(); 17532 final boolean res; 17533 17534 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17535 ? UserHandle.USER_ALL : userId; 17536 17537 if (isPackageDeviceAdmin(packageName, removeUser)) { 17538 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17539 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17540 } 17541 17542 PackageSetting uninstalledPs = null; 17543 PackageParser.Package pkg = null; 17544 17545 // for the uninstall-updates case and restricted profiles, remember the per- 17546 // user handle installed state 17547 int[] allUsers; 17548 synchronized (mPackages) { 17549 uninstalledPs = mSettings.mPackages.get(packageName); 17550 if (uninstalledPs == null) { 17551 Slog.w(TAG, "Not removing non-existent package " + packageName); 17552 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17553 } 17554 17555 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17556 && uninstalledPs.versionCode != versionCode) { 17557 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17558 + uninstalledPs.versionCode + " != " + versionCode); 17559 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17560 } 17561 17562 // Static shared libs can be declared by any package, so let us not 17563 // allow removing a package if it provides a lib others depend on. 17564 pkg = mPackages.get(packageName); 17565 if (pkg != null && pkg.staticSharedLibName != null) { 17566 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17567 pkg.staticSharedLibVersion); 17568 if (libEntry != null) { 17569 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17570 libEntry.info, 0, userId); 17571 if (!ArrayUtils.isEmpty(libClientPackages)) { 17572 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17573 + " hosting lib " + libEntry.info.getName() + " version " 17574 + libEntry.info.getVersion() + " used by " + libClientPackages); 17575 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17576 } 17577 } 17578 } 17579 17580 allUsers = sUserManager.getUserIds(); 17581 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17582 } 17583 17584 final int freezeUser; 17585 if (isUpdatedSystemApp(uninstalledPs) 17586 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17587 // We're downgrading a system app, which will apply to all users, so 17588 // freeze them all during the downgrade 17589 freezeUser = UserHandle.USER_ALL; 17590 } else { 17591 freezeUser = removeUser; 17592 } 17593 17594 synchronized (mInstallLock) { 17595 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17596 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17597 deleteFlags, "deletePackageX")) { 17598 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17599 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17600 } 17601 synchronized (mPackages) { 17602 if (res) { 17603 if (pkg != null) { 17604 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17605 } 17606 updateSequenceNumberLP(packageName, info.removedUsers); 17607 updateInstantAppInstallerLocked(); 17608 } 17609 } 17610 } 17611 17612 if (res) { 17613 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17614 info.sendPackageRemovedBroadcasts(killApp); 17615 info.sendSystemPackageUpdatedBroadcasts(); 17616 info.sendSystemPackageAppearedBroadcasts(); 17617 } 17618 // Force a gc here. 17619 Runtime.getRuntime().gc(); 17620 // Delete the resources here after sending the broadcast to let 17621 // other processes clean up before deleting resources. 17622 if (info.args != null) { 17623 synchronized (mInstallLock) { 17624 info.args.doPostDeleteLI(true); 17625 } 17626 } 17627 17628 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17629 } 17630 17631 class PackageRemovedInfo { 17632 String removedPackage; 17633 int uid = -1; 17634 int removedAppId = -1; 17635 int[] origUsers; 17636 int[] removedUsers = null; 17637 SparseArray<Integer> installReasons; 17638 boolean isRemovedPackageSystemUpdate = false; 17639 boolean isUpdate; 17640 boolean dataRemoved; 17641 boolean removedForAllUsers; 17642 boolean isStaticSharedLib; 17643 // Clean up resources deleted packages. 17644 InstallArgs args = null; 17645 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17646 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17647 17648 void sendPackageRemovedBroadcasts(boolean killApp) { 17649 sendPackageRemovedBroadcastInternal(killApp); 17650 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17651 for (int i = 0; i < childCount; i++) { 17652 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17653 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17654 } 17655 } 17656 17657 void sendSystemPackageUpdatedBroadcasts() { 17658 if (isRemovedPackageSystemUpdate) { 17659 sendSystemPackageUpdatedBroadcastsInternal(); 17660 final int childCount = (removedChildPackages != null) 17661 ? removedChildPackages.size() : 0; 17662 for (int i = 0; i < childCount; i++) { 17663 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17664 if (childInfo.isRemovedPackageSystemUpdate) { 17665 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17666 } 17667 } 17668 } 17669 } 17670 17671 void sendSystemPackageAppearedBroadcasts() { 17672 final int packageCount = (appearedChildPackages != null) 17673 ? appearedChildPackages.size() : 0; 17674 for (int i = 0; i < packageCount; i++) { 17675 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17676 sendPackageAddedForNewUsers(installedInfo.name, true, 17677 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17678 } 17679 } 17680 17681 private void sendSystemPackageUpdatedBroadcastsInternal() { 17682 Bundle extras = new Bundle(2); 17683 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17684 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17685 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17686 extras, 0, null, null, null); 17687 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17688 extras, 0, null, null, null); 17689 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17690 null, 0, removedPackage, null, null); 17691 } 17692 17693 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17694 // Don't send static shared library removal broadcasts as these 17695 // libs are visible only the the apps that depend on them an one 17696 // cannot remove the library if it has a dependency. 17697 if (isStaticSharedLib) { 17698 return; 17699 } 17700 Bundle extras = new Bundle(2); 17701 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17702 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17703 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17704 if (isUpdate || isRemovedPackageSystemUpdate) { 17705 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17706 } 17707 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17708 if (removedPackage != null) { 17709 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17710 extras, 0, null, null, removedUsers); 17711 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17712 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17713 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17714 null, null, removedUsers); 17715 } 17716 } 17717 if (removedAppId >= 0) { 17718 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17719 removedUsers); 17720 } 17721 } 17722 } 17723 17724 /* 17725 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17726 * flag is not set, the data directory is removed as well. 17727 * make sure this flag is set for partially installed apps. If not its meaningless to 17728 * delete a partially installed application. 17729 */ 17730 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17731 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17732 String packageName = ps.name; 17733 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17734 // Retrieve object to delete permissions for shared user later on 17735 final PackageParser.Package deletedPkg; 17736 final PackageSetting deletedPs; 17737 // reader 17738 synchronized (mPackages) { 17739 deletedPkg = mPackages.get(packageName); 17740 deletedPs = mSettings.mPackages.get(packageName); 17741 if (outInfo != null) { 17742 outInfo.removedPackage = packageName; 17743 outInfo.isStaticSharedLib = deletedPkg != null 17744 && deletedPkg.staticSharedLibName != null; 17745 outInfo.removedUsers = deletedPs != null 17746 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17747 : null; 17748 } 17749 } 17750 17751 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17752 17753 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17754 final PackageParser.Package resolvedPkg; 17755 if (deletedPkg != null) { 17756 resolvedPkg = deletedPkg; 17757 } else { 17758 // We don't have a parsed package when it lives on an ejected 17759 // adopted storage device, so fake something together 17760 resolvedPkg = new PackageParser.Package(ps.name); 17761 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17762 } 17763 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17764 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17765 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17766 if (outInfo != null) { 17767 outInfo.dataRemoved = true; 17768 } 17769 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17770 } 17771 17772 int removedAppId = -1; 17773 17774 // writer 17775 synchronized (mPackages) { 17776 boolean installedStateChanged = false; 17777 if (deletedPs != null) { 17778 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17779 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17780 clearDefaultBrowserIfNeeded(packageName); 17781 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17782 removedAppId = mSettings.removePackageLPw(packageName); 17783 if (outInfo != null) { 17784 outInfo.removedAppId = removedAppId; 17785 } 17786 updatePermissionsLPw(deletedPs.name, null, 0); 17787 if (deletedPs.sharedUser != null) { 17788 // Remove permissions associated with package. Since runtime 17789 // permissions are per user we have to kill the removed package 17790 // or packages running under the shared user of the removed 17791 // package if revoking the permissions requested only by the removed 17792 // package is successful and this causes a change in gids. 17793 for (int userId : UserManagerService.getInstance().getUserIds()) { 17794 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17795 userId); 17796 if (userIdToKill == UserHandle.USER_ALL 17797 || userIdToKill >= UserHandle.USER_SYSTEM) { 17798 // If gids changed for this user, kill all affected packages. 17799 mHandler.post(new Runnable() { 17800 @Override 17801 public void run() { 17802 // This has to happen with no lock held. 17803 killApplication(deletedPs.name, deletedPs.appId, 17804 KILL_APP_REASON_GIDS_CHANGED); 17805 } 17806 }); 17807 break; 17808 } 17809 } 17810 } 17811 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17812 } 17813 // make sure to preserve per-user disabled state if this removal was just 17814 // a downgrade of a system app to the factory package 17815 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17816 if (DEBUG_REMOVE) { 17817 Slog.d(TAG, "Propagating install state across downgrade"); 17818 } 17819 for (int userId : allUserHandles) { 17820 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17821 if (DEBUG_REMOVE) { 17822 Slog.d(TAG, " user " + userId + " => " + installed); 17823 } 17824 if (installed != ps.getInstalled(userId)) { 17825 installedStateChanged = true; 17826 } 17827 ps.setInstalled(installed, userId); 17828 } 17829 } 17830 } 17831 // can downgrade to reader 17832 if (writeSettings) { 17833 // Save settings now 17834 mSettings.writeLPr(); 17835 } 17836 if (installedStateChanged) { 17837 mSettings.writeKernelMappingLPr(ps); 17838 } 17839 } 17840 if (removedAppId != -1) { 17841 // A user ID was deleted here. Go through all users and remove it 17842 // from KeyStore. 17843 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17844 } 17845 } 17846 17847 static boolean locationIsPrivileged(File path) { 17848 try { 17849 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17850 .getCanonicalPath(); 17851 return path.getCanonicalPath().startsWith(privilegedAppDir); 17852 } catch (IOException e) { 17853 Slog.e(TAG, "Unable to access code path " + path); 17854 } 17855 return false; 17856 } 17857 17858 /* 17859 * Tries to delete system package. 17860 */ 17861 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17862 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17863 boolean writeSettings) { 17864 if (deletedPs.parentPackageName != null) { 17865 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17866 return false; 17867 } 17868 17869 final boolean applyUserRestrictions 17870 = (allUserHandles != null) && (outInfo.origUsers != null); 17871 final PackageSetting disabledPs; 17872 // Confirm if the system package has been updated 17873 // An updated system app can be deleted. This will also have to restore 17874 // the system pkg from system partition 17875 // reader 17876 synchronized (mPackages) { 17877 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17878 } 17879 17880 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17881 + " disabledPs=" + disabledPs); 17882 17883 if (disabledPs == null) { 17884 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17885 return false; 17886 } else if (DEBUG_REMOVE) { 17887 Slog.d(TAG, "Deleting system pkg from data partition"); 17888 } 17889 17890 if (DEBUG_REMOVE) { 17891 if (applyUserRestrictions) { 17892 Slog.d(TAG, "Remembering install states:"); 17893 for (int userId : allUserHandles) { 17894 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17895 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17896 } 17897 } 17898 } 17899 17900 // Delete the updated package 17901 outInfo.isRemovedPackageSystemUpdate = true; 17902 if (outInfo.removedChildPackages != null) { 17903 final int childCount = (deletedPs.childPackageNames != null) 17904 ? deletedPs.childPackageNames.size() : 0; 17905 for (int i = 0; i < childCount; i++) { 17906 String childPackageName = deletedPs.childPackageNames.get(i); 17907 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17908 .contains(childPackageName)) { 17909 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17910 childPackageName); 17911 if (childInfo != null) { 17912 childInfo.isRemovedPackageSystemUpdate = true; 17913 } 17914 } 17915 } 17916 } 17917 17918 if (disabledPs.versionCode < deletedPs.versionCode) { 17919 // Delete data for downgrades 17920 flags &= ~PackageManager.DELETE_KEEP_DATA; 17921 } else { 17922 // Preserve data by setting flag 17923 flags |= PackageManager.DELETE_KEEP_DATA; 17924 } 17925 17926 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17927 outInfo, writeSettings, disabledPs.pkg); 17928 if (!ret) { 17929 return false; 17930 } 17931 17932 // writer 17933 synchronized (mPackages) { 17934 // Reinstate the old system package 17935 enableSystemPackageLPw(disabledPs.pkg); 17936 // Remove any native libraries from the upgraded package. 17937 removeNativeBinariesLI(deletedPs); 17938 } 17939 17940 // Install the system package 17941 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17942 int parseFlags = mDefParseFlags 17943 | PackageParser.PARSE_MUST_BE_APK 17944 | PackageParser.PARSE_IS_SYSTEM 17945 | PackageParser.PARSE_IS_SYSTEM_DIR; 17946 if (locationIsPrivileged(disabledPs.codePath)) { 17947 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17948 } 17949 17950 final PackageParser.Package newPkg; 17951 try { 17952 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17953 0 /* currentTime */, null); 17954 } catch (PackageManagerException e) { 17955 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17956 + e.getMessage()); 17957 return false; 17958 } 17959 17960 try { 17961 // update shared libraries for the newly re-installed system package 17962 updateSharedLibrariesLPr(newPkg, null); 17963 } catch (PackageManagerException e) { 17964 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17965 } 17966 17967 prepareAppDataAfterInstallLIF(newPkg); 17968 17969 // writer 17970 synchronized (mPackages) { 17971 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17972 17973 // Propagate the permissions state as we do not want to drop on the floor 17974 // runtime permissions. The update permissions method below will take 17975 // care of removing obsolete permissions and grant install permissions. 17976 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17977 updatePermissionsLPw(newPkg.packageName, newPkg, 17978 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17979 17980 if (applyUserRestrictions) { 17981 boolean installedStateChanged = false; 17982 if (DEBUG_REMOVE) { 17983 Slog.d(TAG, "Propagating install state across reinstall"); 17984 } 17985 for (int userId : allUserHandles) { 17986 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17987 if (DEBUG_REMOVE) { 17988 Slog.d(TAG, " user " + userId + " => " + installed); 17989 } 17990 if (installed != ps.getInstalled(userId)) { 17991 installedStateChanged = true; 17992 } 17993 ps.setInstalled(installed, userId); 17994 17995 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17996 } 17997 // Regardless of writeSettings we need to ensure that this restriction 17998 // state propagation is persisted 17999 mSettings.writeAllUsersPackageRestrictionsLPr(); 18000 if (installedStateChanged) { 18001 mSettings.writeKernelMappingLPr(ps); 18002 } 18003 } 18004 // can downgrade to reader here 18005 if (writeSettings) { 18006 mSettings.writeLPr(); 18007 } 18008 } 18009 return true; 18010 } 18011 18012 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18013 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18014 PackageRemovedInfo outInfo, boolean writeSettings, 18015 PackageParser.Package replacingPackage) { 18016 synchronized (mPackages) { 18017 if (outInfo != null) { 18018 outInfo.uid = ps.appId; 18019 } 18020 18021 if (outInfo != null && outInfo.removedChildPackages != null) { 18022 final int childCount = (ps.childPackageNames != null) 18023 ? ps.childPackageNames.size() : 0; 18024 for (int i = 0; i < childCount; i++) { 18025 String childPackageName = ps.childPackageNames.get(i); 18026 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18027 if (childPs == null) { 18028 return false; 18029 } 18030 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18031 childPackageName); 18032 if (childInfo != null) { 18033 childInfo.uid = childPs.appId; 18034 } 18035 } 18036 } 18037 } 18038 18039 // Delete package data from internal structures and also remove data if flag is set 18040 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18041 18042 // Delete the child packages data 18043 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18044 for (int i = 0; i < childCount; i++) { 18045 PackageSetting childPs; 18046 synchronized (mPackages) { 18047 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18048 } 18049 if (childPs != null) { 18050 PackageRemovedInfo childOutInfo = (outInfo != null 18051 && outInfo.removedChildPackages != null) 18052 ? outInfo.removedChildPackages.get(childPs.name) : null; 18053 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18054 && (replacingPackage != null 18055 && !replacingPackage.hasChildPackage(childPs.name)) 18056 ? flags & ~DELETE_KEEP_DATA : flags; 18057 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18058 deleteFlags, writeSettings); 18059 } 18060 } 18061 18062 // Delete application code and resources only for parent packages 18063 if (ps.parentPackageName == null) { 18064 if (deleteCodeAndResources && (outInfo != null)) { 18065 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18066 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18067 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18068 } 18069 } 18070 18071 return true; 18072 } 18073 18074 @Override 18075 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18076 int userId) { 18077 mContext.enforceCallingOrSelfPermission( 18078 android.Manifest.permission.DELETE_PACKAGES, null); 18079 synchronized (mPackages) { 18080 PackageSetting ps = mSettings.mPackages.get(packageName); 18081 if (ps == null) { 18082 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18083 return false; 18084 } 18085 // Cannot block uninstall of static shared libs as they are 18086 // considered a part of the using app (emulating static linking). 18087 // Also static libs are installed always on internal storage. 18088 PackageParser.Package pkg = mPackages.get(packageName); 18089 if (pkg != null && pkg.staticSharedLibName != null) { 18090 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18091 + " providing static shared library: " + pkg.staticSharedLibName); 18092 return false; 18093 } 18094 if (!ps.getInstalled(userId)) { 18095 // Can't block uninstall for an app that is not installed or enabled. 18096 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18097 return false; 18098 } 18099 ps.setBlockUninstall(blockUninstall, userId); 18100 mSettings.writePackageRestrictionsLPr(userId); 18101 } 18102 return true; 18103 } 18104 18105 @Override 18106 public boolean getBlockUninstallForUser(String packageName, int userId) { 18107 synchronized (mPackages) { 18108 PackageSetting ps = mSettings.mPackages.get(packageName); 18109 if (ps == null) { 18110 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18111 return false; 18112 } 18113 return ps.getBlockUninstall(userId); 18114 } 18115 } 18116 18117 @Override 18118 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18119 int callingUid = Binder.getCallingUid(); 18120 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18121 throw new SecurityException( 18122 "setRequiredForSystemUser can only be run by the system or root"); 18123 } 18124 synchronized (mPackages) { 18125 PackageSetting ps = mSettings.mPackages.get(packageName); 18126 if (ps == null) { 18127 Log.w(TAG, "Package doesn't exist: " + packageName); 18128 return false; 18129 } 18130 if (systemUserApp) { 18131 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18132 } else { 18133 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18134 } 18135 mSettings.writeLPr(); 18136 } 18137 return true; 18138 } 18139 18140 /* 18141 * This method handles package deletion in general 18142 */ 18143 private boolean deletePackageLIF(String packageName, UserHandle user, 18144 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18145 PackageRemovedInfo outInfo, boolean writeSettings, 18146 PackageParser.Package replacingPackage) { 18147 if (packageName == null) { 18148 Slog.w(TAG, "Attempt to delete null packageName."); 18149 return false; 18150 } 18151 18152 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18153 18154 PackageSetting ps; 18155 synchronized (mPackages) { 18156 ps = mSettings.mPackages.get(packageName); 18157 if (ps == null) { 18158 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18159 return false; 18160 } 18161 18162 if (ps.parentPackageName != null && (!isSystemApp(ps) 18163 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18164 if (DEBUG_REMOVE) { 18165 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18166 + ((user == null) ? UserHandle.USER_ALL : user)); 18167 } 18168 final int removedUserId = (user != null) ? user.getIdentifier() 18169 : UserHandle.USER_ALL; 18170 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18171 return false; 18172 } 18173 markPackageUninstalledForUserLPw(ps, user); 18174 scheduleWritePackageRestrictionsLocked(user); 18175 return true; 18176 } 18177 } 18178 18179 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18180 && user.getIdentifier() != UserHandle.USER_ALL)) { 18181 // The caller is asking that the package only be deleted for a single 18182 // user. To do this, we just mark its uninstalled state and delete 18183 // its data. If this is a system app, we only allow this to happen if 18184 // they have set the special DELETE_SYSTEM_APP which requests different 18185 // semantics than normal for uninstalling system apps. 18186 markPackageUninstalledForUserLPw(ps, user); 18187 18188 if (!isSystemApp(ps)) { 18189 // Do not uninstall the APK if an app should be cached 18190 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18191 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18192 // Other user still have this package installed, so all 18193 // we need to do is clear this user's data and save that 18194 // it is uninstalled. 18195 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18196 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18197 return false; 18198 } 18199 scheduleWritePackageRestrictionsLocked(user); 18200 return true; 18201 } else { 18202 // We need to set it back to 'installed' so the uninstall 18203 // broadcasts will be sent correctly. 18204 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18205 ps.setInstalled(true, user.getIdentifier()); 18206 mSettings.writeKernelMappingLPr(ps); 18207 } 18208 } else { 18209 // This is a system app, so we assume that the 18210 // other users still have this package installed, so all 18211 // we need to do is clear this user's data and save that 18212 // it is uninstalled. 18213 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18214 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18215 return false; 18216 } 18217 scheduleWritePackageRestrictionsLocked(user); 18218 return true; 18219 } 18220 } 18221 18222 // If we are deleting a composite package for all users, keep track 18223 // of result for each child. 18224 if (ps.childPackageNames != null && outInfo != null) { 18225 synchronized (mPackages) { 18226 final int childCount = ps.childPackageNames.size(); 18227 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18228 for (int i = 0; i < childCount; i++) { 18229 String childPackageName = ps.childPackageNames.get(i); 18230 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18231 childInfo.removedPackage = childPackageName; 18232 outInfo.removedChildPackages.put(childPackageName, childInfo); 18233 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18234 if (childPs != null) { 18235 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18236 } 18237 } 18238 } 18239 } 18240 18241 boolean ret = false; 18242 if (isSystemApp(ps)) { 18243 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18244 // When an updated system application is deleted we delete the existing resources 18245 // as well and fall back to existing code in system partition 18246 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18247 } else { 18248 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18249 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18250 outInfo, writeSettings, replacingPackage); 18251 } 18252 18253 // Take a note whether we deleted the package for all users 18254 if (outInfo != null) { 18255 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18256 if (outInfo.removedChildPackages != null) { 18257 synchronized (mPackages) { 18258 final int childCount = outInfo.removedChildPackages.size(); 18259 for (int i = 0; i < childCount; i++) { 18260 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18261 if (childInfo != null) { 18262 childInfo.removedForAllUsers = mPackages.get( 18263 childInfo.removedPackage) == null; 18264 } 18265 } 18266 } 18267 } 18268 // If we uninstalled an update to a system app there may be some 18269 // child packages that appeared as they are declared in the system 18270 // app but were not declared in the update. 18271 if (isSystemApp(ps)) { 18272 synchronized (mPackages) { 18273 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18274 final int childCount = (updatedPs.childPackageNames != null) 18275 ? updatedPs.childPackageNames.size() : 0; 18276 for (int i = 0; i < childCount; i++) { 18277 String childPackageName = updatedPs.childPackageNames.get(i); 18278 if (outInfo.removedChildPackages == null 18279 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18280 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18281 if (childPs == null) { 18282 continue; 18283 } 18284 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18285 installRes.name = childPackageName; 18286 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18287 installRes.pkg = mPackages.get(childPackageName); 18288 installRes.uid = childPs.pkg.applicationInfo.uid; 18289 if (outInfo.appearedChildPackages == null) { 18290 outInfo.appearedChildPackages = new ArrayMap<>(); 18291 } 18292 outInfo.appearedChildPackages.put(childPackageName, installRes); 18293 } 18294 } 18295 } 18296 } 18297 } 18298 18299 return ret; 18300 } 18301 18302 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18303 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18304 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18305 for (int nextUserId : userIds) { 18306 if (DEBUG_REMOVE) { 18307 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18308 } 18309 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18310 false /*installed*/, 18311 true /*stopped*/, 18312 true /*notLaunched*/, 18313 false /*hidden*/, 18314 false /*suspended*/, 18315 false /*instantApp*/, 18316 null /*lastDisableAppCaller*/, 18317 null /*enabledComponents*/, 18318 null /*disabledComponents*/, 18319 false /*blockUninstall*/, 18320 ps.readUserState(nextUserId).domainVerificationStatus, 18321 0, PackageManager.INSTALL_REASON_UNKNOWN); 18322 } 18323 mSettings.writeKernelMappingLPr(ps); 18324 } 18325 18326 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18327 PackageRemovedInfo outInfo) { 18328 final PackageParser.Package pkg; 18329 synchronized (mPackages) { 18330 pkg = mPackages.get(ps.name); 18331 } 18332 18333 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18334 : new int[] {userId}; 18335 for (int nextUserId : userIds) { 18336 if (DEBUG_REMOVE) { 18337 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18338 + nextUserId); 18339 } 18340 18341 destroyAppDataLIF(pkg, userId, 18342 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18343 destroyAppProfilesLIF(pkg, userId); 18344 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18345 schedulePackageCleaning(ps.name, nextUserId, false); 18346 synchronized (mPackages) { 18347 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18348 scheduleWritePackageRestrictionsLocked(nextUserId); 18349 } 18350 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18351 } 18352 } 18353 18354 if (outInfo != null) { 18355 outInfo.removedPackage = ps.name; 18356 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18357 outInfo.removedAppId = ps.appId; 18358 outInfo.removedUsers = userIds; 18359 } 18360 18361 return true; 18362 } 18363 18364 private final class ClearStorageConnection implements ServiceConnection { 18365 IMediaContainerService mContainerService; 18366 18367 @Override 18368 public void onServiceConnected(ComponentName name, IBinder service) { 18369 synchronized (this) { 18370 mContainerService = IMediaContainerService.Stub 18371 .asInterface(Binder.allowBlocking(service)); 18372 notifyAll(); 18373 } 18374 } 18375 18376 @Override 18377 public void onServiceDisconnected(ComponentName name) { 18378 } 18379 } 18380 18381 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18382 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18383 18384 final boolean mounted; 18385 if (Environment.isExternalStorageEmulated()) { 18386 mounted = true; 18387 } else { 18388 final String status = Environment.getExternalStorageState(); 18389 18390 mounted = status.equals(Environment.MEDIA_MOUNTED) 18391 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18392 } 18393 18394 if (!mounted) { 18395 return; 18396 } 18397 18398 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18399 int[] users; 18400 if (userId == UserHandle.USER_ALL) { 18401 users = sUserManager.getUserIds(); 18402 } else { 18403 users = new int[] { userId }; 18404 } 18405 final ClearStorageConnection conn = new ClearStorageConnection(); 18406 if (mContext.bindServiceAsUser( 18407 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18408 try { 18409 for (int curUser : users) { 18410 long timeout = SystemClock.uptimeMillis() + 5000; 18411 synchronized (conn) { 18412 long now; 18413 while (conn.mContainerService == null && 18414 (now = SystemClock.uptimeMillis()) < timeout) { 18415 try { 18416 conn.wait(timeout - now); 18417 } catch (InterruptedException e) { 18418 } 18419 } 18420 } 18421 if (conn.mContainerService == null) { 18422 return; 18423 } 18424 18425 final UserEnvironment userEnv = new UserEnvironment(curUser); 18426 clearDirectory(conn.mContainerService, 18427 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18428 if (allData) { 18429 clearDirectory(conn.mContainerService, 18430 userEnv.buildExternalStorageAppDataDirs(packageName)); 18431 clearDirectory(conn.mContainerService, 18432 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18433 } 18434 } 18435 } finally { 18436 mContext.unbindService(conn); 18437 } 18438 } 18439 } 18440 18441 @Override 18442 public void clearApplicationProfileData(String packageName) { 18443 enforceSystemOrRoot("Only the system can clear all profile data"); 18444 18445 final PackageParser.Package pkg; 18446 synchronized (mPackages) { 18447 pkg = mPackages.get(packageName); 18448 } 18449 18450 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18451 synchronized (mInstallLock) { 18452 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18453 } 18454 } 18455 } 18456 18457 @Override 18458 public void clearApplicationUserData(final String packageName, 18459 final IPackageDataObserver observer, final int userId) { 18460 mContext.enforceCallingOrSelfPermission( 18461 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18462 18463 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18464 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18465 18466 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18467 throw new SecurityException("Cannot clear data for a protected package: " 18468 + packageName); 18469 } 18470 // Queue up an async operation since the package deletion may take a little while. 18471 mHandler.post(new Runnable() { 18472 public void run() { 18473 mHandler.removeCallbacks(this); 18474 final boolean succeeded; 18475 try (PackageFreezer freezer = freezePackage(packageName, 18476 "clearApplicationUserData")) { 18477 synchronized (mInstallLock) { 18478 succeeded = clearApplicationUserDataLIF(packageName, userId); 18479 } 18480 clearExternalStorageDataSync(packageName, userId, true); 18481 synchronized (mPackages) { 18482 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18483 packageName, userId); 18484 } 18485 } 18486 if (succeeded) { 18487 // invoke DeviceStorageMonitor's update method to clear any notifications 18488 DeviceStorageMonitorInternal dsm = LocalServices 18489 .getService(DeviceStorageMonitorInternal.class); 18490 if (dsm != null) { 18491 dsm.checkMemory(); 18492 } 18493 } 18494 if(observer != null) { 18495 try { 18496 observer.onRemoveCompleted(packageName, succeeded); 18497 } catch (RemoteException e) { 18498 Log.i(TAG, "Observer no longer exists."); 18499 } 18500 } //end if observer 18501 } //end run 18502 }); 18503 } 18504 18505 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18506 if (packageName == null) { 18507 Slog.w(TAG, "Attempt to delete null packageName."); 18508 return false; 18509 } 18510 18511 // Try finding details about the requested package 18512 PackageParser.Package pkg; 18513 synchronized (mPackages) { 18514 pkg = mPackages.get(packageName); 18515 if (pkg == null) { 18516 final PackageSetting ps = mSettings.mPackages.get(packageName); 18517 if (ps != null) { 18518 pkg = ps.pkg; 18519 } 18520 } 18521 18522 if (pkg == null) { 18523 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18524 return false; 18525 } 18526 18527 PackageSetting ps = (PackageSetting) pkg.mExtras; 18528 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18529 } 18530 18531 clearAppDataLIF(pkg, userId, 18532 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18533 18534 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18535 removeKeystoreDataIfNeeded(userId, appId); 18536 18537 UserManagerInternal umInternal = getUserManagerInternal(); 18538 final int flags; 18539 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18540 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18541 } else if (umInternal.isUserRunning(userId)) { 18542 flags = StorageManager.FLAG_STORAGE_DE; 18543 } else { 18544 flags = 0; 18545 } 18546 prepareAppDataContentsLIF(pkg, userId, flags); 18547 18548 return true; 18549 } 18550 18551 /** 18552 * Reverts user permission state changes (permissions and flags) in 18553 * all packages for a given user. 18554 * 18555 * @param userId The device user for which to do a reset. 18556 */ 18557 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18558 final int packageCount = mPackages.size(); 18559 for (int i = 0; i < packageCount; i++) { 18560 PackageParser.Package pkg = mPackages.valueAt(i); 18561 PackageSetting ps = (PackageSetting) pkg.mExtras; 18562 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18563 } 18564 } 18565 18566 private void resetNetworkPolicies(int userId) { 18567 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18568 } 18569 18570 /** 18571 * Reverts user permission state changes (permissions and flags). 18572 * 18573 * @param ps The package for which to reset. 18574 * @param userId The device user for which to do a reset. 18575 */ 18576 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18577 final PackageSetting ps, final int userId) { 18578 if (ps.pkg == null) { 18579 return; 18580 } 18581 18582 // These are flags that can change base on user actions. 18583 final int userSettableMask = FLAG_PERMISSION_USER_SET 18584 | FLAG_PERMISSION_USER_FIXED 18585 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18586 | FLAG_PERMISSION_REVIEW_REQUIRED; 18587 18588 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18589 | FLAG_PERMISSION_POLICY_FIXED; 18590 18591 boolean writeInstallPermissions = false; 18592 boolean writeRuntimePermissions = false; 18593 18594 final int permissionCount = ps.pkg.requestedPermissions.size(); 18595 for (int i = 0; i < permissionCount; i++) { 18596 String permission = ps.pkg.requestedPermissions.get(i); 18597 18598 BasePermission bp = mSettings.mPermissions.get(permission); 18599 if (bp == null) { 18600 continue; 18601 } 18602 18603 // If shared user we just reset the state to which only this app contributed. 18604 if (ps.sharedUser != null) { 18605 boolean used = false; 18606 final int packageCount = ps.sharedUser.packages.size(); 18607 for (int j = 0; j < packageCount; j++) { 18608 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18609 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18610 && pkg.pkg.requestedPermissions.contains(permission)) { 18611 used = true; 18612 break; 18613 } 18614 } 18615 if (used) { 18616 continue; 18617 } 18618 } 18619 18620 PermissionsState permissionsState = ps.getPermissionsState(); 18621 18622 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18623 18624 // Always clear the user settable flags. 18625 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18626 bp.name) != null; 18627 // If permission review is enabled and this is a legacy app, mark the 18628 // permission as requiring a review as this is the initial state. 18629 int flags = 0; 18630 if (mPermissionReviewRequired 18631 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18632 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18633 } 18634 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18635 if (hasInstallState) { 18636 writeInstallPermissions = true; 18637 } else { 18638 writeRuntimePermissions = true; 18639 } 18640 } 18641 18642 // Below is only runtime permission handling. 18643 if (!bp.isRuntime()) { 18644 continue; 18645 } 18646 18647 // Never clobber system or policy. 18648 if ((oldFlags & policyOrSystemFlags) != 0) { 18649 continue; 18650 } 18651 18652 // If this permission was granted by default, make sure it is. 18653 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18654 if (permissionsState.grantRuntimePermission(bp, userId) 18655 != PERMISSION_OPERATION_FAILURE) { 18656 writeRuntimePermissions = true; 18657 } 18658 // If permission review is enabled the permissions for a legacy apps 18659 // are represented as constantly granted runtime ones, so don't revoke. 18660 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18661 // Otherwise, reset the permission. 18662 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18663 switch (revokeResult) { 18664 case PERMISSION_OPERATION_SUCCESS: 18665 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18666 writeRuntimePermissions = true; 18667 final int appId = ps.appId; 18668 mHandler.post(new Runnable() { 18669 @Override 18670 public void run() { 18671 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18672 } 18673 }); 18674 } break; 18675 } 18676 } 18677 } 18678 18679 // Synchronously write as we are taking permissions away. 18680 if (writeRuntimePermissions) { 18681 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18682 } 18683 18684 // Synchronously write as we are taking permissions away. 18685 if (writeInstallPermissions) { 18686 mSettings.writeLPr(); 18687 } 18688 } 18689 18690 /** 18691 * Remove entries from the keystore daemon. Will only remove it if the 18692 * {@code appId} is valid. 18693 */ 18694 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18695 if (appId < 0) { 18696 return; 18697 } 18698 18699 final KeyStore keyStore = KeyStore.getInstance(); 18700 if (keyStore != null) { 18701 if (userId == UserHandle.USER_ALL) { 18702 for (final int individual : sUserManager.getUserIds()) { 18703 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18704 } 18705 } else { 18706 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18707 } 18708 } else { 18709 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18710 } 18711 } 18712 18713 @Override 18714 public void deleteApplicationCacheFiles(final String packageName, 18715 final IPackageDataObserver observer) { 18716 final int userId = UserHandle.getCallingUserId(); 18717 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18718 } 18719 18720 @Override 18721 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18722 final IPackageDataObserver observer) { 18723 mContext.enforceCallingOrSelfPermission( 18724 android.Manifest.permission.DELETE_CACHE_FILES, null); 18725 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18726 /* requireFullPermission= */ true, /* checkShell= */ false, 18727 "delete application cache files"); 18728 18729 final PackageParser.Package pkg; 18730 synchronized (mPackages) { 18731 pkg = mPackages.get(packageName); 18732 } 18733 18734 // Queue up an async operation since the package deletion may take a little while. 18735 mHandler.post(new Runnable() { 18736 public void run() { 18737 synchronized (mInstallLock) { 18738 final int flags = StorageManager.FLAG_STORAGE_DE 18739 | StorageManager.FLAG_STORAGE_CE; 18740 // We're only clearing cache files, so we don't care if the 18741 // app is unfrozen and still able to run 18742 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18743 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18744 } 18745 clearExternalStorageDataSync(packageName, userId, false); 18746 if (observer != null) { 18747 try { 18748 observer.onRemoveCompleted(packageName, true); 18749 } catch (RemoteException e) { 18750 Log.i(TAG, "Observer no longer exists."); 18751 } 18752 } 18753 } 18754 }); 18755 } 18756 18757 @Override 18758 public void getPackageSizeInfo(final String packageName, int userHandle, 18759 final IPackageStatsObserver observer) { 18760 throw new UnsupportedOperationException( 18761 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18762 } 18763 18764 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18765 final PackageSetting ps; 18766 synchronized (mPackages) { 18767 ps = mSettings.mPackages.get(packageName); 18768 if (ps == null) { 18769 Slog.w(TAG, "Failed to find settings for " + packageName); 18770 return false; 18771 } 18772 } 18773 18774 final String[] packageNames = { packageName }; 18775 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18776 final String[] codePaths = { ps.codePathString }; 18777 18778 try { 18779 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18780 ps.appId, ceDataInodes, codePaths, stats); 18781 18782 // For now, ignore code size of packages on system partition 18783 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18784 stats.codeSize = 0; 18785 } 18786 18787 // External clients expect these to be tracked separately 18788 stats.dataSize -= stats.cacheSize; 18789 18790 } catch (InstallerException e) { 18791 Slog.w(TAG, String.valueOf(e)); 18792 return false; 18793 } 18794 18795 return true; 18796 } 18797 18798 private int getUidTargetSdkVersionLockedLPr(int uid) { 18799 Object obj = mSettings.getUserIdLPr(uid); 18800 if (obj instanceof SharedUserSetting) { 18801 final SharedUserSetting sus = (SharedUserSetting) obj; 18802 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18803 final Iterator<PackageSetting> it = sus.packages.iterator(); 18804 while (it.hasNext()) { 18805 final PackageSetting ps = it.next(); 18806 if (ps.pkg != null) { 18807 int v = ps.pkg.applicationInfo.targetSdkVersion; 18808 if (v < vers) vers = v; 18809 } 18810 } 18811 return vers; 18812 } else if (obj instanceof PackageSetting) { 18813 final PackageSetting ps = (PackageSetting) obj; 18814 if (ps.pkg != null) { 18815 return ps.pkg.applicationInfo.targetSdkVersion; 18816 } 18817 } 18818 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18819 } 18820 18821 @Override 18822 public void addPreferredActivity(IntentFilter filter, int match, 18823 ComponentName[] set, ComponentName activity, int userId) { 18824 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18825 "Adding preferred"); 18826 } 18827 18828 private void addPreferredActivityInternal(IntentFilter filter, int match, 18829 ComponentName[] set, ComponentName activity, boolean always, int userId, 18830 String opname) { 18831 // writer 18832 int callingUid = Binder.getCallingUid(); 18833 enforceCrossUserPermission(callingUid, userId, 18834 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18835 if (filter.countActions() == 0) { 18836 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18837 return; 18838 } 18839 synchronized (mPackages) { 18840 if (mContext.checkCallingOrSelfPermission( 18841 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18842 != PackageManager.PERMISSION_GRANTED) { 18843 if (getUidTargetSdkVersionLockedLPr(callingUid) 18844 < Build.VERSION_CODES.FROYO) { 18845 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18846 + callingUid); 18847 return; 18848 } 18849 mContext.enforceCallingOrSelfPermission( 18850 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18851 } 18852 18853 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18854 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18855 + userId + ":"); 18856 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18857 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18858 scheduleWritePackageRestrictionsLocked(userId); 18859 postPreferredActivityChangedBroadcast(userId); 18860 } 18861 } 18862 18863 private void postPreferredActivityChangedBroadcast(int userId) { 18864 mHandler.post(() -> { 18865 final IActivityManager am = ActivityManager.getService(); 18866 if (am == null) { 18867 return; 18868 } 18869 18870 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18871 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18872 try { 18873 am.broadcastIntent(null, intent, null, null, 18874 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18875 null, false, false, userId); 18876 } catch (RemoteException e) { 18877 } 18878 }); 18879 } 18880 18881 @Override 18882 public void replacePreferredActivity(IntentFilter filter, int match, 18883 ComponentName[] set, ComponentName activity, int userId) { 18884 if (filter.countActions() != 1) { 18885 throw new IllegalArgumentException( 18886 "replacePreferredActivity expects filter to have only 1 action."); 18887 } 18888 if (filter.countDataAuthorities() != 0 18889 || filter.countDataPaths() != 0 18890 || filter.countDataSchemes() > 1 18891 || filter.countDataTypes() != 0) { 18892 throw new IllegalArgumentException( 18893 "replacePreferredActivity expects filter to have no data authorities, " + 18894 "paths, or types; and at most one scheme."); 18895 } 18896 18897 final int callingUid = Binder.getCallingUid(); 18898 enforceCrossUserPermission(callingUid, userId, 18899 true /* requireFullPermission */, false /* checkShell */, 18900 "replace preferred activity"); 18901 synchronized (mPackages) { 18902 if (mContext.checkCallingOrSelfPermission( 18903 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18904 != PackageManager.PERMISSION_GRANTED) { 18905 if (getUidTargetSdkVersionLockedLPr(callingUid) 18906 < Build.VERSION_CODES.FROYO) { 18907 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18908 + Binder.getCallingUid()); 18909 return; 18910 } 18911 mContext.enforceCallingOrSelfPermission( 18912 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18913 } 18914 18915 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18916 if (pir != null) { 18917 // Get all of the existing entries that exactly match this filter. 18918 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18919 if (existing != null && existing.size() == 1) { 18920 PreferredActivity cur = existing.get(0); 18921 if (DEBUG_PREFERRED) { 18922 Slog.i(TAG, "Checking replace of preferred:"); 18923 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18924 if (!cur.mPref.mAlways) { 18925 Slog.i(TAG, " -- CUR; not mAlways!"); 18926 } else { 18927 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18928 Slog.i(TAG, " -- CUR: mSet=" 18929 + Arrays.toString(cur.mPref.mSetComponents)); 18930 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18931 Slog.i(TAG, " -- NEW: mMatch=" 18932 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18933 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18934 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18935 } 18936 } 18937 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18938 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18939 && cur.mPref.sameSet(set)) { 18940 // Setting the preferred activity to what it happens to be already 18941 if (DEBUG_PREFERRED) { 18942 Slog.i(TAG, "Replacing with same preferred activity " 18943 + cur.mPref.mShortComponent + " for user " 18944 + userId + ":"); 18945 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18946 } 18947 return; 18948 } 18949 } 18950 18951 if (existing != null) { 18952 if (DEBUG_PREFERRED) { 18953 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18954 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18955 } 18956 for (int i = 0; i < existing.size(); i++) { 18957 PreferredActivity pa = existing.get(i); 18958 if (DEBUG_PREFERRED) { 18959 Slog.i(TAG, "Removing existing preferred activity " 18960 + pa.mPref.mComponent + ":"); 18961 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18962 } 18963 pir.removeFilter(pa); 18964 } 18965 } 18966 } 18967 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18968 "Replacing preferred"); 18969 } 18970 } 18971 18972 @Override 18973 public void clearPackagePreferredActivities(String packageName) { 18974 final int uid = Binder.getCallingUid(); 18975 // writer 18976 synchronized (mPackages) { 18977 PackageParser.Package pkg = mPackages.get(packageName); 18978 if (pkg == null || pkg.applicationInfo.uid != uid) { 18979 if (mContext.checkCallingOrSelfPermission( 18980 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18981 != PackageManager.PERMISSION_GRANTED) { 18982 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18983 < Build.VERSION_CODES.FROYO) { 18984 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18985 + Binder.getCallingUid()); 18986 return; 18987 } 18988 mContext.enforceCallingOrSelfPermission( 18989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18990 } 18991 } 18992 18993 int user = UserHandle.getCallingUserId(); 18994 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18995 scheduleWritePackageRestrictionsLocked(user); 18996 } 18997 } 18998 } 18999 19000 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19001 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19002 ArrayList<PreferredActivity> removed = null; 19003 boolean changed = false; 19004 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19005 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19006 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19007 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19008 continue; 19009 } 19010 Iterator<PreferredActivity> it = pir.filterIterator(); 19011 while (it.hasNext()) { 19012 PreferredActivity pa = it.next(); 19013 // Mark entry for removal only if it matches the package name 19014 // and the entry is of type "always". 19015 if (packageName == null || 19016 (pa.mPref.mComponent.getPackageName().equals(packageName) 19017 && pa.mPref.mAlways)) { 19018 if (removed == null) { 19019 removed = new ArrayList<PreferredActivity>(); 19020 } 19021 removed.add(pa); 19022 } 19023 } 19024 if (removed != null) { 19025 for (int j=0; j<removed.size(); j++) { 19026 PreferredActivity pa = removed.get(j); 19027 pir.removeFilter(pa); 19028 } 19029 changed = true; 19030 } 19031 } 19032 if (changed) { 19033 postPreferredActivityChangedBroadcast(userId); 19034 } 19035 return changed; 19036 } 19037 19038 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19039 private void clearIntentFilterVerificationsLPw(int userId) { 19040 final int packageCount = mPackages.size(); 19041 for (int i = 0; i < packageCount; i++) { 19042 PackageParser.Package pkg = mPackages.valueAt(i); 19043 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19044 } 19045 } 19046 19047 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19048 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19049 if (userId == UserHandle.USER_ALL) { 19050 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19051 sUserManager.getUserIds())) { 19052 for (int oneUserId : sUserManager.getUserIds()) { 19053 scheduleWritePackageRestrictionsLocked(oneUserId); 19054 } 19055 } 19056 } else { 19057 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19058 scheduleWritePackageRestrictionsLocked(userId); 19059 } 19060 } 19061 } 19062 19063 void clearDefaultBrowserIfNeeded(String packageName) { 19064 for (int oneUserId : sUserManager.getUserIds()) { 19065 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19066 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19067 if (packageName.equals(defaultBrowserPackageName)) { 19068 setDefaultBrowserPackageName(null, oneUserId); 19069 } 19070 } 19071 } 19072 19073 @Override 19074 public void resetApplicationPreferences(int userId) { 19075 mContext.enforceCallingOrSelfPermission( 19076 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19077 final long identity = Binder.clearCallingIdentity(); 19078 // writer 19079 try { 19080 synchronized (mPackages) { 19081 clearPackagePreferredActivitiesLPw(null, userId); 19082 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19083 // TODO: We have to reset the default SMS and Phone. This requires 19084 // significant refactoring to keep all default apps in the package 19085 // manager (cleaner but more work) or have the services provide 19086 // callbacks to the package manager to request a default app reset. 19087 applyFactoryDefaultBrowserLPw(userId); 19088 clearIntentFilterVerificationsLPw(userId); 19089 primeDomainVerificationsLPw(userId); 19090 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19091 scheduleWritePackageRestrictionsLocked(userId); 19092 } 19093 resetNetworkPolicies(userId); 19094 } finally { 19095 Binder.restoreCallingIdentity(identity); 19096 } 19097 } 19098 19099 @Override 19100 public int getPreferredActivities(List<IntentFilter> outFilters, 19101 List<ComponentName> outActivities, String packageName) { 19102 19103 int num = 0; 19104 final int userId = UserHandle.getCallingUserId(); 19105 // reader 19106 synchronized (mPackages) { 19107 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19108 if (pir != null) { 19109 final Iterator<PreferredActivity> it = pir.filterIterator(); 19110 while (it.hasNext()) { 19111 final PreferredActivity pa = it.next(); 19112 if (packageName == null 19113 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19114 && pa.mPref.mAlways)) { 19115 if (outFilters != null) { 19116 outFilters.add(new IntentFilter(pa)); 19117 } 19118 if (outActivities != null) { 19119 outActivities.add(pa.mPref.mComponent); 19120 } 19121 } 19122 } 19123 } 19124 } 19125 19126 return num; 19127 } 19128 19129 @Override 19130 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19131 int userId) { 19132 int callingUid = Binder.getCallingUid(); 19133 if (callingUid != Process.SYSTEM_UID) { 19134 throw new SecurityException( 19135 "addPersistentPreferredActivity can only be run by the system"); 19136 } 19137 if (filter.countActions() == 0) { 19138 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19139 return; 19140 } 19141 synchronized (mPackages) { 19142 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19143 ":"); 19144 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19145 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19146 new PersistentPreferredActivity(filter, activity)); 19147 scheduleWritePackageRestrictionsLocked(userId); 19148 postPreferredActivityChangedBroadcast(userId); 19149 } 19150 } 19151 19152 @Override 19153 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19154 int callingUid = Binder.getCallingUid(); 19155 if (callingUid != Process.SYSTEM_UID) { 19156 throw new SecurityException( 19157 "clearPackagePersistentPreferredActivities can only be run by the system"); 19158 } 19159 ArrayList<PersistentPreferredActivity> removed = null; 19160 boolean changed = false; 19161 synchronized (mPackages) { 19162 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19163 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19164 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19165 .valueAt(i); 19166 if (userId != thisUserId) { 19167 continue; 19168 } 19169 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19170 while (it.hasNext()) { 19171 PersistentPreferredActivity ppa = it.next(); 19172 // Mark entry for removal only if it matches the package name. 19173 if (ppa.mComponent.getPackageName().equals(packageName)) { 19174 if (removed == null) { 19175 removed = new ArrayList<PersistentPreferredActivity>(); 19176 } 19177 removed.add(ppa); 19178 } 19179 } 19180 if (removed != null) { 19181 for (int j=0; j<removed.size(); j++) { 19182 PersistentPreferredActivity ppa = removed.get(j); 19183 ppir.removeFilter(ppa); 19184 } 19185 changed = true; 19186 } 19187 } 19188 19189 if (changed) { 19190 scheduleWritePackageRestrictionsLocked(userId); 19191 postPreferredActivityChangedBroadcast(userId); 19192 } 19193 } 19194 } 19195 19196 /** 19197 * Common machinery for picking apart a restored XML blob and passing 19198 * it to a caller-supplied functor to be applied to the running system. 19199 */ 19200 private void restoreFromXml(XmlPullParser parser, int userId, 19201 String expectedStartTag, BlobXmlRestorer functor) 19202 throws IOException, XmlPullParserException { 19203 int type; 19204 while ((type = parser.next()) != XmlPullParser.START_TAG 19205 && type != XmlPullParser.END_DOCUMENT) { 19206 } 19207 if (type != XmlPullParser.START_TAG) { 19208 // oops didn't find a start tag?! 19209 if (DEBUG_BACKUP) { 19210 Slog.e(TAG, "Didn't find start tag during restore"); 19211 } 19212 return; 19213 } 19214Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19215 // this is supposed to be TAG_PREFERRED_BACKUP 19216 if (!expectedStartTag.equals(parser.getName())) { 19217 if (DEBUG_BACKUP) { 19218 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19219 } 19220 return; 19221 } 19222 19223 // skip interfering stuff, then we're aligned with the backing implementation 19224 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19225Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19226 functor.apply(parser, userId); 19227 } 19228 19229 private interface BlobXmlRestorer { 19230 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19231 } 19232 19233 /** 19234 * Non-Binder method, support for the backup/restore mechanism: write the 19235 * full set of preferred activities in its canonical XML format. Returns the 19236 * XML output as a byte array, or null if there is none. 19237 */ 19238 @Override 19239 public byte[] getPreferredActivityBackup(int userId) { 19240 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19241 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19242 } 19243 19244 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19245 try { 19246 final XmlSerializer serializer = new FastXmlSerializer(); 19247 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19248 serializer.startDocument(null, true); 19249 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19250 19251 synchronized (mPackages) { 19252 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19253 } 19254 19255 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19256 serializer.endDocument(); 19257 serializer.flush(); 19258 } catch (Exception e) { 19259 if (DEBUG_BACKUP) { 19260 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19261 } 19262 return null; 19263 } 19264 19265 return dataStream.toByteArray(); 19266 } 19267 19268 @Override 19269 public void restorePreferredActivities(byte[] backup, int userId) { 19270 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19271 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19272 } 19273 19274 try { 19275 final XmlPullParser parser = Xml.newPullParser(); 19276 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19277 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19278 new BlobXmlRestorer() { 19279 @Override 19280 public void apply(XmlPullParser parser, int userId) 19281 throws XmlPullParserException, IOException { 19282 synchronized (mPackages) { 19283 mSettings.readPreferredActivitiesLPw(parser, userId); 19284 } 19285 } 19286 } ); 19287 } catch (Exception e) { 19288 if (DEBUG_BACKUP) { 19289 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19290 } 19291 } 19292 } 19293 19294 /** 19295 * Non-Binder method, support for the backup/restore mechanism: write the 19296 * default browser (etc) settings in its canonical XML format. Returns the default 19297 * browser XML representation as a byte array, or null if there is none. 19298 */ 19299 @Override 19300 public byte[] getDefaultAppsBackup(int userId) { 19301 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19302 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19303 } 19304 19305 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19306 try { 19307 final XmlSerializer serializer = new FastXmlSerializer(); 19308 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19309 serializer.startDocument(null, true); 19310 serializer.startTag(null, TAG_DEFAULT_APPS); 19311 19312 synchronized (mPackages) { 19313 mSettings.writeDefaultAppsLPr(serializer, userId); 19314 } 19315 19316 serializer.endTag(null, TAG_DEFAULT_APPS); 19317 serializer.endDocument(); 19318 serializer.flush(); 19319 } catch (Exception e) { 19320 if (DEBUG_BACKUP) { 19321 Slog.e(TAG, "Unable to write default apps for backup", e); 19322 } 19323 return null; 19324 } 19325 19326 return dataStream.toByteArray(); 19327 } 19328 19329 @Override 19330 public void restoreDefaultApps(byte[] backup, int userId) { 19331 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19332 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19333 } 19334 19335 try { 19336 final XmlPullParser parser = Xml.newPullParser(); 19337 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19338 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19339 new BlobXmlRestorer() { 19340 @Override 19341 public void apply(XmlPullParser parser, int userId) 19342 throws XmlPullParserException, IOException { 19343 synchronized (mPackages) { 19344 mSettings.readDefaultAppsLPw(parser, userId); 19345 } 19346 } 19347 } ); 19348 } catch (Exception e) { 19349 if (DEBUG_BACKUP) { 19350 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19351 } 19352 } 19353 } 19354 19355 @Override 19356 public byte[] getIntentFilterVerificationBackup(int userId) { 19357 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19358 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19359 } 19360 19361 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19362 try { 19363 final XmlSerializer serializer = new FastXmlSerializer(); 19364 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19365 serializer.startDocument(null, true); 19366 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19367 19368 synchronized (mPackages) { 19369 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19370 } 19371 19372 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19373 serializer.endDocument(); 19374 serializer.flush(); 19375 } catch (Exception e) { 19376 if (DEBUG_BACKUP) { 19377 Slog.e(TAG, "Unable to write default apps for backup", e); 19378 } 19379 return null; 19380 } 19381 19382 return dataStream.toByteArray(); 19383 } 19384 19385 @Override 19386 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19387 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19388 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19389 } 19390 19391 try { 19392 final XmlPullParser parser = Xml.newPullParser(); 19393 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19394 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19395 new BlobXmlRestorer() { 19396 @Override 19397 public void apply(XmlPullParser parser, int userId) 19398 throws XmlPullParserException, IOException { 19399 synchronized (mPackages) { 19400 mSettings.readAllDomainVerificationsLPr(parser, userId); 19401 mSettings.writeLPr(); 19402 } 19403 } 19404 } ); 19405 } catch (Exception e) { 19406 if (DEBUG_BACKUP) { 19407 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19408 } 19409 } 19410 } 19411 19412 @Override 19413 public byte[] getPermissionGrantBackup(int userId) { 19414 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19415 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19416 } 19417 19418 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19419 try { 19420 final XmlSerializer serializer = new FastXmlSerializer(); 19421 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19422 serializer.startDocument(null, true); 19423 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19424 19425 synchronized (mPackages) { 19426 serializeRuntimePermissionGrantsLPr(serializer, userId); 19427 } 19428 19429 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19430 serializer.endDocument(); 19431 serializer.flush(); 19432 } catch (Exception e) { 19433 if (DEBUG_BACKUP) { 19434 Slog.e(TAG, "Unable to write default apps for backup", e); 19435 } 19436 return null; 19437 } 19438 19439 return dataStream.toByteArray(); 19440 } 19441 19442 @Override 19443 public void restorePermissionGrants(byte[] backup, int userId) { 19444 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19445 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19446 } 19447 19448 try { 19449 final XmlPullParser parser = Xml.newPullParser(); 19450 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19451 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19452 new BlobXmlRestorer() { 19453 @Override 19454 public void apply(XmlPullParser parser, int userId) 19455 throws XmlPullParserException, IOException { 19456 synchronized (mPackages) { 19457 processRestoredPermissionGrantsLPr(parser, userId); 19458 } 19459 } 19460 } ); 19461 } catch (Exception e) { 19462 if (DEBUG_BACKUP) { 19463 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19464 } 19465 } 19466 } 19467 19468 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19469 throws IOException { 19470 serializer.startTag(null, TAG_ALL_GRANTS); 19471 19472 final int N = mSettings.mPackages.size(); 19473 for (int i = 0; i < N; i++) { 19474 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19475 boolean pkgGrantsKnown = false; 19476 19477 PermissionsState packagePerms = ps.getPermissionsState(); 19478 19479 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19480 final int grantFlags = state.getFlags(); 19481 // only look at grants that are not system/policy fixed 19482 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19483 final boolean isGranted = state.isGranted(); 19484 // And only back up the user-twiddled state bits 19485 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19486 final String packageName = mSettings.mPackages.keyAt(i); 19487 if (!pkgGrantsKnown) { 19488 serializer.startTag(null, TAG_GRANT); 19489 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19490 pkgGrantsKnown = true; 19491 } 19492 19493 final boolean userSet = 19494 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19495 final boolean userFixed = 19496 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19497 final boolean revoke = 19498 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19499 19500 serializer.startTag(null, TAG_PERMISSION); 19501 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19502 if (isGranted) { 19503 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19504 } 19505 if (userSet) { 19506 serializer.attribute(null, ATTR_USER_SET, "true"); 19507 } 19508 if (userFixed) { 19509 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19510 } 19511 if (revoke) { 19512 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19513 } 19514 serializer.endTag(null, TAG_PERMISSION); 19515 } 19516 } 19517 } 19518 19519 if (pkgGrantsKnown) { 19520 serializer.endTag(null, TAG_GRANT); 19521 } 19522 } 19523 19524 serializer.endTag(null, TAG_ALL_GRANTS); 19525 } 19526 19527 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19528 throws XmlPullParserException, IOException { 19529 String pkgName = null; 19530 int outerDepth = parser.getDepth(); 19531 int type; 19532 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19533 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19534 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19535 continue; 19536 } 19537 19538 final String tagName = parser.getName(); 19539 if (tagName.equals(TAG_GRANT)) { 19540 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19541 if (DEBUG_BACKUP) { 19542 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19543 } 19544 } else if (tagName.equals(TAG_PERMISSION)) { 19545 19546 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19547 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19548 19549 int newFlagSet = 0; 19550 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19551 newFlagSet |= FLAG_PERMISSION_USER_SET; 19552 } 19553 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19554 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19555 } 19556 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19557 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19558 } 19559 if (DEBUG_BACKUP) { 19560 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19561 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19562 } 19563 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19564 if (ps != null) { 19565 // Already installed so we apply the grant immediately 19566 if (DEBUG_BACKUP) { 19567 Slog.v(TAG, " + already installed; applying"); 19568 } 19569 PermissionsState perms = ps.getPermissionsState(); 19570 BasePermission bp = mSettings.mPermissions.get(permName); 19571 if (bp != null) { 19572 if (isGranted) { 19573 perms.grantRuntimePermission(bp, userId); 19574 } 19575 if (newFlagSet != 0) { 19576 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19577 } 19578 } 19579 } else { 19580 // Need to wait for post-restore install to apply the grant 19581 if (DEBUG_BACKUP) { 19582 Slog.v(TAG, " - not yet installed; saving for later"); 19583 } 19584 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19585 isGranted, newFlagSet, userId); 19586 } 19587 } else { 19588 PackageManagerService.reportSettingsProblem(Log.WARN, 19589 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19590 XmlUtils.skipCurrentTag(parser); 19591 } 19592 } 19593 19594 scheduleWriteSettingsLocked(); 19595 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19596 } 19597 19598 @Override 19599 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19600 int sourceUserId, int targetUserId, int flags) { 19601 mContext.enforceCallingOrSelfPermission( 19602 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19603 int callingUid = Binder.getCallingUid(); 19604 enforceOwnerRights(ownerPackage, callingUid); 19605 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19606 if (intentFilter.countActions() == 0) { 19607 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19608 return; 19609 } 19610 synchronized (mPackages) { 19611 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19612 ownerPackage, targetUserId, flags); 19613 CrossProfileIntentResolver resolver = 19614 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19615 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19616 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19617 if (existing != null) { 19618 int size = existing.size(); 19619 for (int i = 0; i < size; i++) { 19620 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19621 return; 19622 } 19623 } 19624 } 19625 resolver.addFilter(newFilter); 19626 scheduleWritePackageRestrictionsLocked(sourceUserId); 19627 } 19628 } 19629 19630 @Override 19631 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19632 mContext.enforceCallingOrSelfPermission( 19633 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19634 int callingUid = Binder.getCallingUid(); 19635 enforceOwnerRights(ownerPackage, callingUid); 19636 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19637 synchronized (mPackages) { 19638 CrossProfileIntentResolver resolver = 19639 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19640 ArraySet<CrossProfileIntentFilter> set = 19641 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19642 for (CrossProfileIntentFilter filter : set) { 19643 if (filter.getOwnerPackage().equals(ownerPackage)) { 19644 resolver.removeFilter(filter); 19645 } 19646 } 19647 scheduleWritePackageRestrictionsLocked(sourceUserId); 19648 } 19649 } 19650 19651 // Enforcing that callingUid is owning pkg on userId 19652 private void enforceOwnerRights(String pkg, int callingUid) { 19653 // The system owns everything. 19654 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19655 return; 19656 } 19657 int callingUserId = UserHandle.getUserId(callingUid); 19658 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19659 if (pi == null) { 19660 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19661 + callingUserId); 19662 } 19663 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19664 throw new SecurityException("Calling uid " + callingUid 19665 + " does not own package " + pkg); 19666 } 19667 } 19668 19669 @Override 19670 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19671 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19672 } 19673 19674 /** 19675 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19676 * then reports the most likely home activity or null if there are more than one. 19677 */ 19678 public ComponentName getDefaultHomeActivity(int userId) { 19679 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19680 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19681 if (cn != null) { 19682 return cn; 19683 } 19684 19685 // Find the launcher with the highest priority and return that component if there are no 19686 // other home activity with the same priority. 19687 int lastPriority = Integer.MIN_VALUE; 19688 ComponentName lastComponent = null; 19689 final int size = allHomeCandidates.size(); 19690 for (int i = 0; i < size; i++) { 19691 final ResolveInfo ri = allHomeCandidates.get(i); 19692 if (ri.priority > lastPriority) { 19693 lastComponent = ri.activityInfo.getComponentName(); 19694 lastPriority = ri.priority; 19695 } else if (ri.priority == lastPriority) { 19696 // Two components found with same priority. 19697 lastComponent = null; 19698 } 19699 } 19700 return lastComponent; 19701 } 19702 19703 private Intent getHomeIntent() { 19704 Intent intent = new Intent(Intent.ACTION_MAIN); 19705 intent.addCategory(Intent.CATEGORY_HOME); 19706 intent.addCategory(Intent.CATEGORY_DEFAULT); 19707 return intent; 19708 } 19709 19710 private IntentFilter getHomeFilter() { 19711 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19712 filter.addCategory(Intent.CATEGORY_HOME); 19713 filter.addCategory(Intent.CATEGORY_DEFAULT); 19714 return filter; 19715 } 19716 19717 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19718 int userId) { 19719 Intent intent = getHomeIntent(); 19720 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19721 PackageManager.GET_META_DATA, userId); 19722 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19723 true, false, false, userId); 19724 19725 allHomeCandidates.clear(); 19726 if (list != null) { 19727 for (ResolveInfo ri : list) { 19728 allHomeCandidates.add(ri); 19729 } 19730 } 19731 return (preferred == null || preferred.activityInfo == null) 19732 ? null 19733 : new ComponentName(preferred.activityInfo.packageName, 19734 preferred.activityInfo.name); 19735 } 19736 19737 @Override 19738 public void setHomeActivity(ComponentName comp, int userId) { 19739 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19740 getHomeActivitiesAsUser(homeActivities, userId); 19741 19742 boolean found = false; 19743 19744 final int size = homeActivities.size(); 19745 final ComponentName[] set = new ComponentName[size]; 19746 for (int i = 0; i < size; i++) { 19747 final ResolveInfo candidate = homeActivities.get(i); 19748 final ActivityInfo info = candidate.activityInfo; 19749 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19750 set[i] = activityName; 19751 if (!found && activityName.equals(comp)) { 19752 found = true; 19753 } 19754 } 19755 if (!found) { 19756 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19757 + userId); 19758 } 19759 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19760 set, comp, userId); 19761 } 19762 19763 private @Nullable String getSetupWizardPackageName() { 19764 final Intent intent = new Intent(Intent.ACTION_MAIN); 19765 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19766 19767 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19768 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19769 | MATCH_DISABLED_COMPONENTS, 19770 UserHandle.myUserId()); 19771 if (matches.size() == 1) { 19772 return matches.get(0).getComponentInfo().packageName; 19773 } else { 19774 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19775 + ": matches=" + matches); 19776 return null; 19777 } 19778 } 19779 19780 private @Nullable String getStorageManagerPackageName() { 19781 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19782 19783 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19784 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19785 | MATCH_DISABLED_COMPONENTS, 19786 UserHandle.myUserId()); 19787 if (matches.size() == 1) { 19788 return matches.get(0).getComponentInfo().packageName; 19789 } else { 19790 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19791 + matches.size() + ": matches=" + matches); 19792 return null; 19793 } 19794 } 19795 19796 @Override 19797 public void setApplicationEnabledSetting(String appPackageName, 19798 int newState, int flags, int userId, String callingPackage) { 19799 if (!sUserManager.exists(userId)) return; 19800 if (callingPackage == null) { 19801 callingPackage = Integer.toString(Binder.getCallingUid()); 19802 } 19803 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19804 } 19805 19806 @Override 19807 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19808 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19809 synchronized (mPackages) { 19810 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19811 if (pkgSetting != null) { 19812 pkgSetting.setUpdateAvailable(updateAvailable); 19813 } 19814 } 19815 } 19816 19817 @Override 19818 public void setComponentEnabledSetting(ComponentName componentName, 19819 int newState, int flags, int userId) { 19820 if (!sUserManager.exists(userId)) return; 19821 setEnabledSetting(componentName.getPackageName(), 19822 componentName.getClassName(), newState, flags, userId, null); 19823 } 19824 19825 private void setEnabledSetting(final String packageName, String className, int newState, 19826 final int flags, int userId, String callingPackage) { 19827 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19828 || newState == COMPONENT_ENABLED_STATE_ENABLED 19829 || newState == COMPONENT_ENABLED_STATE_DISABLED 19830 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19831 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19832 throw new IllegalArgumentException("Invalid new component state: " 19833 + newState); 19834 } 19835 PackageSetting pkgSetting; 19836 final int uid = Binder.getCallingUid(); 19837 final int permission; 19838 if (uid == Process.SYSTEM_UID) { 19839 permission = PackageManager.PERMISSION_GRANTED; 19840 } else { 19841 permission = mContext.checkCallingOrSelfPermission( 19842 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19843 } 19844 enforceCrossUserPermission(uid, userId, 19845 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19846 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19847 boolean sendNow = false; 19848 boolean isApp = (className == null); 19849 String componentName = isApp ? packageName : className; 19850 int packageUid = -1; 19851 ArrayList<String> components; 19852 19853 // writer 19854 synchronized (mPackages) { 19855 pkgSetting = mSettings.mPackages.get(packageName); 19856 if (pkgSetting == null) { 19857 if (className == null) { 19858 throw new IllegalArgumentException("Unknown package: " + packageName); 19859 } 19860 throw new IllegalArgumentException( 19861 "Unknown component: " + packageName + "/" + className); 19862 } 19863 } 19864 19865 // Limit who can change which apps 19866 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19867 // Don't allow apps that don't have permission to modify other apps 19868 if (!allowedByPermission) { 19869 throw new SecurityException( 19870 "Permission Denial: attempt to change component state from pid=" 19871 + Binder.getCallingPid() 19872 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19873 } 19874 // Don't allow changing protected packages. 19875 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19876 throw new SecurityException("Cannot disable a protected package: " + packageName); 19877 } 19878 } 19879 19880 synchronized (mPackages) { 19881 if (uid == Process.SHELL_UID 19882 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19883 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19884 // unless it is a test package. 19885 int oldState = pkgSetting.getEnabled(userId); 19886 if (className == null 19887 && 19888 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19889 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19890 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19891 && 19892 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19893 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19894 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19895 // ok 19896 } else { 19897 throw new SecurityException( 19898 "Shell cannot change component state for " + packageName + "/" 19899 + className + " to " + newState); 19900 } 19901 } 19902 if (className == null) { 19903 // We're dealing with an application/package level state change 19904 if (pkgSetting.getEnabled(userId) == newState) { 19905 // Nothing to do 19906 return; 19907 } 19908 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19909 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19910 // Don't care about who enables an app. 19911 callingPackage = null; 19912 } 19913 pkgSetting.setEnabled(newState, userId, callingPackage); 19914 // pkgSetting.pkg.mSetEnabled = newState; 19915 } else { 19916 // We're dealing with a component level state change 19917 // First, verify that this is a valid class name. 19918 PackageParser.Package pkg = pkgSetting.pkg; 19919 if (pkg == null || !pkg.hasComponentClassName(className)) { 19920 if (pkg != null && 19921 pkg.applicationInfo.targetSdkVersion >= 19922 Build.VERSION_CODES.JELLY_BEAN) { 19923 throw new IllegalArgumentException("Component class " + className 19924 + " does not exist in " + packageName); 19925 } else { 19926 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19927 + className + " does not exist in " + packageName); 19928 } 19929 } 19930 switch (newState) { 19931 case COMPONENT_ENABLED_STATE_ENABLED: 19932 if (!pkgSetting.enableComponentLPw(className, userId)) { 19933 return; 19934 } 19935 break; 19936 case COMPONENT_ENABLED_STATE_DISABLED: 19937 if (!pkgSetting.disableComponentLPw(className, userId)) { 19938 return; 19939 } 19940 break; 19941 case COMPONENT_ENABLED_STATE_DEFAULT: 19942 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19943 return; 19944 } 19945 break; 19946 default: 19947 Slog.e(TAG, "Invalid new component state: " + newState); 19948 return; 19949 } 19950 } 19951 scheduleWritePackageRestrictionsLocked(userId); 19952 updateSequenceNumberLP(packageName, new int[] { userId }); 19953 final long callingId = Binder.clearCallingIdentity(); 19954 try { 19955 updateInstantAppInstallerLocked(); 19956 } finally { 19957 Binder.restoreCallingIdentity(callingId); 19958 } 19959 components = mPendingBroadcasts.get(userId, packageName); 19960 final boolean newPackage = components == null; 19961 if (newPackage) { 19962 components = new ArrayList<String>(); 19963 } 19964 if (!components.contains(componentName)) { 19965 components.add(componentName); 19966 } 19967 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19968 sendNow = true; 19969 // Purge entry from pending broadcast list if another one exists already 19970 // since we are sending one right away. 19971 mPendingBroadcasts.remove(userId, packageName); 19972 } else { 19973 if (newPackage) { 19974 mPendingBroadcasts.put(userId, packageName, components); 19975 } 19976 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19977 // Schedule a message 19978 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19979 } 19980 } 19981 } 19982 19983 long callingId = Binder.clearCallingIdentity(); 19984 try { 19985 if (sendNow) { 19986 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19987 sendPackageChangedBroadcast(packageName, 19988 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19989 } 19990 } finally { 19991 Binder.restoreCallingIdentity(callingId); 19992 } 19993 } 19994 19995 @Override 19996 public void flushPackageRestrictionsAsUser(int userId) { 19997 if (!sUserManager.exists(userId)) { 19998 return; 19999 } 20000 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20001 false /* checkShell */, "flushPackageRestrictions"); 20002 synchronized (mPackages) { 20003 mSettings.writePackageRestrictionsLPr(userId); 20004 mDirtyUsers.remove(userId); 20005 if (mDirtyUsers.isEmpty()) { 20006 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20007 } 20008 } 20009 } 20010 20011 private void sendPackageChangedBroadcast(String packageName, 20012 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20013 if (DEBUG_INSTALL) 20014 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20015 + componentNames); 20016 Bundle extras = new Bundle(4); 20017 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20018 String nameList[] = new String[componentNames.size()]; 20019 componentNames.toArray(nameList); 20020 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20021 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20022 extras.putInt(Intent.EXTRA_UID, packageUid); 20023 // If this is not reporting a change of the overall package, then only send it 20024 // to registered receivers. We don't want to launch a swath of apps for every 20025 // little component state change. 20026 final int flags = !componentNames.contains(packageName) 20027 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20028 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20029 new int[] {UserHandle.getUserId(packageUid)}); 20030 } 20031 20032 @Override 20033 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20034 if (!sUserManager.exists(userId)) return; 20035 final int uid = Binder.getCallingUid(); 20036 final int permission = mContext.checkCallingOrSelfPermission( 20037 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20038 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20039 enforceCrossUserPermission(uid, userId, 20040 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20041 // writer 20042 synchronized (mPackages) { 20043 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20044 allowedByPermission, uid, userId)) { 20045 scheduleWritePackageRestrictionsLocked(userId); 20046 } 20047 } 20048 } 20049 20050 @Override 20051 public String getInstallerPackageName(String packageName) { 20052 // reader 20053 synchronized (mPackages) { 20054 return mSettings.getInstallerPackageNameLPr(packageName); 20055 } 20056 } 20057 20058 public boolean isOrphaned(String packageName) { 20059 // reader 20060 synchronized (mPackages) { 20061 return mSettings.isOrphaned(packageName); 20062 } 20063 } 20064 20065 @Override 20066 public int getApplicationEnabledSetting(String packageName, int userId) { 20067 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20068 int uid = Binder.getCallingUid(); 20069 enforceCrossUserPermission(uid, userId, 20070 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20071 // reader 20072 synchronized (mPackages) { 20073 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20074 } 20075 } 20076 20077 @Override 20078 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20079 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20080 int uid = Binder.getCallingUid(); 20081 enforceCrossUserPermission(uid, userId, 20082 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20083 // reader 20084 synchronized (mPackages) { 20085 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20086 } 20087 } 20088 20089 @Override 20090 public void enterSafeMode() { 20091 enforceSystemOrRoot("Only the system can request entering safe mode"); 20092 20093 if (!mSystemReady) { 20094 mSafeMode = true; 20095 } 20096 } 20097 20098 @Override 20099 public void systemReady() { 20100 mSystemReady = true; 20101 20102 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20103 // disabled after already being started. 20104 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20105 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20106 20107 // Read the compatibilty setting when the system is ready. 20108 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20109 mContext.getContentResolver(), 20110 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20111 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20112 if (DEBUG_SETTINGS) { 20113 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20114 } 20115 20116 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20117 20118 synchronized (mPackages) { 20119 // Verify that all of the preferred activity components actually 20120 // exist. It is possible for applications to be updated and at 20121 // that point remove a previously declared activity component that 20122 // had been set as a preferred activity. We try to clean this up 20123 // the next time we encounter that preferred activity, but it is 20124 // possible for the user flow to never be able to return to that 20125 // situation so here we do a sanity check to make sure we haven't 20126 // left any junk around. 20127 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20128 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20129 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20130 removed.clear(); 20131 for (PreferredActivity pa : pir.filterSet()) { 20132 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20133 removed.add(pa); 20134 } 20135 } 20136 if (removed.size() > 0) { 20137 for (int r=0; r<removed.size(); r++) { 20138 PreferredActivity pa = removed.get(r); 20139 Slog.w(TAG, "Removing dangling preferred activity: " 20140 + pa.mPref.mComponent); 20141 pir.removeFilter(pa); 20142 } 20143 mSettings.writePackageRestrictionsLPr( 20144 mSettings.mPreferredActivities.keyAt(i)); 20145 } 20146 } 20147 20148 for (int userId : UserManagerService.getInstance().getUserIds()) { 20149 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20150 grantPermissionsUserIds = ArrayUtils.appendInt( 20151 grantPermissionsUserIds, userId); 20152 } 20153 } 20154 } 20155 sUserManager.systemReady(); 20156 20157 // If we upgraded grant all default permissions before kicking off. 20158 for (int userId : grantPermissionsUserIds) { 20159 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20160 } 20161 20162 // If we did not grant default permissions, we preload from this the 20163 // default permission exceptions lazily to ensure we don't hit the 20164 // disk on a new user creation. 20165 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20166 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20167 } 20168 20169 // Kick off any messages waiting for system ready 20170 if (mPostSystemReadyMessages != null) { 20171 for (Message msg : mPostSystemReadyMessages) { 20172 msg.sendToTarget(); 20173 } 20174 mPostSystemReadyMessages = null; 20175 } 20176 20177 // Watch for external volumes that come and go over time 20178 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20179 storage.registerListener(mStorageListener); 20180 20181 mInstallerService.systemReady(); 20182 mPackageDexOptimizer.systemReady(); 20183 20184 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20185 StorageManagerInternal.class); 20186 StorageManagerInternal.addExternalStoragePolicy( 20187 new StorageManagerInternal.ExternalStorageMountPolicy() { 20188 @Override 20189 public int getMountMode(int uid, String packageName) { 20190 if (Process.isIsolated(uid)) { 20191 return Zygote.MOUNT_EXTERNAL_NONE; 20192 } 20193 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20194 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20195 } 20196 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20197 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20198 } 20199 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20200 return Zygote.MOUNT_EXTERNAL_READ; 20201 } 20202 return Zygote.MOUNT_EXTERNAL_WRITE; 20203 } 20204 20205 @Override 20206 public boolean hasExternalStorage(int uid, String packageName) { 20207 return true; 20208 } 20209 }); 20210 20211 // Now that we're mostly running, clean up stale users and apps 20212 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20213 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20214 20215 if (mPrivappPermissionsViolations != null) { 20216 Slog.wtf(TAG,"Signature|privileged permissions not in " 20217 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20218 mPrivappPermissionsViolations = null; 20219 } 20220 } 20221 20222 public void waitForAppDataPrepared() { 20223 if (mPrepareAppDataFuture == null) { 20224 return; 20225 } 20226 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20227 mPrepareAppDataFuture = null; 20228 } 20229 20230 @Override 20231 public boolean isSafeMode() { 20232 return mSafeMode; 20233 } 20234 20235 @Override 20236 public boolean hasSystemUidErrors() { 20237 return mHasSystemUidErrors; 20238 } 20239 20240 static String arrayToString(int[] array) { 20241 StringBuffer buf = new StringBuffer(128); 20242 buf.append('['); 20243 if (array != null) { 20244 for (int i=0; i<array.length; i++) { 20245 if (i > 0) buf.append(", "); 20246 buf.append(array[i]); 20247 } 20248 } 20249 buf.append(']'); 20250 return buf.toString(); 20251 } 20252 20253 static class DumpState { 20254 public static final int DUMP_LIBS = 1 << 0; 20255 public static final int DUMP_FEATURES = 1 << 1; 20256 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20257 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20258 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20259 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20260 public static final int DUMP_PERMISSIONS = 1 << 6; 20261 public static final int DUMP_PACKAGES = 1 << 7; 20262 public static final int DUMP_SHARED_USERS = 1 << 8; 20263 public static final int DUMP_MESSAGES = 1 << 9; 20264 public static final int DUMP_PROVIDERS = 1 << 10; 20265 public static final int DUMP_VERIFIERS = 1 << 11; 20266 public static final int DUMP_PREFERRED = 1 << 12; 20267 public static final int DUMP_PREFERRED_XML = 1 << 13; 20268 public static final int DUMP_KEYSETS = 1 << 14; 20269 public static final int DUMP_VERSION = 1 << 15; 20270 public static final int DUMP_INSTALLS = 1 << 16; 20271 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20272 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20273 public static final int DUMP_FROZEN = 1 << 19; 20274 public static final int DUMP_DEXOPT = 1 << 20; 20275 public static final int DUMP_COMPILER_STATS = 1 << 21; 20276 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20277 20278 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20279 20280 private int mTypes; 20281 20282 private int mOptions; 20283 20284 private boolean mTitlePrinted; 20285 20286 private SharedUserSetting mSharedUser; 20287 20288 public boolean isDumping(int type) { 20289 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20290 return true; 20291 } 20292 20293 return (mTypes & type) != 0; 20294 } 20295 20296 public void setDump(int type) { 20297 mTypes |= type; 20298 } 20299 20300 public boolean isOptionEnabled(int option) { 20301 return (mOptions & option) != 0; 20302 } 20303 20304 public void setOptionEnabled(int option) { 20305 mOptions |= option; 20306 } 20307 20308 public boolean onTitlePrinted() { 20309 final boolean printed = mTitlePrinted; 20310 mTitlePrinted = true; 20311 return printed; 20312 } 20313 20314 public boolean getTitlePrinted() { 20315 return mTitlePrinted; 20316 } 20317 20318 public void setTitlePrinted(boolean enabled) { 20319 mTitlePrinted = enabled; 20320 } 20321 20322 public SharedUserSetting getSharedUser() { 20323 return mSharedUser; 20324 } 20325 20326 public void setSharedUser(SharedUserSetting user) { 20327 mSharedUser = user; 20328 } 20329 } 20330 20331 @Override 20332 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20333 FileDescriptor err, String[] args, ShellCallback callback, 20334 ResultReceiver resultReceiver) { 20335 (new PackageManagerShellCommand(this)).exec( 20336 this, in, out, err, args, callback, resultReceiver); 20337 } 20338 20339 @Override 20340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20341 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20342 20343 DumpState dumpState = new DumpState(); 20344 boolean fullPreferred = false; 20345 boolean checkin = false; 20346 20347 String packageName = null; 20348 ArraySet<String> permissionNames = null; 20349 20350 int opti = 0; 20351 while (opti < args.length) { 20352 String opt = args[opti]; 20353 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20354 break; 20355 } 20356 opti++; 20357 20358 if ("-a".equals(opt)) { 20359 // Right now we only know how to print all. 20360 } else if ("-h".equals(opt)) { 20361 pw.println("Package manager dump options:"); 20362 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20363 pw.println(" --checkin: dump for a checkin"); 20364 pw.println(" -f: print details of intent filters"); 20365 pw.println(" -h: print this help"); 20366 pw.println(" cmd may be one of:"); 20367 pw.println(" l[ibraries]: list known shared libraries"); 20368 pw.println(" f[eatures]: list device features"); 20369 pw.println(" k[eysets]: print known keysets"); 20370 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20371 pw.println(" perm[issions]: dump permissions"); 20372 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20373 pw.println(" pref[erred]: print preferred package settings"); 20374 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20375 pw.println(" prov[iders]: dump content providers"); 20376 pw.println(" p[ackages]: dump installed packages"); 20377 pw.println(" s[hared-users]: dump shared user IDs"); 20378 pw.println(" m[essages]: print collected runtime messages"); 20379 pw.println(" v[erifiers]: print package verifier info"); 20380 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20381 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20382 pw.println(" version: print database version info"); 20383 pw.println(" write: write current settings now"); 20384 pw.println(" installs: details about install sessions"); 20385 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20386 pw.println(" dexopt: dump dexopt state"); 20387 pw.println(" compiler-stats: dump compiler statistics"); 20388 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20389 pw.println(" <package.name>: info about given package"); 20390 return; 20391 } else if ("--checkin".equals(opt)) { 20392 checkin = true; 20393 } else if ("-f".equals(opt)) { 20394 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20395 } else if ("--proto".equals(opt)) { 20396 dumpProto(fd); 20397 return; 20398 } else { 20399 pw.println("Unknown argument: " + opt + "; use -h for help"); 20400 } 20401 } 20402 20403 // Is the caller requesting to dump a particular piece of data? 20404 if (opti < args.length) { 20405 String cmd = args[opti]; 20406 opti++; 20407 // Is this a package name? 20408 if ("android".equals(cmd) || cmd.contains(".")) { 20409 packageName = cmd; 20410 // When dumping a single package, we always dump all of its 20411 // filter information since the amount of data will be reasonable. 20412 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20413 } else if ("check-permission".equals(cmd)) { 20414 if (opti >= args.length) { 20415 pw.println("Error: check-permission missing permission argument"); 20416 return; 20417 } 20418 String perm = args[opti]; 20419 opti++; 20420 if (opti >= args.length) { 20421 pw.println("Error: check-permission missing package argument"); 20422 return; 20423 } 20424 20425 String pkg = args[opti]; 20426 opti++; 20427 int user = UserHandle.getUserId(Binder.getCallingUid()); 20428 if (opti < args.length) { 20429 try { 20430 user = Integer.parseInt(args[opti]); 20431 } catch (NumberFormatException e) { 20432 pw.println("Error: check-permission user argument is not a number: " 20433 + args[opti]); 20434 return; 20435 } 20436 } 20437 20438 // Normalize package name to handle renamed packages and static libs 20439 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20440 20441 pw.println(checkPermission(perm, pkg, user)); 20442 return; 20443 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20444 dumpState.setDump(DumpState.DUMP_LIBS); 20445 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20446 dumpState.setDump(DumpState.DUMP_FEATURES); 20447 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20448 if (opti >= args.length) { 20449 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20450 | DumpState.DUMP_SERVICE_RESOLVERS 20451 | DumpState.DUMP_RECEIVER_RESOLVERS 20452 | DumpState.DUMP_CONTENT_RESOLVERS); 20453 } else { 20454 while (opti < args.length) { 20455 String name = args[opti]; 20456 if ("a".equals(name) || "activity".equals(name)) { 20457 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20458 } else if ("s".equals(name) || "service".equals(name)) { 20459 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20460 } else if ("r".equals(name) || "receiver".equals(name)) { 20461 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20462 } else if ("c".equals(name) || "content".equals(name)) { 20463 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20464 } else { 20465 pw.println("Error: unknown resolver table type: " + name); 20466 return; 20467 } 20468 opti++; 20469 } 20470 } 20471 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20472 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20473 } else if ("permission".equals(cmd)) { 20474 if (opti >= args.length) { 20475 pw.println("Error: permission requires permission name"); 20476 return; 20477 } 20478 permissionNames = new ArraySet<>(); 20479 while (opti < args.length) { 20480 permissionNames.add(args[opti]); 20481 opti++; 20482 } 20483 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20484 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20485 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20486 dumpState.setDump(DumpState.DUMP_PREFERRED); 20487 } else if ("preferred-xml".equals(cmd)) { 20488 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20489 if (opti < args.length && "--full".equals(args[opti])) { 20490 fullPreferred = true; 20491 opti++; 20492 } 20493 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20494 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20495 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20496 dumpState.setDump(DumpState.DUMP_PACKAGES); 20497 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20498 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20499 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20500 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20501 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20502 dumpState.setDump(DumpState.DUMP_MESSAGES); 20503 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20504 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20505 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20506 || "intent-filter-verifiers".equals(cmd)) { 20507 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20508 } else if ("version".equals(cmd)) { 20509 dumpState.setDump(DumpState.DUMP_VERSION); 20510 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20511 dumpState.setDump(DumpState.DUMP_KEYSETS); 20512 } else if ("installs".equals(cmd)) { 20513 dumpState.setDump(DumpState.DUMP_INSTALLS); 20514 } else if ("frozen".equals(cmd)) { 20515 dumpState.setDump(DumpState.DUMP_FROZEN); 20516 } else if ("dexopt".equals(cmd)) { 20517 dumpState.setDump(DumpState.DUMP_DEXOPT); 20518 } else if ("compiler-stats".equals(cmd)) { 20519 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20520 } else if ("enabled-overlays".equals(cmd)) { 20521 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20522 } else if ("write".equals(cmd)) { 20523 synchronized (mPackages) { 20524 mSettings.writeLPr(); 20525 pw.println("Settings written."); 20526 return; 20527 } 20528 } 20529 } 20530 20531 if (checkin) { 20532 pw.println("vers,1"); 20533 } 20534 20535 // reader 20536 synchronized (mPackages) { 20537 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20538 if (!checkin) { 20539 if (dumpState.onTitlePrinted()) 20540 pw.println(); 20541 pw.println("Database versions:"); 20542 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20543 } 20544 } 20545 20546 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20547 if (!checkin) { 20548 if (dumpState.onTitlePrinted()) 20549 pw.println(); 20550 pw.println("Verifiers:"); 20551 pw.print(" Required: "); 20552 pw.print(mRequiredVerifierPackage); 20553 pw.print(" (uid="); 20554 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20555 UserHandle.USER_SYSTEM)); 20556 pw.println(")"); 20557 } else if (mRequiredVerifierPackage != null) { 20558 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20559 pw.print(","); 20560 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20561 UserHandle.USER_SYSTEM)); 20562 } 20563 } 20564 20565 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20566 packageName == null) { 20567 if (mIntentFilterVerifierComponent != null) { 20568 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20569 if (!checkin) { 20570 if (dumpState.onTitlePrinted()) 20571 pw.println(); 20572 pw.println("Intent Filter Verifier:"); 20573 pw.print(" Using: "); 20574 pw.print(verifierPackageName); 20575 pw.print(" (uid="); 20576 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20577 UserHandle.USER_SYSTEM)); 20578 pw.println(")"); 20579 } else if (verifierPackageName != null) { 20580 pw.print("ifv,"); pw.print(verifierPackageName); 20581 pw.print(","); 20582 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20583 UserHandle.USER_SYSTEM)); 20584 } 20585 } else { 20586 pw.println(); 20587 pw.println("No Intent Filter Verifier available!"); 20588 } 20589 } 20590 20591 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20592 boolean printedHeader = false; 20593 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20594 while (it.hasNext()) { 20595 String libName = it.next(); 20596 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20597 if (versionedLib == null) { 20598 continue; 20599 } 20600 final int versionCount = versionedLib.size(); 20601 for (int i = 0; i < versionCount; i++) { 20602 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20603 if (!checkin) { 20604 if (!printedHeader) { 20605 if (dumpState.onTitlePrinted()) 20606 pw.println(); 20607 pw.println("Libraries:"); 20608 printedHeader = true; 20609 } 20610 pw.print(" "); 20611 } else { 20612 pw.print("lib,"); 20613 } 20614 pw.print(libEntry.info.getName()); 20615 if (libEntry.info.isStatic()) { 20616 pw.print(" version=" + libEntry.info.getVersion()); 20617 } 20618 if (!checkin) { 20619 pw.print(" -> "); 20620 } 20621 if (libEntry.path != null) { 20622 pw.print(" (jar) "); 20623 pw.print(libEntry.path); 20624 } else { 20625 pw.print(" (apk) "); 20626 pw.print(libEntry.apk); 20627 } 20628 pw.println(); 20629 } 20630 } 20631 } 20632 20633 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20634 if (dumpState.onTitlePrinted()) 20635 pw.println(); 20636 if (!checkin) { 20637 pw.println("Features:"); 20638 } 20639 20640 synchronized (mAvailableFeatures) { 20641 for (FeatureInfo feat : mAvailableFeatures.values()) { 20642 if (checkin) { 20643 pw.print("feat,"); 20644 pw.print(feat.name); 20645 pw.print(","); 20646 pw.println(feat.version); 20647 } else { 20648 pw.print(" "); 20649 pw.print(feat.name); 20650 if (feat.version > 0) { 20651 pw.print(" version="); 20652 pw.print(feat.version); 20653 } 20654 pw.println(); 20655 } 20656 } 20657 } 20658 } 20659 20660 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20661 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20662 : "Activity Resolver Table:", " ", packageName, 20663 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20664 dumpState.setTitlePrinted(true); 20665 } 20666 } 20667 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20668 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20669 : "Receiver Resolver Table:", " ", packageName, 20670 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20671 dumpState.setTitlePrinted(true); 20672 } 20673 } 20674 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20675 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20676 : "Service Resolver Table:", " ", packageName, 20677 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20678 dumpState.setTitlePrinted(true); 20679 } 20680 } 20681 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20682 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20683 : "Provider Resolver Table:", " ", packageName, 20684 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20685 dumpState.setTitlePrinted(true); 20686 } 20687 } 20688 20689 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20690 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20691 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20692 int user = mSettings.mPreferredActivities.keyAt(i); 20693 if (pir.dump(pw, 20694 dumpState.getTitlePrinted() 20695 ? "\nPreferred Activities User " + user + ":" 20696 : "Preferred Activities User " + user + ":", " ", 20697 packageName, true, false)) { 20698 dumpState.setTitlePrinted(true); 20699 } 20700 } 20701 } 20702 20703 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20704 pw.flush(); 20705 FileOutputStream fout = new FileOutputStream(fd); 20706 BufferedOutputStream str = new BufferedOutputStream(fout); 20707 XmlSerializer serializer = new FastXmlSerializer(); 20708 try { 20709 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20710 serializer.startDocument(null, true); 20711 serializer.setFeature( 20712 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20713 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20714 serializer.endDocument(); 20715 serializer.flush(); 20716 } catch (IllegalArgumentException e) { 20717 pw.println("Failed writing: " + e); 20718 } catch (IllegalStateException e) { 20719 pw.println("Failed writing: " + e); 20720 } catch (IOException e) { 20721 pw.println("Failed writing: " + e); 20722 } 20723 } 20724 20725 if (!checkin 20726 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20727 && packageName == null) { 20728 pw.println(); 20729 int count = mSettings.mPackages.size(); 20730 if (count == 0) { 20731 pw.println("No applications!"); 20732 pw.println(); 20733 } else { 20734 final String prefix = " "; 20735 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20736 if (allPackageSettings.size() == 0) { 20737 pw.println("No domain preferred apps!"); 20738 pw.println(); 20739 } else { 20740 pw.println("App verification status:"); 20741 pw.println(); 20742 count = 0; 20743 for (PackageSetting ps : allPackageSettings) { 20744 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20745 if (ivi == null || ivi.getPackageName() == null) continue; 20746 pw.println(prefix + "Package: " + ivi.getPackageName()); 20747 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20748 pw.println(prefix + "Status: " + ivi.getStatusString()); 20749 pw.println(); 20750 count++; 20751 } 20752 if (count == 0) { 20753 pw.println(prefix + "No app verification established."); 20754 pw.println(); 20755 } 20756 for (int userId : sUserManager.getUserIds()) { 20757 pw.println("App linkages for user " + userId + ":"); 20758 pw.println(); 20759 count = 0; 20760 for (PackageSetting ps : allPackageSettings) { 20761 final long status = ps.getDomainVerificationStatusForUser(userId); 20762 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20763 && !DEBUG_DOMAIN_VERIFICATION) { 20764 continue; 20765 } 20766 pw.println(prefix + "Package: " + ps.name); 20767 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20768 String statusStr = IntentFilterVerificationInfo. 20769 getStatusStringFromValue(status); 20770 pw.println(prefix + "Status: " + statusStr); 20771 pw.println(); 20772 count++; 20773 } 20774 if (count == 0) { 20775 pw.println(prefix + "No configured app linkages."); 20776 pw.println(); 20777 } 20778 } 20779 } 20780 } 20781 } 20782 20783 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20784 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20785 if (packageName == null && permissionNames == null) { 20786 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20787 if (iperm == 0) { 20788 if (dumpState.onTitlePrinted()) 20789 pw.println(); 20790 pw.println("AppOp Permissions:"); 20791 } 20792 pw.print(" AppOp Permission "); 20793 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20794 pw.println(":"); 20795 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20796 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20797 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20798 } 20799 } 20800 } 20801 } 20802 20803 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20804 boolean printedSomething = false; 20805 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20806 if (packageName != null && !packageName.equals(p.info.packageName)) { 20807 continue; 20808 } 20809 if (!printedSomething) { 20810 if (dumpState.onTitlePrinted()) 20811 pw.println(); 20812 pw.println("Registered ContentProviders:"); 20813 printedSomething = true; 20814 } 20815 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20816 pw.print(" "); pw.println(p.toString()); 20817 } 20818 printedSomething = false; 20819 for (Map.Entry<String, PackageParser.Provider> entry : 20820 mProvidersByAuthority.entrySet()) { 20821 PackageParser.Provider p = entry.getValue(); 20822 if (packageName != null && !packageName.equals(p.info.packageName)) { 20823 continue; 20824 } 20825 if (!printedSomething) { 20826 if (dumpState.onTitlePrinted()) 20827 pw.println(); 20828 pw.println("ContentProvider Authorities:"); 20829 printedSomething = true; 20830 } 20831 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20832 pw.print(" "); pw.println(p.toString()); 20833 if (p.info != null && p.info.applicationInfo != null) { 20834 final String appInfo = p.info.applicationInfo.toString(); 20835 pw.print(" applicationInfo="); pw.println(appInfo); 20836 } 20837 } 20838 } 20839 20840 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20841 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20842 } 20843 20844 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20845 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20846 } 20847 20848 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20849 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20850 } 20851 20852 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20853 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20854 } 20855 20856 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20857 // XXX should handle packageName != null by dumping only install data that 20858 // the given package is involved with. 20859 if (dumpState.onTitlePrinted()) pw.println(); 20860 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20861 } 20862 20863 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20864 // XXX should handle packageName != null by dumping only install data that 20865 // the given package is involved with. 20866 if (dumpState.onTitlePrinted()) pw.println(); 20867 20868 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20869 ipw.println(); 20870 ipw.println("Frozen packages:"); 20871 ipw.increaseIndent(); 20872 if (mFrozenPackages.size() == 0) { 20873 ipw.println("(none)"); 20874 } else { 20875 for (int i = 0; i < mFrozenPackages.size(); i++) { 20876 ipw.println(mFrozenPackages.valueAt(i)); 20877 } 20878 } 20879 ipw.decreaseIndent(); 20880 } 20881 20882 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20883 if (dumpState.onTitlePrinted()) pw.println(); 20884 dumpDexoptStateLPr(pw, packageName); 20885 } 20886 20887 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20888 if (dumpState.onTitlePrinted()) pw.println(); 20889 dumpCompilerStatsLPr(pw, packageName); 20890 } 20891 20892 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20893 if (dumpState.onTitlePrinted()) pw.println(); 20894 dumpEnabledOverlaysLPr(pw); 20895 } 20896 20897 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20898 if (dumpState.onTitlePrinted()) pw.println(); 20899 mSettings.dumpReadMessagesLPr(pw, dumpState); 20900 20901 pw.println(); 20902 pw.println("Package warning messages:"); 20903 BufferedReader in = null; 20904 String line = null; 20905 try { 20906 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20907 while ((line = in.readLine()) != null) { 20908 if (line.contains("ignored: updated version")) continue; 20909 pw.println(line); 20910 } 20911 } catch (IOException ignored) { 20912 } finally { 20913 IoUtils.closeQuietly(in); 20914 } 20915 } 20916 20917 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20918 BufferedReader in = null; 20919 String line = null; 20920 try { 20921 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20922 while ((line = in.readLine()) != null) { 20923 if (line.contains("ignored: updated version")) continue; 20924 pw.print("msg,"); 20925 pw.println(line); 20926 } 20927 } catch (IOException ignored) { 20928 } finally { 20929 IoUtils.closeQuietly(in); 20930 } 20931 } 20932 } 20933 } 20934 20935 private void dumpProto(FileDescriptor fd) { 20936 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20937 20938 synchronized (mPackages) { 20939 final long requiredVerifierPackageToken = 20940 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20941 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20942 proto.write( 20943 PackageServiceDumpProto.PackageShortProto.UID, 20944 getPackageUid( 20945 mRequiredVerifierPackage, 20946 MATCH_DEBUG_TRIAGED_MISSING, 20947 UserHandle.USER_SYSTEM)); 20948 proto.end(requiredVerifierPackageToken); 20949 20950 if (mIntentFilterVerifierComponent != null) { 20951 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20952 final long verifierPackageToken = 20953 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20954 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20955 proto.write( 20956 PackageServiceDumpProto.PackageShortProto.UID, 20957 getPackageUid( 20958 verifierPackageName, 20959 MATCH_DEBUG_TRIAGED_MISSING, 20960 UserHandle.USER_SYSTEM)); 20961 proto.end(verifierPackageToken); 20962 } 20963 20964 dumpSharedLibrariesProto(proto); 20965 dumpFeaturesProto(proto); 20966 mSettings.dumpPackagesProto(proto); 20967 mSettings.dumpSharedUsersProto(proto); 20968 dumpMessagesProto(proto); 20969 } 20970 proto.flush(); 20971 } 20972 20973 private void dumpMessagesProto(ProtoOutputStream proto) { 20974 BufferedReader in = null; 20975 String line = null; 20976 try { 20977 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20978 while ((line = in.readLine()) != null) { 20979 if (line.contains("ignored: updated version")) continue; 20980 proto.write(PackageServiceDumpProto.MESSAGES, line); 20981 } 20982 } catch (IOException ignored) { 20983 } finally { 20984 IoUtils.closeQuietly(in); 20985 } 20986 } 20987 20988 private void dumpFeaturesProto(ProtoOutputStream proto) { 20989 synchronized (mAvailableFeatures) { 20990 final int count = mAvailableFeatures.size(); 20991 for (int i = 0; i < count; i++) { 20992 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20993 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20994 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20995 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20996 proto.end(featureToken); 20997 } 20998 } 20999 } 21000 21001 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21002 final int count = mSharedLibraries.size(); 21003 for (int i = 0; i < count; i++) { 21004 final String libName = mSharedLibraries.keyAt(i); 21005 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21006 if (versionedLib == null) { 21007 continue; 21008 } 21009 final int versionCount = versionedLib.size(); 21010 for (int j = 0; j < versionCount; j++) { 21011 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21012 final long sharedLibraryToken = 21013 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21014 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21015 final boolean isJar = (libEntry.path != null); 21016 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21017 if (isJar) { 21018 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21019 } else { 21020 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21021 } 21022 proto.end(sharedLibraryToken); 21023 } 21024 } 21025 } 21026 21027 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21028 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21029 ipw.println(); 21030 ipw.println("Dexopt state:"); 21031 ipw.increaseIndent(); 21032 Collection<PackageParser.Package> packages = null; 21033 if (packageName != null) { 21034 PackageParser.Package targetPackage = mPackages.get(packageName); 21035 if (targetPackage != null) { 21036 packages = Collections.singletonList(targetPackage); 21037 } else { 21038 ipw.println("Unable to find package: " + packageName); 21039 return; 21040 } 21041 } else { 21042 packages = mPackages.values(); 21043 } 21044 21045 for (PackageParser.Package pkg : packages) { 21046 ipw.println("[" + pkg.packageName + "]"); 21047 ipw.increaseIndent(); 21048 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21049 ipw.decreaseIndent(); 21050 } 21051 } 21052 21053 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21054 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21055 ipw.println(); 21056 ipw.println("Compiler stats:"); 21057 ipw.increaseIndent(); 21058 Collection<PackageParser.Package> packages = null; 21059 if (packageName != null) { 21060 PackageParser.Package targetPackage = mPackages.get(packageName); 21061 if (targetPackage != null) { 21062 packages = Collections.singletonList(targetPackage); 21063 } else { 21064 ipw.println("Unable to find package: " + packageName); 21065 return; 21066 } 21067 } else { 21068 packages = mPackages.values(); 21069 } 21070 21071 for (PackageParser.Package pkg : packages) { 21072 ipw.println("[" + pkg.packageName + "]"); 21073 ipw.increaseIndent(); 21074 21075 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21076 if (stats == null) { 21077 ipw.println("(No recorded stats)"); 21078 } else { 21079 stats.dump(ipw); 21080 } 21081 ipw.decreaseIndent(); 21082 } 21083 } 21084 21085 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21086 pw.println("Enabled overlay paths:"); 21087 final int N = mEnabledOverlayPaths.size(); 21088 for (int i = 0; i < N; i++) { 21089 final int userId = mEnabledOverlayPaths.keyAt(i); 21090 pw.println(String.format(" User %d:", userId)); 21091 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21092 mEnabledOverlayPaths.valueAt(i); 21093 final int M = userSpecificOverlays.size(); 21094 for (int j = 0; j < M; j++) { 21095 final String targetPackageName = userSpecificOverlays.keyAt(j); 21096 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21097 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21098 } 21099 } 21100 } 21101 21102 private String dumpDomainString(String packageName) { 21103 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21104 .getList(); 21105 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21106 21107 ArraySet<String> result = new ArraySet<>(); 21108 if (iviList.size() > 0) { 21109 for (IntentFilterVerificationInfo ivi : iviList) { 21110 for (String host : ivi.getDomains()) { 21111 result.add(host); 21112 } 21113 } 21114 } 21115 if (filters != null && filters.size() > 0) { 21116 for (IntentFilter filter : filters) { 21117 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21118 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21119 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21120 result.addAll(filter.getHostsList()); 21121 } 21122 } 21123 } 21124 21125 StringBuilder sb = new StringBuilder(result.size() * 16); 21126 for (String domain : result) { 21127 if (sb.length() > 0) sb.append(" "); 21128 sb.append(domain); 21129 } 21130 return sb.toString(); 21131 } 21132 21133 // ------- apps on sdcard specific code ------- 21134 static final boolean DEBUG_SD_INSTALL = false; 21135 21136 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21137 21138 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21139 21140 private boolean mMediaMounted = false; 21141 21142 static String getEncryptKey() { 21143 try { 21144 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21145 SD_ENCRYPTION_KEYSTORE_NAME); 21146 if (sdEncKey == null) { 21147 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21148 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21149 if (sdEncKey == null) { 21150 Slog.e(TAG, "Failed to create encryption keys"); 21151 return null; 21152 } 21153 } 21154 return sdEncKey; 21155 } catch (NoSuchAlgorithmException nsae) { 21156 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21157 return null; 21158 } catch (IOException ioe) { 21159 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21160 return null; 21161 } 21162 } 21163 21164 /* 21165 * Update media status on PackageManager. 21166 */ 21167 @Override 21168 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21169 int callingUid = Binder.getCallingUid(); 21170 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21171 throw new SecurityException("Media status can only be updated by the system"); 21172 } 21173 // reader; this apparently protects mMediaMounted, but should probably 21174 // be a different lock in that case. 21175 synchronized (mPackages) { 21176 Log.i(TAG, "Updating external media status from " 21177 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21178 + (mediaStatus ? "mounted" : "unmounted")); 21179 if (DEBUG_SD_INSTALL) 21180 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21181 + ", mMediaMounted=" + mMediaMounted); 21182 if (mediaStatus == mMediaMounted) { 21183 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21184 : 0, -1); 21185 mHandler.sendMessage(msg); 21186 return; 21187 } 21188 mMediaMounted = mediaStatus; 21189 } 21190 // Queue up an async operation since the package installation may take a 21191 // little while. 21192 mHandler.post(new Runnable() { 21193 public void run() { 21194 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21195 } 21196 }); 21197 } 21198 21199 /** 21200 * Called by StorageManagerService when the initial ASECs to scan are available. 21201 * Should block until all the ASEC containers are finished being scanned. 21202 */ 21203 public void scanAvailableAsecs() { 21204 updateExternalMediaStatusInner(true, false, false); 21205 } 21206 21207 /* 21208 * Collect information of applications on external media, map them against 21209 * existing containers and update information based on current mount status. 21210 * Please note that we always have to report status if reportStatus has been 21211 * set to true especially when unloading packages. 21212 */ 21213 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21214 boolean externalStorage) { 21215 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21216 int[] uidArr = EmptyArray.INT; 21217 21218 final String[] list = PackageHelper.getSecureContainerList(); 21219 if (ArrayUtils.isEmpty(list)) { 21220 Log.i(TAG, "No secure containers found"); 21221 } else { 21222 // Process list of secure containers and categorize them 21223 // as active or stale based on their package internal state. 21224 21225 // reader 21226 synchronized (mPackages) { 21227 for (String cid : list) { 21228 // Leave stages untouched for now; installer service owns them 21229 if (PackageInstallerService.isStageName(cid)) continue; 21230 21231 if (DEBUG_SD_INSTALL) 21232 Log.i(TAG, "Processing container " + cid); 21233 String pkgName = getAsecPackageName(cid); 21234 if (pkgName == null) { 21235 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21236 continue; 21237 } 21238 if (DEBUG_SD_INSTALL) 21239 Log.i(TAG, "Looking for pkg : " + pkgName); 21240 21241 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21242 if (ps == null) { 21243 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21244 continue; 21245 } 21246 21247 /* 21248 * Skip packages that are not external if we're unmounting 21249 * external storage. 21250 */ 21251 if (externalStorage && !isMounted && !isExternal(ps)) { 21252 continue; 21253 } 21254 21255 final AsecInstallArgs args = new AsecInstallArgs(cid, 21256 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21257 // The package status is changed only if the code path 21258 // matches between settings and the container id. 21259 if (ps.codePathString != null 21260 && ps.codePathString.startsWith(args.getCodePath())) { 21261 if (DEBUG_SD_INSTALL) { 21262 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21263 + " at code path: " + ps.codePathString); 21264 } 21265 21266 // We do have a valid package installed on sdcard 21267 processCids.put(args, ps.codePathString); 21268 final int uid = ps.appId; 21269 if (uid != -1) { 21270 uidArr = ArrayUtils.appendInt(uidArr, uid); 21271 } 21272 } else { 21273 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21274 + ps.codePathString); 21275 } 21276 } 21277 } 21278 21279 Arrays.sort(uidArr); 21280 } 21281 21282 // Process packages with valid entries. 21283 if (isMounted) { 21284 if (DEBUG_SD_INSTALL) 21285 Log.i(TAG, "Loading packages"); 21286 loadMediaPackages(processCids, uidArr, externalStorage); 21287 startCleaningPackages(); 21288 mInstallerService.onSecureContainersAvailable(); 21289 } else { 21290 if (DEBUG_SD_INSTALL) 21291 Log.i(TAG, "Unloading packages"); 21292 unloadMediaPackages(processCids, uidArr, reportStatus); 21293 } 21294 } 21295 21296 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21297 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21298 final int size = infos.size(); 21299 final String[] packageNames = new String[size]; 21300 final int[] packageUids = new int[size]; 21301 for (int i = 0; i < size; i++) { 21302 final ApplicationInfo info = infos.get(i); 21303 packageNames[i] = info.packageName; 21304 packageUids[i] = info.uid; 21305 } 21306 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21307 finishedReceiver); 21308 } 21309 21310 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21311 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21312 sendResourcesChangedBroadcast(mediaStatus, replacing, 21313 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21314 } 21315 21316 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21317 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21318 int size = pkgList.length; 21319 if (size > 0) { 21320 // Send broadcasts here 21321 Bundle extras = new Bundle(); 21322 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21323 if (uidArr != null) { 21324 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21325 } 21326 if (replacing) { 21327 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21328 } 21329 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21330 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21331 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21332 } 21333 } 21334 21335 /* 21336 * Look at potentially valid container ids from processCids If package 21337 * information doesn't match the one on record or package scanning fails, 21338 * the cid is added to list of removeCids. We currently don't delete stale 21339 * containers. 21340 */ 21341 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21342 boolean externalStorage) { 21343 ArrayList<String> pkgList = new ArrayList<String>(); 21344 Set<AsecInstallArgs> keys = processCids.keySet(); 21345 21346 for (AsecInstallArgs args : keys) { 21347 String codePath = processCids.get(args); 21348 if (DEBUG_SD_INSTALL) 21349 Log.i(TAG, "Loading container : " + args.cid); 21350 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21351 try { 21352 // Make sure there are no container errors first. 21353 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21354 Slog.e(TAG, "Failed to mount cid : " + args.cid 21355 + " when installing from sdcard"); 21356 continue; 21357 } 21358 // Check code path here. 21359 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21360 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21361 + " does not match one in settings " + codePath); 21362 continue; 21363 } 21364 // Parse package 21365 int parseFlags = mDefParseFlags; 21366 if (args.isExternalAsec()) { 21367 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21368 } 21369 if (args.isFwdLocked()) { 21370 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21371 } 21372 21373 synchronized (mInstallLock) { 21374 PackageParser.Package pkg = null; 21375 try { 21376 // Sadly we don't know the package name yet to freeze it 21377 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21378 SCAN_IGNORE_FROZEN, 0, null); 21379 } catch (PackageManagerException e) { 21380 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21381 } 21382 // Scan the package 21383 if (pkg != null) { 21384 /* 21385 * TODO why is the lock being held? doPostInstall is 21386 * called in other places without the lock. This needs 21387 * to be straightened out. 21388 */ 21389 // writer 21390 synchronized (mPackages) { 21391 retCode = PackageManager.INSTALL_SUCCEEDED; 21392 pkgList.add(pkg.packageName); 21393 // Post process args 21394 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21395 pkg.applicationInfo.uid); 21396 } 21397 } else { 21398 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21399 } 21400 } 21401 21402 } finally { 21403 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21404 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21405 } 21406 } 21407 } 21408 // writer 21409 synchronized (mPackages) { 21410 // If the platform SDK has changed since the last time we booted, 21411 // we need to re-grant app permission to catch any new ones that 21412 // appear. This is really a hack, and means that apps can in some 21413 // cases get permissions that the user didn't initially explicitly 21414 // allow... it would be nice to have some better way to handle 21415 // this situation. 21416 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21417 : mSettings.getInternalVersion(); 21418 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21419 : StorageManager.UUID_PRIVATE_INTERNAL; 21420 21421 int updateFlags = UPDATE_PERMISSIONS_ALL; 21422 if (ver.sdkVersion != mSdkVersion) { 21423 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21424 + mSdkVersion + "; regranting permissions for external"); 21425 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21426 } 21427 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21428 21429 // Yay, everything is now upgraded 21430 ver.forceCurrent(); 21431 21432 // can downgrade to reader 21433 // Persist settings 21434 mSettings.writeLPr(); 21435 } 21436 // Send a broadcast to let everyone know we are done processing 21437 if (pkgList.size() > 0) { 21438 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21439 } 21440 } 21441 21442 /* 21443 * Utility method to unload a list of specified containers 21444 */ 21445 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21446 // Just unmount all valid containers. 21447 for (AsecInstallArgs arg : cidArgs) { 21448 synchronized (mInstallLock) { 21449 arg.doPostDeleteLI(false); 21450 } 21451 } 21452 } 21453 21454 /* 21455 * Unload packages mounted on external media. This involves deleting package 21456 * data from internal structures, sending broadcasts about disabled packages, 21457 * gc'ing to free up references, unmounting all secure containers 21458 * corresponding to packages on external media, and posting a 21459 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21460 * that we always have to post this message if status has been requested no 21461 * matter what. 21462 */ 21463 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21464 final boolean reportStatus) { 21465 if (DEBUG_SD_INSTALL) 21466 Log.i(TAG, "unloading media packages"); 21467 ArrayList<String> pkgList = new ArrayList<String>(); 21468 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21469 final Set<AsecInstallArgs> keys = processCids.keySet(); 21470 for (AsecInstallArgs args : keys) { 21471 String pkgName = args.getPackageName(); 21472 if (DEBUG_SD_INSTALL) 21473 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21474 // Delete package internally 21475 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21476 synchronized (mInstallLock) { 21477 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21478 final boolean res; 21479 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21480 "unloadMediaPackages")) { 21481 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21482 null); 21483 } 21484 if (res) { 21485 pkgList.add(pkgName); 21486 } else { 21487 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21488 failedList.add(args); 21489 } 21490 } 21491 } 21492 21493 // reader 21494 synchronized (mPackages) { 21495 // We didn't update the settings after removing each package; 21496 // write them now for all packages. 21497 mSettings.writeLPr(); 21498 } 21499 21500 // We have to absolutely send UPDATED_MEDIA_STATUS only 21501 // after confirming that all the receivers processed the ordered 21502 // broadcast when packages get disabled, force a gc to clean things up. 21503 // and unload all the containers. 21504 if (pkgList.size() > 0) { 21505 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21506 new IIntentReceiver.Stub() { 21507 public void performReceive(Intent intent, int resultCode, String data, 21508 Bundle extras, boolean ordered, boolean sticky, 21509 int sendingUser) throws RemoteException { 21510 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21511 reportStatus ? 1 : 0, 1, keys); 21512 mHandler.sendMessage(msg); 21513 } 21514 }); 21515 } else { 21516 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21517 keys); 21518 mHandler.sendMessage(msg); 21519 } 21520 } 21521 21522 private void loadPrivatePackages(final VolumeInfo vol) { 21523 mHandler.post(new Runnable() { 21524 @Override 21525 public void run() { 21526 loadPrivatePackagesInner(vol); 21527 } 21528 }); 21529 } 21530 21531 private void loadPrivatePackagesInner(VolumeInfo vol) { 21532 final String volumeUuid = vol.fsUuid; 21533 if (TextUtils.isEmpty(volumeUuid)) { 21534 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21535 return; 21536 } 21537 21538 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21539 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21540 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21541 21542 final VersionInfo ver; 21543 final List<PackageSetting> packages; 21544 synchronized (mPackages) { 21545 ver = mSettings.findOrCreateVersion(volumeUuid); 21546 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21547 } 21548 21549 for (PackageSetting ps : packages) { 21550 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21551 synchronized (mInstallLock) { 21552 final PackageParser.Package pkg; 21553 try { 21554 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21555 loaded.add(pkg.applicationInfo); 21556 21557 } catch (PackageManagerException e) { 21558 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21559 } 21560 21561 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21562 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21563 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21564 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21565 } 21566 } 21567 } 21568 21569 // Reconcile app data for all started/unlocked users 21570 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21571 final UserManager um = mContext.getSystemService(UserManager.class); 21572 UserManagerInternal umInternal = getUserManagerInternal(); 21573 for (UserInfo user : um.getUsers()) { 21574 final int flags; 21575 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21576 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21577 } else if (umInternal.isUserRunning(user.id)) { 21578 flags = StorageManager.FLAG_STORAGE_DE; 21579 } else { 21580 continue; 21581 } 21582 21583 try { 21584 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21585 synchronized (mInstallLock) { 21586 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21587 } 21588 } catch (IllegalStateException e) { 21589 // Device was probably ejected, and we'll process that event momentarily 21590 Slog.w(TAG, "Failed to prepare storage: " + e); 21591 } 21592 } 21593 21594 synchronized (mPackages) { 21595 int updateFlags = UPDATE_PERMISSIONS_ALL; 21596 if (ver.sdkVersion != mSdkVersion) { 21597 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21598 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21599 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21600 } 21601 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21602 21603 // Yay, everything is now upgraded 21604 ver.forceCurrent(); 21605 21606 mSettings.writeLPr(); 21607 } 21608 21609 for (PackageFreezer freezer : freezers) { 21610 freezer.close(); 21611 } 21612 21613 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21614 sendResourcesChangedBroadcast(true, false, loaded, null); 21615 } 21616 21617 private void unloadPrivatePackages(final VolumeInfo vol) { 21618 mHandler.post(new Runnable() { 21619 @Override 21620 public void run() { 21621 unloadPrivatePackagesInner(vol); 21622 } 21623 }); 21624 } 21625 21626 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21627 final String volumeUuid = vol.fsUuid; 21628 if (TextUtils.isEmpty(volumeUuid)) { 21629 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21630 return; 21631 } 21632 21633 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21634 synchronized (mInstallLock) { 21635 synchronized (mPackages) { 21636 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21637 for (PackageSetting ps : packages) { 21638 if (ps.pkg == null) continue; 21639 21640 final ApplicationInfo info = ps.pkg.applicationInfo; 21641 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21642 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21643 21644 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21645 "unloadPrivatePackagesInner")) { 21646 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21647 false, null)) { 21648 unloaded.add(info); 21649 } else { 21650 Slog.w(TAG, "Failed to unload " + ps.codePath); 21651 } 21652 } 21653 21654 // Try very hard to release any references to this package 21655 // so we don't risk the system server being killed due to 21656 // open FDs 21657 AttributeCache.instance().removePackage(ps.name); 21658 } 21659 21660 mSettings.writeLPr(); 21661 } 21662 } 21663 21664 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21665 sendResourcesChangedBroadcast(false, false, unloaded, null); 21666 21667 // Try very hard to release any references to this path so we don't risk 21668 // the system server being killed due to open FDs 21669 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21670 21671 for (int i = 0; i < 3; i++) { 21672 System.gc(); 21673 System.runFinalization(); 21674 } 21675 } 21676 21677 private void assertPackageKnown(String volumeUuid, String packageName) 21678 throws PackageManagerException { 21679 synchronized (mPackages) { 21680 // Normalize package name to handle renamed packages 21681 packageName = normalizePackageNameLPr(packageName); 21682 21683 final PackageSetting ps = mSettings.mPackages.get(packageName); 21684 if (ps == null) { 21685 throw new PackageManagerException("Package " + packageName + " is unknown"); 21686 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21687 throw new PackageManagerException( 21688 "Package " + packageName + " found on unknown volume " + volumeUuid 21689 + "; expected volume " + ps.volumeUuid); 21690 } 21691 } 21692 } 21693 21694 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21695 throws PackageManagerException { 21696 synchronized (mPackages) { 21697 // Normalize package name to handle renamed packages 21698 packageName = normalizePackageNameLPr(packageName); 21699 21700 final PackageSetting ps = mSettings.mPackages.get(packageName); 21701 if (ps == null) { 21702 throw new PackageManagerException("Package " + packageName + " is unknown"); 21703 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21704 throw new PackageManagerException( 21705 "Package " + packageName + " found on unknown volume " + volumeUuid 21706 + "; expected volume " + ps.volumeUuid); 21707 } else if (!ps.getInstalled(userId)) { 21708 throw new PackageManagerException( 21709 "Package " + packageName + " not installed for user " + userId); 21710 } 21711 } 21712 } 21713 21714 private List<String> collectAbsoluteCodePaths() { 21715 synchronized (mPackages) { 21716 List<String> codePaths = new ArrayList<>(); 21717 final int packageCount = mSettings.mPackages.size(); 21718 for (int i = 0; i < packageCount; i++) { 21719 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21720 codePaths.add(ps.codePath.getAbsolutePath()); 21721 } 21722 return codePaths; 21723 } 21724 } 21725 21726 /** 21727 * Examine all apps present on given mounted volume, and destroy apps that 21728 * aren't expected, either due to uninstallation or reinstallation on 21729 * another volume. 21730 */ 21731 private void reconcileApps(String volumeUuid) { 21732 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21733 List<File> filesToDelete = null; 21734 21735 final File[] files = FileUtils.listFilesOrEmpty( 21736 Environment.getDataAppDirectory(volumeUuid)); 21737 for (File file : files) { 21738 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21739 && !PackageInstallerService.isStageName(file.getName()); 21740 if (!isPackage) { 21741 // Ignore entries which are not packages 21742 continue; 21743 } 21744 21745 String absolutePath = file.getAbsolutePath(); 21746 21747 boolean pathValid = false; 21748 final int absoluteCodePathCount = absoluteCodePaths.size(); 21749 for (int i = 0; i < absoluteCodePathCount; i++) { 21750 String absoluteCodePath = absoluteCodePaths.get(i); 21751 if (absolutePath.startsWith(absoluteCodePath)) { 21752 pathValid = true; 21753 break; 21754 } 21755 } 21756 21757 if (!pathValid) { 21758 if (filesToDelete == null) { 21759 filesToDelete = new ArrayList<>(); 21760 } 21761 filesToDelete.add(file); 21762 } 21763 } 21764 21765 if (filesToDelete != null) { 21766 final int fileToDeleteCount = filesToDelete.size(); 21767 for (int i = 0; i < fileToDeleteCount; i++) { 21768 File fileToDelete = filesToDelete.get(i); 21769 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21770 synchronized (mInstallLock) { 21771 removeCodePathLI(fileToDelete); 21772 } 21773 } 21774 } 21775 } 21776 21777 /** 21778 * Reconcile all app data for the given user. 21779 * <p> 21780 * Verifies that directories exist and that ownership and labeling is 21781 * correct for all installed apps on all mounted volumes. 21782 */ 21783 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21784 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21785 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21786 final String volumeUuid = vol.getFsUuid(); 21787 synchronized (mInstallLock) { 21788 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21789 } 21790 } 21791 } 21792 21793 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21794 boolean migrateAppData) { 21795 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21796 } 21797 21798 /** 21799 * Reconcile all app data on given mounted volume. 21800 * <p> 21801 * Destroys app data that isn't expected, either due to uninstallation or 21802 * reinstallation on another volume. 21803 * <p> 21804 * Verifies that directories exist and that ownership and labeling is 21805 * correct for all installed apps. 21806 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21807 */ 21808 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21809 boolean migrateAppData, boolean onlyCoreApps) { 21810 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21811 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21812 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21813 21814 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21815 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21816 21817 // First look for stale data that doesn't belong, and check if things 21818 // have changed since we did our last restorecon 21819 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21820 if (StorageManager.isFileEncryptedNativeOrEmulated() 21821 && !StorageManager.isUserKeyUnlocked(userId)) { 21822 throw new RuntimeException( 21823 "Yikes, someone asked us to reconcile CE storage while " + userId 21824 + " was still locked; this would have caused massive data loss!"); 21825 } 21826 21827 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21828 for (File file : files) { 21829 final String packageName = file.getName(); 21830 try { 21831 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21832 } catch (PackageManagerException e) { 21833 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21834 try { 21835 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21836 StorageManager.FLAG_STORAGE_CE, 0); 21837 } catch (InstallerException e2) { 21838 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21839 } 21840 } 21841 } 21842 } 21843 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21844 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21845 for (File file : files) { 21846 final String packageName = file.getName(); 21847 try { 21848 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21849 } catch (PackageManagerException e) { 21850 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21851 try { 21852 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21853 StorageManager.FLAG_STORAGE_DE, 0); 21854 } catch (InstallerException e2) { 21855 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21856 } 21857 } 21858 } 21859 } 21860 21861 // Ensure that data directories are ready to roll for all packages 21862 // installed for this volume and user 21863 final List<PackageSetting> packages; 21864 synchronized (mPackages) { 21865 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21866 } 21867 int preparedCount = 0; 21868 for (PackageSetting ps : packages) { 21869 final String packageName = ps.name; 21870 if (ps.pkg == null) { 21871 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21872 // TODO: might be due to legacy ASEC apps; we should circle back 21873 // and reconcile again once they're scanned 21874 continue; 21875 } 21876 // Skip non-core apps if requested 21877 if (onlyCoreApps && !ps.pkg.coreApp) { 21878 result.add(packageName); 21879 continue; 21880 } 21881 21882 if (ps.getInstalled(userId)) { 21883 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21884 preparedCount++; 21885 } 21886 } 21887 21888 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21889 return result; 21890 } 21891 21892 /** 21893 * Prepare app data for the given app just after it was installed or 21894 * upgraded. This method carefully only touches users that it's installed 21895 * for, and it forces a restorecon to handle any seinfo changes. 21896 * <p> 21897 * Verifies that directories exist and that ownership and labeling is 21898 * correct for all installed apps. If there is an ownership mismatch, it 21899 * will try recovering system apps by wiping data; third-party app data is 21900 * left intact. 21901 * <p> 21902 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21903 */ 21904 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21905 final PackageSetting ps; 21906 synchronized (mPackages) { 21907 ps = mSettings.mPackages.get(pkg.packageName); 21908 mSettings.writeKernelMappingLPr(ps); 21909 } 21910 21911 final UserManager um = mContext.getSystemService(UserManager.class); 21912 UserManagerInternal umInternal = getUserManagerInternal(); 21913 for (UserInfo user : um.getUsers()) { 21914 final int flags; 21915 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21916 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21917 } else if (umInternal.isUserRunning(user.id)) { 21918 flags = StorageManager.FLAG_STORAGE_DE; 21919 } else { 21920 continue; 21921 } 21922 21923 if (ps.getInstalled(user.id)) { 21924 // TODO: when user data is locked, mark that we're still dirty 21925 prepareAppDataLIF(pkg, user.id, flags); 21926 } 21927 } 21928 } 21929 21930 /** 21931 * Prepare app data for the given app. 21932 * <p> 21933 * Verifies that directories exist and that ownership and labeling is 21934 * correct for all installed apps. If there is an ownership mismatch, this 21935 * will try recovering system apps by wiping data; third-party app data is 21936 * left intact. 21937 */ 21938 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21939 if (pkg == null) { 21940 Slog.wtf(TAG, "Package was null!", new Throwable()); 21941 return; 21942 } 21943 prepareAppDataLeafLIF(pkg, userId, flags); 21944 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21945 for (int i = 0; i < childCount; i++) { 21946 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21947 } 21948 } 21949 21950 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21951 boolean maybeMigrateAppData) { 21952 prepareAppDataLIF(pkg, userId, flags); 21953 21954 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21955 // We may have just shuffled around app data directories, so 21956 // prepare them one more time 21957 prepareAppDataLIF(pkg, userId, flags); 21958 } 21959 } 21960 21961 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21962 if (DEBUG_APP_DATA) { 21963 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21964 + Integer.toHexString(flags)); 21965 } 21966 21967 final String volumeUuid = pkg.volumeUuid; 21968 final String packageName = pkg.packageName; 21969 final ApplicationInfo app = pkg.applicationInfo; 21970 final int appId = UserHandle.getAppId(app.uid); 21971 21972 Preconditions.checkNotNull(app.seInfo); 21973 21974 long ceDataInode = -1; 21975 try { 21976 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21977 appId, app.seInfo, app.targetSdkVersion); 21978 } catch (InstallerException e) { 21979 if (app.isSystemApp()) { 21980 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21981 + ", but trying to recover: " + e); 21982 destroyAppDataLeafLIF(pkg, userId, flags); 21983 try { 21984 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21985 appId, app.seInfo, app.targetSdkVersion); 21986 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21987 } catch (InstallerException e2) { 21988 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21989 } 21990 } else { 21991 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21992 } 21993 } 21994 21995 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21996 // TODO: mark this structure as dirty so we persist it! 21997 synchronized (mPackages) { 21998 final PackageSetting ps = mSettings.mPackages.get(packageName); 21999 if (ps != null) { 22000 ps.setCeDataInode(ceDataInode, userId); 22001 } 22002 } 22003 } 22004 22005 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22006 } 22007 22008 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22009 if (pkg == null) { 22010 Slog.wtf(TAG, "Package was null!", new Throwable()); 22011 return; 22012 } 22013 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22014 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22015 for (int i = 0; i < childCount; i++) { 22016 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22017 } 22018 } 22019 22020 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22021 final String volumeUuid = pkg.volumeUuid; 22022 final String packageName = pkg.packageName; 22023 final ApplicationInfo app = pkg.applicationInfo; 22024 22025 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22026 // Create a native library symlink only if we have native libraries 22027 // and if the native libraries are 32 bit libraries. We do not provide 22028 // this symlink for 64 bit libraries. 22029 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22030 final String nativeLibPath = app.nativeLibraryDir; 22031 try { 22032 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22033 nativeLibPath, userId); 22034 } catch (InstallerException e) { 22035 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22036 } 22037 } 22038 } 22039 } 22040 22041 /** 22042 * For system apps on non-FBE devices, this method migrates any existing 22043 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22044 * requested by the app. 22045 */ 22046 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22047 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22048 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22049 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22050 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22051 try { 22052 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22053 storageTarget); 22054 } catch (InstallerException e) { 22055 logCriticalInfo(Log.WARN, 22056 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22057 } 22058 return true; 22059 } else { 22060 return false; 22061 } 22062 } 22063 22064 public PackageFreezer freezePackage(String packageName, String killReason) { 22065 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22066 } 22067 22068 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22069 return new PackageFreezer(packageName, userId, killReason); 22070 } 22071 22072 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22073 String killReason) { 22074 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22075 } 22076 22077 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22078 String killReason) { 22079 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22080 return new PackageFreezer(); 22081 } else { 22082 return freezePackage(packageName, userId, killReason); 22083 } 22084 } 22085 22086 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22087 String killReason) { 22088 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22089 } 22090 22091 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22092 String killReason) { 22093 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22094 return new PackageFreezer(); 22095 } else { 22096 return freezePackage(packageName, userId, killReason); 22097 } 22098 } 22099 22100 /** 22101 * Class that freezes and kills the given package upon creation, and 22102 * unfreezes it upon closing. This is typically used when doing surgery on 22103 * app code/data to prevent the app from running while you're working. 22104 */ 22105 private class PackageFreezer implements AutoCloseable { 22106 private final String mPackageName; 22107 private final PackageFreezer[] mChildren; 22108 22109 private final boolean mWeFroze; 22110 22111 private final AtomicBoolean mClosed = new AtomicBoolean(); 22112 private final CloseGuard mCloseGuard = CloseGuard.get(); 22113 22114 /** 22115 * Create and return a stub freezer that doesn't actually do anything, 22116 * typically used when someone requested 22117 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22118 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22119 */ 22120 public PackageFreezer() { 22121 mPackageName = null; 22122 mChildren = null; 22123 mWeFroze = false; 22124 mCloseGuard.open("close"); 22125 } 22126 22127 public PackageFreezer(String packageName, int userId, String killReason) { 22128 synchronized (mPackages) { 22129 mPackageName = packageName; 22130 mWeFroze = mFrozenPackages.add(mPackageName); 22131 22132 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22133 if (ps != null) { 22134 killApplication(ps.name, ps.appId, userId, killReason); 22135 } 22136 22137 final PackageParser.Package p = mPackages.get(packageName); 22138 if (p != null && p.childPackages != null) { 22139 final int N = p.childPackages.size(); 22140 mChildren = new PackageFreezer[N]; 22141 for (int i = 0; i < N; i++) { 22142 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22143 userId, killReason); 22144 } 22145 } else { 22146 mChildren = null; 22147 } 22148 } 22149 mCloseGuard.open("close"); 22150 } 22151 22152 @Override 22153 protected void finalize() throws Throwable { 22154 try { 22155 mCloseGuard.warnIfOpen(); 22156 close(); 22157 } finally { 22158 super.finalize(); 22159 } 22160 } 22161 22162 @Override 22163 public void close() { 22164 mCloseGuard.close(); 22165 if (mClosed.compareAndSet(false, true)) { 22166 synchronized (mPackages) { 22167 if (mWeFroze) { 22168 mFrozenPackages.remove(mPackageName); 22169 } 22170 22171 if (mChildren != null) { 22172 for (PackageFreezer freezer : mChildren) { 22173 freezer.close(); 22174 } 22175 } 22176 } 22177 } 22178 } 22179 } 22180 22181 /** 22182 * Verify that given package is currently frozen. 22183 */ 22184 private void checkPackageFrozen(String packageName) { 22185 synchronized (mPackages) { 22186 if (!mFrozenPackages.contains(packageName)) { 22187 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22188 } 22189 } 22190 } 22191 22192 @Override 22193 public int movePackage(final String packageName, final String volumeUuid) { 22194 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22195 22196 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22197 final int moveId = mNextMoveId.getAndIncrement(); 22198 mHandler.post(new Runnable() { 22199 @Override 22200 public void run() { 22201 try { 22202 movePackageInternal(packageName, volumeUuid, moveId, user); 22203 } catch (PackageManagerException e) { 22204 Slog.w(TAG, "Failed to move " + packageName, e); 22205 mMoveCallbacks.notifyStatusChanged(moveId, 22206 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22207 } 22208 } 22209 }); 22210 return moveId; 22211 } 22212 22213 private void movePackageInternal(final String packageName, final String volumeUuid, 22214 final int moveId, UserHandle user) throws PackageManagerException { 22215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22216 final PackageManager pm = mContext.getPackageManager(); 22217 22218 final boolean currentAsec; 22219 final String currentVolumeUuid; 22220 final File codeFile; 22221 final String installerPackageName; 22222 final String packageAbiOverride; 22223 final int appId; 22224 final String seinfo; 22225 final String label; 22226 final int targetSdkVersion; 22227 final PackageFreezer freezer; 22228 final int[] installedUserIds; 22229 22230 // reader 22231 synchronized (mPackages) { 22232 final PackageParser.Package pkg = mPackages.get(packageName); 22233 final PackageSetting ps = mSettings.mPackages.get(packageName); 22234 if (pkg == null || ps == null) { 22235 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22236 } 22237 22238 if (pkg.applicationInfo.isSystemApp()) { 22239 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22240 "Cannot move system application"); 22241 } 22242 22243 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22244 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22245 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22246 if (isInternalStorage && !allow3rdPartyOnInternal) { 22247 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22248 "3rd party apps are not allowed on internal storage"); 22249 } 22250 22251 if (pkg.applicationInfo.isExternalAsec()) { 22252 currentAsec = true; 22253 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22254 } else if (pkg.applicationInfo.isForwardLocked()) { 22255 currentAsec = true; 22256 currentVolumeUuid = "forward_locked"; 22257 } else { 22258 currentAsec = false; 22259 currentVolumeUuid = ps.volumeUuid; 22260 22261 final File probe = new File(pkg.codePath); 22262 final File probeOat = new File(probe, "oat"); 22263 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22264 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22265 "Move only supported for modern cluster style installs"); 22266 } 22267 } 22268 22269 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22270 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22271 "Package already moved to " + volumeUuid); 22272 } 22273 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22274 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22275 "Device admin cannot be moved"); 22276 } 22277 22278 if (mFrozenPackages.contains(packageName)) { 22279 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22280 "Failed to move already frozen package"); 22281 } 22282 22283 codeFile = new File(pkg.codePath); 22284 installerPackageName = ps.installerPackageName; 22285 packageAbiOverride = ps.cpuAbiOverrideString; 22286 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22287 seinfo = pkg.applicationInfo.seInfo; 22288 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22289 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22290 freezer = freezePackage(packageName, "movePackageInternal"); 22291 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22292 } 22293 22294 final Bundle extras = new Bundle(); 22295 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22296 extras.putString(Intent.EXTRA_TITLE, label); 22297 mMoveCallbacks.notifyCreated(moveId, extras); 22298 22299 int installFlags; 22300 final boolean moveCompleteApp; 22301 final File measurePath; 22302 22303 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22304 installFlags = INSTALL_INTERNAL; 22305 moveCompleteApp = !currentAsec; 22306 measurePath = Environment.getDataAppDirectory(volumeUuid); 22307 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22308 installFlags = INSTALL_EXTERNAL; 22309 moveCompleteApp = false; 22310 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22311 } else { 22312 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22313 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22314 || !volume.isMountedWritable()) { 22315 freezer.close(); 22316 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22317 "Move location not mounted private volume"); 22318 } 22319 22320 Preconditions.checkState(!currentAsec); 22321 22322 installFlags = INSTALL_INTERNAL; 22323 moveCompleteApp = true; 22324 measurePath = Environment.getDataAppDirectory(volumeUuid); 22325 } 22326 22327 final PackageStats stats = new PackageStats(null, -1); 22328 synchronized (mInstaller) { 22329 for (int userId : installedUserIds) { 22330 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22331 freezer.close(); 22332 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22333 "Failed to measure package size"); 22334 } 22335 } 22336 } 22337 22338 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22339 + stats.dataSize); 22340 22341 final long startFreeBytes = measurePath.getUsableSpace(); 22342 final long sizeBytes; 22343 if (moveCompleteApp) { 22344 sizeBytes = stats.codeSize + stats.dataSize; 22345 } else { 22346 sizeBytes = stats.codeSize; 22347 } 22348 22349 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22350 freezer.close(); 22351 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22352 "Not enough free space to move"); 22353 } 22354 22355 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22356 22357 final CountDownLatch installedLatch = new CountDownLatch(1); 22358 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22359 @Override 22360 public void onUserActionRequired(Intent intent) throws RemoteException { 22361 throw new IllegalStateException(); 22362 } 22363 22364 @Override 22365 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22366 Bundle extras) throws RemoteException { 22367 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22368 + PackageManager.installStatusToString(returnCode, msg)); 22369 22370 installedLatch.countDown(); 22371 freezer.close(); 22372 22373 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22374 switch (status) { 22375 case PackageInstaller.STATUS_SUCCESS: 22376 mMoveCallbacks.notifyStatusChanged(moveId, 22377 PackageManager.MOVE_SUCCEEDED); 22378 break; 22379 case PackageInstaller.STATUS_FAILURE_STORAGE: 22380 mMoveCallbacks.notifyStatusChanged(moveId, 22381 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22382 break; 22383 default: 22384 mMoveCallbacks.notifyStatusChanged(moveId, 22385 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22386 break; 22387 } 22388 } 22389 }; 22390 22391 final MoveInfo move; 22392 if (moveCompleteApp) { 22393 // Kick off a thread to report progress estimates 22394 new Thread() { 22395 @Override 22396 public void run() { 22397 while (true) { 22398 try { 22399 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22400 break; 22401 } 22402 } catch (InterruptedException ignored) { 22403 } 22404 22405 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22406 final int progress = 10 + (int) MathUtils.constrain( 22407 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22408 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22409 } 22410 } 22411 }.start(); 22412 22413 final String dataAppName = codeFile.getName(); 22414 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22415 dataAppName, appId, seinfo, targetSdkVersion); 22416 } else { 22417 move = null; 22418 } 22419 22420 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22421 22422 final Message msg = mHandler.obtainMessage(INIT_COPY); 22423 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22424 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22425 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22426 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22427 PackageManager.INSTALL_REASON_UNKNOWN); 22428 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22429 msg.obj = params; 22430 22431 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22432 System.identityHashCode(msg.obj)); 22433 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22434 System.identityHashCode(msg.obj)); 22435 22436 mHandler.sendMessage(msg); 22437 } 22438 22439 @Override 22440 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22441 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22442 22443 final int realMoveId = mNextMoveId.getAndIncrement(); 22444 final Bundle extras = new Bundle(); 22445 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22446 mMoveCallbacks.notifyCreated(realMoveId, extras); 22447 22448 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22449 @Override 22450 public void onCreated(int moveId, Bundle extras) { 22451 // Ignored 22452 } 22453 22454 @Override 22455 public void onStatusChanged(int moveId, int status, long estMillis) { 22456 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22457 } 22458 }; 22459 22460 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22461 storage.setPrimaryStorageUuid(volumeUuid, callback); 22462 return realMoveId; 22463 } 22464 22465 @Override 22466 public int getMoveStatus(int moveId) { 22467 mContext.enforceCallingOrSelfPermission( 22468 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22469 return mMoveCallbacks.mLastStatus.get(moveId); 22470 } 22471 22472 @Override 22473 public void registerMoveCallback(IPackageMoveObserver callback) { 22474 mContext.enforceCallingOrSelfPermission( 22475 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22476 mMoveCallbacks.register(callback); 22477 } 22478 22479 @Override 22480 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22481 mContext.enforceCallingOrSelfPermission( 22482 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22483 mMoveCallbacks.unregister(callback); 22484 } 22485 22486 @Override 22487 public boolean setInstallLocation(int loc) { 22488 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22489 null); 22490 if (getInstallLocation() == loc) { 22491 return true; 22492 } 22493 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22494 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22495 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22496 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22497 return true; 22498 } 22499 return false; 22500 } 22501 22502 @Override 22503 public int getInstallLocation() { 22504 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22505 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22506 PackageHelper.APP_INSTALL_AUTO); 22507 } 22508 22509 /** Called by UserManagerService */ 22510 void cleanUpUser(UserManagerService userManager, int userHandle) { 22511 synchronized (mPackages) { 22512 mDirtyUsers.remove(userHandle); 22513 mUserNeedsBadging.delete(userHandle); 22514 mSettings.removeUserLPw(userHandle); 22515 mPendingBroadcasts.remove(userHandle); 22516 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22517 removeUnusedPackagesLPw(userManager, userHandle); 22518 } 22519 } 22520 22521 /** 22522 * We're removing userHandle and would like to remove any downloaded packages 22523 * that are no longer in use by any other user. 22524 * @param userHandle the user being removed 22525 */ 22526 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22527 final boolean DEBUG_CLEAN_APKS = false; 22528 int [] users = userManager.getUserIds(); 22529 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22530 while (psit.hasNext()) { 22531 PackageSetting ps = psit.next(); 22532 if (ps.pkg == null) { 22533 continue; 22534 } 22535 final String packageName = ps.pkg.packageName; 22536 // Skip over if system app 22537 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22538 continue; 22539 } 22540 if (DEBUG_CLEAN_APKS) { 22541 Slog.i(TAG, "Checking package " + packageName); 22542 } 22543 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22544 if (keep) { 22545 if (DEBUG_CLEAN_APKS) { 22546 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22547 } 22548 } else { 22549 for (int i = 0; i < users.length; i++) { 22550 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22551 keep = true; 22552 if (DEBUG_CLEAN_APKS) { 22553 Slog.i(TAG, " Keeping package " + packageName + " for user " 22554 + users[i]); 22555 } 22556 break; 22557 } 22558 } 22559 } 22560 if (!keep) { 22561 if (DEBUG_CLEAN_APKS) { 22562 Slog.i(TAG, " Removing package " + packageName); 22563 } 22564 mHandler.post(new Runnable() { 22565 public void run() { 22566 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22567 userHandle, 0); 22568 } //end run 22569 }); 22570 } 22571 } 22572 } 22573 22574 /** Called by UserManagerService */ 22575 void createNewUser(int userId, String[] disallowedPackages) { 22576 synchronized (mInstallLock) { 22577 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22578 } 22579 synchronized (mPackages) { 22580 scheduleWritePackageRestrictionsLocked(userId); 22581 scheduleWritePackageListLocked(userId); 22582 applyFactoryDefaultBrowserLPw(userId); 22583 primeDomainVerificationsLPw(userId); 22584 } 22585 } 22586 22587 void onNewUserCreated(final int userId) { 22588 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22589 // If permission review for legacy apps is required, we represent 22590 // dagerous permissions for such apps as always granted runtime 22591 // permissions to keep per user flag state whether review is needed. 22592 // Hence, if a new user is added we have to propagate dangerous 22593 // permission grants for these legacy apps. 22594 if (mPermissionReviewRequired) { 22595 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22596 | UPDATE_PERMISSIONS_REPLACE_ALL); 22597 } 22598 } 22599 22600 @Override 22601 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22602 mContext.enforceCallingOrSelfPermission( 22603 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22604 "Only package verification agents can read the verifier device identity"); 22605 22606 synchronized (mPackages) { 22607 return mSettings.getVerifierDeviceIdentityLPw(); 22608 } 22609 } 22610 22611 @Override 22612 public void setPermissionEnforced(String permission, boolean enforced) { 22613 // TODO: Now that we no longer change GID for storage, this should to away. 22614 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22615 "setPermissionEnforced"); 22616 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22617 synchronized (mPackages) { 22618 if (mSettings.mReadExternalStorageEnforced == null 22619 || mSettings.mReadExternalStorageEnforced != enforced) { 22620 mSettings.mReadExternalStorageEnforced = enforced; 22621 mSettings.writeLPr(); 22622 } 22623 } 22624 // kill any non-foreground processes so we restart them and 22625 // grant/revoke the GID. 22626 final IActivityManager am = ActivityManager.getService(); 22627 if (am != null) { 22628 final long token = Binder.clearCallingIdentity(); 22629 try { 22630 am.killProcessesBelowForeground("setPermissionEnforcement"); 22631 } catch (RemoteException e) { 22632 } finally { 22633 Binder.restoreCallingIdentity(token); 22634 } 22635 } 22636 } else { 22637 throw new IllegalArgumentException("No selective enforcement for " + permission); 22638 } 22639 } 22640 22641 @Override 22642 @Deprecated 22643 public boolean isPermissionEnforced(String permission) { 22644 return true; 22645 } 22646 22647 @Override 22648 public boolean isStorageLow() { 22649 final long token = Binder.clearCallingIdentity(); 22650 try { 22651 final DeviceStorageMonitorInternal 22652 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22653 if (dsm != null) { 22654 return dsm.isMemoryLow(); 22655 } else { 22656 return false; 22657 } 22658 } finally { 22659 Binder.restoreCallingIdentity(token); 22660 } 22661 } 22662 22663 @Override 22664 public IPackageInstaller getPackageInstaller() { 22665 return mInstallerService; 22666 } 22667 22668 private boolean userNeedsBadging(int userId) { 22669 int index = mUserNeedsBadging.indexOfKey(userId); 22670 if (index < 0) { 22671 final UserInfo userInfo; 22672 final long token = Binder.clearCallingIdentity(); 22673 try { 22674 userInfo = sUserManager.getUserInfo(userId); 22675 } finally { 22676 Binder.restoreCallingIdentity(token); 22677 } 22678 final boolean b; 22679 if (userInfo != null && userInfo.isManagedProfile()) { 22680 b = true; 22681 } else { 22682 b = false; 22683 } 22684 mUserNeedsBadging.put(userId, b); 22685 return b; 22686 } 22687 return mUserNeedsBadging.valueAt(index); 22688 } 22689 22690 @Override 22691 public KeySet getKeySetByAlias(String packageName, String alias) { 22692 if (packageName == null || alias == null) { 22693 return null; 22694 } 22695 synchronized(mPackages) { 22696 final PackageParser.Package pkg = mPackages.get(packageName); 22697 if (pkg == null) { 22698 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22699 throw new IllegalArgumentException("Unknown package: " + packageName); 22700 } 22701 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22702 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22703 } 22704 } 22705 22706 @Override 22707 public KeySet getSigningKeySet(String packageName) { 22708 if (packageName == null) { 22709 return null; 22710 } 22711 synchronized(mPackages) { 22712 final PackageParser.Package pkg = mPackages.get(packageName); 22713 if (pkg == null) { 22714 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22715 throw new IllegalArgumentException("Unknown package: " + packageName); 22716 } 22717 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22718 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22719 throw new SecurityException("May not access signing KeySet of other apps."); 22720 } 22721 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22722 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22723 } 22724 } 22725 22726 @Override 22727 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22728 if (packageName == null || ks == null) { 22729 return false; 22730 } 22731 synchronized(mPackages) { 22732 final PackageParser.Package pkg = mPackages.get(packageName); 22733 if (pkg == null) { 22734 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22735 throw new IllegalArgumentException("Unknown package: " + packageName); 22736 } 22737 IBinder ksh = ks.getToken(); 22738 if (ksh instanceof KeySetHandle) { 22739 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22740 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22741 } 22742 return false; 22743 } 22744 } 22745 22746 @Override 22747 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22748 if (packageName == null || ks == null) { 22749 return false; 22750 } 22751 synchronized(mPackages) { 22752 final PackageParser.Package pkg = mPackages.get(packageName); 22753 if (pkg == null) { 22754 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22755 throw new IllegalArgumentException("Unknown package: " + packageName); 22756 } 22757 IBinder ksh = ks.getToken(); 22758 if (ksh instanceof KeySetHandle) { 22759 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22760 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22761 } 22762 return false; 22763 } 22764 } 22765 22766 private void deletePackageIfUnusedLPr(final String packageName) { 22767 PackageSetting ps = mSettings.mPackages.get(packageName); 22768 if (ps == null) { 22769 return; 22770 } 22771 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22772 // TODO Implement atomic delete if package is unused 22773 // It is currently possible that the package will be deleted even if it is installed 22774 // after this method returns. 22775 mHandler.post(new Runnable() { 22776 public void run() { 22777 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22778 0, PackageManager.DELETE_ALL_USERS); 22779 } 22780 }); 22781 } 22782 } 22783 22784 /** 22785 * Check and throw if the given before/after packages would be considered a 22786 * downgrade. 22787 */ 22788 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22789 throws PackageManagerException { 22790 if (after.versionCode < before.mVersionCode) { 22791 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22792 "Update version code " + after.versionCode + " is older than current " 22793 + before.mVersionCode); 22794 } else if (after.versionCode == before.mVersionCode) { 22795 if (after.baseRevisionCode < before.baseRevisionCode) { 22796 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22797 "Update base revision code " + after.baseRevisionCode 22798 + " is older than current " + before.baseRevisionCode); 22799 } 22800 22801 if (!ArrayUtils.isEmpty(after.splitNames)) { 22802 for (int i = 0; i < after.splitNames.length; i++) { 22803 final String splitName = after.splitNames[i]; 22804 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22805 if (j != -1) { 22806 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22807 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22808 "Update split " + splitName + " revision code " 22809 + after.splitRevisionCodes[i] + " is older than current " 22810 + before.splitRevisionCodes[j]); 22811 } 22812 } 22813 } 22814 } 22815 } 22816 } 22817 22818 private static class MoveCallbacks extends Handler { 22819 private static final int MSG_CREATED = 1; 22820 private static final int MSG_STATUS_CHANGED = 2; 22821 22822 private final RemoteCallbackList<IPackageMoveObserver> 22823 mCallbacks = new RemoteCallbackList<>(); 22824 22825 private final SparseIntArray mLastStatus = new SparseIntArray(); 22826 22827 public MoveCallbacks(Looper looper) { 22828 super(looper); 22829 } 22830 22831 public void register(IPackageMoveObserver callback) { 22832 mCallbacks.register(callback); 22833 } 22834 22835 public void unregister(IPackageMoveObserver callback) { 22836 mCallbacks.unregister(callback); 22837 } 22838 22839 @Override 22840 public void handleMessage(Message msg) { 22841 final SomeArgs args = (SomeArgs) msg.obj; 22842 final int n = mCallbacks.beginBroadcast(); 22843 for (int i = 0; i < n; i++) { 22844 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22845 try { 22846 invokeCallback(callback, msg.what, args); 22847 } catch (RemoteException ignored) { 22848 } 22849 } 22850 mCallbacks.finishBroadcast(); 22851 args.recycle(); 22852 } 22853 22854 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22855 throws RemoteException { 22856 switch (what) { 22857 case MSG_CREATED: { 22858 callback.onCreated(args.argi1, (Bundle) args.arg2); 22859 break; 22860 } 22861 case MSG_STATUS_CHANGED: { 22862 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22863 break; 22864 } 22865 } 22866 } 22867 22868 private void notifyCreated(int moveId, Bundle extras) { 22869 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22870 22871 final SomeArgs args = SomeArgs.obtain(); 22872 args.argi1 = moveId; 22873 args.arg2 = extras; 22874 obtainMessage(MSG_CREATED, args).sendToTarget(); 22875 } 22876 22877 private void notifyStatusChanged(int moveId, int status) { 22878 notifyStatusChanged(moveId, status, -1); 22879 } 22880 22881 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22882 Slog.v(TAG, "Move " + moveId + " status " + status); 22883 22884 final SomeArgs args = SomeArgs.obtain(); 22885 args.argi1 = moveId; 22886 args.argi2 = status; 22887 args.arg3 = estMillis; 22888 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22889 22890 synchronized (mLastStatus) { 22891 mLastStatus.put(moveId, status); 22892 } 22893 } 22894 } 22895 22896 private final static class OnPermissionChangeListeners extends Handler { 22897 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22898 22899 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22900 new RemoteCallbackList<>(); 22901 22902 public OnPermissionChangeListeners(Looper looper) { 22903 super(looper); 22904 } 22905 22906 @Override 22907 public void handleMessage(Message msg) { 22908 switch (msg.what) { 22909 case MSG_ON_PERMISSIONS_CHANGED: { 22910 final int uid = msg.arg1; 22911 handleOnPermissionsChanged(uid); 22912 } break; 22913 } 22914 } 22915 22916 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22917 mPermissionListeners.register(listener); 22918 22919 } 22920 22921 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22922 mPermissionListeners.unregister(listener); 22923 } 22924 22925 public void onPermissionsChanged(int uid) { 22926 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22927 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22928 } 22929 } 22930 22931 private void handleOnPermissionsChanged(int uid) { 22932 final int count = mPermissionListeners.beginBroadcast(); 22933 try { 22934 for (int i = 0; i < count; i++) { 22935 IOnPermissionsChangeListener callback = mPermissionListeners 22936 .getBroadcastItem(i); 22937 try { 22938 callback.onPermissionsChanged(uid); 22939 } catch (RemoteException e) { 22940 Log.e(TAG, "Permission listener is dead", e); 22941 } 22942 } 22943 } finally { 22944 mPermissionListeners.finishBroadcast(); 22945 } 22946 } 22947 } 22948 22949 private class PackageManagerInternalImpl extends PackageManagerInternal { 22950 @Override 22951 public void setLocationPackagesProvider(PackagesProvider provider) { 22952 synchronized (mPackages) { 22953 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22954 } 22955 } 22956 22957 @Override 22958 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22959 synchronized (mPackages) { 22960 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22961 } 22962 } 22963 22964 @Override 22965 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22966 synchronized (mPackages) { 22967 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22968 } 22969 } 22970 22971 @Override 22972 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22973 synchronized (mPackages) { 22974 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22975 } 22976 } 22977 22978 @Override 22979 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22980 synchronized (mPackages) { 22981 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22982 } 22983 } 22984 22985 @Override 22986 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22987 synchronized (mPackages) { 22988 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22989 } 22990 } 22991 22992 @Override 22993 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22994 synchronized (mPackages) { 22995 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22996 packageName, userId); 22997 } 22998 } 22999 23000 @Override 23001 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23002 synchronized (mPackages) { 23003 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23004 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23005 packageName, userId); 23006 } 23007 } 23008 23009 @Override 23010 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23011 synchronized (mPackages) { 23012 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23013 packageName, userId); 23014 } 23015 } 23016 23017 @Override 23018 public void setKeepUninstalledPackages(final List<String> packageList) { 23019 Preconditions.checkNotNull(packageList); 23020 List<String> removedFromList = null; 23021 synchronized (mPackages) { 23022 if (mKeepUninstalledPackages != null) { 23023 final int packagesCount = mKeepUninstalledPackages.size(); 23024 for (int i = 0; i < packagesCount; i++) { 23025 String oldPackage = mKeepUninstalledPackages.get(i); 23026 if (packageList != null && packageList.contains(oldPackage)) { 23027 continue; 23028 } 23029 if (removedFromList == null) { 23030 removedFromList = new ArrayList<>(); 23031 } 23032 removedFromList.add(oldPackage); 23033 } 23034 } 23035 mKeepUninstalledPackages = new ArrayList<>(packageList); 23036 if (removedFromList != null) { 23037 final int removedCount = removedFromList.size(); 23038 for (int i = 0; i < removedCount; i++) { 23039 deletePackageIfUnusedLPr(removedFromList.get(i)); 23040 } 23041 } 23042 } 23043 } 23044 23045 @Override 23046 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23047 synchronized (mPackages) { 23048 // If we do not support permission review, done. 23049 if (!mPermissionReviewRequired) { 23050 return false; 23051 } 23052 23053 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23054 if (packageSetting == null) { 23055 return false; 23056 } 23057 23058 // Permission review applies only to apps not supporting the new permission model. 23059 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23060 return false; 23061 } 23062 23063 // Legacy apps have the permission and get user consent on launch. 23064 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23065 return permissionsState.isPermissionReviewRequired(userId); 23066 } 23067 } 23068 23069 @Override 23070 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23071 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23072 } 23073 23074 @Override 23075 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23076 int userId) { 23077 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23078 } 23079 23080 @Override 23081 public void setDeviceAndProfileOwnerPackages( 23082 int deviceOwnerUserId, String deviceOwnerPackage, 23083 SparseArray<String> profileOwnerPackages) { 23084 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23085 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23086 } 23087 23088 @Override 23089 public boolean isPackageDataProtected(int userId, String packageName) { 23090 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23091 } 23092 23093 @Override 23094 public boolean isPackageEphemeral(int userId, String packageName) { 23095 synchronized (mPackages) { 23096 final PackageSetting ps = mSettings.mPackages.get(packageName); 23097 return ps != null ? ps.getInstantApp(userId) : false; 23098 } 23099 } 23100 23101 @Override 23102 public boolean wasPackageEverLaunched(String packageName, int userId) { 23103 synchronized (mPackages) { 23104 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23105 } 23106 } 23107 23108 @Override 23109 public void grantRuntimePermission(String packageName, String name, int userId, 23110 boolean overridePolicy) { 23111 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23112 overridePolicy); 23113 } 23114 23115 @Override 23116 public void revokeRuntimePermission(String packageName, String name, int userId, 23117 boolean overridePolicy) { 23118 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23119 overridePolicy); 23120 } 23121 23122 @Override 23123 public String getNameForUid(int uid) { 23124 return PackageManagerService.this.getNameForUid(uid); 23125 } 23126 23127 @Override 23128 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23129 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23130 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23131 responseObj, origIntent, resolvedType, callingPackage, userId); 23132 } 23133 23134 @Override 23135 public void grantEphemeralAccess(int userId, Intent intent, 23136 int targetAppId, int ephemeralAppId) { 23137 synchronized (mPackages) { 23138 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23139 targetAppId, ephemeralAppId); 23140 } 23141 } 23142 23143 @Override 23144 public boolean isInstantAppInstallerComponent(ComponentName component) { 23145 synchronized (mPackages) { 23146 return component != null && component.equals(mInstantAppInstallerComponent); 23147 } 23148 } 23149 23150 @Override 23151 public void pruneInstantApps() { 23152 synchronized (mPackages) { 23153 mInstantAppRegistry.pruneInstantAppsLPw(); 23154 } 23155 } 23156 23157 @Override 23158 public String getSetupWizardPackageName() { 23159 return mSetupWizardPackage; 23160 } 23161 23162 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23163 if (policy != null) { 23164 mExternalSourcesPolicy = policy; 23165 } 23166 } 23167 23168 @Override 23169 public boolean isPackagePersistent(String packageName) { 23170 synchronized (mPackages) { 23171 PackageParser.Package pkg = mPackages.get(packageName); 23172 return pkg != null 23173 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23174 | ApplicationInfo.FLAG_PERSISTENT)) == 23175 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23176 : false; 23177 } 23178 } 23179 23180 @Override 23181 public List<PackageInfo> getOverlayPackages(int userId) { 23182 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23183 synchronized (mPackages) { 23184 for (PackageParser.Package p : mPackages.values()) { 23185 if (p.mOverlayTarget != null) { 23186 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23187 if (pkg != null) { 23188 overlayPackages.add(pkg); 23189 } 23190 } 23191 } 23192 } 23193 return overlayPackages; 23194 } 23195 23196 @Override 23197 public List<String> getTargetPackageNames(int userId) { 23198 List<String> targetPackages = new ArrayList<>(); 23199 synchronized (mPackages) { 23200 for (PackageParser.Package p : mPackages.values()) { 23201 if (p.mOverlayTarget == null) { 23202 targetPackages.add(p.packageName); 23203 } 23204 } 23205 } 23206 return targetPackages; 23207 } 23208 23209 @Override 23210 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23211 @Nullable List<String> overlayPackageNames) { 23212 synchronized (mPackages) { 23213 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23214 Slog.e(TAG, "failed to find package " + targetPackageName); 23215 return false; 23216 } 23217 23218 ArrayList<String> paths = null; 23219 if (overlayPackageNames != null) { 23220 final int N = overlayPackageNames.size(); 23221 paths = new ArrayList<>(N); 23222 for (int i = 0; i < N; i++) { 23223 final String packageName = overlayPackageNames.get(i); 23224 final PackageParser.Package pkg = mPackages.get(packageName); 23225 if (pkg == null) { 23226 Slog.e(TAG, "failed to find package " + packageName); 23227 return false; 23228 } 23229 paths.add(pkg.baseCodePath); 23230 } 23231 } 23232 23233 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23234 mEnabledOverlayPaths.get(userId); 23235 if (userSpecificOverlays == null) { 23236 userSpecificOverlays = new ArrayMap<>(); 23237 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23238 } 23239 23240 if (paths != null && paths.size() > 0) { 23241 userSpecificOverlays.put(targetPackageName, paths); 23242 } else { 23243 userSpecificOverlays.remove(targetPackageName); 23244 } 23245 return true; 23246 } 23247 } 23248 23249 @Override 23250 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23251 int flags, int userId) { 23252 return resolveIntentInternal( 23253 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23254 } 23255 23256 @Override 23257 public ResolveInfo resolveService(Intent intent, String resolvedType, 23258 int flags, int userId, int callingUid) { 23259 return resolveServiceInternal( 23260 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23261 } 23262 23263 23264 @Override 23265 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23266 synchronized (mPackages) { 23267 mIsolatedOwners.put(isolatedUid, ownerUid); 23268 } 23269 } 23270 23271 @Override 23272 public void removeIsolatedUid(int isolatedUid) { 23273 synchronized (mPackages) { 23274 mIsolatedOwners.delete(isolatedUid); 23275 } 23276 } 23277 } 23278 23279 @Override 23280 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23281 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23282 synchronized (mPackages) { 23283 final long identity = Binder.clearCallingIdentity(); 23284 try { 23285 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23286 packageNames, userId); 23287 } finally { 23288 Binder.restoreCallingIdentity(identity); 23289 } 23290 } 23291 } 23292 23293 @Override 23294 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23295 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23296 synchronized (mPackages) { 23297 final long identity = Binder.clearCallingIdentity(); 23298 try { 23299 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23300 packageNames, userId); 23301 } finally { 23302 Binder.restoreCallingIdentity(identity); 23303 } 23304 } 23305 } 23306 23307 private static void enforceSystemOrPhoneCaller(String tag) { 23308 int callingUid = Binder.getCallingUid(); 23309 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23310 throw new SecurityException( 23311 "Cannot call " + tag + " from UID " + callingUid); 23312 } 23313 } 23314 23315 boolean isHistoricalPackageUsageAvailable() { 23316 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23317 } 23318 23319 /** 23320 * Return a <b>copy</b> of the collection of packages known to the package manager. 23321 * @return A copy of the values of mPackages. 23322 */ 23323 Collection<PackageParser.Package> getPackages() { 23324 synchronized (mPackages) { 23325 return new ArrayList<>(mPackages.values()); 23326 } 23327 } 23328 23329 /** 23330 * Logs process start information (including base APK hash) to the security log. 23331 * @hide 23332 */ 23333 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23334 String apkFile, int pid) { 23335 if (!SecurityLog.isLoggingEnabled()) { 23336 return; 23337 } 23338 Bundle data = new Bundle(); 23339 data.putLong("startTimestamp", System.currentTimeMillis()); 23340 data.putString("processName", processName); 23341 data.putInt("uid", uid); 23342 data.putString("seinfo", seinfo); 23343 data.putString("apkFile", apkFile); 23344 data.putInt("pid", pid); 23345 Message msg = mProcessLoggingHandler.obtainMessage( 23346 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23347 msg.setData(data); 23348 mProcessLoggingHandler.sendMessage(msg); 23349 } 23350 23351 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23352 return mCompilerStats.getPackageStats(pkgName); 23353 } 23354 23355 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23356 return getOrCreateCompilerPackageStats(pkg.packageName); 23357 } 23358 23359 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23360 return mCompilerStats.getOrCreatePackageStats(pkgName); 23361 } 23362 23363 public void deleteCompilerPackageStats(String pkgName) { 23364 mCompilerStats.deletePackageStats(pkgName); 23365 } 23366 23367 @Override 23368 public int getInstallReason(String packageName, int userId) { 23369 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23370 true /* requireFullPermission */, false /* checkShell */, 23371 "get install reason"); 23372 synchronized (mPackages) { 23373 final PackageSetting ps = mSettings.mPackages.get(packageName); 23374 if (ps != null) { 23375 return ps.getInstallReason(userId); 23376 } 23377 } 23378 return PackageManager.INSTALL_REASON_UNKNOWN; 23379 } 23380 23381 @Override 23382 public boolean canRequestPackageInstalls(String packageName, int userId) { 23383 int callingUid = Binder.getCallingUid(); 23384 int uid = getPackageUid(packageName, 0, userId); 23385 if (callingUid != uid && callingUid != Process.ROOT_UID 23386 && callingUid != Process.SYSTEM_UID) { 23387 throw new SecurityException( 23388 "Caller uid " + callingUid + " does not own package " + packageName); 23389 } 23390 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23391 if (info == null) { 23392 return false; 23393 } 23394 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23395 throw new UnsupportedOperationException( 23396 "Operation only supported on apps targeting Android O or higher"); 23397 } 23398 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23399 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23400 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23401 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23402 } 23403 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23404 return false; 23405 } 23406 if (mExternalSourcesPolicy != null) { 23407 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23408 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23409 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23410 } 23411 } 23412 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23413 } 23414 23415 @Override 23416 public ComponentName getInstantAppResolverSettingsComponent() { 23417 return mInstantAppResolverSettingsComponent; 23418 } 23419} 23420