PackageManagerService.java revision 30f18587e3bf6079f910699c89f1b702664982b5
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.FastPrintWriter; 258import com.android.internal.util.FastXmlSerializer; 259import com.android.internal.util.IndentingPrintWriter; 260import com.android.internal.util.Preconditions; 261import com.android.internal.util.XmlUtils; 262import com.android.server.AttributeCache; 263import com.android.server.DeviceIdleController; 264import com.android.server.EventLogTags; 265import com.android.server.FgThread; 266import com.android.server.IntentResolver; 267import com.android.server.LocalServices; 268import com.android.server.LockGuard; 269import com.android.server.ServiceThread; 270import com.android.server.SystemConfig; 271import com.android.server.SystemServerInitThreadPool; 272import com.android.server.Watchdog; 273import com.android.server.net.NetworkPolicyManagerInternal; 274import com.android.server.pm.BackgroundDexOptService; 275import com.android.server.pm.Installer.InstallerException; 276import com.android.server.pm.PermissionsState.PermissionState; 277import com.android.server.pm.Settings.DatabaseVersion; 278import com.android.server.pm.Settings.VersionInfo; 279import com.android.server.pm.dex.DexManager; 280import com.android.server.storage.DeviceStorageMonitorInternal; 281 282import dalvik.system.CloseGuard; 283import dalvik.system.DexFile; 284import dalvik.system.VMRuntime; 285 286import libcore.io.IoUtils; 287import libcore.util.EmptyArray; 288 289import org.xmlpull.v1.XmlPullParser; 290import org.xmlpull.v1.XmlPullParserException; 291import org.xmlpull.v1.XmlSerializer; 292 293import java.io.BufferedOutputStream; 294import java.io.BufferedReader; 295import java.io.ByteArrayInputStream; 296import java.io.ByteArrayOutputStream; 297import java.io.File; 298import java.io.FileDescriptor; 299import java.io.FileInputStream; 300import java.io.FileNotFoundException; 301import java.io.FileOutputStream; 302import java.io.FileReader; 303import java.io.FilenameFilter; 304import java.io.IOException; 305import java.io.PrintWriter; 306import java.nio.charset.StandardCharsets; 307import java.security.DigestInputStream; 308import java.security.MessageDigest; 309import java.security.NoSuchAlgorithmException; 310import java.security.PublicKey; 311import java.security.SecureRandom; 312import java.security.cert.Certificate; 313import java.security.cert.CertificateEncodingException; 314import java.security.cert.CertificateException; 315import java.text.SimpleDateFormat; 316import java.util.ArrayList; 317import java.util.Arrays; 318import java.util.Collection; 319import java.util.Collections; 320import java.util.Comparator; 321import java.util.Date; 322import java.util.HashMap; 323import java.util.HashSet; 324import java.util.Iterator; 325import java.util.List; 326import java.util.Map; 327import java.util.Objects; 328import java.util.Set; 329import java.util.concurrent.CountDownLatch; 330import java.util.concurrent.Future; 331import java.util.concurrent.TimeUnit; 332import java.util.concurrent.atomic.AtomicBoolean; 333import java.util.concurrent.atomic.AtomicInteger; 334 335/** 336 * Keep track of all those APKs everywhere. 337 * <p> 338 * Internally there are two important locks: 339 * <ul> 340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 341 * and other related state. It is a fine-grained lock that should only be held 342 * momentarily, as it's one of the most contended locks in the system. 343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 344 * operations typically involve heavy lifting of application data on disk. Since 345 * {@code installd} is single-threaded, and it's operations can often be slow, 346 * this lock should never be acquired while already holding {@link #mPackages}. 347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 348 * holding {@link #mInstallLock}. 349 * </ul> 350 * Many internal methods rely on the caller to hold the appropriate locks, and 351 * this contract is expressed through method name suffixes: 352 * <ul> 353 * <li>fooLI(): the caller must hold {@link #mInstallLock} 354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 355 * being modified must be frozen 356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 358 * </ul> 359 * <p> 360 * Because this class is very central to the platform's security; please run all 361 * CTS and unit tests whenever making modifications: 362 * 363 * <pre> 364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 366 * </pre> 367 */ 368public class PackageManagerService extends IPackageManager.Stub { 369 static final String TAG = "PackageManager"; 370 static final boolean DEBUG_SETTINGS = false; 371 static final boolean DEBUG_PREFERRED = false; 372 static final boolean DEBUG_UPGRADE = false; 373 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 374 private static final boolean DEBUG_BACKUP = false; 375 private static final boolean DEBUG_INSTALL = false; 376 private static final boolean DEBUG_REMOVE = false; 377 private static final boolean DEBUG_BROADCASTS = false; 378 private static final boolean DEBUG_SHOW_INFO = false; 379 private static final boolean DEBUG_PACKAGE_INFO = false; 380 private static final boolean DEBUG_INTENT_MATCHING = false; 381 private static final boolean DEBUG_PACKAGE_SCANNING = false; 382 private static final boolean DEBUG_VERIFY = false; 383 private static final boolean DEBUG_FILTERS = false; 384 385 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 386 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 387 // user, but by default initialize to this. 388 public static final boolean DEBUG_DEXOPT = false; 389 390 private static final boolean DEBUG_ABI_SELECTION = false; 391 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 392 private static final boolean DEBUG_TRIAGED_MISSING = false; 393 private static final boolean DEBUG_APP_DATA = false; 394 395 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 396 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 397 398 private static final boolean DISABLE_EPHEMERAL_APPS = false; 399 private static final boolean HIDE_EPHEMERAL_APIS = false; 400 401 private static final boolean ENABLE_FREE_CACHE_V2 = 402 SystemProperties.getBoolean("fw.free_cache_v2", true); 403 404 private static final int RADIO_UID = Process.PHONE_UID; 405 private static final int LOG_UID = Process.LOG_UID; 406 private static final int NFC_UID = Process.NFC_UID; 407 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 408 private static final int SHELL_UID = Process.SHELL_UID; 409 410 // Cap the size of permission trees that 3rd party apps can define 411 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 412 413 // Suffix used during package installation when copying/moving 414 // package apks to install directory. 415 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 416 417 static final int SCAN_NO_DEX = 1<<1; 418 static final int SCAN_FORCE_DEX = 1<<2; 419 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 420 static final int SCAN_NEW_INSTALL = 1<<4; 421 static final int SCAN_UPDATE_TIME = 1<<5; 422 static final int SCAN_BOOTING = 1<<6; 423 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 424 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 425 static final int SCAN_REPLACING = 1<<9; 426 static final int SCAN_REQUIRE_KNOWN = 1<<10; 427 static final int SCAN_MOVE = 1<<11; 428 static final int SCAN_INITIAL = 1<<12; 429 static final int SCAN_CHECK_ONLY = 1<<13; 430 static final int SCAN_DONT_KILL_APP = 1<<14; 431 static final int SCAN_IGNORE_FROZEN = 1<<15; 432 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 433 static final int SCAN_AS_INSTANT_APP = 1<<17; 434 static final int SCAN_AS_FULL_APP = 1<<18; 435 /** Should not be with the scan flags */ 436 static final int FLAGS_REMOVE_CHATTY = 1<<31; 437 438 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 439 440 private static final int[] EMPTY_INT_ARRAY = new int[0]; 441 442 /** 443 * Timeout (in milliseconds) after which the watchdog should declare that 444 * our handler thread is wedged. The usual default for such things is one 445 * minute but we sometimes do very lengthy I/O operations on this thread, 446 * such as installing multi-gigabyte applications, so ours needs to be longer. 447 */ 448 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 449 450 /** 451 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 452 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 453 * settings entry if available, otherwise we use the hardcoded default. If it's been 454 * more than this long since the last fstrim, we force one during the boot sequence. 455 * 456 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 457 * one gets run at the next available charging+idle time. This final mandatory 458 * no-fstrim check kicks in only of the other scheduling criteria is never met. 459 */ 460 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 461 462 /** 463 * Whether verification is enabled by default. 464 */ 465 private static final boolean DEFAULT_VERIFY_ENABLE = true; 466 467 /** 468 * The default maximum time to wait for the verification agent to return in 469 * milliseconds. 470 */ 471 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 472 473 /** 474 * The default response for package verification timeout. 475 * 476 * This can be either PackageManager.VERIFICATION_ALLOW or 477 * PackageManager.VERIFICATION_REJECT. 478 */ 479 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 480 481 static final String PLATFORM_PACKAGE_NAME = "android"; 482 483 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 484 485 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 486 DEFAULT_CONTAINER_PACKAGE, 487 "com.android.defcontainer.DefaultContainerService"); 488 489 private static final String KILL_APP_REASON_GIDS_CHANGED = 490 "permission grant or revoke changed gids"; 491 492 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 493 "permissions revoked"; 494 495 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 496 497 private static final String PACKAGE_SCHEME = "package"; 498 499 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 500 501 /** Permission grant: not grant the permission. */ 502 private static final int GRANT_DENIED = 1; 503 504 /** Permission grant: grant the permission as an install permission. */ 505 private static final int GRANT_INSTALL = 2; 506 507 /** Permission grant: grant the permission as a runtime one. */ 508 private static final int GRANT_RUNTIME = 3; 509 510 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 511 private static final int GRANT_UPGRADE = 4; 512 513 /** Canonical intent used to identify what counts as a "web browser" app */ 514 private static final Intent sBrowserIntent; 515 static { 516 sBrowserIntent = new Intent(); 517 sBrowserIntent.setAction(Intent.ACTION_VIEW); 518 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 519 sBrowserIntent.setData(Uri.parse("http:")); 520 } 521 522 /** 523 * The set of all protected actions [i.e. those actions for which a high priority 524 * intent filter is disallowed]. 525 */ 526 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 527 static { 528 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 531 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 532 } 533 534 // Compilation reasons. 535 public static final int REASON_FIRST_BOOT = 0; 536 public static final int REASON_BOOT = 1; 537 public static final int REASON_INSTALL = 2; 538 public static final int REASON_BACKGROUND_DEXOPT = 3; 539 public static final int REASON_AB_OTA = 4; 540 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 541 public static final int REASON_SHARED_APK = 6; 542 public static final int REASON_FORCED_DEXOPT = 7; 543 544 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 545 546 /** All dangerous permission names in the same order as the events in MetricsEvent */ 547 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 548 Manifest.permission.READ_CALENDAR, 549 Manifest.permission.WRITE_CALENDAR, 550 Manifest.permission.CAMERA, 551 Manifest.permission.READ_CONTACTS, 552 Manifest.permission.WRITE_CONTACTS, 553 Manifest.permission.GET_ACCOUNTS, 554 Manifest.permission.ACCESS_FINE_LOCATION, 555 Manifest.permission.ACCESS_COARSE_LOCATION, 556 Manifest.permission.RECORD_AUDIO, 557 Manifest.permission.READ_PHONE_STATE, 558 Manifest.permission.CALL_PHONE, 559 Manifest.permission.READ_CALL_LOG, 560 Manifest.permission.WRITE_CALL_LOG, 561 Manifest.permission.ADD_VOICEMAIL, 562 Manifest.permission.USE_SIP, 563 Manifest.permission.PROCESS_OUTGOING_CALLS, 564 Manifest.permission.READ_CELL_BROADCASTS, 565 Manifest.permission.BODY_SENSORS, 566 Manifest.permission.SEND_SMS, 567 Manifest.permission.RECEIVE_SMS, 568 Manifest.permission.READ_SMS, 569 Manifest.permission.RECEIVE_WAP_PUSH, 570 Manifest.permission.RECEIVE_MMS, 571 Manifest.permission.READ_EXTERNAL_STORAGE, 572 Manifest.permission.WRITE_EXTERNAL_STORAGE, 573 Manifest.permission.READ_PHONE_NUMBER, 574 Manifest.permission.ANSWER_PHONE_CALLS); 575 576 577 /** 578 * Version number for the package parser cache. Increment this whenever the format or 579 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 580 */ 581 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 582 583 /** 584 * Whether the package parser cache is enabled. 585 */ 586 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 587 588 final ServiceThread mHandlerThread; 589 590 final PackageHandler mHandler; 591 592 private final ProcessLoggingHandler mProcessLoggingHandler; 593 594 /** 595 * Messages for {@link #mHandler} that need to wait for system ready before 596 * being dispatched. 597 */ 598 private ArrayList<Message> mPostSystemReadyMessages; 599 600 final int mSdkVersion = Build.VERSION.SDK_INT; 601 602 final Context mContext; 603 final boolean mFactoryTest; 604 final boolean mOnlyCore; 605 final DisplayMetrics mMetrics; 606 final int mDefParseFlags; 607 final String[] mSeparateProcesses; 608 final boolean mIsUpgrade; 609 final boolean mIsPreNUpgrade; 610 final boolean mIsPreNMR1Upgrade; 611 612 @GuardedBy("mPackages") 613 private boolean mDexOptDialogShown; 614 615 /** The location for ASEC container files on internal storage. */ 616 final String mAsecInternalPath; 617 618 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 619 // LOCK HELD. Can be called with mInstallLock held. 620 @GuardedBy("mInstallLock") 621 final Installer mInstaller; 622 623 /** Directory where installed third-party apps stored */ 624 final File mAppInstallDir; 625 626 /** 627 * Directory to which applications installed internally have their 628 * 32 bit native libraries copied. 629 */ 630 private File mAppLib32InstallDir; 631 632 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 633 // apps. 634 final File mDrmAppPrivateInstallDir; 635 636 // ---------------------------------------------------------------- 637 638 // Lock for state used when installing and doing other long running 639 // operations. Methods that must be called with this lock held have 640 // the suffix "LI". 641 final Object mInstallLock = new Object(); 642 643 // ---------------------------------------------------------------- 644 645 // Keys are String (package name), values are Package. This also serves 646 // as the lock for the global state. Methods that must be called with 647 // this lock held have the prefix "LP". 648 @GuardedBy("mPackages") 649 final ArrayMap<String, PackageParser.Package> mPackages = 650 new ArrayMap<String, PackageParser.Package>(); 651 652 final ArrayMap<String, Set<String>> mKnownCodebase = 653 new ArrayMap<String, Set<String>>(); 654 655 // List of APK paths to load for each user and package. This data is never 656 // persisted by the package manager. Instead, the overlay manager will 657 // ensure the data is up-to-date in runtime. 658 @GuardedBy("mPackages") 659 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 660 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 661 662 /** 663 * Tracks new system packages [received in an OTA] that we expect to 664 * find updated user-installed versions. Keys are package name, values 665 * are package location. 666 */ 667 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 668 /** 669 * Tracks high priority intent filters for protected actions. During boot, certain 670 * filter actions are protected and should never be allowed to have a high priority 671 * intent filter for them. However, there is one, and only one exception -- the 672 * setup wizard. It must be able to define a high priority intent filter for these 673 * actions to ensure there are no escapes from the wizard. We need to delay processing 674 * of these during boot as we need to look at all of the system packages in order 675 * to know which component is the setup wizard. 676 */ 677 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 678 /** 679 * Whether or not processing protected filters should be deferred. 680 */ 681 private boolean mDeferProtectedFilters = true; 682 683 /** 684 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 685 */ 686 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 687 /** 688 * Whether or not system app permissions should be promoted from install to runtime. 689 */ 690 boolean mPromoteSystemApps; 691 692 @GuardedBy("mPackages") 693 final Settings mSettings; 694 695 /** 696 * Set of package names that are currently "frozen", which means active 697 * surgery is being done on the code/data for that package. The platform 698 * will refuse to launch frozen packages to avoid race conditions. 699 * 700 * @see PackageFreezer 701 */ 702 @GuardedBy("mPackages") 703 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 704 705 final ProtectedPackages mProtectedPackages; 706 707 boolean mFirstBoot; 708 709 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 710 711 // System configuration read by SystemConfig. 712 final int[] mGlobalGids; 713 final SparseArray<ArraySet<String>> mSystemPermissions; 714 @GuardedBy("mAvailableFeatures") 715 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 716 717 // If mac_permissions.xml was found for seinfo labeling. 718 boolean mFoundPolicyFile; 719 720 private final InstantAppRegistry mInstantAppRegistry; 721 722 @GuardedBy("mPackages") 723 int mChangedPackagesSequenceNumber; 724 /** 725 * List of changed [installed, removed or updated] packages. 726 * mapping from user id -> sequence number -> package name 727 */ 728 @GuardedBy("mPackages") 729 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 730 /** 731 * The sequence number of the last change to a package. 732 * mapping from user id -> package name -> sequence number 733 */ 734 @GuardedBy("mPackages") 735 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 736 737 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 738 @Override public boolean hasFeature(String feature) { 739 return PackageManagerService.this.hasSystemFeature(feature, 0); 740 } 741 }; 742 743 public static final class SharedLibraryEntry { 744 public final String path; 745 public final String apk; 746 public final SharedLibraryInfo info; 747 748 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 749 String declaringPackageName, int declaringPackageVersionCode) { 750 path = _path; 751 apk = _apk; 752 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 753 declaringPackageName, declaringPackageVersionCode), null); 754 } 755 } 756 757 // Currently known shared libraries. 758 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 760 new ArrayMap<>(); 761 762 // All available activities, for your resolving pleasure. 763 final ActivityIntentResolver mActivities = 764 new ActivityIntentResolver(); 765 766 // All available receivers, for your resolving pleasure. 767 final ActivityIntentResolver mReceivers = 768 new ActivityIntentResolver(); 769 770 // All available services, for your resolving pleasure. 771 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 772 773 // All available providers, for your resolving pleasure. 774 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 775 776 // Mapping from provider base names (first directory in content URI codePath) 777 // to the provider information. 778 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 779 new ArrayMap<String, PackageParser.Provider>(); 780 781 // Mapping from instrumentation class names to info about them. 782 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 783 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 784 785 // Mapping from permission names to info about them. 786 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 787 new ArrayMap<String, PackageParser.PermissionGroup>(); 788 789 // Packages whose data we have transfered into another package, thus 790 // should no longer exist. 791 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 792 793 // Broadcast actions that are only available to the system. 794 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 795 796 /** List of packages waiting for verification. */ 797 final SparseArray<PackageVerificationState> mPendingVerification 798 = new SparseArray<PackageVerificationState>(); 799 800 /** Set of packages associated with each app op permission. */ 801 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 802 803 final PackageInstallerService mInstallerService; 804 805 private final PackageDexOptimizer mPackageDexOptimizer; 806 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 807 // is used by other apps). 808 private final DexManager mDexManager; 809 810 private AtomicInteger mNextMoveId = new AtomicInteger(); 811 private final MoveCallbacks mMoveCallbacks; 812 813 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 814 815 // Cache of users who need badging. 816 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 817 818 /** Token for keys in mPendingVerification. */ 819 private int mPendingVerificationToken = 0; 820 821 volatile boolean mSystemReady; 822 volatile boolean mSafeMode; 823 volatile boolean mHasSystemUidErrors; 824 825 ApplicationInfo mAndroidApplication; 826 final ActivityInfo mResolveActivity = new ActivityInfo(); 827 final ResolveInfo mResolveInfo = new ResolveInfo(); 828 ComponentName mResolveComponentName; 829 PackageParser.Package mPlatformPackage; 830 ComponentName mCustomResolverComponentName; 831 832 boolean mResolverReplaced = false; 833 834 private final @Nullable ComponentName mIntentFilterVerifierComponent; 835 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 836 837 private int mIntentFilterVerificationToken = 0; 838 839 /** The service connection to the ephemeral resolver */ 840 final EphemeralResolverConnection mInstantAppResolverConnection; 841 842 /** Component used to install ephemeral applications */ 843 ComponentName mInstantAppInstallerComponent; 844 /** Component used to show resolver settings for Instant Apps */ 845 ComponentName mInstantAppResolverSettingsComponent; 846 ActivityInfo mInstantAppInstallerActivity; 847 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 848 849 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 850 = new SparseArray<IntentFilterVerificationState>(); 851 852 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 853 854 // List of packages names to keep cached, even if they are uninstalled for all users 855 private List<String> mKeepUninstalledPackages; 856 857 private UserManagerInternal mUserManagerInternal; 858 859 private DeviceIdleController.LocalService mDeviceIdleController; 860 861 private File mCacheDir; 862 863 private ArraySet<String> mPrivappPermissionsViolations; 864 865 private Future<?> mPrepareAppDataFuture; 866 867 private static class IFVerificationParams { 868 PackageParser.Package pkg; 869 boolean replacing; 870 int userId; 871 int verifierUid; 872 873 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 874 int _userId, int _verifierUid) { 875 pkg = _pkg; 876 replacing = _replacing; 877 userId = _userId; 878 replacing = _replacing; 879 verifierUid = _verifierUid; 880 } 881 } 882 883 private interface IntentFilterVerifier<T extends IntentFilter> { 884 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 885 T filter, String packageName); 886 void startVerifications(int userId); 887 void receiveVerificationResponse(int verificationId); 888 } 889 890 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 891 private Context mContext; 892 private ComponentName mIntentFilterVerifierComponent; 893 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 894 895 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 896 mContext = context; 897 mIntentFilterVerifierComponent = verifierComponent; 898 } 899 900 private String getDefaultScheme() { 901 return IntentFilter.SCHEME_HTTPS; 902 } 903 904 @Override 905 public void startVerifications(int userId) { 906 // Launch verifications requests 907 int count = mCurrentIntentFilterVerifications.size(); 908 for (int n=0; n<count; n++) { 909 int verificationId = mCurrentIntentFilterVerifications.get(n); 910 final IntentFilterVerificationState ivs = 911 mIntentFilterVerificationStates.get(verificationId); 912 913 String packageName = ivs.getPackageName(); 914 915 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 916 final int filterCount = filters.size(); 917 ArraySet<String> domainsSet = new ArraySet<>(); 918 for (int m=0; m<filterCount; m++) { 919 PackageParser.ActivityIntentInfo filter = filters.get(m); 920 domainsSet.addAll(filter.getHostsList()); 921 } 922 synchronized (mPackages) { 923 if (mSettings.createIntentFilterVerificationIfNeededLPw( 924 packageName, domainsSet) != null) { 925 scheduleWriteSettingsLocked(); 926 } 927 } 928 sendVerificationRequest(userId, verificationId, ivs); 929 } 930 mCurrentIntentFilterVerifications.clear(); 931 } 932 933 private void sendVerificationRequest(int userId, int verificationId, 934 IntentFilterVerificationState ivs) { 935 936 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 937 verificationIntent.putExtra( 938 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 939 verificationId); 940 verificationIntent.putExtra( 941 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 942 getDefaultScheme()); 943 verificationIntent.putExtra( 944 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 945 ivs.getHostsString()); 946 verificationIntent.putExtra( 947 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 948 ivs.getPackageName()); 949 verificationIntent.setComponent(mIntentFilterVerifierComponent); 950 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 951 952 UserHandle user = new UserHandle(userId); 953 mContext.sendBroadcastAsUser(verificationIntent, user); 954 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 955 "Sending IntentFilter verification broadcast"); 956 } 957 958 public void receiveVerificationResponse(int verificationId) { 959 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 960 961 final boolean verified = ivs.isVerified(); 962 963 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 964 final int count = filters.size(); 965 if (DEBUG_DOMAIN_VERIFICATION) { 966 Slog.i(TAG, "Received verification response " + verificationId 967 + " for " + count + " filters, verified=" + verified); 968 } 969 for (int n=0; n<count; n++) { 970 PackageParser.ActivityIntentInfo filter = filters.get(n); 971 filter.setVerified(verified); 972 973 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 974 + " verified with result:" + verified + " and hosts:" 975 + ivs.getHostsString()); 976 } 977 978 mIntentFilterVerificationStates.remove(verificationId); 979 980 final String packageName = ivs.getPackageName(); 981 IntentFilterVerificationInfo ivi = null; 982 983 synchronized (mPackages) { 984 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 985 } 986 if (ivi == null) { 987 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 988 + verificationId + " packageName:" + packageName); 989 return; 990 } 991 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 992 "Updating IntentFilterVerificationInfo for package " + packageName 993 +" verificationId:" + verificationId); 994 995 synchronized (mPackages) { 996 if (verified) { 997 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 998 } else { 999 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1000 } 1001 scheduleWriteSettingsLocked(); 1002 1003 final int userId = ivs.getUserId(); 1004 if (userId != UserHandle.USER_ALL) { 1005 final int userStatus = 1006 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1007 1008 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1009 boolean needUpdate = false; 1010 1011 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1012 // already been set by the User thru the Disambiguation dialog 1013 switch (userStatus) { 1014 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1015 if (verified) { 1016 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1017 } else { 1018 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1019 } 1020 needUpdate = true; 1021 break; 1022 1023 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1024 if (verified) { 1025 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1026 needUpdate = true; 1027 } 1028 break; 1029 1030 default: 1031 // Nothing to do 1032 } 1033 1034 if (needUpdate) { 1035 mSettings.updateIntentFilterVerificationStatusLPw( 1036 packageName, updatedStatus, userId); 1037 scheduleWritePackageRestrictionsLocked(userId); 1038 } 1039 } 1040 } 1041 } 1042 1043 @Override 1044 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1045 ActivityIntentInfo filter, String packageName) { 1046 if (!hasValidDomains(filter)) { 1047 return false; 1048 } 1049 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1050 if (ivs == null) { 1051 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1052 packageName); 1053 } 1054 if (DEBUG_DOMAIN_VERIFICATION) { 1055 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1056 } 1057 ivs.addFilter(filter); 1058 return true; 1059 } 1060 1061 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1062 int userId, int verificationId, String packageName) { 1063 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1064 verifierUid, userId, packageName); 1065 ivs.setPendingState(); 1066 synchronized (mPackages) { 1067 mIntentFilterVerificationStates.append(verificationId, ivs); 1068 mCurrentIntentFilterVerifications.add(verificationId); 1069 } 1070 return ivs; 1071 } 1072 } 1073 1074 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1075 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1076 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1077 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1078 } 1079 1080 // Set of pending broadcasts for aggregating enable/disable of components. 1081 static class PendingPackageBroadcasts { 1082 // for each user id, a map of <package name -> components within that package> 1083 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1084 1085 public PendingPackageBroadcasts() { 1086 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1087 } 1088 1089 public ArrayList<String> get(int userId, String packageName) { 1090 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1091 return packages.get(packageName); 1092 } 1093 1094 public void put(int userId, String packageName, ArrayList<String> components) { 1095 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1096 packages.put(packageName, components); 1097 } 1098 1099 public void remove(int userId, String packageName) { 1100 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1101 if (packages != null) { 1102 packages.remove(packageName); 1103 } 1104 } 1105 1106 public void remove(int userId) { 1107 mUidMap.remove(userId); 1108 } 1109 1110 public int userIdCount() { 1111 return mUidMap.size(); 1112 } 1113 1114 public int userIdAt(int n) { 1115 return mUidMap.keyAt(n); 1116 } 1117 1118 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1119 return mUidMap.get(userId); 1120 } 1121 1122 public int size() { 1123 // total number of pending broadcast entries across all userIds 1124 int num = 0; 1125 for (int i = 0; i< mUidMap.size(); i++) { 1126 num += mUidMap.valueAt(i).size(); 1127 } 1128 return num; 1129 } 1130 1131 public void clear() { 1132 mUidMap.clear(); 1133 } 1134 1135 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1136 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1137 if (map == null) { 1138 map = new ArrayMap<String, ArrayList<String>>(); 1139 mUidMap.put(userId, map); 1140 } 1141 return map; 1142 } 1143 } 1144 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1145 1146 // Service Connection to remote media container service to copy 1147 // package uri's from external media onto secure containers 1148 // or internal storage. 1149 private IMediaContainerService mContainerService = null; 1150 1151 static final int SEND_PENDING_BROADCAST = 1; 1152 static final int MCS_BOUND = 3; 1153 static final int END_COPY = 4; 1154 static final int INIT_COPY = 5; 1155 static final int MCS_UNBIND = 6; 1156 static final int START_CLEANING_PACKAGE = 7; 1157 static final int FIND_INSTALL_LOC = 8; 1158 static final int POST_INSTALL = 9; 1159 static final int MCS_RECONNECT = 10; 1160 static final int MCS_GIVE_UP = 11; 1161 static final int UPDATED_MEDIA_STATUS = 12; 1162 static final int WRITE_SETTINGS = 13; 1163 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1164 static final int PACKAGE_VERIFIED = 15; 1165 static final int CHECK_PENDING_VERIFICATION = 16; 1166 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1167 static final int INTENT_FILTER_VERIFIED = 18; 1168 static final int WRITE_PACKAGE_LIST = 19; 1169 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1170 1171 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1172 1173 // Delay time in millisecs 1174 static final int BROADCAST_DELAY = 10 * 1000; 1175 1176 static UserManagerService sUserManager; 1177 1178 // Stores a list of users whose package restrictions file needs to be updated 1179 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1180 1181 final private DefaultContainerConnection mDefContainerConn = 1182 new DefaultContainerConnection(); 1183 class DefaultContainerConnection implements ServiceConnection { 1184 public void onServiceConnected(ComponentName name, IBinder service) { 1185 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1186 final IMediaContainerService imcs = IMediaContainerService.Stub 1187 .asInterface(Binder.allowBlocking(service)); 1188 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1189 } 1190 1191 public void onServiceDisconnected(ComponentName name) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1193 } 1194 } 1195 1196 // Recordkeeping of restore-after-install operations that are currently in flight 1197 // between the Package Manager and the Backup Manager 1198 static class PostInstallData { 1199 public InstallArgs args; 1200 public PackageInstalledInfo res; 1201 1202 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1203 args = _a; 1204 res = _r; 1205 } 1206 } 1207 1208 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1209 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1210 1211 // XML tags for backup/restore of various bits of state 1212 private static final String TAG_PREFERRED_BACKUP = "pa"; 1213 private static final String TAG_DEFAULT_APPS = "da"; 1214 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1215 1216 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1217 private static final String TAG_ALL_GRANTS = "rt-grants"; 1218 private static final String TAG_GRANT = "grant"; 1219 private static final String ATTR_PACKAGE_NAME = "pkg"; 1220 1221 private static final String TAG_PERMISSION = "perm"; 1222 private static final String ATTR_PERMISSION_NAME = "name"; 1223 private static final String ATTR_IS_GRANTED = "g"; 1224 private static final String ATTR_USER_SET = "set"; 1225 private static final String ATTR_USER_FIXED = "fixed"; 1226 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1227 1228 // System/policy permission grants are not backed up 1229 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1230 FLAG_PERMISSION_POLICY_FIXED 1231 | FLAG_PERMISSION_SYSTEM_FIXED 1232 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1233 1234 // And we back up these user-adjusted states 1235 private static final int USER_RUNTIME_GRANT_MASK = 1236 FLAG_PERMISSION_USER_SET 1237 | FLAG_PERMISSION_USER_FIXED 1238 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1239 1240 final @Nullable String mRequiredVerifierPackage; 1241 final @NonNull String mRequiredInstallerPackage; 1242 final @NonNull String mRequiredUninstallerPackage; 1243 final @Nullable String mSetupWizardPackage; 1244 final @Nullable String mStorageManagerPackage; 1245 final @NonNull String mServicesSystemSharedLibraryPackageName; 1246 final @NonNull String mSharedSystemSharedLibraryPackageName; 1247 1248 final boolean mPermissionReviewRequired; 1249 1250 private final PackageUsage mPackageUsage = new PackageUsage(); 1251 private final CompilerStats mCompilerStats = new CompilerStats(); 1252 1253 class PackageHandler extends Handler { 1254 private boolean mBound = false; 1255 final ArrayList<HandlerParams> mPendingInstalls = 1256 new ArrayList<HandlerParams>(); 1257 1258 private boolean connectToService() { 1259 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1260 " DefaultContainerService"); 1261 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1263 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1264 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1265 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1266 mBound = true; 1267 return true; 1268 } 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1270 return false; 1271 } 1272 1273 private void disconnectService() { 1274 mContainerService = null; 1275 mBound = false; 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1277 mContext.unbindService(mDefContainerConn); 1278 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1279 } 1280 1281 PackageHandler(Looper looper) { 1282 super(looper); 1283 } 1284 1285 public void handleMessage(Message msg) { 1286 try { 1287 doHandleMessage(msg); 1288 } finally { 1289 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1290 } 1291 } 1292 1293 void doHandleMessage(Message msg) { 1294 switch (msg.what) { 1295 case INIT_COPY: { 1296 HandlerParams params = (HandlerParams) msg.obj; 1297 int idx = mPendingInstalls.size(); 1298 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1299 // If a bind was already initiated we dont really 1300 // need to do anything. The pending install 1301 // will be processed later on. 1302 if (!mBound) { 1303 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1304 System.identityHashCode(mHandler)); 1305 // If this is the only one pending we might 1306 // have to bind to the service again. 1307 if (!connectToService()) { 1308 Slog.e(TAG, "Failed to bind to media container service"); 1309 params.serviceError(); 1310 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1311 System.identityHashCode(mHandler)); 1312 if (params.traceMethod != null) { 1313 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1314 params.traceCookie); 1315 } 1316 return; 1317 } else { 1318 // Once we bind to the service, the first 1319 // pending request will be processed. 1320 mPendingInstalls.add(idx, params); 1321 } 1322 } else { 1323 mPendingInstalls.add(idx, params); 1324 // Already bound to the service. Just make 1325 // sure we trigger off processing the first request. 1326 if (idx == 0) { 1327 mHandler.sendEmptyMessage(MCS_BOUND); 1328 } 1329 } 1330 break; 1331 } 1332 case MCS_BOUND: { 1333 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1334 if (msg.obj != null) { 1335 mContainerService = (IMediaContainerService) msg.obj; 1336 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1337 System.identityHashCode(mHandler)); 1338 } 1339 if (mContainerService == null) { 1340 if (!mBound) { 1341 // Something seriously wrong since we are not bound and we are not 1342 // waiting for connection. Bail out. 1343 Slog.e(TAG, "Cannot bind to media container service"); 1344 for (HandlerParams params : mPendingInstalls) { 1345 // Indicate service bind error 1346 params.serviceError(); 1347 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1348 System.identityHashCode(params)); 1349 if (params.traceMethod != null) { 1350 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1351 params.traceMethod, params.traceCookie); 1352 } 1353 return; 1354 } 1355 mPendingInstalls.clear(); 1356 } else { 1357 Slog.w(TAG, "Waiting to connect to media container service"); 1358 } 1359 } else if (mPendingInstalls.size() > 0) { 1360 HandlerParams params = mPendingInstalls.get(0); 1361 if (params != null) { 1362 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1363 System.identityHashCode(params)); 1364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1365 if (params.startCopy()) { 1366 // We are done... look for more work or to 1367 // go idle. 1368 if (DEBUG_SD_INSTALL) Log.i(TAG, 1369 "Checking for more work or unbind..."); 1370 // Delete pending install 1371 if (mPendingInstalls.size() > 0) { 1372 mPendingInstalls.remove(0); 1373 } 1374 if (mPendingInstalls.size() == 0) { 1375 if (mBound) { 1376 if (DEBUG_SD_INSTALL) Log.i(TAG, 1377 "Posting delayed MCS_UNBIND"); 1378 removeMessages(MCS_UNBIND); 1379 Message ubmsg = obtainMessage(MCS_UNBIND); 1380 // Unbind after a little delay, to avoid 1381 // continual thrashing. 1382 sendMessageDelayed(ubmsg, 10000); 1383 } 1384 } else { 1385 // There are more pending requests in queue. 1386 // Just post MCS_BOUND message to trigger processing 1387 // of next pending install. 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, 1389 "Posting MCS_BOUND for next work"); 1390 mHandler.sendEmptyMessage(MCS_BOUND); 1391 } 1392 } 1393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1394 } 1395 } else { 1396 // Should never happen ideally. 1397 Slog.w(TAG, "Empty queue"); 1398 } 1399 break; 1400 } 1401 case MCS_RECONNECT: { 1402 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1403 if (mPendingInstalls.size() > 0) { 1404 if (mBound) { 1405 disconnectService(); 1406 } 1407 if (!connectToService()) { 1408 Slog.e(TAG, "Failed to bind to media container service"); 1409 for (HandlerParams params : mPendingInstalls) { 1410 // Indicate service bind error 1411 params.serviceError(); 1412 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1413 System.identityHashCode(params)); 1414 } 1415 mPendingInstalls.clear(); 1416 } 1417 } 1418 break; 1419 } 1420 case MCS_UNBIND: { 1421 // If there is no actual work left, then time to unbind. 1422 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1423 1424 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1425 if (mBound) { 1426 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1427 1428 disconnectService(); 1429 } 1430 } else if (mPendingInstalls.size() > 0) { 1431 // There are more pending requests in queue. 1432 // Just post MCS_BOUND message to trigger processing 1433 // of next pending install. 1434 mHandler.sendEmptyMessage(MCS_BOUND); 1435 } 1436 1437 break; 1438 } 1439 case MCS_GIVE_UP: { 1440 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1441 HandlerParams params = mPendingInstalls.remove(0); 1442 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1443 System.identityHashCode(params)); 1444 break; 1445 } 1446 case SEND_PENDING_BROADCAST: { 1447 String packages[]; 1448 ArrayList<String> components[]; 1449 int size = 0; 1450 int uids[]; 1451 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1452 synchronized (mPackages) { 1453 if (mPendingBroadcasts == null) { 1454 return; 1455 } 1456 size = mPendingBroadcasts.size(); 1457 if (size <= 0) { 1458 // Nothing to be done. Just return 1459 return; 1460 } 1461 packages = new String[size]; 1462 components = new ArrayList[size]; 1463 uids = new int[size]; 1464 int i = 0; // filling out the above arrays 1465 1466 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1467 int packageUserId = mPendingBroadcasts.userIdAt(n); 1468 Iterator<Map.Entry<String, ArrayList<String>>> it 1469 = mPendingBroadcasts.packagesForUserId(packageUserId) 1470 .entrySet().iterator(); 1471 while (it.hasNext() && i < size) { 1472 Map.Entry<String, ArrayList<String>> ent = it.next(); 1473 packages[i] = ent.getKey(); 1474 components[i] = ent.getValue(); 1475 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1476 uids[i] = (ps != null) 1477 ? UserHandle.getUid(packageUserId, ps.appId) 1478 : -1; 1479 i++; 1480 } 1481 } 1482 size = i; 1483 mPendingBroadcasts.clear(); 1484 } 1485 // Send broadcasts 1486 for (int i = 0; i < size; i++) { 1487 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1488 } 1489 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1490 break; 1491 } 1492 case START_CLEANING_PACKAGE: { 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1494 final String packageName = (String)msg.obj; 1495 final int userId = msg.arg1; 1496 final boolean andCode = msg.arg2 != 0; 1497 synchronized (mPackages) { 1498 if (userId == UserHandle.USER_ALL) { 1499 int[] users = sUserManager.getUserIds(); 1500 for (int user : users) { 1501 mSettings.addPackageToCleanLPw( 1502 new PackageCleanItem(user, packageName, andCode)); 1503 } 1504 } else { 1505 mSettings.addPackageToCleanLPw( 1506 new PackageCleanItem(userId, packageName, andCode)); 1507 } 1508 } 1509 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1510 startCleaningPackages(); 1511 } break; 1512 case POST_INSTALL: { 1513 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1514 1515 PostInstallData data = mRunningInstalls.get(msg.arg1); 1516 final boolean didRestore = (msg.arg2 != 0); 1517 mRunningInstalls.delete(msg.arg1); 1518 1519 if (data != null) { 1520 InstallArgs args = data.args; 1521 PackageInstalledInfo parentRes = data.res; 1522 1523 final boolean grantPermissions = (args.installFlags 1524 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1525 final boolean killApp = (args.installFlags 1526 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1527 final String[] grantedPermissions = args.installGrantPermissions; 1528 1529 // Handle the parent package 1530 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1531 grantedPermissions, didRestore, args.installerPackageName, 1532 args.observer); 1533 1534 // Handle the child packages 1535 final int childCount = (parentRes.addedChildPackages != null) 1536 ? parentRes.addedChildPackages.size() : 0; 1537 for (int i = 0; i < childCount; i++) { 1538 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1539 handlePackagePostInstall(childRes, grantPermissions, killApp, 1540 grantedPermissions, false, args.installerPackageName, 1541 args.observer); 1542 } 1543 1544 // Log tracing if needed 1545 if (args.traceMethod != null) { 1546 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1547 args.traceCookie); 1548 } 1549 } else { 1550 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1551 } 1552 1553 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1554 } break; 1555 case UPDATED_MEDIA_STATUS: { 1556 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1557 boolean reportStatus = msg.arg1 == 1; 1558 boolean doGc = msg.arg2 == 1; 1559 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1560 if (doGc) { 1561 // Force a gc to clear up stale containers. 1562 Runtime.getRuntime().gc(); 1563 } 1564 if (msg.obj != null) { 1565 @SuppressWarnings("unchecked") 1566 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1567 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1568 // Unload containers 1569 unloadAllContainers(args); 1570 } 1571 if (reportStatus) { 1572 try { 1573 if (DEBUG_SD_INSTALL) Log.i(TAG, 1574 "Invoking StorageManagerService call back"); 1575 PackageHelper.getStorageManager().finishMediaUpdate(); 1576 } catch (RemoteException e) { 1577 Log.e(TAG, "StorageManagerService not running?"); 1578 } 1579 } 1580 } break; 1581 case WRITE_SETTINGS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_SETTINGS); 1585 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1586 mSettings.writeLPr(); 1587 mDirtyUsers.clear(); 1588 } 1589 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1590 } break; 1591 case WRITE_PACKAGE_RESTRICTIONS: { 1592 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1593 synchronized (mPackages) { 1594 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1595 for (int userId : mDirtyUsers) { 1596 mSettings.writePackageRestrictionsLPr(userId); 1597 } 1598 mDirtyUsers.clear(); 1599 } 1600 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1601 } break; 1602 case WRITE_PACKAGE_LIST: { 1603 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1604 synchronized (mPackages) { 1605 removeMessages(WRITE_PACKAGE_LIST); 1606 mSettings.writePackageListLPr(msg.arg1); 1607 } 1608 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1609 } break; 1610 case CHECK_PENDING_VERIFICATION: { 1611 final int verificationId = msg.arg1; 1612 final PackageVerificationState state = mPendingVerification.get(verificationId); 1613 1614 if ((state != null) && !state.timeoutExtended()) { 1615 final InstallArgs args = state.getInstallArgs(); 1616 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1617 1618 Slog.i(TAG, "Verification timed out for " + originUri); 1619 mPendingVerification.remove(verificationId); 1620 1621 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1622 1623 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1624 Slog.i(TAG, "Continuing with installation of " + originUri); 1625 state.setVerifierResponse(Binder.getCallingUid(), 1626 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1627 broadcastPackageVerified(verificationId, originUri, 1628 PackageManager.VERIFICATION_ALLOW, 1629 state.getInstallArgs().getUser()); 1630 try { 1631 ret = args.copyApk(mContainerService, true); 1632 } catch (RemoteException e) { 1633 Slog.e(TAG, "Could not contact the ContainerService"); 1634 } 1635 } else { 1636 broadcastPackageVerified(verificationId, originUri, 1637 PackageManager.VERIFICATION_REJECT, 1638 state.getInstallArgs().getUser()); 1639 } 1640 1641 Trace.asyncTraceEnd( 1642 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1643 1644 processPendingInstall(args, ret); 1645 mHandler.sendEmptyMessage(MCS_UNBIND); 1646 } 1647 break; 1648 } 1649 case PACKAGE_VERIFIED: { 1650 final int verificationId = msg.arg1; 1651 1652 final PackageVerificationState state = mPendingVerification.get(verificationId); 1653 if (state == null) { 1654 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1655 break; 1656 } 1657 1658 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1659 1660 state.setVerifierResponse(response.callerUid, response.code); 1661 1662 if (state.isVerificationComplete()) { 1663 mPendingVerification.remove(verificationId); 1664 1665 final InstallArgs args = state.getInstallArgs(); 1666 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1667 1668 int ret; 1669 if (state.isInstallAllowed()) { 1670 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1671 broadcastPackageVerified(verificationId, originUri, 1672 response.code, state.getInstallArgs().getUser()); 1673 try { 1674 ret = args.copyApk(mContainerService, true); 1675 } catch (RemoteException e) { 1676 Slog.e(TAG, "Could not contact the ContainerService"); 1677 } 1678 } else { 1679 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1680 } 1681 1682 Trace.asyncTraceEnd( 1683 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1684 1685 processPendingInstall(args, ret); 1686 mHandler.sendEmptyMessage(MCS_UNBIND); 1687 } 1688 1689 break; 1690 } 1691 case START_INTENT_FILTER_VERIFICATIONS: { 1692 IFVerificationParams params = (IFVerificationParams) msg.obj; 1693 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1694 params.replacing, params.pkg); 1695 break; 1696 } 1697 case INTENT_FILTER_VERIFIED: { 1698 final int verificationId = msg.arg1; 1699 1700 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1701 verificationId); 1702 if (state == null) { 1703 Slog.w(TAG, "Invalid IntentFilter verification token " 1704 + verificationId + " received"); 1705 break; 1706 } 1707 1708 final int userId = state.getUserId(); 1709 1710 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1711 "Processing IntentFilter verification with token:" 1712 + verificationId + " and userId:" + userId); 1713 1714 final IntentFilterVerificationResponse response = 1715 (IntentFilterVerificationResponse) msg.obj; 1716 1717 state.setVerifierResponse(response.callerUid, response.code); 1718 1719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1720 "IntentFilter verification with token:" + verificationId 1721 + " and userId:" + userId 1722 + " is settings verifier response with response code:" 1723 + response.code); 1724 1725 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1726 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1727 + response.getFailedDomainsString()); 1728 } 1729 1730 if (state.isVerificationComplete()) { 1731 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1732 } else { 1733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1734 "IntentFilter verification with token:" + verificationId 1735 + " was not said to be complete"); 1736 } 1737 1738 break; 1739 } 1740 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1741 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1742 mInstantAppResolverConnection, 1743 (InstantAppRequest) msg.obj, 1744 mInstantAppInstallerActivity, 1745 mHandler); 1746 } 1747 } 1748 } 1749 } 1750 1751 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1752 boolean killApp, String[] grantedPermissions, 1753 boolean launchedForRestore, String installerPackage, 1754 IPackageInstallObserver2 installObserver) { 1755 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1756 // Send the removed broadcasts 1757 if (res.removedInfo != null) { 1758 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1759 } 1760 1761 // Now that we successfully installed the package, grant runtime 1762 // permissions if requested before broadcasting the install. Also 1763 // for legacy apps in permission review mode we clear the permission 1764 // review flag which is used to emulate runtime permissions for 1765 // legacy apps. 1766 if (grantPermissions) { 1767 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1768 } 1769 1770 final boolean update = res.removedInfo != null 1771 && res.removedInfo.removedPackage != null; 1772 1773 // If this is the first time we have child packages for a disabled privileged 1774 // app that had no children, we grant requested runtime permissions to the new 1775 // children if the parent on the system image had them already granted. 1776 if (res.pkg.parentPackage != null) { 1777 synchronized (mPackages) { 1778 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1779 } 1780 } 1781 1782 synchronized (mPackages) { 1783 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1784 } 1785 1786 final String packageName = res.pkg.applicationInfo.packageName; 1787 1788 // Determine the set of users who are adding this package for 1789 // the first time vs. those who are seeing an update. 1790 int[] firstUsers = EMPTY_INT_ARRAY; 1791 int[] updateUsers = EMPTY_INT_ARRAY; 1792 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1793 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1794 for (int newUser : res.newUsers) { 1795 if (ps.getInstantApp(newUser)) { 1796 continue; 1797 } 1798 if (allNewUsers) { 1799 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1800 continue; 1801 } 1802 boolean isNew = true; 1803 for (int origUser : res.origUsers) { 1804 if (origUser == newUser) { 1805 isNew = false; 1806 break; 1807 } 1808 } 1809 if (isNew) { 1810 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1811 } else { 1812 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1813 } 1814 } 1815 1816 // Send installed broadcasts if the package is not a static shared lib. 1817 if (res.pkg.staticSharedLibName == null) { 1818 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1819 1820 // Send added for users that see the package for the first time 1821 // sendPackageAddedForNewUsers also deals with system apps 1822 int appId = UserHandle.getAppId(res.uid); 1823 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1824 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1825 1826 // Send added for users that don't see the package for the first time 1827 Bundle extras = new Bundle(1); 1828 extras.putInt(Intent.EXTRA_UID, res.uid); 1829 if (update) { 1830 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1831 } 1832 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1833 extras, 0 /*flags*/, null /*targetPackage*/, 1834 null /*finishedReceiver*/, updateUsers); 1835 1836 // Send replaced for users that don't see the package for the first time 1837 if (update) { 1838 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1839 packageName, extras, 0 /*flags*/, 1840 null /*targetPackage*/, null /*finishedReceiver*/, 1841 updateUsers); 1842 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1843 null /*package*/, null /*extras*/, 0 /*flags*/, 1844 packageName /*targetPackage*/, 1845 null /*finishedReceiver*/, updateUsers); 1846 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1847 // First-install and we did a restore, so we're responsible for the 1848 // first-launch broadcast. 1849 if (DEBUG_BACKUP) { 1850 Slog.i(TAG, "Post-restore of " + packageName 1851 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1852 } 1853 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1854 } 1855 1856 // Send broadcast package appeared if forward locked/external for all users 1857 // treat asec-hosted packages like removable media on upgrade 1858 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1859 if (DEBUG_INSTALL) { 1860 Slog.i(TAG, "upgrading pkg " + res.pkg 1861 + " is ASEC-hosted -> AVAILABLE"); 1862 } 1863 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1864 ArrayList<String> pkgList = new ArrayList<>(1); 1865 pkgList.add(packageName); 1866 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1867 } 1868 } 1869 1870 // Work that needs to happen on first install within each user 1871 if (firstUsers != null && firstUsers.length > 0) { 1872 synchronized (mPackages) { 1873 for (int userId : firstUsers) { 1874 // If this app is a browser and it's newly-installed for some 1875 // users, clear any default-browser state in those users. The 1876 // app's nature doesn't depend on the user, so we can just check 1877 // its browser nature in any user and generalize. 1878 if (packageIsBrowser(packageName, userId)) { 1879 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1880 } 1881 1882 // We may also need to apply pending (restored) runtime 1883 // permission grants within these users. 1884 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1885 } 1886 } 1887 } 1888 1889 // Log current value of "unknown sources" setting 1890 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1891 getUnknownSourcesSettings()); 1892 1893 // Force a gc to clear up things 1894 Runtime.getRuntime().gc(); 1895 1896 // Remove the replaced package's older resources safely now 1897 // We delete after a gc for applications on sdcard. 1898 if (res.removedInfo != null && res.removedInfo.args != null) { 1899 synchronized (mInstallLock) { 1900 res.removedInfo.args.doPostDeleteLI(true); 1901 } 1902 } 1903 1904 // Notify DexManager that the package was installed for new users. 1905 // The updated users should already be indexed and the package code paths 1906 // should not change. 1907 // Don't notify the manager for ephemeral apps as they are not expected to 1908 // survive long enough to benefit of background optimizations. 1909 for (int userId : firstUsers) { 1910 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1911 mDexManager.notifyPackageInstalled(info, userId); 1912 } 1913 } 1914 1915 // If someone is watching installs - notify them 1916 if (installObserver != null) { 1917 try { 1918 Bundle extras = extrasForInstallResult(res); 1919 installObserver.onPackageInstalled(res.name, res.returnCode, 1920 res.returnMsg, extras); 1921 } catch (RemoteException e) { 1922 Slog.i(TAG, "Observer no longer exists."); 1923 } 1924 } 1925 } 1926 1927 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1928 PackageParser.Package pkg) { 1929 if (pkg.parentPackage == null) { 1930 return; 1931 } 1932 if (pkg.requestedPermissions == null) { 1933 return; 1934 } 1935 final PackageSetting disabledSysParentPs = mSettings 1936 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1937 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1938 || !disabledSysParentPs.isPrivileged() 1939 || (disabledSysParentPs.childPackageNames != null 1940 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1941 return; 1942 } 1943 final int[] allUserIds = sUserManager.getUserIds(); 1944 final int permCount = pkg.requestedPermissions.size(); 1945 for (int i = 0; i < permCount; i++) { 1946 String permission = pkg.requestedPermissions.get(i); 1947 BasePermission bp = mSettings.mPermissions.get(permission); 1948 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1949 continue; 1950 } 1951 for (int userId : allUserIds) { 1952 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1953 permission, userId)) { 1954 grantRuntimePermission(pkg.packageName, permission, userId); 1955 } 1956 } 1957 } 1958 } 1959 1960 private StorageEventListener mStorageListener = new StorageEventListener() { 1961 @Override 1962 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1963 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1964 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1965 final String volumeUuid = vol.getFsUuid(); 1966 1967 // Clean up any users or apps that were removed or recreated 1968 // while this volume was missing 1969 sUserManager.reconcileUsers(volumeUuid); 1970 reconcileApps(volumeUuid); 1971 1972 // Clean up any install sessions that expired or were 1973 // cancelled while this volume was missing 1974 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1975 1976 loadPrivatePackages(vol); 1977 1978 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1979 unloadPrivatePackages(vol); 1980 } 1981 } 1982 1983 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1984 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1985 updateExternalMediaStatus(true, false); 1986 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1987 updateExternalMediaStatus(false, false); 1988 } 1989 } 1990 } 1991 1992 @Override 1993 public void onVolumeForgotten(String fsUuid) { 1994 if (TextUtils.isEmpty(fsUuid)) { 1995 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1996 return; 1997 } 1998 1999 // Remove any apps installed on the forgotten volume 2000 synchronized (mPackages) { 2001 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2002 for (PackageSetting ps : packages) { 2003 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2004 deletePackageVersioned(new VersionedPackage(ps.name, 2005 PackageManager.VERSION_CODE_HIGHEST), 2006 new LegacyPackageDeleteObserver(null).getBinder(), 2007 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2008 // Try very hard to release any references to this package 2009 // so we don't risk the system server being killed due to 2010 // open FDs 2011 AttributeCache.instance().removePackage(ps.name); 2012 } 2013 2014 mSettings.onVolumeForgotten(fsUuid); 2015 mSettings.writeLPr(); 2016 } 2017 } 2018 }; 2019 2020 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2021 String[] grantedPermissions) { 2022 for (int userId : userIds) { 2023 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2024 } 2025 } 2026 2027 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2028 String[] grantedPermissions) { 2029 SettingBase sb = (SettingBase) pkg.mExtras; 2030 if (sb == null) { 2031 return; 2032 } 2033 2034 PermissionsState permissionsState = sb.getPermissionsState(); 2035 2036 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2037 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2038 2039 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2040 >= Build.VERSION_CODES.M; 2041 2042 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2043 2044 for (String permission : pkg.requestedPermissions) { 2045 final BasePermission bp; 2046 synchronized (mPackages) { 2047 bp = mSettings.mPermissions.get(permission); 2048 } 2049 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2050 && (!instantApp || bp.isInstant()) 2051 && (grantedPermissions == null 2052 || ArrayUtils.contains(grantedPermissions, permission))) { 2053 final int flags = permissionsState.getPermissionFlags(permission, userId); 2054 if (supportsRuntimePermissions) { 2055 // Installer cannot change immutable permissions. 2056 if ((flags & immutableFlags) == 0) { 2057 grantRuntimePermission(pkg.packageName, permission, userId); 2058 } 2059 } else if (mPermissionReviewRequired) { 2060 // In permission review mode we clear the review flag when we 2061 // are asked to install the app with all permissions granted. 2062 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2063 updatePermissionFlags(permission, pkg.packageName, 2064 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2065 } 2066 } 2067 } 2068 } 2069 } 2070 2071 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2072 Bundle extras = null; 2073 switch (res.returnCode) { 2074 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2075 extras = new Bundle(); 2076 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2077 res.origPermission); 2078 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2079 res.origPackage); 2080 break; 2081 } 2082 case PackageManager.INSTALL_SUCCEEDED: { 2083 extras = new Bundle(); 2084 extras.putBoolean(Intent.EXTRA_REPLACING, 2085 res.removedInfo != null && res.removedInfo.removedPackage != null); 2086 break; 2087 } 2088 } 2089 return extras; 2090 } 2091 2092 void scheduleWriteSettingsLocked() { 2093 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2094 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2095 } 2096 } 2097 2098 void scheduleWritePackageListLocked(int userId) { 2099 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2100 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2101 msg.arg1 = userId; 2102 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2103 } 2104 } 2105 2106 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2107 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2108 scheduleWritePackageRestrictionsLocked(userId); 2109 } 2110 2111 void scheduleWritePackageRestrictionsLocked(int userId) { 2112 final int[] userIds = (userId == UserHandle.USER_ALL) 2113 ? sUserManager.getUserIds() : new int[]{userId}; 2114 for (int nextUserId : userIds) { 2115 if (!sUserManager.exists(nextUserId)) return; 2116 mDirtyUsers.add(nextUserId); 2117 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2118 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2119 } 2120 } 2121 } 2122 2123 public static PackageManagerService main(Context context, Installer installer, 2124 boolean factoryTest, boolean onlyCore) { 2125 // Self-check for initial settings. 2126 PackageManagerServiceCompilerMapping.checkProperties(); 2127 2128 PackageManagerService m = new PackageManagerService(context, installer, 2129 factoryTest, onlyCore); 2130 m.enableSystemUserPackages(); 2131 ServiceManager.addService("package", m); 2132 return m; 2133 } 2134 2135 private void enableSystemUserPackages() { 2136 if (!UserManager.isSplitSystemUser()) { 2137 return; 2138 } 2139 // For system user, enable apps based on the following conditions: 2140 // - app is whitelisted or belong to one of these groups: 2141 // -- system app which has no launcher icons 2142 // -- system app which has INTERACT_ACROSS_USERS permission 2143 // -- system IME app 2144 // - app is not in the blacklist 2145 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2146 Set<String> enableApps = new ArraySet<>(); 2147 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2148 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2149 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2150 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2151 enableApps.addAll(wlApps); 2152 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2153 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2154 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2155 enableApps.removeAll(blApps); 2156 Log.i(TAG, "Applications installed for system user: " + enableApps); 2157 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2158 UserHandle.SYSTEM); 2159 final int allAppsSize = allAps.size(); 2160 synchronized (mPackages) { 2161 for (int i = 0; i < allAppsSize; i++) { 2162 String pName = allAps.get(i); 2163 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2164 // Should not happen, but we shouldn't be failing if it does 2165 if (pkgSetting == null) { 2166 continue; 2167 } 2168 boolean install = enableApps.contains(pName); 2169 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2170 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2171 + " for system user"); 2172 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2173 } 2174 } 2175 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2176 } 2177 } 2178 2179 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2180 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2181 Context.DISPLAY_SERVICE); 2182 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2183 } 2184 2185 /** 2186 * Requests that files preopted on a secondary system partition be copied to the data partition 2187 * if possible. Note that the actual copying of the files is accomplished by init for security 2188 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2189 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2190 */ 2191 private static void requestCopyPreoptedFiles() { 2192 final int WAIT_TIME_MS = 100; 2193 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2194 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2195 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2196 // We will wait for up to 100 seconds. 2197 final long timeStart = SystemClock.uptimeMillis(); 2198 final long timeEnd = timeStart + 100 * 1000; 2199 long timeNow = timeStart; 2200 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2201 try { 2202 Thread.sleep(WAIT_TIME_MS); 2203 } catch (InterruptedException e) { 2204 // Do nothing 2205 } 2206 timeNow = SystemClock.uptimeMillis(); 2207 if (timeNow > timeEnd) { 2208 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2209 Slog.wtf(TAG, "cppreopt did not finish!"); 2210 break; 2211 } 2212 } 2213 2214 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2215 } 2216 } 2217 2218 public PackageManagerService(Context context, Installer installer, 2219 boolean factoryTest, boolean onlyCore) { 2220 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2221 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2222 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2223 SystemClock.uptimeMillis()); 2224 2225 if (mSdkVersion <= 0) { 2226 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2227 } 2228 2229 mContext = context; 2230 2231 mPermissionReviewRequired = context.getResources().getBoolean( 2232 R.bool.config_permissionReviewRequired); 2233 2234 mFactoryTest = factoryTest; 2235 mOnlyCore = onlyCore; 2236 mMetrics = new DisplayMetrics(); 2237 mSettings = new Settings(mPackages); 2238 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2245 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2246 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2247 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2248 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2249 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2250 2251 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2252 if (separateProcesses != null && separateProcesses.length() > 0) { 2253 if ("*".equals(separateProcesses)) { 2254 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2255 mSeparateProcesses = null; 2256 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = separateProcesses.split(","); 2260 Slog.w(TAG, "Running with debug.separate_processes: " 2261 + separateProcesses); 2262 } 2263 } else { 2264 mDefParseFlags = 0; 2265 mSeparateProcesses = null; 2266 } 2267 2268 mInstaller = installer; 2269 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2270 "*dexopt*"); 2271 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2272 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2273 2274 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2275 FgThread.get().getLooper()); 2276 2277 getDefaultDisplayMetrics(context, mMetrics); 2278 2279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2280 SystemConfig systemConfig = SystemConfig.getInstance(); 2281 mGlobalGids = systemConfig.getGlobalGids(); 2282 mSystemPermissions = systemConfig.getSystemPermissions(); 2283 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2285 2286 mProtectedPackages = new ProtectedPackages(mContext); 2287 2288 synchronized (mInstallLock) { 2289 // writer 2290 synchronized (mPackages) { 2291 mHandlerThread = new ServiceThread(TAG, 2292 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2293 mHandlerThread.start(); 2294 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2295 mProcessLoggingHandler = new ProcessLoggingHandler(); 2296 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2297 2298 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2299 mInstantAppRegistry = new InstantAppRegistry(this); 2300 2301 File dataDir = Environment.getDataDirectory(); 2302 mAppInstallDir = new File(dataDir, "app"); 2303 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2304 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2305 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2306 sUserManager = new UserManagerService(context, this, 2307 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2308 2309 // Propagate permission configuration in to package manager. 2310 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2311 = systemConfig.getPermissions(); 2312 for (int i=0; i<permConfig.size(); i++) { 2313 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2314 BasePermission bp = mSettings.mPermissions.get(perm.name); 2315 if (bp == null) { 2316 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2317 mSettings.mPermissions.put(perm.name, bp); 2318 } 2319 if (perm.gids != null) { 2320 bp.setGids(perm.gids, perm.perUser); 2321 } 2322 } 2323 2324 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2325 final int builtInLibCount = libConfig.size(); 2326 for (int i = 0; i < builtInLibCount; i++) { 2327 String name = libConfig.keyAt(i); 2328 String path = libConfig.valueAt(i); 2329 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2330 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2331 } 2332 2333 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2334 2335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2336 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2338 2339 // Clean up orphaned packages for which the code path doesn't exist 2340 // and they are an update to a system app - caused by bug/32321269 2341 final int packageSettingCount = mSettings.mPackages.size(); 2342 for (int i = packageSettingCount - 1; i >= 0; i--) { 2343 PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2345 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2346 mSettings.mPackages.removeAt(i); 2347 mSettings.enableSystemPackageLPw(ps.name); 2348 } 2349 } 2350 2351 if (mFirstBoot) { 2352 requestCopyPreoptedFiles(); 2353 } 2354 2355 String customResolverActivity = Resources.getSystem().getString( 2356 R.string.config_customResolverActivity); 2357 if (TextUtils.isEmpty(customResolverActivity)) { 2358 customResolverActivity = null; 2359 } else { 2360 mCustomResolverComponentName = ComponentName.unflattenFromString( 2361 customResolverActivity); 2362 } 2363 2364 long startTime = SystemClock.uptimeMillis(); 2365 2366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2367 startTime); 2368 2369 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2370 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2371 2372 if (bootClassPath == null) { 2373 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2374 } 2375 2376 if (systemServerClassPath == null) { 2377 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2378 } 2379 2380 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2381 final String[] dexCodeInstructionSets = 2382 getDexCodeInstructionSets( 2383 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2384 2385 /** 2386 * Ensure all external libraries have had dexopt run on them. 2387 */ 2388 if (mSharedLibraries.size() > 0) { 2389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2390 // NOTE: For now, we're compiling these system "shared libraries" 2391 // (and framework jars) into all available architectures. It's possible 2392 // to compile them only when we come across an app that uses them (there's 2393 // already logic for that in scanPackageLI) but that adds some complexity. 2394 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2395 final int libCount = mSharedLibraries.size(); 2396 for (int i = 0; i < libCount; i++) { 2397 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2398 final int versionCount = versionedLib.size(); 2399 for (int j = 0; j < versionCount; j++) { 2400 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2401 final String libPath = libEntry.path != null 2402 ? libEntry.path : libEntry.apk; 2403 if (libPath == null) { 2404 continue; 2405 } 2406 try { 2407 // Shared libraries do not have profiles so we perform a full 2408 // AOT compilation (if needed). 2409 int dexoptNeeded = DexFile.getDexOptNeeded( 2410 libPath, dexCodeInstructionSet, 2411 getCompilerFilterForReason(REASON_SHARED_APK), 2412 false /* newProfile */); 2413 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2414 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2415 dexCodeInstructionSet, dexoptNeeded, null, 2416 DEXOPT_PUBLIC, 2417 getCompilerFilterForReason(REASON_SHARED_APK), 2418 StorageManager.UUID_PRIVATE_INTERNAL, 2419 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2420 } 2421 } catch (FileNotFoundException e) { 2422 Slog.w(TAG, "Library not found: " + libPath); 2423 } catch (IOException | InstallerException e) { 2424 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2425 + e.getMessage()); 2426 } 2427 } 2428 } 2429 } 2430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2431 } 2432 2433 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2434 2435 final VersionInfo ver = mSettings.getInternalVersion(); 2436 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2437 2438 // when upgrading from pre-M, promote system app permissions from install to runtime 2439 mPromoteSystemApps = 2440 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2441 2442 // When upgrading from pre-N, we need to handle package extraction like first boot, 2443 // as there is no profiling data available. 2444 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2445 2446 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2447 2448 // save off the names of pre-existing system packages prior to scanning; we don't 2449 // want to automatically grant runtime permissions for new system apps 2450 if (mPromoteSystemApps) { 2451 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2452 while (pkgSettingIter.hasNext()) { 2453 PackageSetting ps = pkgSettingIter.next(); 2454 if (isSystemApp(ps)) { 2455 mExistingSystemPackages.add(ps.name); 2456 } 2457 } 2458 } 2459 2460 mCacheDir = preparePackageParserCache(mIsUpgrade); 2461 2462 // Set flag to monitor and not change apk file paths when 2463 // scanning install directories. 2464 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2465 2466 if (mIsUpgrade || mFirstBoot) { 2467 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2468 } 2469 2470 // Collect vendor overlay packages. (Do this before scanning any apps.) 2471 // For security and version matching reason, only consider 2472 // overlay packages if they reside in the right directory. 2473 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2474 | PackageParser.PARSE_IS_SYSTEM 2475 | PackageParser.PARSE_IS_SYSTEM_DIR 2476 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2477 2478 // Find base frameworks (resource packages without code). 2479 scanDirTracedLI(frameworkDir, mDefParseFlags 2480 | PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR 2482 | PackageParser.PARSE_IS_PRIVILEGED, 2483 scanFlags | SCAN_NO_DEX, 0); 2484 2485 // Collected privileged system packages. 2486 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2487 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2488 | PackageParser.PARSE_IS_SYSTEM 2489 | PackageParser.PARSE_IS_SYSTEM_DIR 2490 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2491 2492 // Collect ordinary system packages. 2493 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2494 scanDirTracedLI(systemAppDir, mDefParseFlags 2495 | PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2497 2498 // Collect all vendor packages. 2499 File vendorAppDir = new File("/vendor/app"); 2500 try { 2501 vendorAppDir = vendorAppDir.getCanonicalFile(); 2502 } catch (IOException e) { 2503 // failed to look up canonical path, continue with original one 2504 } 2505 scanDirTracedLI(vendorAppDir, mDefParseFlags 2506 | PackageParser.PARSE_IS_SYSTEM 2507 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2508 2509 // Collect all OEM packages. 2510 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2511 scanDirTracedLI(oemAppDir, mDefParseFlags 2512 | PackageParser.PARSE_IS_SYSTEM 2513 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2514 2515 // Prune any system packages that no longer exist. 2516 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2517 if (!mOnlyCore) { 2518 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2519 while (psit.hasNext()) { 2520 PackageSetting ps = psit.next(); 2521 2522 /* 2523 * If this is not a system app, it can't be a 2524 * disable system app. 2525 */ 2526 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2527 continue; 2528 } 2529 2530 /* 2531 * If the package is scanned, it's not erased. 2532 */ 2533 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2534 if (scannedPkg != null) { 2535 /* 2536 * If the system app is both scanned and in the 2537 * disabled packages list, then it must have been 2538 * added via OTA. Remove it from the currently 2539 * scanned package so the previously user-installed 2540 * application can be scanned. 2541 */ 2542 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2543 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2544 + ps.name + "; removing system app. Last known codePath=" 2545 + ps.codePathString + ", installStatus=" + ps.installStatus 2546 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2547 + scannedPkg.mVersionCode); 2548 removePackageLI(scannedPkg, true); 2549 mExpectingBetter.put(ps.name, ps.codePath); 2550 } 2551 2552 continue; 2553 } 2554 2555 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2556 psit.remove(); 2557 logCriticalInfo(Log.WARN, "System package " + ps.name 2558 + " no longer exists; it's data will be wiped"); 2559 // Actual deletion of code and data will be handled by later 2560 // reconciliation step 2561 } else { 2562 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2563 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2564 possiblyDeletedUpdatedSystemApps.add(ps.name); 2565 } 2566 } 2567 } 2568 } 2569 2570 //look for any incomplete package installations 2571 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2572 for (int i = 0; i < deletePkgsList.size(); i++) { 2573 // Actual deletion of code and data will be handled by later 2574 // reconciliation step 2575 final String packageName = deletePkgsList.get(i).name; 2576 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2577 synchronized (mPackages) { 2578 mSettings.removePackageLPw(packageName); 2579 } 2580 } 2581 2582 //delete tmp files 2583 deleteTempPackageFiles(); 2584 2585 // Remove any shared userIDs that have no associated packages 2586 mSettings.pruneSharedUsersLPw(); 2587 2588 if (!mOnlyCore) { 2589 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2590 SystemClock.uptimeMillis()); 2591 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2592 2593 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2594 | PackageParser.PARSE_FORWARD_LOCK, 2595 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2596 2597 /** 2598 * Remove disable package settings for any updated system 2599 * apps that were removed via an OTA. If they're not a 2600 * previously-updated app, remove them completely. 2601 * Otherwise, just revoke their system-level permissions. 2602 */ 2603 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2604 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2605 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2606 2607 String msg; 2608 if (deletedPkg == null) { 2609 msg = "Updated system package " + deletedAppName 2610 + " no longer exists; it's data will be wiped"; 2611 // Actual deletion of code and data will be handled by later 2612 // reconciliation step 2613 } else { 2614 msg = "Updated system app + " + deletedAppName 2615 + " no longer present; removing system privileges for " 2616 + deletedAppName; 2617 2618 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2619 2620 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2621 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2622 } 2623 logCriticalInfo(Log.WARN, msg); 2624 } 2625 2626 /** 2627 * Make sure all system apps that we expected to appear on 2628 * the userdata partition actually showed up. If they never 2629 * appeared, crawl back and revive the system version. 2630 */ 2631 for (int i = 0; i < mExpectingBetter.size(); i++) { 2632 final String packageName = mExpectingBetter.keyAt(i); 2633 if (!mPackages.containsKey(packageName)) { 2634 final File scanFile = mExpectingBetter.valueAt(i); 2635 2636 logCriticalInfo(Log.WARN, "Expected better " + packageName 2637 + " but never showed up; reverting to system"); 2638 2639 int reparseFlags = mDefParseFlags; 2640 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2641 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2642 | PackageParser.PARSE_IS_SYSTEM_DIR 2643 | PackageParser.PARSE_IS_PRIVILEGED; 2644 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR; 2647 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2648 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2649 | PackageParser.PARSE_IS_SYSTEM_DIR; 2650 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2651 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2652 | PackageParser.PARSE_IS_SYSTEM_DIR; 2653 } else { 2654 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2655 continue; 2656 } 2657 2658 mSettings.enableSystemPackageLPw(packageName); 2659 2660 try { 2661 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2662 } catch (PackageManagerException e) { 2663 Slog.e(TAG, "Failed to parse original system package: " 2664 + e.getMessage()); 2665 } 2666 } 2667 } 2668 } 2669 mExpectingBetter.clear(); 2670 2671 // Resolve the storage manager. 2672 mStorageManagerPackage = getStorageManagerPackageName(); 2673 2674 // Resolve protected action filters. Only the setup wizard is allowed to 2675 // have a high priority filter for these actions. 2676 mSetupWizardPackage = getSetupWizardPackageName(); 2677 if (mProtectedFilters.size() > 0) { 2678 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2679 Slog.i(TAG, "No setup wizard;" 2680 + " All protected intents capped to priority 0"); 2681 } 2682 for (ActivityIntentInfo filter : mProtectedFilters) { 2683 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2684 if (DEBUG_FILTERS) { 2685 Slog.i(TAG, "Found setup wizard;" 2686 + " allow priority " + filter.getPriority() + ";" 2687 + " package: " + filter.activity.info.packageName 2688 + " activity: " + filter.activity.className 2689 + " priority: " + filter.getPriority()); 2690 } 2691 // skip setup wizard; allow it to keep the high priority filter 2692 continue; 2693 } 2694 Slog.w(TAG, "Protected action; cap priority to 0;" 2695 + " package: " + filter.activity.info.packageName 2696 + " activity: " + filter.activity.className 2697 + " origPrio: " + filter.getPriority()); 2698 filter.setPriority(0); 2699 } 2700 } 2701 mDeferProtectedFilters = false; 2702 mProtectedFilters.clear(); 2703 2704 // Now that we know all of the shared libraries, update all clients to have 2705 // the correct library paths. 2706 updateAllSharedLibrariesLPw(null); 2707 2708 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2709 // NOTE: We ignore potential failures here during a system scan (like 2710 // the rest of the commands above) because there's precious little we 2711 // can do about it. A settings error is reported, though. 2712 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2713 } 2714 2715 // Now that we know all the packages we are keeping, 2716 // read and update their last usage times. 2717 mPackageUsage.read(mPackages); 2718 mCompilerStats.read(); 2719 2720 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2721 SystemClock.uptimeMillis()); 2722 Slog.i(TAG, "Time to scan packages: " 2723 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2724 + " seconds"); 2725 2726 // If the platform SDK has changed since the last time we booted, 2727 // we need to re-grant app permission to catch any new ones that 2728 // appear. This is really a hack, and means that apps can in some 2729 // cases get permissions that the user didn't initially explicitly 2730 // allow... it would be nice to have some better way to handle 2731 // this situation. 2732 int updateFlags = UPDATE_PERMISSIONS_ALL; 2733 if (ver.sdkVersion != mSdkVersion) { 2734 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2735 + mSdkVersion + "; regranting permissions for internal storage"); 2736 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2737 } 2738 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2739 ver.sdkVersion = mSdkVersion; 2740 2741 // If this is the first boot or an update from pre-M, and it is a normal 2742 // boot, then we need to initialize the default preferred apps across 2743 // all defined users. 2744 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2745 for (UserInfo user : sUserManager.getUsers(true)) { 2746 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2747 applyFactoryDefaultBrowserLPw(user.id); 2748 primeDomainVerificationsLPw(user.id); 2749 } 2750 } 2751 2752 // Prepare storage for system user really early during boot, 2753 // since core system apps like SettingsProvider and SystemUI 2754 // can't wait for user to start 2755 final int storageFlags; 2756 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2757 storageFlags = StorageManager.FLAG_STORAGE_DE; 2758 } else { 2759 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2760 } 2761 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2762 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2763 true /* onlyCoreApps */); 2764 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2765 if (deferPackages == null || deferPackages.isEmpty()) { 2766 return; 2767 } 2768 int count = 0; 2769 for (String pkgName : deferPackages) { 2770 PackageParser.Package pkg = null; 2771 synchronized (mPackages) { 2772 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2773 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2774 pkg = ps.pkg; 2775 } 2776 } 2777 if (pkg != null) { 2778 synchronized (mInstallLock) { 2779 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2780 true /* maybeMigrateAppData */); 2781 } 2782 count++; 2783 } 2784 } 2785 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2786 }, "prepareAppData"); 2787 2788 // If this is first boot after an OTA, and a normal boot, then 2789 // we need to clear code cache directories. 2790 // Note that we do *not* clear the application profiles. These remain valid 2791 // across OTAs and are used to drive profile verification (post OTA) and 2792 // profile compilation (without waiting to collect a fresh set of profiles). 2793 if (mIsUpgrade && !onlyCore) { 2794 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2795 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2796 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2797 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2798 // No apps are running this early, so no need to freeze 2799 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2800 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2801 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2802 } 2803 } 2804 ver.fingerprint = Build.FINGERPRINT; 2805 } 2806 2807 checkDefaultBrowser(); 2808 2809 // clear only after permissions and other defaults have been updated 2810 mExistingSystemPackages.clear(); 2811 mPromoteSystemApps = false; 2812 2813 // All the changes are done during package scanning. 2814 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2815 2816 // can downgrade to reader 2817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2818 mSettings.writeLPr(); 2819 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2820 2821 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2822 SystemClock.uptimeMillis()); 2823 2824 if (!mOnlyCore) { 2825 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2826 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2827 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2828 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2829 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2830 mIntentFilterVerifierComponent); 2831 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2832 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2833 SharedLibraryInfo.VERSION_UNDEFINED); 2834 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2835 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2836 SharedLibraryInfo.VERSION_UNDEFINED); 2837 } else { 2838 mRequiredVerifierPackage = null; 2839 mRequiredInstallerPackage = null; 2840 mRequiredUninstallerPackage = null; 2841 mIntentFilterVerifierComponent = null; 2842 mIntentFilterVerifier = null; 2843 mServicesSystemSharedLibraryPackageName = null; 2844 mSharedSystemSharedLibraryPackageName = null; 2845 } 2846 2847 mInstallerService = new PackageInstallerService(context, this); 2848 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2849 if (ephemeralResolverComponent != null) { 2850 if (DEBUG_EPHEMERAL) { 2851 Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent); 2852 } 2853 mInstantAppResolverConnection = 2854 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2855 } else { 2856 mInstantAppResolverConnection = null; 2857 } 2858 updateInstantAppInstallerLocked(); 2859 mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr(); 2860 2861 // Read and update the usage of dex files. 2862 // Do this at the end of PM init so that all the packages have their 2863 // data directory reconciled. 2864 // At this point we know the code paths of the packages, so we can validate 2865 // the disk file and build the internal cache. 2866 // The usage file is expected to be small so loading and verifying it 2867 // should take a fairly small time compare to the other activities (e.g. package 2868 // scanning). 2869 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2870 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2871 for (int userId : currentUserIds) { 2872 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2873 } 2874 mDexManager.load(userPackages); 2875 } // synchronized (mPackages) 2876 } // synchronized (mInstallLock) 2877 2878 // Now after opening every single application zip, make sure they 2879 // are all flushed. Not really needed, but keeps things nice and 2880 // tidy. 2881 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2882 Runtime.getRuntime().gc(); 2883 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2884 2885 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2886 FallbackCategoryProvider.loadFallbacks(); 2887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2888 2889 // The initial scanning above does many calls into installd while 2890 // holding the mPackages lock, but we're mostly interested in yelling 2891 // once we have a booted system. 2892 mInstaller.setWarnIfHeld(mPackages); 2893 2894 // Expose private service for system components to use. 2895 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2897 } 2898 2899 private void updateInstantAppInstallerLocked() { 2900 final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent; 2901 final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr(); 2902 ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null 2903 ? null : newInstantAppInstaller.getComponentName(); 2904 2905 if (newInstantAppInstallerComponent != null 2906 && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) { 2907 if (DEBUG_EPHEMERAL) { 2908 Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent); 2909 } 2910 setUpInstantAppInstallerActivityLP(newInstantAppInstaller); 2911 } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) { 2912 Slog.d(TAG, "Unset ephemeral installer; none available"); 2913 } 2914 mInstantAppInstallerComponent = newInstantAppInstallerComponent; 2915 } 2916 2917 private static File preparePackageParserCache(boolean isUpgrade) { 2918 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2919 return null; 2920 } 2921 2922 // Disable package parsing on eng builds to allow for faster incremental development. 2923 if ("eng".equals(Build.TYPE)) { 2924 return null; 2925 } 2926 2927 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2928 Slog.i(TAG, "Disabling package parser cache due to system property."); 2929 return null; 2930 } 2931 2932 // The base directory for the package parser cache lives under /data/system/. 2933 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2934 "package_cache"); 2935 if (cacheBaseDir == null) { 2936 return null; 2937 } 2938 2939 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2940 // This also serves to "GC" unused entries when the package cache version changes (which 2941 // can only happen during upgrades). 2942 if (isUpgrade) { 2943 FileUtils.deleteContents(cacheBaseDir); 2944 } 2945 2946 2947 // Return the versioned package cache directory. This is something like 2948 // "/data/system/package_cache/1" 2949 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2950 2951 // The following is a workaround to aid development on non-numbered userdebug 2952 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2953 // the system partition is newer. 2954 // 2955 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2956 // that starts with "eng." to signify that this is an engineering build and not 2957 // destined for release. 2958 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2959 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2960 2961 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2962 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2963 // in general and should not be used for production changes. In this specific case, 2964 // we know that they will work. 2965 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2966 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2967 FileUtils.deleteContents(cacheBaseDir); 2968 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2969 } 2970 } 2971 2972 return cacheDir; 2973 } 2974 2975 @Override 2976 public boolean isFirstBoot() { 2977 return mFirstBoot; 2978 } 2979 2980 @Override 2981 public boolean isOnlyCoreApps() { 2982 return mOnlyCore; 2983 } 2984 2985 @Override 2986 public boolean isUpgrade() { 2987 return mIsUpgrade; 2988 } 2989 2990 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2991 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2992 2993 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2994 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2995 UserHandle.USER_SYSTEM); 2996 if (matches.size() == 1) { 2997 return matches.get(0).getComponentInfo().packageName; 2998 } else if (matches.size() == 0) { 2999 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3000 return null; 3001 } 3002 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3003 } 3004 3005 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3006 synchronized (mPackages) { 3007 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3008 if (libraryEntry == null) { 3009 throw new IllegalStateException("Missing required shared library:" + name); 3010 } 3011 return libraryEntry.apk; 3012 } 3013 } 3014 3015 private @NonNull String getRequiredInstallerLPr() { 3016 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3017 intent.addCategory(Intent.CATEGORY_DEFAULT); 3018 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3019 3020 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3021 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3022 UserHandle.USER_SYSTEM); 3023 if (matches.size() == 1) { 3024 ResolveInfo resolveInfo = matches.get(0); 3025 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3026 throw new RuntimeException("The installer must be a privileged app"); 3027 } 3028 return matches.get(0).getComponentInfo().packageName; 3029 } else { 3030 throw new RuntimeException("There must be exactly one installer; found " + matches); 3031 } 3032 } 3033 3034 private @NonNull String getRequiredUninstallerLPr() { 3035 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3036 intent.addCategory(Intent.CATEGORY_DEFAULT); 3037 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3038 3039 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3040 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3041 UserHandle.USER_SYSTEM); 3042 if (resolveInfo == null || 3043 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3044 throw new RuntimeException("There must be exactly one uninstaller; found " 3045 + resolveInfo); 3046 } 3047 return resolveInfo.getComponentInfo().packageName; 3048 } 3049 3050 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3051 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3052 3053 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3054 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3055 UserHandle.USER_SYSTEM); 3056 ResolveInfo best = null; 3057 final int N = matches.size(); 3058 for (int i = 0; i < N; i++) { 3059 final ResolveInfo cur = matches.get(i); 3060 final String packageName = cur.getComponentInfo().packageName; 3061 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3062 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3063 continue; 3064 } 3065 3066 if (best == null || cur.priority > best.priority) { 3067 best = cur; 3068 } 3069 } 3070 3071 if (best != null) { 3072 return best.getComponentInfo().getComponentName(); 3073 } else { 3074 throw new RuntimeException("There must be at least one intent filter verifier"); 3075 } 3076 } 3077 3078 private @Nullable ComponentName getEphemeralResolverLPr() { 3079 final String[] packageArray = 3080 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3081 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3082 if (DEBUG_EPHEMERAL) { 3083 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3084 } 3085 return null; 3086 } 3087 3088 final int resolveFlags = 3089 MATCH_DIRECT_BOOT_AWARE 3090 | MATCH_DIRECT_BOOT_UNAWARE 3091 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3092 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3093 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3094 resolveFlags, UserHandle.USER_SYSTEM); 3095 3096 final int N = resolvers.size(); 3097 if (N == 0) { 3098 if (DEBUG_EPHEMERAL) { 3099 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3100 } 3101 return null; 3102 } 3103 3104 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3105 for (int i = 0; i < N; i++) { 3106 final ResolveInfo info = resolvers.get(i); 3107 3108 if (info.serviceInfo == null) { 3109 continue; 3110 } 3111 3112 final String packageName = info.serviceInfo.packageName; 3113 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3114 if (DEBUG_EPHEMERAL) { 3115 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3116 + " pkg: " + packageName + ", info:" + info); 3117 } 3118 continue; 3119 } 3120 3121 if (DEBUG_EPHEMERAL) { 3122 Slog.v(TAG, "Ephemeral resolver found;" 3123 + " pkg: " + packageName + ", info:" + info); 3124 } 3125 return new ComponentName(packageName, info.serviceInfo.name); 3126 } 3127 if (DEBUG_EPHEMERAL) { 3128 Slog.v(TAG, "Ephemeral resolver NOT found"); 3129 } 3130 return null; 3131 } 3132 3133 private @Nullable ActivityInfo getEphemeralInstallerLPr() { 3134 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3135 intent.addCategory(Intent.CATEGORY_DEFAULT); 3136 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3137 3138 final int resolveFlags = 3139 MATCH_DIRECT_BOOT_AWARE 3140 | MATCH_DIRECT_BOOT_UNAWARE 3141 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3142 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3143 resolveFlags, UserHandle.USER_SYSTEM); 3144 Iterator<ResolveInfo> iter = matches.iterator(); 3145 while (iter.hasNext()) { 3146 final ResolveInfo rInfo = iter.next(); 3147 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3148 if (ps != null) { 3149 final PermissionsState permissionsState = ps.getPermissionsState(); 3150 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3151 continue; 3152 } 3153 } 3154 iter.remove(); 3155 } 3156 if (matches.size() == 0) { 3157 return null; 3158 } else if (matches.size() == 1) { 3159 return (ActivityInfo) matches.get(0).getComponentInfo(); 3160 } else { 3161 throw new RuntimeException( 3162 "There must be at most one ephemeral installer; found " + matches); 3163 } 3164 } 3165 3166 private @Nullable ComponentName getEphemeralResolverSettingsLPr() { 3167 final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3168 intent.addCategory(Intent.CATEGORY_DEFAULT); 3169 final int resolveFlags = 3170 MATCH_DIRECT_BOOT_AWARE 3171 | MATCH_DIRECT_BOOT_UNAWARE 3172 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3173 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 3174 resolveFlags, UserHandle.USER_SYSTEM); 3175 Iterator<ResolveInfo> iter = matches.iterator(); 3176 while (iter.hasNext()) { 3177 final ResolveInfo rInfo = iter.next(); 3178 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3179 if (ps != null) { 3180 final PermissionsState permissionsState = ps.getPermissionsState(); 3181 if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) { 3182 continue; 3183 } 3184 } 3185 iter.remove(); 3186 } 3187 if (matches.size() == 0) { 3188 return null; 3189 } else if (matches.size() == 1) { 3190 return matches.get(0).getComponentInfo().getComponentName(); 3191 } else { 3192 throw new RuntimeException( 3193 "There must be at most one ephemeral resolver settings; found " + matches); 3194 } 3195 } 3196 3197 private void primeDomainVerificationsLPw(int userId) { 3198 if (DEBUG_DOMAIN_VERIFICATION) { 3199 Slog.d(TAG, "Priming domain verifications in user " + userId); 3200 } 3201 3202 SystemConfig systemConfig = SystemConfig.getInstance(); 3203 ArraySet<String> packages = systemConfig.getLinkedApps(); 3204 3205 for (String packageName : packages) { 3206 PackageParser.Package pkg = mPackages.get(packageName); 3207 if (pkg != null) { 3208 if (!pkg.isSystemApp()) { 3209 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3210 continue; 3211 } 3212 3213 ArraySet<String> domains = null; 3214 for (PackageParser.Activity a : pkg.activities) { 3215 for (ActivityIntentInfo filter : a.intents) { 3216 if (hasValidDomains(filter)) { 3217 if (domains == null) { 3218 domains = new ArraySet<String>(); 3219 } 3220 domains.addAll(filter.getHostsList()); 3221 } 3222 } 3223 } 3224 3225 if (domains != null && domains.size() > 0) { 3226 if (DEBUG_DOMAIN_VERIFICATION) { 3227 Slog.v(TAG, " + " + packageName); 3228 } 3229 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3230 // state w.r.t. the formal app-linkage "no verification attempted" state; 3231 // and then 'always' in the per-user state actually used for intent resolution. 3232 final IntentFilterVerificationInfo ivi; 3233 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3234 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3235 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3236 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3237 } else { 3238 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3239 + "' does not handle web links"); 3240 } 3241 } else { 3242 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3243 } 3244 } 3245 3246 scheduleWritePackageRestrictionsLocked(userId); 3247 scheduleWriteSettingsLocked(); 3248 } 3249 3250 private void applyFactoryDefaultBrowserLPw(int userId) { 3251 // The default browser app's package name is stored in a string resource, 3252 // with a product-specific overlay used for vendor customization. 3253 String browserPkg = mContext.getResources().getString( 3254 com.android.internal.R.string.default_browser); 3255 if (!TextUtils.isEmpty(browserPkg)) { 3256 // non-empty string => required to be a known package 3257 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3258 if (ps == null) { 3259 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3260 browserPkg = null; 3261 } else { 3262 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3263 } 3264 } 3265 3266 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3267 // default. If there's more than one, just leave everything alone. 3268 if (browserPkg == null) { 3269 calculateDefaultBrowserLPw(userId); 3270 } 3271 } 3272 3273 private void calculateDefaultBrowserLPw(int userId) { 3274 List<String> allBrowsers = resolveAllBrowserApps(userId); 3275 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3276 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3277 } 3278 3279 private List<String> resolveAllBrowserApps(int userId) { 3280 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3281 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3282 PackageManager.MATCH_ALL, userId); 3283 3284 final int count = list.size(); 3285 List<String> result = new ArrayList<String>(count); 3286 for (int i=0; i<count; i++) { 3287 ResolveInfo info = list.get(i); 3288 if (info.activityInfo == null 3289 || !info.handleAllWebDataURI 3290 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3291 || result.contains(info.activityInfo.packageName)) { 3292 continue; 3293 } 3294 result.add(info.activityInfo.packageName); 3295 } 3296 3297 return result; 3298 } 3299 3300 private boolean packageIsBrowser(String packageName, int userId) { 3301 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3302 PackageManager.MATCH_ALL, userId); 3303 final int N = list.size(); 3304 for (int i = 0; i < N; i++) { 3305 ResolveInfo info = list.get(i); 3306 if (packageName.equals(info.activityInfo.packageName)) { 3307 return true; 3308 } 3309 } 3310 return false; 3311 } 3312 3313 private void checkDefaultBrowser() { 3314 final int myUserId = UserHandle.myUserId(); 3315 final String packageName = getDefaultBrowserPackageName(myUserId); 3316 if (packageName != null) { 3317 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3318 if (info == null) { 3319 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3320 synchronized (mPackages) { 3321 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3322 } 3323 } 3324 } 3325 } 3326 3327 @Override 3328 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3329 throws RemoteException { 3330 try { 3331 return super.onTransact(code, data, reply, flags); 3332 } catch (RuntimeException e) { 3333 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3334 Slog.wtf(TAG, "Package Manager Crash", e); 3335 } 3336 throw e; 3337 } 3338 } 3339 3340 static int[] appendInts(int[] cur, int[] add) { 3341 if (add == null) return cur; 3342 if (cur == null) return add; 3343 final int N = add.length; 3344 for (int i=0; i<N; i++) { 3345 cur = appendInt(cur, add[i]); 3346 } 3347 return cur; 3348 } 3349 3350 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3351 if (!sUserManager.exists(userId)) return null; 3352 if (ps == null) { 3353 return null; 3354 } 3355 final PackageParser.Package p = ps.pkg; 3356 if (p == null) { 3357 return null; 3358 } 3359 // Filter out ephemeral app metadata: 3360 // * The system/shell/root can see metadata for any app 3361 // * An installed app can see metadata for 1) other installed apps 3362 // and 2) ephemeral apps that have explicitly interacted with it 3363 // * Ephemeral apps can only see their own data and exposed installed apps 3364 // * Holding a signature permission allows seeing instant apps 3365 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3366 if (callingAppId != Process.SYSTEM_UID 3367 && callingAppId != Process.SHELL_UID 3368 && callingAppId != Process.ROOT_UID 3369 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3370 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3371 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3372 if (instantAppPackageName != null) { 3373 // ephemeral apps can only get information on themselves or 3374 // installed apps that are exposed. 3375 if (!instantAppPackageName.equals(p.packageName) 3376 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3377 return null; 3378 } 3379 } else { 3380 if (ps.getInstantApp(userId)) { 3381 // only get access to the ephemeral app if we've been granted access 3382 if (!mInstantAppRegistry.isInstantAccessGranted( 3383 userId, callingAppId, ps.appId)) { 3384 return null; 3385 } 3386 } 3387 } 3388 } 3389 3390 final PermissionsState permissionsState = ps.getPermissionsState(); 3391 3392 // Compute GIDs only if requested 3393 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3394 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3395 // Compute granted permissions only if package has requested permissions 3396 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3397 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3398 final PackageUserState state = ps.readUserState(userId); 3399 3400 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3401 && ps.isSystem()) { 3402 flags |= MATCH_ANY_USER; 3403 } 3404 3405 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3406 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3407 3408 if (packageInfo == null) { 3409 return null; 3410 } 3411 3412 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3413 3414 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3415 resolveExternalPackageNameLPr(p); 3416 3417 return packageInfo; 3418 } 3419 3420 @Override 3421 public void checkPackageStartable(String packageName, int userId) { 3422 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3423 3424 synchronized (mPackages) { 3425 final PackageSetting ps = mSettings.mPackages.get(packageName); 3426 if (ps == null) { 3427 throw new SecurityException("Package " + packageName + " was not found!"); 3428 } 3429 3430 if (!ps.getInstalled(userId)) { 3431 throw new SecurityException( 3432 "Package " + packageName + " was not installed for user " + userId + "!"); 3433 } 3434 3435 if (mSafeMode && !ps.isSystem()) { 3436 throw new SecurityException("Package " + packageName + " not a system app!"); 3437 } 3438 3439 if (mFrozenPackages.contains(packageName)) { 3440 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3441 } 3442 3443 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3444 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3445 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3446 } 3447 } 3448 } 3449 3450 @Override 3451 public boolean isPackageAvailable(String packageName, int userId) { 3452 if (!sUserManager.exists(userId)) return false; 3453 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3454 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3455 synchronized (mPackages) { 3456 PackageParser.Package p = mPackages.get(packageName); 3457 if (p != null) { 3458 final PackageSetting ps = (PackageSetting) p.mExtras; 3459 if (ps != null) { 3460 final PackageUserState state = ps.readUserState(userId); 3461 if (state != null) { 3462 return PackageParser.isAvailable(state); 3463 } 3464 } 3465 } 3466 } 3467 return false; 3468 } 3469 3470 @Override 3471 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3472 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3473 flags, userId); 3474 } 3475 3476 @Override 3477 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3478 int flags, int userId) { 3479 return getPackageInfoInternal(versionedPackage.getPackageName(), 3480 // TODO: We will change version code to long, so in the new API it is long 3481 (int) versionedPackage.getVersionCode(), flags, userId); 3482 } 3483 3484 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3485 int flags, int userId) { 3486 if (!sUserManager.exists(userId)) return null; 3487 flags = updateFlagsForPackage(flags, userId, packageName); 3488 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3489 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3490 3491 // reader 3492 synchronized (mPackages) { 3493 // Normalize package name to handle renamed packages and static libs 3494 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3495 3496 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3497 if (matchFactoryOnly) { 3498 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3499 if (ps != null) { 3500 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3501 return null; 3502 } 3503 return generatePackageInfo(ps, flags, userId); 3504 } 3505 } 3506 3507 PackageParser.Package p = mPackages.get(packageName); 3508 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3509 return null; 3510 } 3511 if (DEBUG_PACKAGE_INFO) 3512 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3513 if (p != null) { 3514 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3515 Binder.getCallingUid(), userId)) { 3516 return null; 3517 } 3518 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3519 } 3520 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3521 final PackageSetting ps = mSettings.mPackages.get(packageName); 3522 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3523 return null; 3524 } 3525 return generatePackageInfo(ps, flags, userId); 3526 } 3527 } 3528 return null; 3529 } 3530 3531 3532 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3533 // System/shell/root get to see all static libs 3534 final int appId = UserHandle.getAppId(uid); 3535 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3536 || appId == Process.ROOT_UID) { 3537 return false; 3538 } 3539 3540 // No package means no static lib as it is always on internal storage 3541 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3542 return false; 3543 } 3544 3545 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3546 ps.pkg.staticSharedLibVersion); 3547 if (libEntry == null) { 3548 return false; 3549 } 3550 3551 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3552 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3553 if (uidPackageNames == null) { 3554 return true; 3555 } 3556 3557 for (String uidPackageName : uidPackageNames) { 3558 if (ps.name.equals(uidPackageName)) { 3559 return false; 3560 } 3561 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3562 if (uidPs != null) { 3563 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3564 libEntry.info.getName()); 3565 if (index < 0) { 3566 continue; 3567 } 3568 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3569 return false; 3570 } 3571 } 3572 } 3573 return true; 3574 } 3575 3576 @Override 3577 public String[] currentToCanonicalPackageNames(String[] names) { 3578 String[] out = new String[names.length]; 3579 // reader 3580 synchronized (mPackages) { 3581 for (int i=names.length-1; i>=0; i--) { 3582 PackageSetting ps = mSettings.mPackages.get(names[i]); 3583 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3584 } 3585 } 3586 return out; 3587 } 3588 3589 @Override 3590 public String[] canonicalToCurrentPackageNames(String[] names) { 3591 String[] out = new String[names.length]; 3592 // reader 3593 synchronized (mPackages) { 3594 for (int i=names.length-1; i>=0; i--) { 3595 String cur = mSettings.getRenamedPackageLPr(names[i]); 3596 out[i] = cur != null ? cur : names[i]; 3597 } 3598 } 3599 return out; 3600 } 3601 3602 @Override 3603 public int getPackageUid(String packageName, int flags, int userId) { 3604 if (!sUserManager.exists(userId)) return -1; 3605 flags = updateFlagsForPackage(flags, userId, packageName); 3606 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3607 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3608 3609 // reader 3610 synchronized (mPackages) { 3611 final PackageParser.Package p = mPackages.get(packageName); 3612 if (p != null && p.isMatch(flags)) { 3613 return UserHandle.getUid(userId, p.applicationInfo.uid); 3614 } 3615 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3616 final PackageSetting ps = mSettings.mPackages.get(packageName); 3617 if (ps != null && ps.isMatch(flags)) { 3618 return UserHandle.getUid(userId, ps.appId); 3619 } 3620 } 3621 } 3622 3623 return -1; 3624 } 3625 3626 @Override 3627 public int[] getPackageGids(String packageName, int flags, int userId) { 3628 if (!sUserManager.exists(userId)) return null; 3629 flags = updateFlagsForPackage(flags, userId, packageName); 3630 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3631 false /* requireFullPermission */, false /* checkShell */, 3632 "getPackageGids"); 3633 3634 // reader 3635 synchronized (mPackages) { 3636 final PackageParser.Package p = mPackages.get(packageName); 3637 if (p != null && p.isMatch(flags)) { 3638 PackageSetting ps = (PackageSetting) p.mExtras; 3639 // TODO: Shouldn't this be checking for package installed state for userId and 3640 // return null? 3641 return ps.getPermissionsState().computeGids(userId); 3642 } 3643 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3644 final PackageSetting ps = mSettings.mPackages.get(packageName); 3645 if (ps != null && ps.isMatch(flags)) { 3646 return ps.getPermissionsState().computeGids(userId); 3647 } 3648 } 3649 } 3650 3651 return null; 3652 } 3653 3654 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3655 if (bp.perm != null) { 3656 return PackageParser.generatePermissionInfo(bp.perm, flags); 3657 } 3658 PermissionInfo pi = new PermissionInfo(); 3659 pi.name = bp.name; 3660 pi.packageName = bp.sourcePackage; 3661 pi.nonLocalizedLabel = bp.name; 3662 pi.protectionLevel = bp.protectionLevel; 3663 return pi; 3664 } 3665 3666 @Override 3667 public PermissionInfo getPermissionInfo(String name, int flags) { 3668 // reader 3669 synchronized (mPackages) { 3670 final BasePermission p = mSettings.mPermissions.get(name); 3671 if (p != null) { 3672 return generatePermissionInfo(p, flags); 3673 } 3674 return null; 3675 } 3676 } 3677 3678 @Override 3679 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3680 int flags) { 3681 // reader 3682 synchronized (mPackages) { 3683 if (group != null && !mPermissionGroups.containsKey(group)) { 3684 // This is thrown as NameNotFoundException 3685 return null; 3686 } 3687 3688 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3689 for (BasePermission p : mSettings.mPermissions.values()) { 3690 if (group == null) { 3691 if (p.perm == null || p.perm.info.group == null) { 3692 out.add(generatePermissionInfo(p, flags)); 3693 } 3694 } else { 3695 if (p.perm != null && group.equals(p.perm.info.group)) { 3696 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3697 } 3698 } 3699 } 3700 return new ParceledListSlice<>(out); 3701 } 3702 } 3703 3704 @Override 3705 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3706 // reader 3707 synchronized (mPackages) { 3708 return PackageParser.generatePermissionGroupInfo( 3709 mPermissionGroups.get(name), flags); 3710 } 3711 } 3712 3713 @Override 3714 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3715 // reader 3716 synchronized (mPackages) { 3717 final int N = mPermissionGroups.size(); 3718 ArrayList<PermissionGroupInfo> out 3719 = new ArrayList<PermissionGroupInfo>(N); 3720 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3721 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3722 } 3723 return new ParceledListSlice<>(out); 3724 } 3725 } 3726 3727 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3728 int uid, int userId) { 3729 if (!sUserManager.exists(userId)) return null; 3730 PackageSetting ps = mSettings.mPackages.get(packageName); 3731 if (ps != null) { 3732 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3733 return null; 3734 } 3735 if (ps.pkg == null) { 3736 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3737 if (pInfo != null) { 3738 return pInfo.applicationInfo; 3739 } 3740 return null; 3741 } 3742 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3743 ps.readUserState(userId), userId); 3744 if (ai != null) { 3745 rebaseEnabledOverlays(ai, userId); 3746 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3747 } 3748 return ai; 3749 } 3750 return null; 3751 } 3752 3753 @Override 3754 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3755 if (!sUserManager.exists(userId)) return null; 3756 flags = updateFlagsForApplication(flags, userId, packageName); 3757 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3758 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3759 3760 // writer 3761 synchronized (mPackages) { 3762 // Normalize package name to handle renamed packages and static libs 3763 packageName = resolveInternalPackageNameLPr(packageName, 3764 PackageManager.VERSION_CODE_HIGHEST); 3765 3766 PackageParser.Package p = mPackages.get(packageName); 3767 if (DEBUG_PACKAGE_INFO) Log.v( 3768 TAG, "getApplicationInfo " + packageName 3769 + ": " + p); 3770 if (p != null) { 3771 PackageSetting ps = mSettings.mPackages.get(packageName); 3772 if (ps == null) return null; 3773 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3774 return null; 3775 } 3776 // Note: isEnabledLP() does not apply here - always return info 3777 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3778 p, flags, ps.readUserState(userId), userId); 3779 if (ai != null) { 3780 rebaseEnabledOverlays(ai, userId); 3781 ai.packageName = resolveExternalPackageNameLPr(p); 3782 } 3783 return ai; 3784 } 3785 if ("android".equals(packageName)||"system".equals(packageName)) { 3786 return mAndroidApplication; 3787 } 3788 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3789 // Already generates the external package name 3790 return generateApplicationInfoFromSettingsLPw(packageName, 3791 Binder.getCallingUid(), flags, userId); 3792 } 3793 } 3794 return null; 3795 } 3796 3797 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3798 List<String> paths = new ArrayList<>(); 3799 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3800 mEnabledOverlayPaths.get(userId); 3801 if (userSpecificOverlays != null) { 3802 if (!"android".equals(ai.packageName)) { 3803 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3804 if (frameworkOverlays != null) { 3805 paths.addAll(frameworkOverlays); 3806 } 3807 } 3808 3809 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3810 if (appOverlays != null) { 3811 paths.addAll(appOverlays); 3812 } 3813 } 3814 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3815 } 3816 3817 private String normalizePackageNameLPr(String packageName) { 3818 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3819 return normalizedPackageName != null ? normalizedPackageName : packageName; 3820 } 3821 3822 @Override 3823 public void deletePreloadsFileCache() { 3824 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3825 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3826 } 3827 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3828 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3829 FileUtils.deleteContents(dir); 3830 } 3831 3832 @Override 3833 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3834 final IPackageDataObserver observer) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.CLEAR_APP_CACHE, null); 3837 mHandler.post(() -> { 3838 boolean success = false; 3839 try { 3840 freeStorage(volumeUuid, freeStorageSize, 0); 3841 success = true; 3842 } catch (IOException e) { 3843 Slog.w(TAG, e); 3844 } 3845 if (observer != null) { 3846 try { 3847 observer.onRemoveCompleted(null, success); 3848 } catch (RemoteException e) { 3849 Slog.w(TAG, e); 3850 } 3851 } 3852 }); 3853 } 3854 3855 @Override 3856 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3857 final IntentSender pi) { 3858 mContext.enforceCallingOrSelfPermission( 3859 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3860 mHandler.post(() -> { 3861 boolean success = false; 3862 try { 3863 freeStorage(volumeUuid, freeStorageSize, 0); 3864 success = true; 3865 } catch (IOException e) { 3866 Slog.w(TAG, e); 3867 } 3868 if (pi != null) { 3869 try { 3870 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3871 } catch (SendIntentException e) { 3872 Slog.w(TAG, e); 3873 } 3874 } 3875 }); 3876 } 3877 3878 /** 3879 * Blocking call to clear various types of cached data across the system 3880 * until the requested bytes are available. 3881 */ 3882 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3883 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3884 final File file = storage.findPathForUuid(volumeUuid); 3885 if (file.getUsableSpace() >= bytes) return; 3886 3887 if (ENABLE_FREE_CACHE_V2) { 3888 final boolean aggressive = (storageFlags 3889 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3890 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3891 volumeUuid); 3892 3893 // 1. Pre-flight to determine if we have any chance to succeed 3894 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3895 if (internalVolume && (aggressive || SystemProperties 3896 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3897 deletePreloadsFileCache(); 3898 if (file.getUsableSpace() >= bytes) return; 3899 } 3900 3901 // 3. Consider parsed APK data (aggressive only) 3902 if (internalVolume && aggressive) { 3903 FileUtils.deleteContents(mCacheDir); 3904 if (file.getUsableSpace() >= bytes) return; 3905 } 3906 3907 // 4. Consider cached app data (above quotas) 3908 try { 3909 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3910 } catch (InstallerException ignored) { 3911 } 3912 if (file.getUsableSpace() >= bytes) return; 3913 3914 // 5. Consider shared libraries with refcount=0 and age>2h 3915 // 6. Consider dexopt output (aggressive only) 3916 // 7. Consider ephemeral apps not used in last week 3917 3918 // 8. Consider cached app data (below quotas) 3919 try { 3920 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3921 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3922 } catch (InstallerException ignored) { 3923 } 3924 if (file.getUsableSpace() >= bytes) return; 3925 3926 // 9. Consider DropBox entries 3927 // 10. Consider ephemeral cookies 3928 3929 } else { 3930 try { 3931 mInstaller.freeCache(volumeUuid, bytes, 0); 3932 } catch (InstallerException ignored) { 3933 } 3934 if (file.getUsableSpace() >= bytes) return; 3935 } 3936 3937 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3938 } 3939 3940 /** 3941 * Update given flags based on encryption status of current user. 3942 */ 3943 private int updateFlags(int flags, int userId) { 3944 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3945 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3946 // Caller expressed an explicit opinion about what encryption 3947 // aware/unaware components they want to see, so fall through and 3948 // give them what they want 3949 } else { 3950 // Caller expressed no opinion, so match based on user state 3951 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3952 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3953 } else { 3954 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3955 } 3956 } 3957 return flags; 3958 } 3959 3960 private UserManagerInternal getUserManagerInternal() { 3961 if (mUserManagerInternal == null) { 3962 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3963 } 3964 return mUserManagerInternal; 3965 } 3966 3967 private DeviceIdleController.LocalService getDeviceIdleController() { 3968 if (mDeviceIdleController == null) { 3969 mDeviceIdleController = 3970 LocalServices.getService(DeviceIdleController.LocalService.class); 3971 } 3972 return mDeviceIdleController; 3973 } 3974 3975 /** 3976 * Update given flags when being used to request {@link PackageInfo}. 3977 */ 3978 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3979 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3980 boolean triaged = true; 3981 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3982 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3983 // Caller is asking for component details, so they'd better be 3984 // asking for specific encryption matching behavior, or be triaged 3985 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3986 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3987 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3988 triaged = false; 3989 } 3990 } 3991 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3992 | PackageManager.MATCH_SYSTEM_ONLY 3993 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3994 triaged = false; 3995 } 3996 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3997 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3998 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3999 + Debug.getCallers(5)); 4000 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4001 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4002 // If the caller wants all packages and has a restricted profile associated with it, 4003 // then match all users. This is to make sure that launchers that need to access work 4004 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4005 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4006 flags |= PackageManager.MATCH_ANY_USER; 4007 } 4008 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4009 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4010 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4011 } 4012 return updateFlags(flags, userId); 4013 } 4014 4015 /** 4016 * Update given flags when being used to request {@link ApplicationInfo}. 4017 */ 4018 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4019 return updateFlagsForPackage(flags, userId, cookie); 4020 } 4021 4022 /** 4023 * Update given flags when being used to request {@link ComponentInfo}. 4024 */ 4025 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4026 if (cookie instanceof Intent) { 4027 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4028 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4029 } 4030 } 4031 4032 boolean triaged = true; 4033 // Caller is asking for component details, so they'd better be 4034 // asking for specific encryption matching behavior, or be triaged 4035 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4036 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4037 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4038 triaged = false; 4039 } 4040 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4041 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4042 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4043 } 4044 4045 return updateFlags(flags, userId); 4046 } 4047 4048 /** 4049 * Update given intent when being used to request {@link ResolveInfo}. 4050 */ 4051 private Intent updateIntentForResolve(Intent intent) { 4052 if (intent.getSelector() != null) { 4053 intent = intent.getSelector(); 4054 } 4055 if (DEBUG_PREFERRED) { 4056 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4057 } 4058 return intent; 4059 } 4060 4061 /** 4062 * Update given flags when being used to request {@link ResolveInfo}. 4063 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4064 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4065 * flag set. However, this flag is only honoured in three circumstances: 4066 * <ul> 4067 * <li>when called from a system process</li> 4068 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4069 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4070 * action and a {@code android.intent.category.BROWSABLE} category</li> 4071 * </ul> 4072 */ 4073 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4074 // Safe mode means we shouldn't match any third-party components 4075 if (mSafeMode) { 4076 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4077 } 4078 final int callingUid = Binder.getCallingUid(); 4079 if (getInstantAppPackageName(callingUid) != null) { 4080 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4081 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4082 flags |= PackageManager.MATCH_INSTANT; 4083 } else { 4084 // Otherwise, prevent leaking ephemeral components 4085 final boolean isSpecialProcess = 4086 callingUid == Process.SYSTEM_UID 4087 || callingUid == Process.SHELL_UID 4088 || callingUid == 0; 4089 final boolean allowMatchInstant = 4090 (includeInstantApp 4091 && Intent.ACTION_VIEW.equals(intent.getAction()) 4092 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4093 && hasWebURI(intent)) 4094 || isSpecialProcess 4095 || mContext.checkCallingOrSelfPermission( 4096 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4097 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4098 if (!allowMatchInstant) { 4099 flags &= ~PackageManager.MATCH_INSTANT; 4100 } 4101 } 4102 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4103 } 4104 4105 @Override 4106 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4107 if (!sUserManager.exists(userId)) return null; 4108 flags = updateFlagsForComponent(flags, userId, component); 4109 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4110 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4111 synchronized (mPackages) { 4112 PackageParser.Activity a = mActivities.mActivities.get(component); 4113 4114 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4115 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4116 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4117 if (ps == null) return null; 4118 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4119 userId); 4120 } 4121 if (mResolveComponentName.equals(component)) { 4122 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4123 new PackageUserState(), userId); 4124 } 4125 } 4126 return null; 4127 } 4128 4129 @Override 4130 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4131 String resolvedType) { 4132 synchronized (mPackages) { 4133 if (component.equals(mResolveComponentName)) { 4134 // The resolver supports EVERYTHING! 4135 return true; 4136 } 4137 PackageParser.Activity a = mActivities.mActivities.get(component); 4138 if (a == null) { 4139 return false; 4140 } 4141 for (int i=0; i<a.intents.size(); i++) { 4142 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4143 intent.getData(), intent.getCategories(), TAG) >= 0) { 4144 return true; 4145 } 4146 } 4147 return false; 4148 } 4149 } 4150 4151 @Override 4152 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4153 if (!sUserManager.exists(userId)) return null; 4154 flags = updateFlagsForComponent(flags, userId, component); 4155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4156 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4157 synchronized (mPackages) { 4158 PackageParser.Activity a = mReceivers.mActivities.get(component); 4159 if (DEBUG_PACKAGE_INFO) Log.v( 4160 TAG, "getReceiverInfo " + component + ": " + a); 4161 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4162 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4163 if (ps == null) return null; 4164 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4165 ps.readUserState(userId), userId); 4166 if (ri != null) { 4167 rebaseEnabledOverlays(ri.applicationInfo, userId); 4168 } 4169 return ri; 4170 } 4171 } 4172 return null; 4173 } 4174 4175 @Override 4176 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4177 if (!sUserManager.exists(userId)) return null; 4178 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4179 4180 flags = updateFlagsForPackage(flags, userId, null); 4181 4182 final boolean canSeeStaticLibraries = 4183 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4184 == PERMISSION_GRANTED 4185 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4186 == PERMISSION_GRANTED 4187 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4188 == PERMISSION_GRANTED 4189 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4190 == PERMISSION_GRANTED; 4191 4192 synchronized (mPackages) { 4193 List<SharedLibraryInfo> result = null; 4194 4195 final int libCount = mSharedLibraries.size(); 4196 for (int i = 0; i < libCount; i++) { 4197 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4198 if (versionedLib == null) { 4199 continue; 4200 } 4201 4202 final int versionCount = versionedLib.size(); 4203 for (int j = 0; j < versionCount; j++) { 4204 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4205 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4206 break; 4207 } 4208 final long identity = Binder.clearCallingIdentity(); 4209 try { 4210 // TODO: We will change version code to long, so in the new API it is long 4211 PackageInfo packageInfo = getPackageInfoVersioned( 4212 libInfo.getDeclaringPackage(), flags, userId); 4213 if (packageInfo == null) { 4214 continue; 4215 } 4216 } finally { 4217 Binder.restoreCallingIdentity(identity); 4218 } 4219 4220 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4221 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4222 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4223 4224 if (result == null) { 4225 result = new ArrayList<>(); 4226 } 4227 result.add(resLibInfo); 4228 } 4229 } 4230 4231 return result != null ? new ParceledListSlice<>(result) : null; 4232 } 4233 } 4234 4235 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4236 SharedLibraryInfo libInfo, int flags, int userId) { 4237 List<VersionedPackage> versionedPackages = null; 4238 final int packageCount = mSettings.mPackages.size(); 4239 for (int i = 0; i < packageCount; i++) { 4240 PackageSetting ps = mSettings.mPackages.valueAt(i); 4241 4242 if (ps == null) { 4243 continue; 4244 } 4245 4246 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4247 continue; 4248 } 4249 4250 final String libName = libInfo.getName(); 4251 if (libInfo.isStatic()) { 4252 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4253 if (libIdx < 0) { 4254 continue; 4255 } 4256 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4257 continue; 4258 } 4259 if (versionedPackages == null) { 4260 versionedPackages = new ArrayList<>(); 4261 } 4262 // If the dependent is a static shared lib, use the public package name 4263 String dependentPackageName = ps.name; 4264 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4265 dependentPackageName = ps.pkg.manifestPackageName; 4266 } 4267 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4268 } else if (ps.pkg != null) { 4269 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4270 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4271 if (versionedPackages == null) { 4272 versionedPackages = new ArrayList<>(); 4273 } 4274 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4275 } 4276 } 4277 } 4278 4279 return versionedPackages; 4280 } 4281 4282 @Override 4283 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4284 if (!sUserManager.exists(userId)) return null; 4285 flags = updateFlagsForComponent(flags, userId, component); 4286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4287 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4288 synchronized (mPackages) { 4289 PackageParser.Service s = mServices.mServices.get(component); 4290 if (DEBUG_PACKAGE_INFO) Log.v( 4291 TAG, "getServiceInfo " + component + ": " + s); 4292 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4293 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4294 if (ps == null) return null; 4295 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4296 ps.readUserState(userId), userId); 4297 if (si != null) { 4298 rebaseEnabledOverlays(si.applicationInfo, userId); 4299 } 4300 return si; 4301 } 4302 } 4303 return null; 4304 } 4305 4306 @Override 4307 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4308 if (!sUserManager.exists(userId)) return null; 4309 flags = updateFlagsForComponent(flags, userId, component); 4310 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4311 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4312 synchronized (mPackages) { 4313 PackageParser.Provider p = mProviders.mProviders.get(component); 4314 if (DEBUG_PACKAGE_INFO) Log.v( 4315 TAG, "getProviderInfo " + component + ": " + p); 4316 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4317 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4318 if (ps == null) return null; 4319 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4320 ps.readUserState(userId), userId); 4321 if (pi != null) { 4322 rebaseEnabledOverlays(pi.applicationInfo, userId); 4323 } 4324 return pi; 4325 } 4326 } 4327 return null; 4328 } 4329 4330 @Override 4331 public String[] getSystemSharedLibraryNames() { 4332 synchronized (mPackages) { 4333 Set<String> libs = null; 4334 final int libCount = mSharedLibraries.size(); 4335 for (int i = 0; i < libCount; i++) { 4336 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4337 if (versionedLib == null) { 4338 continue; 4339 } 4340 final int versionCount = versionedLib.size(); 4341 for (int j = 0; j < versionCount; j++) { 4342 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4343 if (!libEntry.info.isStatic()) { 4344 if (libs == null) { 4345 libs = new ArraySet<>(); 4346 } 4347 libs.add(libEntry.info.getName()); 4348 break; 4349 } 4350 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4351 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4352 UserHandle.getUserId(Binder.getCallingUid()))) { 4353 if (libs == null) { 4354 libs = new ArraySet<>(); 4355 } 4356 libs.add(libEntry.info.getName()); 4357 break; 4358 } 4359 } 4360 } 4361 4362 if (libs != null) { 4363 String[] libsArray = new String[libs.size()]; 4364 libs.toArray(libsArray); 4365 return libsArray; 4366 } 4367 4368 return null; 4369 } 4370 } 4371 4372 @Override 4373 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4374 synchronized (mPackages) { 4375 return mServicesSystemSharedLibraryPackageName; 4376 } 4377 } 4378 4379 @Override 4380 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4381 synchronized (mPackages) { 4382 return mSharedSystemSharedLibraryPackageName; 4383 } 4384 } 4385 4386 private void updateSequenceNumberLP(String packageName, int[] userList) { 4387 for (int i = userList.length - 1; i >= 0; --i) { 4388 final int userId = userList[i]; 4389 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4390 if (changedPackages == null) { 4391 changedPackages = new SparseArray<>(); 4392 mChangedPackages.put(userId, changedPackages); 4393 } 4394 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4395 if (sequenceNumbers == null) { 4396 sequenceNumbers = new HashMap<>(); 4397 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4398 } 4399 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4400 if (sequenceNumber != null) { 4401 changedPackages.remove(sequenceNumber); 4402 } 4403 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4404 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4405 } 4406 mChangedPackagesSequenceNumber++; 4407 } 4408 4409 @Override 4410 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4411 synchronized (mPackages) { 4412 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4413 return null; 4414 } 4415 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4416 if (changedPackages == null) { 4417 return null; 4418 } 4419 final List<String> packageNames = 4420 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4421 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4422 final String packageName = changedPackages.get(i); 4423 if (packageName != null) { 4424 packageNames.add(packageName); 4425 } 4426 } 4427 return packageNames.isEmpty() 4428 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4429 } 4430 } 4431 4432 @Override 4433 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4434 ArrayList<FeatureInfo> res; 4435 synchronized (mAvailableFeatures) { 4436 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4437 res.addAll(mAvailableFeatures.values()); 4438 } 4439 final FeatureInfo fi = new FeatureInfo(); 4440 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4441 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4442 res.add(fi); 4443 4444 return new ParceledListSlice<>(res); 4445 } 4446 4447 @Override 4448 public boolean hasSystemFeature(String name, int version) { 4449 synchronized (mAvailableFeatures) { 4450 final FeatureInfo feat = mAvailableFeatures.get(name); 4451 if (feat == null) { 4452 return false; 4453 } else { 4454 return feat.version >= version; 4455 } 4456 } 4457 } 4458 4459 @Override 4460 public int checkPermission(String permName, String pkgName, int userId) { 4461 if (!sUserManager.exists(userId)) { 4462 return PackageManager.PERMISSION_DENIED; 4463 } 4464 4465 synchronized (mPackages) { 4466 final PackageParser.Package p = mPackages.get(pkgName); 4467 if (p != null && p.mExtras != null) { 4468 final PackageSetting ps = (PackageSetting) p.mExtras; 4469 final PermissionsState permissionsState = ps.getPermissionsState(); 4470 if (permissionsState.hasPermission(permName, userId)) { 4471 return PackageManager.PERMISSION_GRANTED; 4472 } 4473 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4474 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4475 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4476 return PackageManager.PERMISSION_GRANTED; 4477 } 4478 } 4479 } 4480 4481 return PackageManager.PERMISSION_DENIED; 4482 } 4483 4484 @Override 4485 public int checkUidPermission(String permName, int uid) { 4486 final int userId = UserHandle.getUserId(uid); 4487 4488 if (!sUserManager.exists(userId)) { 4489 return PackageManager.PERMISSION_DENIED; 4490 } 4491 4492 synchronized (mPackages) { 4493 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4494 if (obj != null) { 4495 final SettingBase ps = (SettingBase) obj; 4496 final PermissionsState permissionsState = ps.getPermissionsState(); 4497 if (permissionsState.hasPermission(permName, userId)) { 4498 return PackageManager.PERMISSION_GRANTED; 4499 } 4500 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4501 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4502 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4503 return PackageManager.PERMISSION_GRANTED; 4504 } 4505 } else { 4506 ArraySet<String> perms = mSystemPermissions.get(uid); 4507 if (perms != null) { 4508 if (perms.contains(permName)) { 4509 return PackageManager.PERMISSION_GRANTED; 4510 } 4511 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4512 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4513 return PackageManager.PERMISSION_GRANTED; 4514 } 4515 } 4516 } 4517 } 4518 4519 return PackageManager.PERMISSION_DENIED; 4520 } 4521 4522 @Override 4523 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4524 if (UserHandle.getCallingUserId() != userId) { 4525 mContext.enforceCallingPermission( 4526 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4527 "isPermissionRevokedByPolicy for user " + userId); 4528 } 4529 4530 if (checkPermission(permission, packageName, userId) 4531 == PackageManager.PERMISSION_GRANTED) { 4532 return false; 4533 } 4534 4535 final long identity = Binder.clearCallingIdentity(); 4536 try { 4537 final int flags = getPermissionFlags(permission, packageName, userId); 4538 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4539 } finally { 4540 Binder.restoreCallingIdentity(identity); 4541 } 4542 } 4543 4544 @Override 4545 public String getPermissionControllerPackageName() { 4546 synchronized (mPackages) { 4547 return mRequiredInstallerPackage; 4548 } 4549 } 4550 4551 /** 4552 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4553 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4554 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4555 * @param message the message to log on security exception 4556 */ 4557 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4558 boolean checkShell, String message) { 4559 if (userId < 0) { 4560 throw new IllegalArgumentException("Invalid userId " + userId); 4561 } 4562 if (checkShell) { 4563 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4564 } 4565 if (userId == UserHandle.getUserId(callingUid)) return; 4566 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4567 if (requireFullPermission) { 4568 mContext.enforceCallingOrSelfPermission( 4569 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4570 } else { 4571 try { 4572 mContext.enforceCallingOrSelfPermission( 4573 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4574 } catch (SecurityException se) { 4575 mContext.enforceCallingOrSelfPermission( 4576 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4577 } 4578 } 4579 } 4580 } 4581 4582 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4583 if (callingUid == Process.SHELL_UID) { 4584 if (userHandle >= 0 4585 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4586 throw new SecurityException("Shell does not have permission to access user " 4587 + userHandle); 4588 } else if (userHandle < 0) { 4589 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4590 + Debug.getCallers(3)); 4591 } 4592 } 4593 } 4594 4595 private BasePermission findPermissionTreeLP(String permName) { 4596 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4597 if (permName.startsWith(bp.name) && 4598 permName.length() > bp.name.length() && 4599 permName.charAt(bp.name.length()) == '.') { 4600 return bp; 4601 } 4602 } 4603 return null; 4604 } 4605 4606 private BasePermission checkPermissionTreeLP(String permName) { 4607 if (permName != null) { 4608 BasePermission bp = findPermissionTreeLP(permName); 4609 if (bp != null) { 4610 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4611 return bp; 4612 } 4613 throw new SecurityException("Calling uid " 4614 + Binder.getCallingUid() 4615 + " is not allowed to add to permission tree " 4616 + bp.name + " owned by uid " + bp.uid); 4617 } 4618 } 4619 throw new SecurityException("No permission tree found for " + permName); 4620 } 4621 4622 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4623 if (s1 == null) { 4624 return s2 == null; 4625 } 4626 if (s2 == null) { 4627 return false; 4628 } 4629 if (s1.getClass() != s2.getClass()) { 4630 return false; 4631 } 4632 return s1.equals(s2); 4633 } 4634 4635 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4636 if (pi1.icon != pi2.icon) return false; 4637 if (pi1.logo != pi2.logo) return false; 4638 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4639 if (!compareStrings(pi1.name, pi2.name)) return false; 4640 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4641 // We'll take care of setting this one. 4642 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4643 // These are not currently stored in settings. 4644 //if (!compareStrings(pi1.group, pi2.group)) return false; 4645 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4646 //if (pi1.labelRes != pi2.labelRes) return false; 4647 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4648 return true; 4649 } 4650 4651 int permissionInfoFootprint(PermissionInfo info) { 4652 int size = info.name.length(); 4653 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4654 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4655 return size; 4656 } 4657 4658 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4659 int size = 0; 4660 for (BasePermission perm : mSettings.mPermissions.values()) { 4661 if (perm.uid == tree.uid) { 4662 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4663 } 4664 } 4665 return size; 4666 } 4667 4668 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4669 // We calculate the max size of permissions defined by this uid and throw 4670 // if that plus the size of 'info' would exceed our stated maximum. 4671 if (tree.uid != Process.SYSTEM_UID) { 4672 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4673 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4674 throw new SecurityException("Permission tree size cap exceeded"); 4675 } 4676 } 4677 } 4678 4679 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4680 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4681 throw new SecurityException("Label must be specified in permission"); 4682 } 4683 BasePermission tree = checkPermissionTreeLP(info.name); 4684 BasePermission bp = mSettings.mPermissions.get(info.name); 4685 boolean added = bp == null; 4686 boolean changed = true; 4687 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4688 if (added) { 4689 enforcePermissionCapLocked(info, tree); 4690 bp = new BasePermission(info.name, tree.sourcePackage, 4691 BasePermission.TYPE_DYNAMIC); 4692 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4693 throw new SecurityException( 4694 "Not allowed to modify non-dynamic permission " 4695 + info.name); 4696 } else { 4697 if (bp.protectionLevel == fixedLevel 4698 && bp.perm.owner.equals(tree.perm.owner) 4699 && bp.uid == tree.uid 4700 && comparePermissionInfos(bp.perm.info, info)) { 4701 changed = false; 4702 } 4703 } 4704 bp.protectionLevel = fixedLevel; 4705 info = new PermissionInfo(info); 4706 info.protectionLevel = fixedLevel; 4707 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4708 bp.perm.info.packageName = tree.perm.info.packageName; 4709 bp.uid = tree.uid; 4710 if (added) { 4711 mSettings.mPermissions.put(info.name, bp); 4712 } 4713 if (changed) { 4714 if (!async) { 4715 mSettings.writeLPr(); 4716 } else { 4717 scheduleWriteSettingsLocked(); 4718 } 4719 } 4720 return added; 4721 } 4722 4723 @Override 4724 public boolean addPermission(PermissionInfo info) { 4725 synchronized (mPackages) { 4726 return addPermissionLocked(info, false); 4727 } 4728 } 4729 4730 @Override 4731 public boolean addPermissionAsync(PermissionInfo info) { 4732 synchronized (mPackages) { 4733 return addPermissionLocked(info, true); 4734 } 4735 } 4736 4737 @Override 4738 public void removePermission(String name) { 4739 synchronized (mPackages) { 4740 checkPermissionTreeLP(name); 4741 BasePermission bp = mSettings.mPermissions.get(name); 4742 if (bp != null) { 4743 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4744 throw new SecurityException( 4745 "Not allowed to modify non-dynamic permission " 4746 + name); 4747 } 4748 mSettings.mPermissions.remove(name); 4749 mSettings.writeLPr(); 4750 } 4751 } 4752 } 4753 4754 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4755 BasePermission bp) { 4756 int index = pkg.requestedPermissions.indexOf(bp.name); 4757 if (index == -1) { 4758 throw new SecurityException("Package " + pkg.packageName 4759 + " has not requested permission " + bp.name); 4760 } 4761 if (!bp.isRuntime() && !bp.isDevelopment()) { 4762 throw new SecurityException("Permission " + bp.name 4763 + " is not a changeable permission type"); 4764 } 4765 } 4766 4767 @Override 4768 public void grantRuntimePermission(String packageName, String name, final int userId) { 4769 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4770 } 4771 4772 private void grantRuntimePermission(String packageName, String name, final int userId, 4773 boolean overridePolicy) { 4774 if (!sUserManager.exists(userId)) { 4775 Log.e(TAG, "No such user:" + userId); 4776 return; 4777 } 4778 4779 mContext.enforceCallingOrSelfPermission( 4780 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4781 "grantRuntimePermission"); 4782 4783 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4784 true /* requireFullPermission */, true /* checkShell */, 4785 "grantRuntimePermission"); 4786 4787 final int uid; 4788 final SettingBase sb; 4789 4790 synchronized (mPackages) { 4791 final PackageParser.Package pkg = mPackages.get(packageName); 4792 if (pkg == null) { 4793 throw new IllegalArgumentException("Unknown package: " + packageName); 4794 } 4795 4796 final BasePermission bp = mSettings.mPermissions.get(name); 4797 if (bp == null) { 4798 throw new IllegalArgumentException("Unknown permission: " + name); 4799 } 4800 4801 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4802 4803 // If a permission review is required for legacy apps we represent 4804 // their permissions as always granted runtime ones since we need 4805 // to keep the review required permission flag per user while an 4806 // install permission's state is shared across all users. 4807 if (mPermissionReviewRequired 4808 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4809 && bp.isRuntime()) { 4810 return; 4811 } 4812 4813 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4814 sb = (SettingBase) pkg.mExtras; 4815 if (sb == null) { 4816 throw new IllegalArgumentException("Unknown package: " + packageName); 4817 } 4818 4819 final PermissionsState permissionsState = sb.getPermissionsState(); 4820 4821 final int flags = permissionsState.getPermissionFlags(name, userId); 4822 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4823 throw new SecurityException("Cannot grant system fixed permission " 4824 + name + " for package " + packageName); 4825 } 4826 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4827 throw new SecurityException("Cannot grant policy fixed permission " 4828 + name + " for package " + packageName); 4829 } 4830 4831 if (bp.isDevelopment()) { 4832 // Development permissions must be handled specially, since they are not 4833 // normal runtime permissions. For now they apply to all users. 4834 if (permissionsState.grantInstallPermission(bp) != 4835 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4836 scheduleWriteSettingsLocked(); 4837 } 4838 return; 4839 } 4840 4841 final PackageSetting ps = mSettings.mPackages.get(packageName); 4842 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4843 throw new SecurityException("Cannot grant non-ephemeral permission" 4844 + name + " for package " + packageName); 4845 } 4846 4847 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4848 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4849 return; 4850 } 4851 4852 final int result = permissionsState.grantRuntimePermission(bp, userId); 4853 switch (result) { 4854 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4855 return; 4856 } 4857 4858 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4859 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4860 mHandler.post(new Runnable() { 4861 @Override 4862 public void run() { 4863 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4864 } 4865 }); 4866 } 4867 break; 4868 } 4869 4870 if (bp.isRuntime()) { 4871 logPermissionGranted(mContext, name, packageName); 4872 } 4873 4874 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4875 4876 // Not critical if that is lost - app has to request again. 4877 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4878 } 4879 4880 // Only need to do this if user is initialized. Otherwise it's a new user 4881 // and there are no processes running as the user yet and there's no need 4882 // to make an expensive call to remount processes for the changed permissions. 4883 if (READ_EXTERNAL_STORAGE.equals(name) 4884 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4885 final long token = Binder.clearCallingIdentity(); 4886 try { 4887 if (sUserManager.isInitialized(userId)) { 4888 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4889 StorageManagerInternal.class); 4890 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4891 } 4892 } finally { 4893 Binder.restoreCallingIdentity(token); 4894 } 4895 } 4896 } 4897 4898 @Override 4899 public void revokeRuntimePermission(String packageName, String name, int userId) { 4900 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4901 } 4902 4903 private void revokeRuntimePermission(String packageName, String name, int userId, 4904 boolean overridePolicy) { 4905 if (!sUserManager.exists(userId)) { 4906 Log.e(TAG, "No such user:" + userId); 4907 return; 4908 } 4909 4910 mContext.enforceCallingOrSelfPermission( 4911 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4912 "revokeRuntimePermission"); 4913 4914 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4915 true /* requireFullPermission */, true /* checkShell */, 4916 "revokeRuntimePermission"); 4917 4918 final int appId; 4919 4920 synchronized (mPackages) { 4921 final PackageParser.Package pkg = mPackages.get(packageName); 4922 if (pkg == null) { 4923 throw new IllegalArgumentException("Unknown package: " + packageName); 4924 } 4925 4926 final BasePermission bp = mSettings.mPermissions.get(name); 4927 if (bp == null) { 4928 throw new IllegalArgumentException("Unknown permission: " + name); 4929 } 4930 4931 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4932 4933 // If a permission review is required for legacy apps we represent 4934 // their permissions as always granted runtime ones since we need 4935 // to keep the review required permission flag per user while an 4936 // install permission's state is shared across all users. 4937 if (mPermissionReviewRequired 4938 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4939 && bp.isRuntime()) { 4940 return; 4941 } 4942 4943 SettingBase sb = (SettingBase) pkg.mExtras; 4944 if (sb == null) { 4945 throw new IllegalArgumentException("Unknown package: " + packageName); 4946 } 4947 4948 final PermissionsState permissionsState = sb.getPermissionsState(); 4949 4950 final int flags = permissionsState.getPermissionFlags(name, userId); 4951 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4952 throw new SecurityException("Cannot revoke system fixed permission " 4953 + name + " for package " + packageName); 4954 } 4955 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4956 throw new SecurityException("Cannot revoke policy fixed permission " 4957 + name + " for package " + packageName); 4958 } 4959 4960 if (bp.isDevelopment()) { 4961 // Development permissions must be handled specially, since they are not 4962 // normal runtime permissions. For now they apply to all users. 4963 if (permissionsState.revokeInstallPermission(bp) != 4964 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4965 scheduleWriteSettingsLocked(); 4966 } 4967 return; 4968 } 4969 4970 if (permissionsState.revokeRuntimePermission(bp, userId) == 4971 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4972 return; 4973 } 4974 4975 if (bp.isRuntime()) { 4976 logPermissionRevoked(mContext, name, packageName); 4977 } 4978 4979 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4980 4981 // Critical, after this call app should never have the permission. 4982 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4983 4984 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4985 } 4986 4987 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4988 } 4989 4990 /** 4991 * Get the first event id for the permission. 4992 * 4993 * <p>There are four events for each permission: <ul> 4994 * <li>Request permission: first id + 0</li> 4995 * <li>Grant permission: first id + 1</li> 4996 * <li>Request for permission denied: first id + 2</li> 4997 * <li>Revoke permission: first id + 3</li> 4998 * </ul></p> 4999 * 5000 * @param name name of the permission 5001 * 5002 * @return The first event id for the permission 5003 */ 5004 private static int getBaseEventId(@NonNull String name) { 5005 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5006 5007 if (eventIdIndex == -1) { 5008 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5009 || "user".equals(Build.TYPE)) { 5010 Log.i(TAG, "Unknown permission " + name); 5011 5012 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5013 } else { 5014 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5015 // 5016 // Also update 5017 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5018 // - metrics_constants.proto 5019 throw new IllegalStateException("Unknown permission " + name); 5020 } 5021 } 5022 5023 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5024 } 5025 5026 /** 5027 * Log that a permission was revoked. 5028 * 5029 * @param context Context of the caller 5030 * @param name name of the permission 5031 * @param packageName package permission if for 5032 */ 5033 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5034 @NonNull String packageName) { 5035 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5036 } 5037 5038 /** 5039 * Log that a permission request was granted. 5040 * 5041 * @param context Context of the caller 5042 * @param name name of the permission 5043 * @param packageName package permission if for 5044 */ 5045 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5046 @NonNull String packageName) { 5047 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5048 } 5049 5050 @Override 5051 public void resetRuntimePermissions() { 5052 mContext.enforceCallingOrSelfPermission( 5053 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5054 "revokeRuntimePermission"); 5055 5056 int callingUid = Binder.getCallingUid(); 5057 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5058 mContext.enforceCallingOrSelfPermission( 5059 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5060 "resetRuntimePermissions"); 5061 } 5062 5063 synchronized (mPackages) { 5064 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5065 for (int userId : UserManagerService.getInstance().getUserIds()) { 5066 final int packageCount = mPackages.size(); 5067 for (int i = 0; i < packageCount; i++) { 5068 PackageParser.Package pkg = mPackages.valueAt(i); 5069 if (!(pkg.mExtras instanceof PackageSetting)) { 5070 continue; 5071 } 5072 PackageSetting ps = (PackageSetting) pkg.mExtras; 5073 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5074 } 5075 } 5076 } 5077 } 5078 5079 @Override 5080 public int getPermissionFlags(String name, String packageName, int userId) { 5081 if (!sUserManager.exists(userId)) { 5082 return 0; 5083 } 5084 5085 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5086 5087 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5088 true /* requireFullPermission */, false /* checkShell */, 5089 "getPermissionFlags"); 5090 5091 synchronized (mPackages) { 5092 final PackageParser.Package pkg = mPackages.get(packageName); 5093 if (pkg == null) { 5094 return 0; 5095 } 5096 5097 final BasePermission bp = mSettings.mPermissions.get(name); 5098 if (bp == null) { 5099 return 0; 5100 } 5101 5102 SettingBase sb = (SettingBase) pkg.mExtras; 5103 if (sb == null) { 5104 return 0; 5105 } 5106 5107 PermissionsState permissionsState = sb.getPermissionsState(); 5108 return permissionsState.getPermissionFlags(name, userId); 5109 } 5110 } 5111 5112 @Override 5113 public void updatePermissionFlags(String name, String packageName, int flagMask, 5114 int flagValues, int userId) { 5115 if (!sUserManager.exists(userId)) { 5116 return; 5117 } 5118 5119 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5120 5121 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5122 true /* requireFullPermission */, true /* checkShell */, 5123 "updatePermissionFlags"); 5124 5125 // Only the system can change these flags and nothing else. 5126 if (getCallingUid() != Process.SYSTEM_UID) { 5127 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5128 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5129 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5130 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5131 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5132 } 5133 5134 synchronized (mPackages) { 5135 final PackageParser.Package pkg = mPackages.get(packageName); 5136 if (pkg == null) { 5137 throw new IllegalArgumentException("Unknown package: " + packageName); 5138 } 5139 5140 final BasePermission bp = mSettings.mPermissions.get(name); 5141 if (bp == null) { 5142 throw new IllegalArgumentException("Unknown permission: " + name); 5143 } 5144 5145 SettingBase sb = (SettingBase) pkg.mExtras; 5146 if (sb == null) { 5147 throw new IllegalArgumentException("Unknown package: " + packageName); 5148 } 5149 5150 PermissionsState permissionsState = sb.getPermissionsState(); 5151 5152 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5153 5154 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5155 // Install and runtime permissions are stored in different places, 5156 // so figure out what permission changed and persist the change. 5157 if (permissionsState.getInstallPermissionState(name) != null) { 5158 scheduleWriteSettingsLocked(); 5159 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5160 || hadState) { 5161 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5162 } 5163 } 5164 } 5165 } 5166 5167 /** 5168 * Update the permission flags for all packages and runtime permissions of a user in order 5169 * to allow device or profile owner to remove POLICY_FIXED. 5170 */ 5171 @Override 5172 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5173 if (!sUserManager.exists(userId)) { 5174 return; 5175 } 5176 5177 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5178 5179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5180 true /* requireFullPermission */, true /* checkShell */, 5181 "updatePermissionFlagsForAllApps"); 5182 5183 // Only the system can change system fixed flags. 5184 if (getCallingUid() != Process.SYSTEM_UID) { 5185 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5186 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5187 } 5188 5189 synchronized (mPackages) { 5190 boolean changed = false; 5191 final int packageCount = mPackages.size(); 5192 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5193 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5194 SettingBase sb = (SettingBase) pkg.mExtras; 5195 if (sb == null) { 5196 continue; 5197 } 5198 PermissionsState permissionsState = sb.getPermissionsState(); 5199 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5200 userId, flagMask, flagValues); 5201 } 5202 if (changed) { 5203 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5204 } 5205 } 5206 } 5207 5208 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5209 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5210 != PackageManager.PERMISSION_GRANTED 5211 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5212 != PackageManager.PERMISSION_GRANTED) { 5213 throw new SecurityException(message + " requires " 5214 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5215 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5216 } 5217 } 5218 5219 @Override 5220 public boolean shouldShowRequestPermissionRationale(String permissionName, 5221 String packageName, int userId) { 5222 if (UserHandle.getCallingUserId() != userId) { 5223 mContext.enforceCallingPermission( 5224 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5225 "canShowRequestPermissionRationale for user " + userId); 5226 } 5227 5228 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5229 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5230 return false; 5231 } 5232 5233 if (checkPermission(permissionName, packageName, userId) 5234 == PackageManager.PERMISSION_GRANTED) { 5235 return false; 5236 } 5237 5238 final int flags; 5239 5240 final long identity = Binder.clearCallingIdentity(); 5241 try { 5242 flags = getPermissionFlags(permissionName, 5243 packageName, userId); 5244 } finally { 5245 Binder.restoreCallingIdentity(identity); 5246 } 5247 5248 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5249 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5250 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5251 5252 if ((flags & fixedFlags) != 0) { 5253 return false; 5254 } 5255 5256 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5257 } 5258 5259 @Override 5260 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5261 mContext.enforceCallingOrSelfPermission( 5262 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5263 "addOnPermissionsChangeListener"); 5264 5265 synchronized (mPackages) { 5266 mOnPermissionChangeListeners.addListenerLocked(listener); 5267 } 5268 } 5269 5270 @Override 5271 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5272 synchronized (mPackages) { 5273 mOnPermissionChangeListeners.removeListenerLocked(listener); 5274 } 5275 } 5276 5277 @Override 5278 public boolean isProtectedBroadcast(String actionName) { 5279 synchronized (mPackages) { 5280 if (mProtectedBroadcasts.contains(actionName)) { 5281 return true; 5282 } else if (actionName != null) { 5283 // TODO: remove these terrible hacks 5284 if (actionName.startsWith("android.net.netmon.lingerExpired") 5285 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5286 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5287 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5288 return true; 5289 } 5290 } 5291 } 5292 return false; 5293 } 5294 5295 @Override 5296 public int checkSignatures(String pkg1, String pkg2) { 5297 synchronized (mPackages) { 5298 final PackageParser.Package p1 = mPackages.get(pkg1); 5299 final PackageParser.Package p2 = mPackages.get(pkg2); 5300 if (p1 == null || p1.mExtras == null 5301 || p2 == null || p2.mExtras == null) { 5302 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5303 } 5304 return compareSignatures(p1.mSignatures, p2.mSignatures); 5305 } 5306 } 5307 5308 @Override 5309 public int checkUidSignatures(int uid1, int uid2) { 5310 // Map to base uids. 5311 uid1 = UserHandle.getAppId(uid1); 5312 uid2 = UserHandle.getAppId(uid2); 5313 // reader 5314 synchronized (mPackages) { 5315 Signature[] s1; 5316 Signature[] s2; 5317 Object obj = mSettings.getUserIdLPr(uid1); 5318 if (obj != null) { 5319 if (obj instanceof SharedUserSetting) { 5320 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5321 } else if (obj instanceof PackageSetting) { 5322 s1 = ((PackageSetting)obj).signatures.mSignatures; 5323 } else { 5324 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5325 } 5326 } else { 5327 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5328 } 5329 obj = mSettings.getUserIdLPr(uid2); 5330 if (obj != null) { 5331 if (obj instanceof SharedUserSetting) { 5332 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5333 } else if (obj instanceof PackageSetting) { 5334 s2 = ((PackageSetting)obj).signatures.mSignatures; 5335 } else { 5336 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5337 } 5338 } else { 5339 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5340 } 5341 return compareSignatures(s1, s2); 5342 } 5343 } 5344 5345 /** 5346 * This method should typically only be used when granting or revoking 5347 * permissions, since the app may immediately restart after this call. 5348 * <p> 5349 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5350 * guard your work against the app being relaunched. 5351 */ 5352 private void killUid(int appId, int userId, String reason) { 5353 final long identity = Binder.clearCallingIdentity(); 5354 try { 5355 IActivityManager am = ActivityManager.getService(); 5356 if (am != null) { 5357 try { 5358 am.killUid(appId, userId, reason); 5359 } catch (RemoteException e) { 5360 /* ignore - same process */ 5361 } 5362 } 5363 } finally { 5364 Binder.restoreCallingIdentity(identity); 5365 } 5366 } 5367 5368 /** 5369 * Compares two sets of signatures. Returns: 5370 * <br /> 5371 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5372 * <br /> 5373 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5374 * <br /> 5375 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5376 * <br /> 5377 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5378 * <br /> 5379 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5380 */ 5381 static int compareSignatures(Signature[] s1, Signature[] s2) { 5382 if (s1 == null) { 5383 return s2 == null 5384 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5385 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5386 } 5387 5388 if (s2 == null) { 5389 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5390 } 5391 5392 if (s1.length != s2.length) { 5393 return PackageManager.SIGNATURE_NO_MATCH; 5394 } 5395 5396 // Since both signature sets are of size 1, we can compare without HashSets. 5397 if (s1.length == 1) { 5398 return s1[0].equals(s2[0]) ? 5399 PackageManager.SIGNATURE_MATCH : 5400 PackageManager.SIGNATURE_NO_MATCH; 5401 } 5402 5403 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5404 for (Signature sig : s1) { 5405 set1.add(sig); 5406 } 5407 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5408 for (Signature sig : s2) { 5409 set2.add(sig); 5410 } 5411 // Make sure s2 contains all signatures in s1. 5412 if (set1.equals(set2)) { 5413 return PackageManager.SIGNATURE_MATCH; 5414 } 5415 return PackageManager.SIGNATURE_NO_MATCH; 5416 } 5417 5418 /** 5419 * If the database version for this type of package (internal storage or 5420 * external storage) is less than the version where package signatures 5421 * were updated, return true. 5422 */ 5423 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5424 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5425 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5426 } 5427 5428 /** 5429 * Used for backward compatibility to make sure any packages with 5430 * certificate chains get upgraded to the new style. {@code existingSigs} 5431 * will be in the old format (since they were stored on disk from before the 5432 * system upgrade) and {@code scannedSigs} will be in the newer format. 5433 */ 5434 private int compareSignaturesCompat(PackageSignatures existingSigs, 5435 PackageParser.Package scannedPkg) { 5436 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5437 return PackageManager.SIGNATURE_NO_MATCH; 5438 } 5439 5440 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5441 for (Signature sig : existingSigs.mSignatures) { 5442 existingSet.add(sig); 5443 } 5444 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5445 for (Signature sig : scannedPkg.mSignatures) { 5446 try { 5447 Signature[] chainSignatures = sig.getChainSignatures(); 5448 for (Signature chainSig : chainSignatures) { 5449 scannedCompatSet.add(chainSig); 5450 } 5451 } catch (CertificateEncodingException e) { 5452 scannedCompatSet.add(sig); 5453 } 5454 } 5455 /* 5456 * Make sure the expanded scanned set contains all signatures in the 5457 * existing one. 5458 */ 5459 if (scannedCompatSet.equals(existingSet)) { 5460 // Migrate the old signatures to the new scheme. 5461 existingSigs.assignSignatures(scannedPkg.mSignatures); 5462 // The new KeySets will be re-added later in the scanning process. 5463 synchronized (mPackages) { 5464 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5465 } 5466 return PackageManager.SIGNATURE_MATCH; 5467 } 5468 return PackageManager.SIGNATURE_NO_MATCH; 5469 } 5470 5471 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5472 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5473 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5474 } 5475 5476 private int compareSignaturesRecover(PackageSignatures existingSigs, 5477 PackageParser.Package scannedPkg) { 5478 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5479 return PackageManager.SIGNATURE_NO_MATCH; 5480 } 5481 5482 String msg = null; 5483 try { 5484 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5485 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5486 + scannedPkg.packageName); 5487 return PackageManager.SIGNATURE_MATCH; 5488 } 5489 } catch (CertificateException e) { 5490 msg = e.getMessage(); 5491 } 5492 5493 logCriticalInfo(Log.INFO, 5494 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5495 return PackageManager.SIGNATURE_NO_MATCH; 5496 } 5497 5498 @Override 5499 public List<String> getAllPackages() { 5500 synchronized (mPackages) { 5501 return new ArrayList<String>(mPackages.keySet()); 5502 } 5503 } 5504 5505 @Override 5506 public String[] getPackagesForUid(int uid) { 5507 final int userId = UserHandle.getUserId(uid); 5508 uid = UserHandle.getAppId(uid); 5509 // reader 5510 synchronized (mPackages) { 5511 Object obj = mSettings.getUserIdLPr(uid); 5512 if (obj instanceof SharedUserSetting) { 5513 final SharedUserSetting sus = (SharedUserSetting) obj; 5514 final int N = sus.packages.size(); 5515 String[] res = new String[N]; 5516 final Iterator<PackageSetting> it = sus.packages.iterator(); 5517 int i = 0; 5518 while (it.hasNext()) { 5519 PackageSetting ps = it.next(); 5520 if (ps.getInstalled(userId)) { 5521 res[i++] = ps.name; 5522 } else { 5523 res = ArrayUtils.removeElement(String.class, res, res[i]); 5524 } 5525 } 5526 return res; 5527 } else if (obj instanceof PackageSetting) { 5528 final PackageSetting ps = (PackageSetting) obj; 5529 if (ps.getInstalled(userId)) { 5530 return new String[]{ps.name}; 5531 } 5532 } 5533 } 5534 return null; 5535 } 5536 5537 @Override 5538 public String getNameForUid(int uid) { 5539 // reader 5540 synchronized (mPackages) { 5541 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5542 if (obj instanceof SharedUserSetting) { 5543 final SharedUserSetting sus = (SharedUserSetting) obj; 5544 return sus.name + ":" + sus.userId; 5545 } else if (obj instanceof PackageSetting) { 5546 final PackageSetting ps = (PackageSetting) obj; 5547 return ps.name; 5548 } 5549 } 5550 return null; 5551 } 5552 5553 @Override 5554 public int getUidForSharedUser(String sharedUserName) { 5555 if(sharedUserName == null) { 5556 return -1; 5557 } 5558 // reader 5559 synchronized (mPackages) { 5560 SharedUserSetting suid; 5561 try { 5562 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5563 if (suid != null) { 5564 return suid.userId; 5565 } 5566 } catch (PackageManagerException ignore) { 5567 // can't happen, but, still need to catch it 5568 } 5569 return -1; 5570 } 5571 } 5572 5573 @Override 5574 public int getFlagsForUid(int uid) { 5575 synchronized (mPackages) { 5576 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5577 if (obj instanceof SharedUserSetting) { 5578 final SharedUserSetting sus = (SharedUserSetting) obj; 5579 return sus.pkgFlags; 5580 } else if (obj instanceof PackageSetting) { 5581 final PackageSetting ps = (PackageSetting) obj; 5582 return ps.pkgFlags; 5583 } 5584 } 5585 return 0; 5586 } 5587 5588 @Override 5589 public int getPrivateFlagsForUid(int uid) { 5590 synchronized (mPackages) { 5591 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5592 if (obj instanceof SharedUserSetting) { 5593 final SharedUserSetting sus = (SharedUserSetting) obj; 5594 return sus.pkgPrivateFlags; 5595 } else if (obj instanceof PackageSetting) { 5596 final PackageSetting ps = (PackageSetting) obj; 5597 return ps.pkgPrivateFlags; 5598 } 5599 } 5600 return 0; 5601 } 5602 5603 @Override 5604 public boolean isUidPrivileged(int uid) { 5605 uid = UserHandle.getAppId(uid); 5606 // reader 5607 synchronized (mPackages) { 5608 Object obj = mSettings.getUserIdLPr(uid); 5609 if (obj instanceof SharedUserSetting) { 5610 final SharedUserSetting sus = (SharedUserSetting) obj; 5611 final Iterator<PackageSetting> it = sus.packages.iterator(); 5612 while (it.hasNext()) { 5613 if (it.next().isPrivileged()) { 5614 return true; 5615 } 5616 } 5617 } else if (obj instanceof PackageSetting) { 5618 final PackageSetting ps = (PackageSetting) obj; 5619 return ps.isPrivileged(); 5620 } 5621 } 5622 return false; 5623 } 5624 5625 @Override 5626 public String[] getAppOpPermissionPackages(String permissionName) { 5627 synchronized (mPackages) { 5628 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5629 if (pkgs == null) { 5630 return null; 5631 } 5632 return pkgs.toArray(new String[pkgs.size()]); 5633 } 5634 } 5635 5636 @Override 5637 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5638 int flags, int userId) { 5639 return resolveIntentInternal( 5640 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5641 } 5642 5643 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5644 int flags, int userId, boolean includeInstantApp) { 5645 try { 5646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5647 5648 if (!sUserManager.exists(userId)) return null; 5649 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5650 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5651 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5652 5653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5654 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5655 flags, userId, includeInstantApp); 5656 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5657 5658 final ResolveInfo bestChoice = 5659 chooseBestActivity(intent, resolvedType, flags, query, userId); 5660 return bestChoice; 5661 } finally { 5662 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5663 } 5664 } 5665 5666 @Override 5667 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5668 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5669 throw new SecurityException( 5670 "findPersistentPreferredActivity can only be run by the system"); 5671 } 5672 if (!sUserManager.exists(userId)) { 5673 return null; 5674 } 5675 intent = updateIntentForResolve(intent); 5676 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5677 final int flags = updateFlagsForResolve(0, userId, intent, false); 5678 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5679 userId); 5680 synchronized (mPackages) { 5681 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5682 userId); 5683 } 5684 } 5685 5686 @Override 5687 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5688 IntentFilter filter, int match, ComponentName activity) { 5689 final int userId = UserHandle.getCallingUserId(); 5690 if (DEBUG_PREFERRED) { 5691 Log.v(TAG, "setLastChosenActivity intent=" + intent 5692 + " resolvedType=" + resolvedType 5693 + " flags=" + flags 5694 + " filter=" + filter 5695 + " match=" + match 5696 + " activity=" + activity); 5697 filter.dump(new PrintStreamPrinter(System.out), " "); 5698 } 5699 intent.setComponent(null); 5700 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5701 userId); 5702 // Find any earlier preferred or last chosen entries and nuke them 5703 findPreferredActivity(intent, resolvedType, 5704 flags, query, 0, false, true, false, userId); 5705 // Add the new activity as the last chosen for this filter 5706 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5707 "Setting last chosen"); 5708 } 5709 5710 @Override 5711 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5712 final int userId = UserHandle.getCallingUserId(); 5713 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5714 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5715 userId); 5716 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5717 false, false, false, userId); 5718 } 5719 5720 /** 5721 * Returns whether or not instant apps have been disabled remotely. 5722 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5723 * held. Otherwise we run the risk of deadlock. 5724 */ 5725 private boolean isEphemeralDisabled() { 5726 // ephemeral apps have been disabled across the board 5727 if (DISABLE_EPHEMERAL_APPS) { 5728 return true; 5729 } 5730 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5731 if (!mSystemReady) { 5732 return true; 5733 } 5734 // we can't get a content resolver until the system is ready; these checks must happen last 5735 final ContentResolver resolver = mContext.getContentResolver(); 5736 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5737 return true; 5738 } 5739 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5740 } 5741 5742 private boolean isEphemeralAllowed( 5743 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5744 boolean skipPackageCheck) { 5745 final int callingUser = UserHandle.getCallingUserId(); 5746 if (callingUser != UserHandle.USER_SYSTEM) { 5747 return false; 5748 } 5749 if (mInstantAppResolverConnection == null) { 5750 return false; 5751 } 5752 if (mInstantAppInstallerComponent == null) { 5753 return false; 5754 } 5755 if (intent.getComponent() != null) { 5756 return false; 5757 } 5758 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5759 return false; 5760 } 5761 if (!skipPackageCheck && intent.getPackage() != null) { 5762 return false; 5763 } 5764 final boolean isWebUri = hasWebURI(intent); 5765 if (!isWebUri || intent.getData().getHost() == null) { 5766 return false; 5767 } 5768 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5769 // Or if there's already an ephemeral app installed that handles the action 5770 synchronized (mPackages) { 5771 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5772 for (int n = 0; n < count; n++) { 5773 ResolveInfo info = resolvedActivities.get(n); 5774 String packageName = info.activityInfo.packageName; 5775 PackageSetting ps = mSettings.mPackages.get(packageName); 5776 if (ps != null) { 5777 // Try to get the status from User settings first 5778 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5779 int status = (int) (packedStatus >> 32); 5780 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5781 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5782 if (DEBUG_EPHEMERAL) { 5783 Slog.v(TAG, "DENY ephemeral apps;" 5784 + " pkg: " + packageName + ", status: " + status); 5785 } 5786 return false; 5787 } 5788 if (ps.getInstantApp(userId)) { 5789 if (DEBUG_EPHEMERAL) { 5790 Slog.v(TAG, "DENY instant app installed;" 5791 + " pkg: " + packageName); 5792 } 5793 return false; 5794 } 5795 } 5796 } 5797 } 5798 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5799 return true; 5800 } 5801 5802 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5803 Intent origIntent, String resolvedType, String callingPackage, 5804 int userId) { 5805 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5806 new InstantAppRequest(responseObj, origIntent, resolvedType, 5807 callingPackage, userId)); 5808 mHandler.sendMessage(msg); 5809 } 5810 5811 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5812 int flags, List<ResolveInfo> query, int userId) { 5813 if (query != null) { 5814 final int N = query.size(); 5815 if (N == 1) { 5816 return query.get(0); 5817 } else if (N > 1) { 5818 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5819 // If there is more than one activity with the same priority, 5820 // then let the user decide between them. 5821 ResolveInfo r0 = query.get(0); 5822 ResolveInfo r1 = query.get(1); 5823 if (DEBUG_INTENT_MATCHING || debug) { 5824 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5825 + r1.activityInfo.name + "=" + r1.priority); 5826 } 5827 // If the first activity has a higher priority, or a different 5828 // default, then it is always desirable to pick it. 5829 if (r0.priority != r1.priority 5830 || r0.preferredOrder != r1.preferredOrder 5831 || r0.isDefault != r1.isDefault) { 5832 return query.get(0); 5833 } 5834 // If we have saved a preference for a preferred activity for 5835 // this Intent, use that. 5836 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5837 flags, query, r0.priority, true, false, debug, userId); 5838 if (ri != null) { 5839 return ri; 5840 } 5841 // If we have an ephemeral app, use it 5842 for (int i = 0; i < N; i++) { 5843 ri = query.get(i); 5844 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5845 return ri; 5846 } 5847 } 5848 ri = new ResolveInfo(mResolveInfo); 5849 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5850 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5851 // If all of the options come from the same package, show the application's 5852 // label and icon instead of the generic resolver's. 5853 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5854 // and then throw away the ResolveInfo itself, meaning that the caller loses 5855 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5856 // a fallback for this case; we only set the target package's resources on 5857 // the ResolveInfo, not the ActivityInfo. 5858 final String intentPackage = intent.getPackage(); 5859 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5860 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5861 ri.resolvePackageName = intentPackage; 5862 if (userNeedsBadging(userId)) { 5863 ri.noResourceId = true; 5864 } else { 5865 ri.icon = appi.icon; 5866 } 5867 ri.iconResourceId = appi.icon; 5868 ri.labelRes = appi.labelRes; 5869 } 5870 ri.activityInfo.applicationInfo = new ApplicationInfo( 5871 ri.activityInfo.applicationInfo); 5872 if (userId != 0) { 5873 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5874 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5875 } 5876 // Make sure that the resolver is displayable in car mode 5877 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5878 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5879 return ri; 5880 } 5881 } 5882 return null; 5883 } 5884 5885 /** 5886 * Return true if the given list is not empty and all of its contents have 5887 * an activityInfo with the given package name. 5888 */ 5889 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5890 if (ArrayUtils.isEmpty(list)) { 5891 return false; 5892 } 5893 for (int i = 0, N = list.size(); i < N; i++) { 5894 final ResolveInfo ri = list.get(i); 5895 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5896 if (ai == null || !packageName.equals(ai.packageName)) { 5897 return false; 5898 } 5899 } 5900 return true; 5901 } 5902 5903 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5904 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5905 final int N = query.size(); 5906 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5907 .get(userId); 5908 // Get the list of persistent preferred activities that handle the intent 5909 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5910 List<PersistentPreferredActivity> pprefs = ppir != null 5911 ? ppir.queryIntent(intent, resolvedType, 5912 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5913 userId) 5914 : null; 5915 if (pprefs != null && pprefs.size() > 0) { 5916 final int M = pprefs.size(); 5917 for (int i=0; i<M; i++) { 5918 final PersistentPreferredActivity ppa = pprefs.get(i); 5919 if (DEBUG_PREFERRED || debug) { 5920 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5921 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5922 + "\n component=" + ppa.mComponent); 5923 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5924 } 5925 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5926 flags | MATCH_DISABLED_COMPONENTS, userId); 5927 if (DEBUG_PREFERRED || debug) { 5928 Slog.v(TAG, "Found persistent preferred activity:"); 5929 if (ai != null) { 5930 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5931 } else { 5932 Slog.v(TAG, " null"); 5933 } 5934 } 5935 if (ai == null) { 5936 // This previously registered persistent preferred activity 5937 // component is no longer known. Ignore it and do NOT remove it. 5938 continue; 5939 } 5940 for (int j=0; j<N; j++) { 5941 final ResolveInfo ri = query.get(j); 5942 if (!ri.activityInfo.applicationInfo.packageName 5943 .equals(ai.applicationInfo.packageName)) { 5944 continue; 5945 } 5946 if (!ri.activityInfo.name.equals(ai.name)) { 5947 continue; 5948 } 5949 // Found a persistent preference that can handle the intent. 5950 if (DEBUG_PREFERRED || debug) { 5951 Slog.v(TAG, "Returning persistent preferred activity: " + 5952 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5953 } 5954 return ri; 5955 } 5956 } 5957 } 5958 return null; 5959 } 5960 5961 // TODO: handle preferred activities missing while user has amnesia 5962 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5963 List<ResolveInfo> query, int priority, boolean always, 5964 boolean removeMatches, boolean debug, int userId) { 5965 if (!sUserManager.exists(userId)) return null; 5966 flags = updateFlagsForResolve(flags, userId, intent, false); 5967 intent = updateIntentForResolve(intent); 5968 // writer 5969 synchronized (mPackages) { 5970 // Try to find a matching persistent preferred activity. 5971 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5972 debug, userId); 5973 5974 // If a persistent preferred activity matched, use it. 5975 if (pri != null) { 5976 return pri; 5977 } 5978 5979 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5980 // Get the list of preferred activities that handle the intent 5981 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5982 List<PreferredActivity> prefs = pir != null 5983 ? pir.queryIntent(intent, resolvedType, 5984 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5985 userId) 5986 : null; 5987 if (prefs != null && prefs.size() > 0) { 5988 boolean changed = false; 5989 try { 5990 // First figure out how good the original match set is. 5991 // We will only allow preferred activities that came 5992 // from the same match quality. 5993 int match = 0; 5994 5995 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5996 5997 final int N = query.size(); 5998 for (int j=0; j<N; j++) { 5999 final ResolveInfo ri = query.get(j); 6000 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6001 + ": 0x" + Integer.toHexString(match)); 6002 if (ri.match > match) { 6003 match = ri.match; 6004 } 6005 } 6006 6007 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6008 + Integer.toHexString(match)); 6009 6010 match &= IntentFilter.MATCH_CATEGORY_MASK; 6011 final int M = prefs.size(); 6012 for (int i=0; i<M; i++) { 6013 final PreferredActivity pa = prefs.get(i); 6014 if (DEBUG_PREFERRED || debug) { 6015 Slog.v(TAG, "Checking PreferredActivity ds=" 6016 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6017 + "\n component=" + pa.mPref.mComponent); 6018 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6019 } 6020 if (pa.mPref.mMatch != match) { 6021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6022 + Integer.toHexString(pa.mPref.mMatch)); 6023 continue; 6024 } 6025 // If it's not an "always" type preferred activity and that's what we're 6026 // looking for, skip it. 6027 if (always && !pa.mPref.mAlways) { 6028 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6029 continue; 6030 } 6031 final ActivityInfo ai = getActivityInfo( 6032 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6033 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6034 userId); 6035 if (DEBUG_PREFERRED || debug) { 6036 Slog.v(TAG, "Found preferred activity:"); 6037 if (ai != null) { 6038 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6039 } else { 6040 Slog.v(TAG, " null"); 6041 } 6042 } 6043 if (ai == null) { 6044 // This previously registered preferred activity 6045 // component is no longer known. Most likely an update 6046 // to the app was installed and in the new version this 6047 // component no longer exists. Clean it up by removing 6048 // it from the preferred activities list, and skip it. 6049 Slog.w(TAG, "Removing dangling preferred activity: " 6050 + pa.mPref.mComponent); 6051 pir.removeFilter(pa); 6052 changed = true; 6053 continue; 6054 } 6055 for (int j=0; j<N; j++) { 6056 final ResolveInfo ri = query.get(j); 6057 if (!ri.activityInfo.applicationInfo.packageName 6058 .equals(ai.applicationInfo.packageName)) { 6059 continue; 6060 } 6061 if (!ri.activityInfo.name.equals(ai.name)) { 6062 continue; 6063 } 6064 6065 if (removeMatches) { 6066 pir.removeFilter(pa); 6067 changed = true; 6068 if (DEBUG_PREFERRED) { 6069 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6070 } 6071 break; 6072 } 6073 6074 // Okay we found a previously set preferred or last chosen app. 6075 // If the result set is different from when this 6076 // was created, we need to clear it and re-ask the 6077 // user their preference, if we're looking for an "always" type entry. 6078 if (always && !pa.mPref.sameSet(query)) { 6079 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6080 + intent + " type " + resolvedType); 6081 if (DEBUG_PREFERRED) { 6082 Slog.v(TAG, "Removing preferred activity since set changed " 6083 + pa.mPref.mComponent); 6084 } 6085 pir.removeFilter(pa); 6086 // Re-add the filter as a "last chosen" entry (!always) 6087 PreferredActivity lastChosen = new PreferredActivity( 6088 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6089 pir.addFilter(lastChosen); 6090 changed = true; 6091 return null; 6092 } 6093 6094 // Yay! Either the set matched or we're looking for the last chosen 6095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6096 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6097 return ri; 6098 } 6099 } 6100 } finally { 6101 if (changed) { 6102 if (DEBUG_PREFERRED) { 6103 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6104 } 6105 scheduleWritePackageRestrictionsLocked(userId); 6106 } 6107 } 6108 } 6109 } 6110 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6111 return null; 6112 } 6113 6114 /* 6115 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6116 */ 6117 @Override 6118 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6119 int targetUserId) { 6120 mContext.enforceCallingOrSelfPermission( 6121 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6122 List<CrossProfileIntentFilter> matches = 6123 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6124 if (matches != null) { 6125 int size = matches.size(); 6126 for (int i = 0; i < size; i++) { 6127 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6128 } 6129 } 6130 if (hasWebURI(intent)) { 6131 // cross-profile app linking works only towards the parent. 6132 final UserInfo parent = getProfileParent(sourceUserId); 6133 synchronized(mPackages) { 6134 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6135 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6136 intent, resolvedType, flags, sourceUserId, parent.id); 6137 return xpDomainInfo != null; 6138 } 6139 } 6140 return false; 6141 } 6142 6143 private UserInfo getProfileParent(int userId) { 6144 final long identity = Binder.clearCallingIdentity(); 6145 try { 6146 return sUserManager.getProfileParent(userId); 6147 } finally { 6148 Binder.restoreCallingIdentity(identity); 6149 } 6150 } 6151 6152 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6153 String resolvedType, int userId) { 6154 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6155 if (resolver != null) { 6156 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6157 } 6158 return null; 6159 } 6160 6161 @Override 6162 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6163 String resolvedType, int flags, int userId) { 6164 try { 6165 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6166 6167 return new ParceledListSlice<>( 6168 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6169 } finally { 6170 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6171 } 6172 } 6173 6174 /** 6175 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6176 * instant, returns {@code null}. 6177 */ 6178 private String getInstantAppPackageName(int callingUid) { 6179 final int appId = UserHandle.getAppId(callingUid); 6180 synchronized (mPackages) { 6181 final Object obj = mSettings.getUserIdLPr(appId); 6182 if (obj instanceof PackageSetting) { 6183 final PackageSetting ps = (PackageSetting) obj; 6184 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6185 return isInstantApp ? ps.pkg.packageName : null; 6186 } 6187 } 6188 return null; 6189 } 6190 6191 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6192 String resolvedType, int flags, int userId) { 6193 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6194 } 6195 6196 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6197 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6198 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6199 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6200 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6201 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6202 false /* requireFullPermission */, false /* checkShell */, 6203 "query intent activities"); 6204 ComponentName comp = intent.getComponent(); 6205 if (comp == null) { 6206 if (intent.getSelector() != null) { 6207 intent = intent.getSelector(); 6208 comp = intent.getComponent(); 6209 } 6210 } 6211 6212 if (comp != null) { 6213 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6214 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6215 if (ai != null) { 6216 // When specifying an explicit component, we prevent the activity from being 6217 // used when either 1) the calling package is normal and the activity is within 6218 // an ephemeral application or 2) the calling package is ephemeral and the 6219 // activity is not visible to ephemeral applications. 6220 final boolean matchInstantApp = 6221 (flags & PackageManager.MATCH_INSTANT) != 0; 6222 final boolean matchVisibleToInstantAppOnly = 6223 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6224 final boolean isCallerInstantApp = 6225 instantAppPkgName != null; 6226 final boolean isTargetSameInstantApp = 6227 comp.getPackageName().equals(instantAppPkgName); 6228 final boolean isTargetInstantApp = 6229 (ai.applicationInfo.privateFlags 6230 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6231 final boolean isTargetHiddenFromInstantApp = 6232 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6233 final boolean blockResolution = 6234 !isTargetSameInstantApp 6235 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6236 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6237 && isTargetHiddenFromInstantApp)); 6238 if (!blockResolution) { 6239 final ResolveInfo ri = new ResolveInfo(); 6240 ri.activityInfo = ai; 6241 list.add(ri); 6242 } 6243 } 6244 return applyPostResolutionFilter(list, instantAppPkgName); 6245 } 6246 6247 // reader 6248 boolean sortResult = false; 6249 boolean addEphemeral = false; 6250 List<ResolveInfo> result; 6251 final String pkgName = intent.getPackage(); 6252 final boolean ephemeralDisabled = isEphemeralDisabled(); 6253 synchronized (mPackages) { 6254 if (pkgName == null) { 6255 List<CrossProfileIntentFilter> matchingFilters = 6256 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6257 // Check for results that need to skip the current profile. 6258 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6259 resolvedType, flags, userId); 6260 if (xpResolveInfo != null) { 6261 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6262 xpResult.add(xpResolveInfo); 6263 return applyPostResolutionFilter( 6264 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6265 } 6266 6267 // Check for results in the current profile. 6268 result = filterIfNotSystemUser(mActivities.queryIntent( 6269 intent, resolvedType, flags, userId), userId); 6270 addEphemeral = !ephemeralDisabled 6271 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6272 // Check for cross profile results. 6273 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6274 xpResolveInfo = queryCrossProfileIntents( 6275 matchingFilters, intent, resolvedType, flags, userId, 6276 hasNonNegativePriorityResult); 6277 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6278 boolean isVisibleToUser = filterIfNotSystemUser( 6279 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6280 if (isVisibleToUser) { 6281 result.add(xpResolveInfo); 6282 sortResult = true; 6283 } 6284 } 6285 if (hasWebURI(intent)) { 6286 CrossProfileDomainInfo xpDomainInfo = null; 6287 final UserInfo parent = getProfileParent(userId); 6288 if (parent != null) { 6289 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6290 flags, userId, parent.id); 6291 } 6292 if (xpDomainInfo != null) { 6293 if (xpResolveInfo != null) { 6294 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6295 // in the result. 6296 result.remove(xpResolveInfo); 6297 } 6298 if (result.size() == 0 && !addEphemeral) { 6299 // No result in current profile, but found candidate in parent user. 6300 // And we are not going to add emphemeral app, so we can return the 6301 // result straight away. 6302 result.add(xpDomainInfo.resolveInfo); 6303 return applyPostResolutionFilter(result, instantAppPkgName); 6304 } 6305 } else if (result.size() <= 1 && !addEphemeral) { 6306 // No result in parent user and <= 1 result in current profile, and we 6307 // are not going to add emphemeral app, so we can return the result without 6308 // further processing. 6309 return applyPostResolutionFilter(result, instantAppPkgName); 6310 } 6311 // We have more than one candidate (combining results from current and parent 6312 // profile), so we need filtering and sorting. 6313 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6314 intent, flags, result, xpDomainInfo, userId); 6315 sortResult = true; 6316 } 6317 } else { 6318 final PackageParser.Package pkg = mPackages.get(pkgName); 6319 if (pkg != null) { 6320 return applyPostResolutionFilter(filterIfNotSystemUser( 6321 mActivities.queryIntentForPackage( 6322 intent, resolvedType, flags, pkg.activities, userId), 6323 userId), instantAppPkgName); 6324 } else { 6325 // the caller wants to resolve for a particular package; however, there 6326 // were no installed results, so, try to find an ephemeral result 6327 addEphemeral = !ephemeralDisabled 6328 && isEphemeralAllowed( 6329 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6330 result = new ArrayList<ResolveInfo>(); 6331 } 6332 } 6333 } 6334 if (addEphemeral) { 6335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6336 final InstantAppRequest requestObject = new InstantAppRequest( 6337 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6338 null /*callingPackage*/, userId); 6339 final AuxiliaryResolveInfo auxiliaryResponse = 6340 InstantAppResolver.doInstantAppResolutionPhaseOne( 6341 mContext, mInstantAppResolverConnection, requestObject); 6342 if (auxiliaryResponse != null) { 6343 if (DEBUG_EPHEMERAL) { 6344 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6345 } 6346 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6347 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6348 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6349 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6350 // make sure this resolver is the default 6351 ephemeralInstaller.isDefault = true; 6352 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6353 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6354 // add a non-generic filter 6355 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6356 ephemeralInstaller.filter.addDataPath( 6357 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6358 ephemeralInstaller.instantAppAvailable = true; 6359 result.add(ephemeralInstaller); 6360 } 6361 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6362 } 6363 if (sortResult) { 6364 Collections.sort(result, mResolvePrioritySorter); 6365 } 6366 return applyPostResolutionFilter(result, instantAppPkgName); 6367 } 6368 6369 private static class CrossProfileDomainInfo { 6370 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6371 ResolveInfo resolveInfo; 6372 /* Best domain verification status of the activities found in the other profile */ 6373 int bestDomainVerificationStatus; 6374 } 6375 6376 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6377 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6378 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6379 sourceUserId)) { 6380 return null; 6381 } 6382 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6383 resolvedType, flags, parentUserId); 6384 6385 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6386 return null; 6387 } 6388 CrossProfileDomainInfo result = null; 6389 int size = resultTargetUser.size(); 6390 for (int i = 0; i < size; i++) { 6391 ResolveInfo riTargetUser = resultTargetUser.get(i); 6392 // Intent filter verification is only for filters that specify a host. So don't return 6393 // those that handle all web uris. 6394 if (riTargetUser.handleAllWebDataURI) { 6395 continue; 6396 } 6397 String packageName = riTargetUser.activityInfo.packageName; 6398 PackageSetting ps = mSettings.mPackages.get(packageName); 6399 if (ps == null) { 6400 continue; 6401 } 6402 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6403 int status = (int)(verificationState >> 32); 6404 if (result == null) { 6405 result = new CrossProfileDomainInfo(); 6406 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6407 sourceUserId, parentUserId); 6408 result.bestDomainVerificationStatus = status; 6409 } else { 6410 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6411 result.bestDomainVerificationStatus); 6412 } 6413 } 6414 // Don't consider matches with status NEVER across profiles. 6415 if (result != null && result.bestDomainVerificationStatus 6416 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6417 return null; 6418 } 6419 return result; 6420 } 6421 6422 /** 6423 * Verification statuses are ordered from the worse to the best, except for 6424 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6425 */ 6426 private int bestDomainVerificationStatus(int status1, int status2) { 6427 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6428 return status2; 6429 } 6430 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6431 return status1; 6432 } 6433 return (int) MathUtils.max(status1, status2); 6434 } 6435 6436 private boolean isUserEnabled(int userId) { 6437 long callingId = Binder.clearCallingIdentity(); 6438 try { 6439 UserInfo userInfo = sUserManager.getUserInfo(userId); 6440 return userInfo != null && userInfo.isEnabled(); 6441 } finally { 6442 Binder.restoreCallingIdentity(callingId); 6443 } 6444 } 6445 6446 /** 6447 * Filter out activities with systemUserOnly flag set, when current user is not System. 6448 * 6449 * @return filtered list 6450 */ 6451 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6452 if (userId == UserHandle.USER_SYSTEM) { 6453 return resolveInfos; 6454 } 6455 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6456 ResolveInfo info = resolveInfos.get(i); 6457 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6458 resolveInfos.remove(i); 6459 } 6460 } 6461 return resolveInfos; 6462 } 6463 6464 /** 6465 * Filters out ephemeral activities. 6466 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6467 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6468 * 6469 * @param resolveInfos The pre-filtered list of resolved activities 6470 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6471 * is performed. 6472 * @return A filtered list of resolved activities. 6473 */ 6474 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6475 String ephemeralPkgName) { 6476 // TODO: When adding on-demand split support for non-instant apps, remove this check 6477 // and always apply post filtering 6478 if (ephemeralPkgName == null) { 6479 return resolveInfos; 6480 } 6481 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6482 final ResolveInfo info = resolveInfos.get(i); 6483 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6484 // allow activities that are defined in the provided package 6485 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6486 if (info.activityInfo.splitName != null 6487 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6488 info.activityInfo.splitName)) { 6489 // requested activity is defined in a split that hasn't been installed yet. 6490 // add the installer to the resolve list 6491 if (DEBUG_EPHEMERAL) { 6492 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6493 } 6494 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6495 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6496 info.activityInfo.packageName, info.activityInfo.splitName, 6497 info.activityInfo.applicationInfo.versionCode); 6498 // make sure this resolver is the default 6499 installerInfo.isDefault = true; 6500 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6501 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6502 // add a non-generic filter 6503 installerInfo.filter = new IntentFilter(); 6504 // load resources from the correct package 6505 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6506 resolveInfos.set(i, installerInfo); 6507 } 6508 continue; 6509 } 6510 // allow activities that have been explicitly exposed to ephemeral apps 6511 if (!isEphemeralApp 6512 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6513 continue; 6514 } 6515 resolveInfos.remove(i); 6516 } 6517 return resolveInfos; 6518 } 6519 6520 /** 6521 * @param resolveInfos list of resolve infos in descending priority order 6522 * @return if the list contains a resolve info with non-negative priority 6523 */ 6524 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6525 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6526 } 6527 6528 private static boolean hasWebURI(Intent intent) { 6529 if (intent.getData() == null) { 6530 return false; 6531 } 6532 final String scheme = intent.getScheme(); 6533 if (TextUtils.isEmpty(scheme)) { 6534 return false; 6535 } 6536 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6537 } 6538 6539 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6540 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6541 int userId) { 6542 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6543 6544 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6545 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6546 candidates.size()); 6547 } 6548 6549 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6550 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6551 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6552 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6553 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6554 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6555 6556 synchronized (mPackages) { 6557 final int count = candidates.size(); 6558 // First, try to use linked apps. Partition the candidates into four lists: 6559 // one for the final results, one for the "do not use ever", one for "undefined status" 6560 // and finally one for "browser app type". 6561 for (int n=0; n<count; n++) { 6562 ResolveInfo info = candidates.get(n); 6563 String packageName = info.activityInfo.packageName; 6564 PackageSetting ps = mSettings.mPackages.get(packageName); 6565 if (ps != null) { 6566 // Add to the special match all list (Browser use case) 6567 if (info.handleAllWebDataURI) { 6568 matchAllList.add(info); 6569 continue; 6570 } 6571 // Try to get the status from User settings first 6572 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6573 int status = (int)(packedStatus >> 32); 6574 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6575 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6576 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6577 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6578 + " : linkgen=" + linkGeneration); 6579 } 6580 // Use link-enabled generation as preferredOrder, i.e. 6581 // prefer newly-enabled over earlier-enabled. 6582 info.preferredOrder = linkGeneration; 6583 alwaysList.add(info); 6584 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6585 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6586 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6587 } 6588 neverList.add(info); 6589 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6590 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6591 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6592 } 6593 alwaysAskList.add(info); 6594 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6595 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6596 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6597 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6598 } 6599 undefinedList.add(info); 6600 } 6601 } 6602 } 6603 6604 // We'll want to include browser possibilities in a few cases 6605 boolean includeBrowser = false; 6606 6607 // First try to add the "always" resolution(s) for the current user, if any 6608 if (alwaysList.size() > 0) { 6609 result.addAll(alwaysList); 6610 } else { 6611 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6612 result.addAll(undefinedList); 6613 // Maybe add one for the other profile. 6614 if (xpDomainInfo != null && ( 6615 xpDomainInfo.bestDomainVerificationStatus 6616 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6617 result.add(xpDomainInfo.resolveInfo); 6618 } 6619 includeBrowser = true; 6620 } 6621 6622 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6623 // If there were 'always' entries their preferred order has been set, so we also 6624 // back that off to make the alternatives equivalent 6625 if (alwaysAskList.size() > 0) { 6626 for (ResolveInfo i : result) { 6627 i.preferredOrder = 0; 6628 } 6629 result.addAll(alwaysAskList); 6630 includeBrowser = true; 6631 } 6632 6633 if (includeBrowser) { 6634 // Also add browsers (all of them or only the default one) 6635 if (DEBUG_DOMAIN_VERIFICATION) { 6636 Slog.v(TAG, " ...including browsers in candidate set"); 6637 } 6638 if ((matchFlags & MATCH_ALL) != 0) { 6639 result.addAll(matchAllList); 6640 } else { 6641 // Browser/generic handling case. If there's a default browser, go straight 6642 // to that (but only if there is no other higher-priority match). 6643 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6644 int maxMatchPrio = 0; 6645 ResolveInfo defaultBrowserMatch = null; 6646 final int numCandidates = matchAllList.size(); 6647 for (int n = 0; n < numCandidates; n++) { 6648 ResolveInfo info = matchAllList.get(n); 6649 // track the highest overall match priority... 6650 if (info.priority > maxMatchPrio) { 6651 maxMatchPrio = info.priority; 6652 } 6653 // ...and the highest-priority default browser match 6654 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6655 if (defaultBrowserMatch == null 6656 || (defaultBrowserMatch.priority < info.priority)) { 6657 if (debug) { 6658 Slog.v(TAG, "Considering default browser match " + info); 6659 } 6660 defaultBrowserMatch = info; 6661 } 6662 } 6663 } 6664 if (defaultBrowserMatch != null 6665 && defaultBrowserMatch.priority >= maxMatchPrio 6666 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6667 { 6668 if (debug) { 6669 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6670 } 6671 result.add(defaultBrowserMatch); 6672 } else { 6673 result.addAll(matchAllList); 6674 } 6675 } 6676 6677 // If there is nothing selected, add all candidates and remove the ones that the user 6678 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6679 if (result.size() == 0) { 6680 result.addAll(candidates); 6681 result.removeAll(neverList); 6682 } 6683 } 6684 } 6685 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6686 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6687 result.size()); 6688 for (ResolveInfo info : result) { 6689 Slog.v(TAG, " + " + info.activityInfo); 6690 } 6691 } 6692 return result; 6693 } 6694 6695 // Returns a packed value as a long: 6696 // 6697 // high 'int'-sized word: link status: undefined/ask/never/always. 6698 // low 'int'-sized word: relative priority among 'always' results. 6699 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6700 long result = ps.getDomainVerificationStatusForUser(userId); 6701 // if none available, get the master status 6702 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6703 if (ps.getIntentFilterVerificationInfo() != null) { 6704 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6705 } 6706 } 6707 return result; 6708 } 6709 6710 private ResolveInfo querySkipCurrentProfileIntents( 6711 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6712 int flags, int sourceUserId) { 6713 if (matchingFilters != null) { 6714 int size = matchingFilters.size(); 6715 for (int i = 0; i < size; i ++) { 6716 CrossProfileIntentFilter filter = matchingFilters.get(i); 6717 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6718 // Checking if there are activities in the target user that can handle the 6719 // intent. 6720 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6721 resolvedType, flags, sourceUserId); 6722 if (resolveInfo != null) { 6723 return resolveInfo; 6724 } 6725 } 6726 } 6727 } 6728 return null; 6729 } 6730 6731 // Return matching ResolveInfo in target user if any. 6732 private ResolveInfo queryCrossProfileIntents( 6733 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6734 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6735 if (matchingFilters != null) { 6736 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6737 // match the same intent. For performance reasons, it is better not to 6738 // run queryIntent twice for the same userId 6739 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6740 int size = matchingFilters.size(); 6741 for (int i = 0; i < size; i++) { 6742 CrossProfileIntentFilter filter = matchingFilters.get(i); 6743 int targetUserId = filter.getTargetUserId(); 6744 boolean skipCurrentProfile = 6745 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6746 boolean skipCurrentProfileIfNoMatchFound = 6747 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6748 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6749 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6750 // Checking if there are activities in the target user that can handle the 6751 // intent. 6752 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6753 resolvedType, flags, sourceUserId); 6754 if (resolveInfo != null) return resolveInfo; 6755 alreadyTriedUserIds.put(targetUserId, true); 6756 } 6757 } 6758 } 6759 return null; 6760 } 6761 6762 /** 6763 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6764 * will forward the intent to the filter's target user. 6765 * Otherwise, returns null. 6766 */ 6767 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6768 String resolvedType, int flags, int sourceUserId) { 6769 int targetUserId = filter.getTargetUserId(); 6770 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6771 resolvedType, flags, targetUserId); 6772 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6773 // If all the matches in the target profile are suspended, return null. 6774 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6775 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6776 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6777 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6778 targetUserId); 6779 } 6780 } 6781 } 6782 return null; 6783 } 6784 6785 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6786 int sourceUserId, int targetUserId) { 6787 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6788 long ident = Binder.clearCallingIdentity(); 6789 boolean targetIsProfile; 6790 try { 6791 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6792 } finally { 6793 Binder.restoreCallingIdentity(ident); 6794 } 6795 String className; 6796 if (targetIsProfile) { 6797 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6798 } else { 6799 className = FORWARD_INTENT_TO_PARENT; 6800 } 6801 ComponentName forwardingActivityComponentName = new ComponentName( 6802 mAndroidApplication.packageName, className); 6803 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6804 sourceUserId); 6805 if (!targetIsProfile) { 6806 forwardingActivityInfo.showUserIcon = targetUserId; 6807 forwardingResolveInfo.noResourceId = true; 6808 } 6809 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6810 forwardingResolveInfo.priority = 0; 6811 forwardingResolveInfo.preferredOrder = 0; 6812 forwardingResolveInfo.match = 0; 6813 forwardingResolveInfo.isDefault = true; 6814 forwardingResolveInfo.filter = filter; 6815 forwardingResolveInfo.targetUserId = targetUserId; 6816 return forwardingResolveInfo; 6817 } 6818 6819 @Override 6820 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6821 Intent[] specifics, String[] specificTypes, Intent intent, 6822 String resolvedType, int flags, int userId) { 6823 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6824 specificTypes, intent, resolvedType, flags, userId)); 6825 } 6826 6827 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6828 Intent[] specifics, String[] specificTypes, Intent intent, 6829 String resolvedType, int flags, int userId) { 6830 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6831 flags = updateFlagsForResolve(flags, userId, intent, false); 6832 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6833 false /* requireFullPermission */, false /* checkShell */, 6834 "query intent activity options"); 6835 final String resultsAction = intent.getAction(); 6836 6837 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6838 | PackageManager.GET_RESOLVED_FILTER, userId); 6839 6840 if (DEBUG_INTENT_MATCHING) { 6841 Log.v(TAG, "Query " + intent + ": " + results); 6842 } 6843 6844 int specificsPos = 0; 6845 int N; 6846 6847 // todo: note that the algorithm used here is O(N^2). This 6848 // isn't a problem in our current environment, but if we start running 6849 // into situations where we have more than 5 or 10 matches then this 6850 // should probably be changed to something smarter... 6851 6852 // First we go through and resolve each of the specific items 6853 // that were supplied, taking care of removing any corresponding 6854 // duplicate items in the generic resolve list. 6855 if (specifics != null) { 6856 for (int i=0; i<specifics.length; i++) { 6857 final Intent sintent = specifics[i]; 6858 if (sintent == null) { 6859 continue; 6860 } 6861 6862 if (DEBUG_INTENT_MATCHING) { 6863 Log.v(TAG, "Specific #" + i + ": " + sintent); 6864 } 6865 6866 String action = sintent.getAction(); 6867 if (resultsAction != null && resultsAction.equals(action)) { 6868 // If this action was explicitly requested, then don't 6869 // remove things that have it. 6870 action = null; 6871 } 6872 6873 ResolveInfo ri = null; 6874 ActivityInfo ai = null; 6875 6876 ComponentName comp = sintent.getComponent(); 6877 if (comp == null) { 6878 ri = resolveIntent( 6879 sintent, 6880 specificTypes != null ? specificTypes[i] : null, 6881 flags, userId); 6882 if (ri == null) { 6883 continue; 6884 } 6885 if (ri == mResolveInfo) { 6886 // ACK! Must do something better with this. 6887 } 6888 ai = ri.activityInfo; 6889 comp = new ComponentName(ai.applicationInfo.packageName, 6890 ai.name); 6891 } else { 6892 ai = getActivityInfo(comp, flags, userId); 6893 if (ai == null) { 6894 continue; 6895 } 6896 } 6897 6898 // Look for any generic query activities that are duplicates 6899 // of this specific one, and remove them from the results. 6900 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6901 N = results.size(); 6902 int j; 6903 for (j=specificsPos; j<N; j++) { 6904 ResolveInfo sri = results.get(j); 6905 if ((sri.activityInfo.name.equals(comp.getClassName()) 6906 && sri.activityInfo.applicationInfo.packageName.equals( 6907 comp.getPackageName())) 6908 || (action != null && sri.filter.matchAction(action))) { 6909 results.remove(j); 6910 if (DEBUG_INTENT_MATCHING) Log.v( 6911 TAG, "Removing duplicate item from " + j 6912 + " due to specific " + specificsPos); 6913 if (ri == null) { 6914 ri = sri; 6915 } 6916 j--; 6917 N--; 6918 } 6919 } 6920 6921 // Add this specific item to its proper place. 6922 if (ri == null) { 6923 ri = new ResolveInfo(); 6924 ri.activityInfo = ai; 6925 } 6926 results.add(specificsPos, ri); 6927 ri.specificIndex = i; 6928 specificsPos++; 6929 } 6930 } 6931 6932 // Now we go through the remaining generic results and remove any 6933 // duplicate actions that are found here. 6934 N = results.size(); 6935 for (int i=specificsPos; i<N-1; i++) { 6936 final ResolveInfo rii = results.get(i); 6937 if (rii.filter == null) { 6938 continue; 6939 } 6940 6941 // Iterate over all of the actions of this result's intent 6942 // filter... typically this should be just one. 6943 final Iterator<String> it = rii.filter.actionsIterator(); 6944 if (it == null) { 6945 continue; 6946 } 6947 while (it.hasNext()) { 6948 final String action = it.next(); 6949 if (resultsAction != null && resultsAction.equals(action)) { 6950 // If this action was explicitly requested, then don't 6951 // remove things that have it. 6952 continue; 6953 } 6954 for (int j=i+1; j<N; j++) { 6955 final ResolveInfo rij = results.get(j); 6956 if (rij.filter != null && rij.filter.hasAction(action)) { 6957 results.remove(j); 6958 if (DEBUG_INTENT_MATCHING) Log.v( 6959 TAG, "Removing duplicate item from " + j 6960 + " due to action " + action + " at " + i); 6961 j--; 6962 N--; 6963 } 6964 } 6965 } 6966 6967 // If the caller didn't request filter information, drop it now 6968 // so we don't have to marshall/unmarshall it. 6969 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6970 rii.filter = null; 6971 } 6972 } 6973 6974 // Filter out the caller activity if so requested. 6975 if (caller != null) { 6976 N = results.size(); 6977 for (int i=0; i<N; i++) { 6978 ActivityInfo ainfo = results.get(i).activityInfo; 6979 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6980 && caller.getClassName().equals(ainfo.name)) { 6981 results.remove(i); 6982 break; 6983 } 6984 } 6985 } 6986 6987 // If the caller didn't request filter information, 6988 // drop them now so we don't have to 6989 // marshall/unmarshall it. 6990 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6991 N = results.size(); 6992 for (int i=0; i<N; i++) { 6993 results.get(i).filter = null; 6994 } 6995 } 6996 6997 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6998 return results; 6999 } 7000 7001 @Override 7002 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7003 String resolvedType, int flags, int userId) { 7004 return new ParceledListSlice<>( 7005 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7006 } 7007 7008 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7009 String resolvedType, int flags, int userId) { 7010 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7011 flags = updateFlagsForResolve(flags, userId, intent, false); 7012 ComponentName comp = intent.getComponent(); 7013 if (comp == null) { 7014 if (intent.getSelector() != null) { 7015 intent = intent.getSelector(); 7016 comp = intent.getComponent(); 7017 } 7018 } 7019 if (comp != null) { 7020 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7021 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7022 if (ai != null) { 7023 ResolveInfo ri = new ResolveInfo(); 7024 ri.activityInfo = ai; 7025 list.add(ri); 7026 } 7027 return list; 7028 } 7029 7030 // reader 7031 synchronized (mPackages) { 7032 String pkgName = intent.getPackage(); 7033 if (pkgName == null) { 7034 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7035 } 7036 final PackageParser.Package pkg = mPackages.get(pkgName); 7037 if (pkg != null) { 7038 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7039 userId); 7040 } 7041 return Collections.emptyList(); 7042 } 7043 } 7044 7045 @Override 7046 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7047 if (!sUserManager.exists(userId)) return null; 7048 flags = updateFlagsForResolve(flags, userId, intent, false); 7049 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 7050 if (query != null) { 7051 if (query.size() >= 1) { 7052 // If there is more than one service with the same priority, 7053 // just arbitrarily pick the first one. 7054 return query.get(0); 7055 } 7056 } 7057 return null; 7058 } 7059 7060 @Override 7061 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7062 String resolvedType, int flags, int userId) { 7063 return new ParceledListSlice<>( 7064 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 7065 } 7066 7067 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7068 String resolvedType, int flags, int userId) { 7069 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7070 flags = updateFlagsForResolve(flags, userId, intent, false); 7071 ComponentName comp = intent.getComponent(); 7072 if (comp == null) { 7073 if (intent.getSelector() != null) { 7074 intent = intent.getSelector(); 7075 comp = intent.getComponent(); 7076 } 7077 } 7078 if (comp != null) { 7079 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7080 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7081 if (si != null) { 7082 final ResolveInfo ri = new ResolveInfo(); 7083 ri.serviceInfo = si; 7084 list.add(ri); 7085 } 7086 return list; 7087 } 7088 7089 // reader 7090 synchronized (mPackages) { 7091 String pkgName = intent.getPackage(); 7092 if (pkgName == null) { 7093 return mServices.queryIntent(intent, resolvedType, flags, userId); 7094 } 7095 final PackageParser.Package pkg = mPackages.get(pkgName); 7096 if (pkg != null) { 7097 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7098 userId); 7099 } 7100 return Collections.emptyList(); 7101 } 7102 } 7103 7104 @Override 7105 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7106 String resolvedType, int flags, int userId) { 7107 return new ParceledListSlice<>( 7108 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7109 } 7110 7111 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7112 Intent intent, String resolvedType, int flags, int userId) { 7113 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7114 flags = updateFlagsForResolve(flags, userId, intent, false); 7115 ComponentName comp = intent.getComponent(); 7116 if (comp == null) { 7117 if (intent.getSelector() != null) { 7118 intent = intent.getSelector(); 7119 comp = intent.getComponent(); 7120 } 7121 } 7122 if (comp != null) { 7123 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7124 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7125 if (pi != null) { 7126 final ResolveInfo ri = new ResolveInfo(); 7127 ri.providerInfo = pi; 7128 list.add(ri); 7129 } 7130 return list; 7131 } 7132 7133 // reader 7134 synchronized (mPackages) { 7135 String pkgName = intent.getPackage(); 7136 if (pkgName == null) { 7137 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7138 } 7139 final PackageParser.Package pkg = mPackages.get(pkgName); 7140 if (pkg != null) { 7141 return mProviders.queryIntentForPackage( 7142 intent, resolvedType, flags, pkg.providers, userId); 7143 } 7144 return Collections.emptyList(); 7145 } 7146 } 7147 7148 @Override 7149 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7150 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7151 flags = updateFlagsForPackage(flags, userId, null); 7152 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7153 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7154 true /* requireFullPermission */, false /* checkShell */, 7155 "get installed packages"); 7156 7157 // writer 7158 synchronized (mPackages) { 7159 ArrayList<PackageInfo> list; 7160 if (listUninstalled) { 7161 list = new ArrayList<>(mSettings.mPackages.size()); 7162 for (PackageSetting ps : mSettings.mPackages.values()) { 7163 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7164 continue; 7165 } 7166 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7167 if (pi != null) { 7168 list.add(pi); 7169 } 7170 } 7171 } else { 7172 list = new ArrayList<>(mPackages.size()); 7173 for (PackageParser.Package p : mPackages.values()) { 7174 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7175 Binder.getCallingUid(), userId)) { 7176 continue; 7177 } 7178 final PackageInfo pi = generatePackageInfo((PackageSetting) 7179 p.mExtras, flags, userId); 7180 if (pi != null) { 7181 list.add(pi); 7182 } 7183 } 7184 } 7185 7186 return new ParceledListSlice<>(list); 7187 } 7188 } 7189 7190 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7191 String[] permissions, boolean[] tmp, int flags, int userId) { 7192 int numMatch = 0; 7193 final PermissionsState permissionsState = ps.getPermissionsState(); 7194 for (int i=0; i<permissions.length; i++) { 7195 final String permission = permissions[i]; 7196 if (permissionsState.hasPermission(permission, userId)) { 7197 tmp[i] = true; 7198 numMatch++; 7199 } else { 7200 tmp[i] = false; 7201 } 7202 } 7203 if (numMatch == 0) { 7204 return; 7205 } 7206 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7207 7208 // The above might return null in cases of uninstalled apps or install-state 7209 // skew across users/profiles. 7210 if (pi != null) { 7211 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7212 if (numMatch == permissions.length) { 7213 pi.requestedPermissions = permissions; 7214 } else { 7215 pi.requestedPermissions = new String[numMatch]; 7216 numMatch = 0; 7217 for (int i=0; i<permissions.length; i++) { 7218 if (tmp[i]) { 7219 pi.requestedPermissions[numMatch] = permissions[i]; 7220 numMatch++; 7221 } 7222 } 7223 } 7224 } 7225 list.add(pi); 7226 } 7227 } 7228 7229 @Override 7230 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7231 String[] permissions, int flags, int userId) { 7232 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7233 flags = updateFlagsForPackage(flags, userId, permissions); 7234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7235 true /* requireFullPermission */, false /* checkShell */, 7236 "get packages holding permissions"); 7237 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7238 7239 // writer 7240 synchronized (mPackages) { 7241 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7242 boolean[] tmpBools = new boolean[permissions.length]; 7243 if (listUninstalled) { 7244 for (PackageSetting ps : mSettings.mPackages.values()) { 7245 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7246 userId); 7247 } 7248 } else { 7249 for (PackageParser.Package pkg : mPackages.values()) { 7250 PackageSetting ps = (PackageSetting)pkg.mExtras; 7251 if (ps != null) { 7252 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7253 userId); 7254 } 7255 } 7256 } 7257 7258 return new ParceledListSlice<PackageInfo>(list); 7259 } 7260 } 7261 7262 @Override 7263 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7264 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7265 flags = updateFlagsForApplication(flags, userId, null); 7266 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7267 7268 // writer 7269 synchronized (mPackages) { 7270 ArrayList<ApplicationInfo> list; 7271 if (listUninstalled) { 7272 list = new ArrayList<>(mSettings.mPackages.size()); 7273 for (PackageSetting ps : mSettings.mPackages.values()) { 7274 ApplicationInfo ai; 7275 int effectiveFlags = flags; 7276 if (ps.isSystem()) { 7277 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7278 } 7279 if (ps.pkg != null) { 7280 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7281 continue; 7282 } 7283 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7284 ps.readUserState(userId), userId); 7285 if (ai != null) { 7286 rebaseEnabledOverlays(ai, userId); 7287 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7288 } 7289 } else { 7290 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7291 // and already converts to externally visible package name 7292 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7293 Binder.getCallingUid(), effectiveFlags, userId); 7294 } 7295 if (ai != null) { 7296 list.add(ai); 7297 } 7298 } 7299 } else { 7300 list = new ArrayList<>(mPackages.size()); 7301 for (PackageParser.Package p : mPackages.values()) { 7302 if (p.mExtras != null) { 7303 PackageSetting ps = (PackageSetting) p.mExtras; 7304 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7305 continue; 7306 } 7307 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7308 ps.readUserState(userId), userId); 7309 if (ai != null) { 7310 rebaseEnabledOverlays(ai, userId); 7311 ai.packageName = resolveExternalPackageNameLPr(p); 7312 list.add(ai); 7313 } 7314 } 7315 } 7316 } 7317 7318 return new ParceledListSlice<>(list); 7319 } 7320 } 7321 7322 @Override 7323 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7324 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7325 return null; 7326 } 7327 7328 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7329 "getEphemeralApplications"); 7330 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7331 true /* requireFullPermission */, false /* checkShell */, 7332 "getEphemeralApplications"); 7333 synchronized (mPackages) { 7334 List<InstantAppInfo> instantApps = mInstantAppRegistry 7335 .getInstantAppsLPr(userId); 7336 if (instantApps != null) { 7337 return new ParceledListSlice<>(instantApps); 7338 } 7339 } 7340 return null; 7341 } 7342 7343 @Override 7344 public boolean isInstantApp(String packageName, int userId) { 7345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7346 true /* requireFullPermission */, false /* checkShell */, 7347 "isInstantApp"); 7348 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7349 return false; 7350 } 7351 7352 synchronized (mPackages) { 7353 final PackageSetting ps = mSettings.mPackages.get(packageName); 7354 final boolean returnAllowed = 7355 ps != null 7356 && (isCallerSameApp(packageName) 7357 || mContext.checkCallingOrSelfPermission( 7358 android.Manifest.permission.ACCESS_INSTANT_APPS) 7359 == PERMISSION_GRANTED 7360 || mInstantAppRegistry.isInstantAccessGranted( 7361 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7362 if (returnAllowed) { 7363 return ps.getInstantApp(userId); 7364 } 7365 } 7366 return false; 7367 } 7368 7369 @Override 7370 public byte[] getInstantAppCookie(String packageName, int userId) { 7371 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7372 return null; 7373 } 7374 7375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7376 true /* requireFullPermission */, false /* checkShell */, 7377 "getInstantAppCookie"); 7378 if (!isCallerSameApp(packageName)) { 7379 return null; 7380 } 7381 synchronized (mPackages) { 7382 return mInstantAppRegistry.getInstantAppCookieLPw( 7383 packageName, userId); 7384 } 7385 } 7386 7387 @Override 7388 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7389 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7390 return true; 7391 } 7392 7393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7394 true /* requireFullPermission */, true /* checkShell */, 7395 "setInstantAppCookie"); 7396 if (!isCallerSameApp(packageName)) { 7397 return false; 7398 } 7399 synchronized (mPackages) { 7400 return mInstantAppRegistry.setInstantAppCookieLPw( 7401 packageName, cookie, userId); 7402 } 7403 } 7404 7405 @Override 7406 public Bitmap getInstantAppIcon(String packageName, int userId) { 7407 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7408 return null; 7409 } 7410 7411 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7412 "getInstantAppIcon"); 7413 7414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7415 true /* requireFullPermission */, false /* checkShell */, 7416 "getInstantAppIcon"); 7417 7418 synchronized (mPackages) { 7419 return mInstantAppRegistry.getInstantAppIconLPw( 7420 packageName, userId); 7421 } 7422 } 7423 7424 private boolean isCallerSameApp(String packageName) { 7425 PackageParser.Package pkg = mPackages.get(packageName); 7426 return pkg != null 7427 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7428 } 7429 7430 @Override 7431 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7432 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7433 } 7434 7435 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7436 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7437 7438 // reader 7439 synchronized (mPackages) { 7440 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7441 final int userId = UserHandle.getCallingUserId(); 7442 while (i.hasNext()) { 7443 final PackageParser.Package p = i.next(); 7444 if (p.applicationInfo == null) continue; 7445 7446 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7447 && !p.applicationInfo.isDirectBootAware(); 7448 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7449 && p.applicationInfo.isDirectBootAware(); 7450 7451 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7452 && (!mSafeMode || isSystemApp(p)) 7453 && (matchesUnaware || matchesAware)) { 7454 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7455 if (ps != null) { 7456 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7457 ps.readUserState(userId), userId); 7458 if (ai != null) { 7459 rebaseEnabledOverlays(ai, userId); 7460 finalList.add(ai); 7461 } 7462 } 7463 } 7464 } 7465 } 7466 7467 return finalList; 7468 } 7469 7470 @Override 7471 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7472 if (!sUserManager.exists(userId)) return null; 7473 flags = updateFlagsForComponent(flags, userId, name); 7474 // reader 7475 synchronized (mPackages) { 7476 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7477 PackageSetting ps = provider != null 7478 ? mSettings.mPackages.get(provider.owner.packageName) 7479 : null; 7480 return ps != null 7481 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7482 ? PackageParser.generateProviderInfo(provider, flags, 7483 ps.readUserState(userId), userId) 7484 : null; 7485 } 7486 } 7487 7488 /** 7489 * @deprecated 7490 */ 7491 @Deprecated 7492 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7493 // reader 7494 synchronized (mPackages) { 7495 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7496 .entrySet().iterator(); 7497 final int userId = UserHandle.getCallingUserId(); 7498 while (i.hasNext()) { 7499 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7500 PackageParser.Provider p = entry.getValue(); 7501 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7502 7503 if (ps != null && p.syncable 7504 && (!mSafeMode || (p.info.applicationInfo.flags 7505 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7506 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7507 ps.readUserState(userId), userId); 7508 if (info != null) { 7509 outNames.add(entry.getKey()); 7510 outInfo.add(info); 7511 } 7512 } 7513 } 7514 } 7515 } 7516 7517 @Override 7518 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7519 int uid, int flags, String metaDataKey) { 7520 final int userId = processName != null ? UserHandle.getUserId(uid) 7521 : UserHandle.getCallingUserId(); 7522 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7523 flags = updateFlagsForComponent(flags, userId, processName); 7524 7525 ArrayList<ProviderInfo> finalList = null; 7526 // reader 7527 synchronized (mPackages) { 7528 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7529 while (i.hasNext()) { 7530 final PackageParser.Provider p = i.next(); 7531 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7532 if (ps != null && p.info.authority != null 7533 && (processName == null 7534 || (p.info.processName.equals(processName) 7535 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7536 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7537 7538 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7539 // parameter. 7540 if (metaDataKey != null 7541 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7542 continue; 7543 } 7544 7545 if (finalList == null) { 7546 finalList = new ArrayList<ProviderInfo>(3); 7547 } 7548 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7549 ps.readUserState(userId), userId); 7550 if (info != null) { 7551 finalList.add(info); 7552 } 7553 } 7554 } 7555 } 7556 7557 if (finalList != null) { 7558 Collections.sort(finalList, mProviderInitOrderSorter); 7559 return new ParceledListSlice<ProviderInfo>(finalList); 7560 } 7561 7562 return ParceledListSlice.emptyList(); 7563 } 7564 7565 @Override 7566 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7567 // reader 7568 synchronized (mPackages) { 7569 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7570 return PackageParser.generateInstrumentationInfo(i, flags); 7571 } 7572 } 7573 7574 @Override 7575 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7576 String targetPackage, int flags) { 7577 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7578 } 7579 7580 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7581 int flags) { 7582 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7583 7584 // reader 7585 synchronized (mPackages) { 7586 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7587 while (i.hasNext()) { 7588 final PackageParser.Instrumentation p = i.next(); 7589 if (targetPackage == null 7590 || targetPackage.equals(p.info.targetPackage)) { 7591 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7592 flags); 7593 if (ii != null) { 7594 finalList.add(ii); 7595 } 7596 } 7597 } 7598 } 7599 7600 return finalList; 7601 } 7602 7603 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7605 try { 7606 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7607 } finally { 7608 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7609 } 7610 } 7611 7612 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7613 final File[] files = dir.listFiles(); 7614 if (ArrayUtils.isEmpty(files)) { 7615 Log.d(TAG, "No files in app dir " + dir); 7616 return; 7617 } 7618 7619 if (DEBUG_PACKAGE_SCANNING) { 7620 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7621 + " flags=0x" + Integer.toHexString(parseFlags)); 7622 } 7623 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7624 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7625 7626 // Submit files for parsing in parallel 7627 int fileCount = 0; 7628 for (File file : files) { 7629 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7630 && !PackageInstallerService.isStageName(file.getName()); 7631 if (!isPackage) { 7632 // Ignore entries which are not packages 7633 continue; 7634 } 7635 parallelPackageParser.submit(file, parseFlags); 7636 fileCount++; 7637 } 7638 7639 // Process results one by one 7640 for (; fileCount > 0; fileCount--) { 7641 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7642 Throwable throwable = parseResult.throwable; 7643 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7644 7645 if (throwable == null) { 7646 // Static shared libraries have synthetic package names 7647 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7648 renameStaticSharedLibraryPackage(parseResult.pkg); 7649 } 7650 try { 7651 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7652 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7653 currentTime, null); 7654 } 7655 } catch (PackageManagerException e) { 7656 errorCode = e.error; 7657 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7658 } 7659 } else if (throwable instanceof PackageParser.PackageParserException) { 7660 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7661 throwable; 7662 errorCode = e.error; 7663 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7664 } else { 7665 throw new IllegalStateException("Unexpected exception occurred while parsing " 7666 + parseResult.scanFile, throwable); 7667 } 7668 7669 // Delete invalid userdata apps 7670 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7671 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7672 logCriticalInfo(Log.WARN, 7673 "Deleting invalid package at " + parseResult.scanFile); 7674 removeCodePathLI(parseResult.scanFile); 7675 } 7676 } 7677 parallelPackageParser.close(); 7678 } 7679 7680 private static File getSettingsProblemFile() { 7681 File dataDir = Environment.getDataDirectory(); 7682 File systemDir = new File(dataDir, "system"); 7683 File fname = new File(systemDir, "uiderrors.txt"); 7684 return fname; 7685 } 7686 7687 static void reportSettingsProblem(int priority, String msg) { 7688 logCriticalInfo(priority, msg); 7689 } 7690 7691 public static void logCriticalInfo(int priority, String msg) { 7692 Slog.println(priority, TAG, msg); 7693 EventLogTags.writePmCriticalInfo(msg); 7694 try { 7695 File fname = getSettingsProblemFile(); 7696 FileOutputStream out = new FileOutputStream(fname, true); 7697 PrintWriter pw = new FastPrintWriter(out); 7698 SimpleDateFormat formatter = new SimpleDateFormat(); 7699 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7700 pw.println(dateString + ": " + msg); 7701 pw.close(); 7702 FileUtils.setPermissions( 7703 fname.toString(), 7704 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7705 -1, -1); 7706 } catch (java.io.IOException e) { 7707 } 7708 } 7709 7710 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7711 if (srcFile.isDirectory()) { 7712 final File baseFile = new File(pkg.baseCodePath); 7713 long maxModifiedTime = baseFile.lastModified(); 7714 if (pkg.splitCodePaths != null) { 7715 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7716 final File splitFile = new File(pkg.splitCodePaths[i]); 7717 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7718 } 7719 } 7720 return maxModifiedTime; 7721 } 7722 return srcFile.lastModified(); 7723 } 7724 7725 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7726 final int policyFlags) throws PackageManagerException { 7727 // When upgrading from pre-N MR1, verify the package time stamp using the package 7728 // directory and not the APK file. 7729 final long lastModifiedTime = mIsPreNMR1Upgrade 7730 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7731 if (ps != null 7732 && ps.codePath.equals(srcFile) 7733 && ps.timeStamp == lastModifiedTime 7734 && !isCompatSignatureUpdateNeeded(pkg) 7735 && !isRecoverSignatureUpdateNeeded(pkg)) { 7736 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7737 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7738 ArraySet<PublicKey> signingKs; 7739 synchronized (mPackages) { 7740 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7741 } 7742 if (ps.signatures.mSignatures != null 7743 && ps.signatures.mSignatures.length != 0 7744 && signingKs != null) { 7745 // Optimization: reuse the existing cached certificates 7746 // if the package appears to be unchanged. 7747 pkg.mSignatures = ps.signatures.mSignatures; 7748 pkg.mSigningKeys = signingKs; 7749 return; 7750 } 7751 7752 Slog.w(TAG, "PackageSetting for " + ps.name 7753 + " is missing signatures. Collecting certs again to recover them."); 7754 } else { 7755 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7756 } 7757 7758 try { 7759 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7760 PackageParser.collectCertificates(pkg, policyFlags); 7761 } catch (PackageParserException e) { 7762 throw PackageManagerException.from(e); 7763 } finally { 7764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7765 } 7766 } 7767 7768 /** 7769 * Traces a package scan. 7770 * @see #scanPackageLI(File, int, int, long, UserHandle) 7771 */ 7772 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7773 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7774 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7775 try { 7776 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7777 } finally { 7778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7779 } 7780 } 7781 7782 /** 7783 * Scans a package and returns the newly parsed package. 7784 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7785 */ 7786 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7787 long currentTime, UserHandle user) throws PackageManagerException { 7788 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7789 PackageParser pp = new PackageParser(); 7790 pp.setSeparateProcesses(mSeparateProcesses); 7791 pp.setOnlyCoreApps(mOnlyCore); 7792 pp.setDisplayMetrics(mMetrics); 7793 pp.setCallback(mPackageParserCallback); 7794 7795 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7796 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7797 } 7798 7799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7800 final PackageParser.Package pkg; 7801 try { 7802 pkg = pp.parsePackage(scanFile, parseFlags); 7803 } catch (PackageParserException e) { 7804 throw PackageManagerException.from(e); 7805 } finally { 7806 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7807 } 7808 7809 // Static shared libraries have synthetic package names 7810 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7811 renameStaticSharedLibraryPackage(pkg); 7812 } 7813 7814 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7815 } 7816 7817 /** 7818 * Scans a package and returns the newly parsed package. 7819 * @throws PackageManagerException on a parse error. 7820 */ 7821 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7822 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7823 throws PackageManagerException { 7824 // If the package has children and this is the first dive in the function 7825 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7826 // packages (parent and children) would be successfully scanned before the 7827 // actual scan since scanning mutates internal state and we want to atomically 7828 // install the package and its children. 7829 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7830 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7831 scanFlags |= SCAN_CHECK_ONLY; 7832 } 7833 } else { 7834 scanFlags &= ~SCAN_CHECK_ONLY; 7835 } 7836 7837 // Scan the parent 7838 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7839 scanFlags, currentTime, user); 7840 7841 // Scan the children 7842 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7843 for (int i = 0; i < childCount; i++) { 7844 PackageParser.Package childPackage = pkg.childPackages.get(i); 7845 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7846 currentTime, user); 7847 } 7848 7849 7850 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7851 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7852 } 7853 7854 return scannedPkg; 7855 } 7856 7857 /** 7858 * Scans a package and returns the newly parsed package. 7859 * @throws PackageManagerException on a parse error. 7860 */ 7861 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7862 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7863 throws PackageManagerException { 7864 PackageSetting ps = null; 7865 PackageSetting updatedPkg; 7866 // reader 7867 synchronized (mPackages) { 7868 // Look to see if we already know about this package. 7869 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7870 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7871 // This package has been renamed to its original name. Let's 7872 // use that. 7873 ps = mSettings.getPackageLPr(oldName); 7874 } 7875 // If there was no original package, see one for the real package name. 7876 if (ps == null) { 7877 ps = mSettings.getPackageLPr(pkg.packageName); 7878 } 7879 // Check to see if this package could be hiding/updating a system 7880 // package. Must look for it either under the original or real 7881 // package name depending on our state. 7882 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7883 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7884 7885 // If this is a package we don't know about on the system partition, we 7886 // may need to remove disabled child packages on the system partition 7887 // or may need to not add child packages if the parent apk is updated 7888 // on the data partition and no longer defines this child package. 7889 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7890 // If this is a parent package for an updated system app and this system 7891 // app got an OTA update which no longer defines some of the child packages 7892 // we have to prune them from the disabled system packages. 7893 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7894 if (disabledPs != null) { 7895 final int scannedChildCount = (pkg.childPackages != null) 7896 ? pkg.childPackages.size() : 0; 7897 final int disabledChildCount = disabledPs.childPackageNames != null 7898 ? disabledPs.childPackageNames.size() : 0; 7899 for (int i = 0; i < disabledChildCount; i++) { 7900 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7901 boolean disabledPackageAvailable = false; 7902 for (int j = 0; j < scannedChildCount; j++) { 7903 PackageParser.Package childPkg = pkg.childPackages.get(j); 7904 if (childPkg.packageName.equals(disabledChildPackageName)) { 7905 disabledPackageAvailable = true; 7906 break; 7907 } 7908 } 7909 if (!disabledPackageAvailable) { 7910 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7911 } 7912 } 7913 } 7914 } 7915 } 7916 7917 boolean updatedPkgBetter = false; 7918 // First check if this is a system package that may involve an update 7919 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7920 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7921 // it needs to drop FLAG_PRIVILEGED. 7922 if (locationIsPrivileged(scanFile)) { 7923 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7924 } else { 7925 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7926 } 7927 7928 if (ps != null && !ps.codePath.equals(scanFile)) { 7929 // The path has changed from what was last scanned... check the 7930 // version of the new path against what we have stored to determine 7931 // what to do. 7932 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7933 if (pkg.mVersionCode <= ps.versionCode) { 7934 // The system package has been updated and the code path does not match 7935 // Ignore entry. Skip it. 7936 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7937 + " ignored: updated version " + ps.versionCode 7938 + " better than this " + pkg.mVersionCode); 7939 if (!updatedPkg.codePath.equals(scanFile)) { 7940 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7941 + ps.name + " changing from " + updatedPkg.codePathString 7942 + " to " + scanFile); 7943 updatedPkg.codePath = scanFile; 7944 updatedPkg.codePathString = scanFile.toString(); 7945 updatedPkg.resourcePath = scanFile; 7946 updatedPkg.resourcePathString = scanFile.toString(); 7947 } 7948 updatedPkg.pkg = pkg; 7949 updatedPkg.versionCode = pkg.mVersionCode; 7950 7951 // Update the disabled system child packages to point to the package too. 7952 final int childCount = updatedPkg.childPackageNames != null 7953 ? updatedPkg.childPackageNames.size() : 0; 7954 for (int i = 0; i < childCount; i++) { 7955 String childPackageName = updatedPkg.childPackageNames.get(i); 7956 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7957 childPackageName); 7958 if (updatedChildPkg != null) { 7959 updatedChildPkg.pkg = pkg; 7960 updatedChildPkg.versionCode = pkg.mVersionCode; 7961 } 7962 } 7963 7964 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7965 + scanFile + " ignored: updated version " + ps.versionCode 7966 + " better than this " + pkg.mVersionCode); 7967 } else { 7968 // The current app on the system partition is better than 7969 // what we have updated to on the data partition; switch 7970 // back to the system partition version. 7971 // At this point, its safely assumed that package installation for 7972 // apps in system partition will go through. If not there won't be a working 7973 // version of the app 7974 // writer 7975 synchronized (mPackages) { 7976 // Just remove the loaded entries from package lists. 7977 mPackages.remove(ps.name); 7978 } 7979 7980 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7981 + " reverting from " + ps.codePathString 7982 + ": new version " + pkg.mVersionCode 7983 + " better than installed " + ps.versionCode); 7984 7985 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7986 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7987 synchronized (mInstallLock) { 7988 args.cleanUpResourcesLI(); 7989 } 7990 synchronized (mPackages) { 7991 mSettings.enableSystemPackageLPw(ps.name); 7992 } 7993 updatedPkgBetter = true; 7994 } 7995 } 7996 } 7997 7998 if (updatedPkg != null) { 7999 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8000 // initially 8001 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8002 8003 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8004 // flag set initially 8005 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8006 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8007 } 8008 } 8009 8010 // Verify certificates against what was last scanned 8011 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8012 8013 /* 8014 * A new system app appeared, but we already had a non-system one of the 8015 * same name installed earlier. 8016 */ 8017 boolean shouldHideSystemApp = false; 8018 if (updatedPkg == null && ps != null 8019 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8020 /* 8021 * Check to make sure the signatures match first. If they don't, 8022 * wipe the installed application and its data. 8023 */ 8024 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8025 != PackageManager.SIGNATURE_MATCH) { 8026 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8027 + " signatures don't match existing userdata copy; removing"); 8028 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8029 "scanPackageInternalLI")) { 8030 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8031 } 8032 ps = null; 8033 } else { 8034 /* 8035 * If the newly-added system app is an older version than the 8036 * already installed version, hide it. It will be scanned later 8037 * and re-added like an update. 8038 */ 8039 if (pkg.mVersionCode <= ps.versionCode) { 8040 shouldHideSystemApp = true; 8041 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8042 + " but new version " + pkg.mVersionCode + " better than installed " 8043 + ps.versionCode + "; hiding system"); 8044 } else { 8045 /* 8046 * The newly found system app is a newer version that the 8047 * one previously installed. Simply remove the 8048 * already-installed application and replace it with our own 8049 * while keeping the application data. 8050 */ 8051 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8052 + " reverting from " + ps.codePathString + ": new version " 8053 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8054 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8055 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8056 synchronized (mInstallLock) { 8057 args.cleanUpResourcesLI(); 8058 } 8059 } 8060 } 8061 } 8062 8063 // The apk is forward locked (not public) if its code and resources 8064 // are kept in different files. (except for app in either system or 8065 // vendor path). 8066 // TODO grab this value from PackageSettings 8067 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8068 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8069 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8070 } 8071 } 8072 8073 // TODO: extend to support forward-locked splits 8074 String resourcePath = null; 8075 String baseResourcePath = null; 8076 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8077 if (ps != null && ps.resourcePathString != null) { 8078 resourcePath = ps.resourcePathString; 8079 baseResourcePath = ps.resourcePathString; 8080 } else { 8081 // Should not happen at all. Just log an error. 8082 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8083 } 8084 } else { 8085 resourcePath = pkg.codePath; 8086 baseResourcePath = pkg.baseCodePath; 8087 } 8088 8089 // Set application objects path explicitly. 8090 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8091 pkg.setApplicationInfoCodePath(pkg.codePath); 8092 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8093 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8094 pkg.setApplicationInfoResourcePath(resourcePath); 8095 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8096 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8097 8098 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8099 if (ps != null && ps.getInstantApp(userId)) { 8100 scanFlags |= SCAN_AS_INSTANT_APP; 8101 } 8102 8103 // Note that we invoke the following method only if we are about to unpack an application 8104 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8105 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8106 8107 /* 8108 * If the system app should be overridden by a previously installed 8109 * data, hide the system app now and let the /data/app scan pick it up 8110 * again. 8111 */ 8112 if (shouldHideSystemApp) { 8113 synchronized (mPackages) { 8114 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8115 } 8116 } 8117 8118 return scannedPkg; 8119 } 8120 8121 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8122 // Derive the new package synthetic package name 8123 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8124 + pkg.staticSharedLibVersion); 8125 } 8126 8127 private static String fixProcessName(String defProcessName, 8128 String processName) { 8129 if (processName == null) { 8130 return defProcessName; 8131 } 8132 return processName; 8133 } 8134 8135 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8136 throws PackageManagerException { 8137 if (pkgSetting.signatures.mSignatures != null) { 8138 // Already existing package. Make sure signatures match 8139 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8140 == PackageManager.SIGNATURE_MATCH; 8141 if (!match) { 8142 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8143 == PackageManager.SIGNATURE_MATCH; 8144 } 8145 if (!match) { 8146 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8147 == PackageManager.SIGNATURE_MATCH; 8148 } 8149 if (!match) { 8150 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8151 + pkg.packageName + " signatures do not match the " 8152 + "previously installed version; ignoring!"); 8153 } 8154 } 8155 8156 // Check for shared user signatures 8157 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8158 // Already existing package. Make sure signatures match 8159 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8160 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8161 if (!match) { 8162 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8163 == PackageManager.SIGNATURE_MATCH; 8164 } 8165 if (!match) { 8166 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8167 == PackageManager.SIGNATURE_MATCH; 8168 } 8169 if (!match) { 8170 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8171 "Package " + pkg.packageName 8172 + " has no signatures that match those in shared user " 8173 + pkgSetting.sharedUser.name + "; ignoring!"); 8174 } 8175 } 8176 } 8177 8178 /** 8179 * Enforces that only the system UID or root's UID can call a method exposed 8180 * via Binder. 8181 * 8182 * @param message used as message if SecurityException is thrown 8183 * @throws SecurityException if the caller is not system or root 8184 */ 8185 private static final void enforceSystemOrRoot(String message) { 8186 final int uid = Binder.getCallingUid(); 8187 if (uid != Process.SYSTEM_UID && uid != 0) { 8188 throw new SecurityException(message); 8189 } 8190 } 8191 8192 @Override 8193 public void performFstrimIfNeeded() { 8194 enforceSystemOrRoot("Only the system can request fstrim"); 8195 8196 // Before everything else, see whether we need to fstrim. 8197 try { 8198 IStorageManager sm = PackageHelper.getStorageManager(); 8199 if (sm != null) { 8200 boolean doTrim = false; 8201 final long interval = android.provider.Settings.Global.getLong( 8202 mContext.getContentResolver(), 8203 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8204 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8205 if (interval > 0) { 8206 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8207 if (timeSinceLast > interval) { 8208 doTrim = true; 8209 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8210 + "; running immediately"); 8211 } 8212 } 8213 if (doTrim) { 8214 final boolean dexOptDialogShown; 8215 synchronized (mPackages) { 8216 dexOptDialogShown = mDexOptDialogShown; 8217 } 8218 if (!isFirstBoot() && dexOptDialogShown) { 8219 try { 8220 ActivityManager.getService().showBootMessage( 8221 mContext.getResources().getString( 8222 R.string.android_upgrading_fstrim), true); 8223 } catch (RemoteException e) { 8224 } 8225 } 8226 sm.runMaintenance(); 8227 } 8228 } else { 8229 Slog.e(TAG, "storageManager service unavailable!"); 8230 } 8231 } catch (RemoteException e) { 8232 // Can't happen; StorageManagerService is local 8233 } 8234 } 8235 8236 @Override 8237 public void updatePackagesIfNeeded() { 8238 enforceSystemOrRoot("Only the system can request package update"); 8239 8240 // We need to re-extract after an OTA. 8241 boolean causeUpgrade = isUpgrade(); 8242 8243 // First boot or factory reset. 8244 // Note: we also handle devices that are upgrading to N right now as if it is their 8245 // first boot, as they do not have profile data. 8246 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8247 8248 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8249 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8250 8251 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8252 return; 8253 } 8254 8255 List<PackageParser.Package> pkgs; 8256 synchronized (mPackages) { 8257 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8258 } 8259 8260 final long startTime = System.nanoTime(); 8261 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8262 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8263 8264 final int elapsedTimeSeconds = 8265 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8266 8267 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8268 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8269 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8270 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8271 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8272 } 8273 8274 /** 8275 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8276 * containing statistics about the invocation. The array consists of three elements, 8277 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8278 * and {@code numberOfPackagesFailed}. 8279 */ 8280 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8281 String compilerFilter) { 8282 8283 int numberOfPackagesVisited = 0; 8284 int numberOfPackagesOptimized = 0; 8285 int numberOfPackagesSkipped = 0; 8286 int numberOfPackagesFailed = 0; 8287 final int numberOfPackagesToDexopt = pkgs.size(); 8288 8289 for (PackageParser.Package pkg : pkgs) { 8290 numberOfPackagesVisited++; 8291 8292 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8293 if (DEBUG_DEXOPT) { 8294 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8295 } 8296 numberOfPackagesSkipped++; 8297 continue; 8298 } 8299 8300 if (DEBUG_DEXOPT) { 8301 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8302 numberOfPackagesToDexopt + ": " + pkg.packageName); 8303 } 8304 8305 if (showDialog) { 8306 try { 8307 ActivityManager.getService().showBootMessage( 8308 mContext.getResources().getString(R.string.android_upgrading_apk, 8309 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8310 } catch (RemoteException e) { 8311 } 8312 synchronized (mPackages) { 8313 mDexOptDialogShown = true; 8314 } 8315 } 8316 8317 // If the OTA updates a system app which was previously preopted to a non-preopted state 8318 // the app might end up being verified at runtime. That's because by default the apps 8319 // are verify-profile but for preopted apps there's no profile. 8320 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8321 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8322 // filter (by default interpret-only). 8323 // Note that at this stage unused apps are already filtered. 8324 if (isSystemApp(pkg) && 8325 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8326 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8327 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8328 } 8329 8330 // checkProfiles is false to avoid merging profiles during boot which 8331 // might interfere with background compilation (b/28612421). 8332 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8333 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8334 // trade-off worth doing to save boot time work. 8335 int dexOptStatus = performDexOptTraced(pkg.packageName, 8336 false /* checkProfiles */, 8337 compilerFilter, 8338 false /* force */); 8339 switch (dexOptStatus) { 8340 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8341 numberOfPackagesOptimized++; 8342 break; 8343 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8344 numberOfPackagesSkipped++; 8345 break; 8346 case PackageDexOptimizer.DEX_OPT_FAILED: 8347 numberOfPackagesFailed++; 8348 break; 8349 default: 8350 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8351 break; 8352 } 8353 } 8354 8355 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8356 numberOfPackagesFailed }; 8357 } 8358 8359 @Override 8360 public void notifyPackageUse(String packageName, int reason) { 8361 synchronized (mPackages) { 8362 PackageParser.Package p = mPackages.get(packageName); 8363 if (p == null) { 8364 return; 8365 } 8366 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8367 } 8368 } 8369 8370 @Override 8371 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8372 int userId = UserHandle.getCallingUserId(); 8373 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8374 if (ai == null) { 8375 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8376 + loadingPackageName + ", user=" + userId); 8377 return; 8378 } 8379 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8380 } 8381 8382 // TODO: this is not used nor needed. Delete it. 8383 @Override 8384 public boolean performDexOptIfNeeded(String packageName) { 8385 int dexOptStatus = performDexOptTraced(packageName, 8386 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8387 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8388 } 8389 8390 @Override 8391 public boolean performDexOpt(String packageName, 8392 boolean checkProfiles, int compileReason, boolean force) { 8393 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8394 getCompilerFilterForReason(compileReason), force); 8395 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8396 } 8397 8398 @Override 8399 public boolean performDexOptMode(String packageName, 8400 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8401 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8402 targetCompilerFilter, force); 8403 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8404 } 8405 8406 private int performDexOptTraced(String packageName, 8407 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8409 try { 8410 return performDexOptInternal(packageName, checkProfiles, 8411 targetCompilerFilter, force); 8412 } finally { 8413 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8414 } 8415 } 8416 8417 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8418 // if the package can now be considered up to date for the given filter. 8419 private int performDexOptInternal(String packageName, 8420 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8421 PackageParser.Package p; 8422 synchronized (mPackages) { 8423 p = mPackages.get(packageName); 8424 if (p == null) { 8425 // Package could not be found. Report failure. 8426 return PackageDexOptimizer.DEX_OPT_FAILED; 8427 } 8428 mPackageUsage.maybeWriteAsync(mPackages); 8429 mCompilerStats.maybeWriteAsync(); 8430 } 8431 long callingId = Binder.clearCallingIdentity(); 8432 try { 8433 synchronized (mInstallLock) { 8434 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8435 targetCompilerFilter, force); 8436 } 8437 } finally { 8438 Binder.restoreCallingIdentity(callingId); 8439 } 8440 } 8441 8442 public ArraySet<String> getOptimizablePackages() { 8443 ArraySet<String> pkgs = new ArraySet<String>(); 8444 synchronized (mPackages) { 8445 for (PackageParser.Package p : mPackages.values()) { 8446 if (PackageDexOptimizer.canOptimizePackage(p)) { 8447 pkgs.add(p.packageName); 8448 } 8449 } 8450 } 8451 return pkgs; 8452 } 8453 8454 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8455 boolean checkProfiles, String targetCompilerFilter, 8456 boolean force) { 8457 // Select the dex optimizer based on the force parameter. 8458 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8459 // allocate an object here. 8460 PackageDexOptimizer pdo = force 8461 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8462 : mPackageDexOptimizer; 8463 8464 // Optimize all dependencies first. Note: we ignore the return value and march on 8465 // on errors. 8466 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8467 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8468 if (!deps.isEmpty()) { 8469 for (PackageParser.Package depPackage : deps) { 8470 // TODO: Analyze and investigate if we (should) profile libraries. 8471 // Currently this will do a full compilation of the library by default. 8472 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8473 false /* checkProfiles */, 8474 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8475 getOrCreateCompilerPackageStats(depPackage), 8476 mDexManager.isUsedByOtherApps(p.packageName)); 8477 } 8478 } 8479 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8480 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8481 mDexManager.isUsedByOtherApps(p.packageName)); 8482 } 8483 8484 // Performs dexopt on the used secondary dex files belonging to the given package. 8485 // Returns true if all dex files were process successfully (which could mean either dexopt or 8486 // skip). Returns false if any of the files caused errors. 8487 @Override 8488 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8489 boolean force) { 8490 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8491 } 8492 8493 public boolean performDexOptSecondary(String packageName, int compileReason, 8494 boolean force) { 8495 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8496 } 8497 8498 /** 8499 * Reconcile the information we have about the secondary dex files belonging to 8500 * {@code packagName} and the actual dex files. For all dex files that were 8501 * deleted, update the internal records and delete the generated oat files. 8502 */ 8503 @Override 8504 public void reconcileSecondaryDexFiles(String packageName) { 8505 mDexManager.reconcileSecondaryDexFiles(packageName); 8506 } 8507 8508 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8509 // a reference there. 8510 /*package*/ DexManager getDexManager() { 8511 return mDexManager; 8512 } 8513 8514 /** 8515 * Execute the background dexopt job immediately. 8516 */ 8517 @Override 8518 public boolean runBackgroundDexoptJob() { 8519 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8520 } 8521 8522 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8523 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8524 || p.usesStaticLibraries != null) { 8525 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8526 Set<String> collectedNames = new HashSet<>(); 8527 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8528 8529 retValue.remove(p); 8530 8531 return retValue; 8532 } else { 8533 return Collections.emptyList(); 8534 } 8535 } 8536 8537 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8538 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8539 if (!collectedNames.contains(p.packageName)) { 8540 collectedNames.add(p.packageName); 8541 collected.add(p); 8542 8543 if (p.usesLibraries != null) { 8544 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8545 null, collected, collectedNames); 8546 } 8547 if (p.usesOptionalLibraries != null) { 8548 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8549 null, collected, collectedNames); 8550 } 8551 if (p.usesStaticLibraries != null) { 8552 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8553 p.usesStaticLibrariesVersions, collected, collectedNames); 8554 } 8555 } 8556 } 8557 8558 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8559 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8560 final int libNameCount = libs.size(); 8561 for (int i = 0; i < libNameCount; i++) { 8562 String libName = libs.get(i); 8563 int version = (versions != null && versions.length == libNameCount) 8564 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8565 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8566 if (libPkg != null) { 8567 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8568 } 8569 } 8570 } 8571 8572 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8573 synchronized (mPackages) { 8574 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8575 if (libEntry != null) { 8576 return mPackages.get(libEntry.apk); 8577 } 8578 return null; 8579 } 8580 } 8581 8582 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8583 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8584 if (versionedLib == null) { 8585 return null; 8586 } 8587 return versionedLib.get(version); 8588 } 8589 8590 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8591 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8592 pkg.staticSharedLibName); 8593 if (versionedLib == null) { 8594 return null; 8595 } 8596 int previousLibVersion = -1; 8597 final int versionCount = versionedLib.size(); 8598 for (int i = 0; i < versionCount; i++) { 8599 final int libVersion = versionedLib.keyAt(i); 8600 if (libVersion < pkg.staticSharedLibVersion) { 8601 previousLibVersion = Math.max(previousLibVersion, libVersion); 8602 } 8603 } 8604 if (previousLibVersion >= 0) { 8605 return versionedLib.get(previousLibVersion); 8606 } 8607 return null; 8608 } 8609 8610 public void shutdown() { 8611 mPackageUsage.writeNow(mPackages); 8612 mCompilerStats.writeNow(); 8613 } 8614 8615 @Override 8616 public void dumpProfiles(String packageName) { 8617 PackageParser.Package pkg; 8618 synchronized (mPackages) { 8619 pkg = mPackages.get(packageName); 8620 if (pkg == null) { 8621 throw new IllegalArgumentException("Unknown package: " + packageName); 8622 } 8623 } 8624 /* Only the shell, root, or the app user should be able to dump profiles. */ 8625 int callingUid = Binder.getCallingUid(); 8626 if (callingUid != Process.SHELL_UID && 8627 callingUid != Process.ROOT_UID && 8628 callingUid != pkg.applicationInfo.uid) { 8629 throw new SecurityException("dumpProfiles"); 8630 } 8631 8632 synchronized (mInstallLock) { 8633 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8634 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8635 try { 8636 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8637 String codePaths = TextUtils.join(";", allCodePaths); 8638 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8639 } catch (InstallerException e) { 8640 Slog.w(TAG, "Failed to dump profiles", e); 8641 } 8642 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8643 } 8644 } 8645 8646 @Override 8647 public void forceDexOpt(String packageName) { 8648 enforceSystemOrRoot("forceDexOpt"); 8649 8650 PackageParser.Package pkg; 8651 synchronized (mPackages) { 8652 pkg = mPackages.get(packageName); 8653 if (pkg == null) { 8654 throw new IllegalArgumentException("Unknown package: " + packageName); 8655 } 8656 } 8657 8658 synchronized (mInstallLock) { 8659 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8660 8661 // Whoever is calling forceDexOpt wants a fully compiled package. 8662 // Don't use profiles since that may cause compilation to be skipped. 8663 final int res = performDexOptInternalWithDependenciesLI(pkg, 8664 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8665 true /* force */); 8666 8667 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8668 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8669 throw new IllegalStateException("Failed to dexopt: " + res); 8670 } 8671 } 8672 } 8673 8674 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8675 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8676 Slog.w(TAG, "Unable to update from " + oldPkg.name 8677 + " to " + newPkg.packageName 8678 + ": old package not in system partition"); 8679 return false; 8680 } else if (mPackages.get(oldPkg.name) != null) { 8681 Slog.w(TAG, "Unable to update from " + oldPkg.name 8682 + " to " + newPkg.packageName 8683 + ": old package still exists"); 8684 return false; 8685 } 8686 return true; 8687 } 8688 8689 void removeCodePathLI(File codePath) { 8690 if (codePath.isDirectory()) { 8691 try { 8692 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8693 } catch (InstallerException e) { 8694 Slog.w(TAG, "Failed to remove code path", e); 8695 } 8696 } else { 8697 codePath.delete(); 8698 } 8699 } 8700 8701 private int[] resolveUserIds(int userId) { 8702 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8703 } 8704 8705 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8706 if (pkg == null) { 8707 Slog.wtf(TAG, "Package was null!", new Throwable()); 8708 return; 8709 } 8710 clearAppDataLeafLIF(pkg, userId, flags); 8711 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8712 for (int i = 0; i < childCount; i++) { 8713 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8714 } 8715 } 8716 8717 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8718 final PackageSetting ps; 8719 synchronized (mPackages) { 8720 ps = mSettings.mPackages.get(pkg.packageName); 8721 } 8722 for (int realUserId : resolveUserIds(userId)) { 8723 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8724 try { 8725 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8726 ceDataInode); 8727 } catch (InstallerException e) { 8728 Slog.w(TAG, String.valueOf(e)); 8729 } 8730 } 8731 } 8732 8733 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8734 if (pkg == null) { 8735 Slog.wtf(TAG, "Package was null!", new Throwable()); 8736 return; 8737 } 8738 destroyAppDataLeafLIF(pkg, userId, flags); 8739 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8740 for (int i = 0; i < childCount; i++) { 8741 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8742 } 8743 } 8744 8745 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8746 final PackageSetting ps; 8747 synchronized (mPackages) { 8748 ps = mSettings.mPackages.get(pkg.packageName); 8749 } 8750 for (int realUserId : resolveUserIds(userId)) { 8751 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8752 try { 8753 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8754 ceDataInode); 8755 } catch (InstallerException e) { 8756 Slog.w(TAG, String.valueOf(e)); 8757 } 8758 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8759 } 8760 } 8761 8762 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8763 if (pkg == null) { 8764 Slog.wtf(TAG, "Package was null!", new Throwable()); 8765 return; 8766 } 8767 destroyAppProfilesLeafLIF(pkg); 8768 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8769 for (int i = 0; i < childCount; i++) { 8770 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8771 } 8772 } 8773 8774 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8775 try { 8776 mInstaller.destroyAppProfiles(pkg.packageName); 8777 } catch (InstallerException e) { 8778 Slog.w(TAG, String.valueOf(e)); 8779 } 8780 } 8781 8782 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8783 if (pkg == null) { 8784 Slog.wtf(TAG, "Package was null!", new Throwable()); 8785 return; 8786 } 8787 clearAppProfilesLeafLIF(pkg); 8788 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8789 for (int i = 0; i < childCount; i++) { 8790 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8791 } 8792 } 8793 8794 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8795 try { 8796 mInstaller.clearAppProfiles(pkg.packageName); 8797 } catch (InstallerException e) { 8798 Slog.w(TAG, String.valueOf(e)); 8799 } 8800 } 8801 8802 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8803 long lastUpdateTime) { 8804 // Set parent install/update time 8805 PackageSetting ps = (PackageSetting) pkg.mExtras; 8806 if (ps != null) { 8807 ps.firstInstallTime = firstInstallTime; 8808 ps.lastUpdateTime = lastUpdateTime; 8809 } 8810 // Set children install/update time 8811 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8812 for (int i = 0; i < childCount; i++) { 8813 PackageParser.Package childPkg = pkg.childPackages.get(i); 8814 ps = (PackageSetting) childPkg.mExtras; 8815 if (ps != null) { 8816 ps.firstInstallTime = firstInstallTime; 8817 ps.lastUpdateTime = lastUpdateTime; 8818 } 8819 } 8820 } 8821 8822 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8823 PackageParser.Package changingLib) { 8824 if (file.path != null) { 8825 usesLibraryFiles.add(file.path); 8826 return; 8827 } 8828 PackageParser.Package p = mPackages.get(file.apk); 8829 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8830 // If we are doing this while in the middle of updating a library apk, 8831 // then we need to make sure to use that new apk for determining the 8832 // dependencies here. (We haven't yet finished committing the new apk 8833 // to the package manager state.) 8834 if (p == null || p.packageName.equals(changingLib.packageName)) { 8835 p = changingLib; 8836 } 8837 } 8838 if (p != null) { 8839 usesLibraryFiles.addAll(p.getAllCodePaths()); 8840 } 8841 } 8842 8843 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8844 PackageParser.Package changingLib) throws PackageManagerException { 8845 if (pkg == null) { 8846 return; 8847 } 8848 ArraySet<String> usesLibraryFiles = null; 8849 if (pkg.usesLibraries != null) { 8850 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8851 null, null, pkg.packageName, changingLib, true, null); 8852 } 8853 if (pkg.usesStaticLibraries != null) { 8854 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8855 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8856 pkg.packageName, changingLib, true, usesLibraryFiles); 8857 } 8858 if (pkg.usesOptionalLibraries != null) { 8859 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8860 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8861 } 8862 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8863 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8864 } else { 8865 pkg.usesLibraryFiles = null; 8866 } 8867 } 8868 8869 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8870 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8871 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8872 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8873 throws PackageManagerException { 8874 final int libCount = requestedLibraries.size(); 8875 for (int i = 0; i < libCount; i++) { 8876 final String libName = requestedLibraries.get(i); 8877 final int libVersion = requiredVersions != null ? requiredVersions[i] 8878 : SharedLibraryInfo.VERSION_UNDEFINED; 8879 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8880 if (libEntry == null) { 8881 if (required) { 8882 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8883 "Package " + packageName + " requires unavailable shared library " 8884 + libName + "; failing!"); 8885 } else { 8886 Slog.w(TAG, "Package " + packageName 8887 + " desires unavailable shared library " 8888 + libName + "; ignoring!"); 8889 } 8890 } else { 8891 if (requiredVersions != null && requiredCertDigests != null) { 8892 if (libEntry.info.getVersion() != requiredVersions[i]) { 8893 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8894 "Package " + packageName + " requires unavailable static shared" 8895 + " library " + libName + " version " 8896 + libEntry.info.getVersion() + "; failing!"); 8897 } 8898 8899 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8900 if (libPkg == null) { 8901 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8902 "Package " + packageName + " requires unavailable static shared" 8903 + " library; failing!"); 8904 } 8905 8906 String expectedCertDigest = requiredCertDigests[i]; 8907 String libCertDigest = PackageUtils.computeCertSha256Digest( 8908 libPkg.mSignatures[0]); 8909 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8910 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8911 "Package " + packageName + " requires differently signed" + 8912 " static shared library; failing!"); 8913 } 8914 } 8915 8916 if (outUsedLibraries == null) { 8917 outUsedLibraries = new ArraySet<>(); 8918 } 8919 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8920 } 8921 } 8922 return outUsedLibraries; 8923 } 8924 8925 private static boolean hasString(List<String> list, List<String> which) { 8926 if (list == null) { 8927 return false; 8928 } 8929 for (int i=list.size()-1; i>=0; i--) { 8930 for (int j=which.size()-1; j>=0; j--) { 8931 if (which.get(j).equals(list.get(i))) { 8932 return true; 8933 } 8934 } 8935 } 8936 return false; 8937 } 8938 8939 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8940 PackageParser.Package changingPkg) { 8941 ArrayList<PackageParser.Package> res = null; 8942 for (PackageParser.Package pkg : mPackages.values()) { 8943 if (changingPkg != null 8944 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8945 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8946 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8947 changingPkg.staticSharedLibName)) { 8948 return null; 8949 } 8950 if (res == null) { 8951 res = new ArrayList<>(); 8952 } 8953 res.add(pkg); 8954 try { 8955 updateSharedLibrariesLPr(pkg, changingPkg); 8956 } catch (PackageManagerException e) { 8957 // If a system app update or an app and a required lib missing we 8958 // delete the package and for updated system apps keep the data as 8959 // it is better for the user to reinstall than to be in an limbo 8960 // state. Also libs disappearing under an app should never happen 8961 // - just in case. 8962 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8963 final int flags = pkg.isUpdatedSystemApp() 8964 ? PackageManager.DELETE_KEEP_DATA : 0; 8965 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8966 flags , null, true, null); 8967 } 8968 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8969 } 8970 } 8971 return res; 8972 } 8973 8974 /** 8975 * Derive the value of the {@code cpuAbiOverride} based on the provided 8976 * value and an optional stored value from the package settings. 8977 */ 8978 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8979 String cpuAbiOverride = null; 8980 8981 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8982 cpuAbiOverride = null; 8983 } else if (abiOverride != null) { 8984 cpuAbiOverride = abiOverride; 8985 } else if (settings != null) { 8986 cpuAbiOverride = settings.cpuAbiOverrideString; 8987 } 8988 8989 return cpuAbiOverride; 8990 } 8991 8992 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8993 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8994 throws PackageManagerException { 8995 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8996 // If the package has children and this is the first dive in the function 8997 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8998 // whether all packages (parent and children) would be successfully scanned 8999 // before the actual scan since scanning mutates internal state and we want 9000 // to atomically install the package and its children. 9001 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9002 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9003 scanFlags |= SCAN_CHECK_ONLY; 9004 } 9005 } else { 9006 scanFlags &= ~SCAN_CHECK_ONLY; 9007 } 9008 9009 final PackageParser.Package scannedPkg; 9010 try { 9011 // Scan the parent 9012 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9013 // Scan the children 9014 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9015 for (int i = 0; i < childCount; i++) { 9016 PackageParser.Package childPkg = pkg.childPackages.get(i); 9017 scanPackageLI(childPkg, policyFlags, 9018 scanFlags, currentTime, user); 9019 } 9020 } finally { 9021 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9022 } 9023 9024 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9025 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9026 } 9027 9028 return scannedPkg; 9029 } 9030 9031 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9032 int scanFlags, long currentTime, @Nullable UserHandle user) 9033 throws PackageManagerException { 9034 boolean success = false; 9035 try { 9036 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9037 currentTime, user); 9038 success = true; 9039 return res; 9040 } finally { 9041 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9042 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9043 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9044 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9045 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9046 } 9047 } 9048 } 9049 9050 /** 9051 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9052 */ 9053 private static boolean apkHasCode(String fileName) { 9054 StrictJarFile jarFile = null; 9055 try { 9056 jarFile = new StrictJarFile(fileName, 9057 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9058 return jarFile.findEntry("classes.dex") != null; 9059 } catch (IOException ignore) { 9060 } finally { 9061 try { 9062 if (jarFile != null) { 9063 jarFile.close(); 9064 } 9065 } catch (IOException ignore) {} 9066 } 9067 return false; 9068 } 9069 9070 /** 9071 * Enforces code policy for the package. This ensures that if an APK has 9072 * declared hasCode="true" in its manifest that the APK actually contains 9073 * code. 9074 * 9075 * @throws PackageManagerException If bytecode could not be found when it should exist 9076 */ 9077 private static void assertCodePolicy(PackageParser.Package pkg) 9078 throws PackageManagerException { 9079 final boolean shouldHaveCode = 9080 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9081 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9082 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9083 "Package " + pkg.baseCodePath + " code is missing"); 9084 } 9085 9086 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9087 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9088 final boolean splitShouldHaveCode = 9089 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9090 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9091 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9092 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9093 } 9094 } 9095 } 9096 } 9097 9098 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9099 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9100 throws PackageManagerException { 9101 if (DEBUG_PACKAGE_SCANNING) { 9102 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9103 Log.d(TAG, "Scanning package " + pkg.packageName); 9104 } 9105 9106 applyPolicy(pkg, policyFlags); 9107 9108 assertPackageIsValid(pkg, policyFlags, scanFlags); 9109 9110 // Initialize package source and resource directories 9111 final File scanFile = new File(pkg.codePath); 9112 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9113 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9114 9115 SharedUserSetting suid = null; 9116 PackageSetting pkgSetting = null; 9117 9118 // Getting the package setting may have a side-effect, so if we 9119 // are only checking if scan would succeed, stash a copy of the 9120 // old setting to restore at the end. 9121 PackageSetting nonMutatedPs = null; 9122 9123 // We keep references to the derived CPU Abis from settings in oder to reuse 9124 // them in the case where we're not upgrading or booting for the first time. 9125 String primaryCpuAbiFromSettings = null; 9126 String secondaryCpuAbiFromSettings = null; 9127 9128 // writer 9129 synchronized (mPackages) { 9130 if (pkg.mSharedUserId != null) { 9131 // SIDE EFFECTS; may potentially allocate a new shared user 9132 suid = mSettings.getSharedUserLPw( 9133 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9134 if (DEBUG_PACKAGE_SCANNING) { 9135 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9136 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9137 + "): packages=" + suid.packages); 9138 } 9139 } 9140 9141 // Check if we are renaming from an original package name. 9142 PackageSetting origPackage = null; 9143 String realName = null; 9144 if (pkg.mOriginalPackages != null) { 9145 // This package may need to be renamed to a previously 9146 // installed name. Let's check on that... 9147 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9148 if (pkg.mOriginalPackages.contains(renamed)) { 9149 // This package had originally been installed as the 9150 // original name, and we have already taken care of 9151 // transitioning to the new one. Just update the new 9152 // one to continue using the old name. 9153 realName = pkg.mRealPackage; 9154 if (!pkg.packageName.equals(renamed)) { 9155 // Callers into this function may have already taken 9156 // care of renaming the package; only do it here if 9157 // it is not already done. 9158 pkg.setPackageName(renamed); 9159 } 9160 } else { 9161 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9162 if ((origPackage = mSettings.getPackageLPr( 9163 pkg.mOriginalPackages.get(i))) != null) { 9164 // We do have the package already installed under its 9165 // original name... should we use it? 9166 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9167 // New package is not compatible with original. 9168 origPackage = null; 9169 continue; 9170 } else if (origPackage.sharedUser != null) { 9171 // Make sure uid is compatible between packages. 9172 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9173 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9174 + " to " + pkg.packageName + ": old uid " 9175 + origPackage.sharedUser.name 9176 + " differs from " + pkg.mSharedUserId); 9177 origPackage = null; 9178 continue; 9179 } 9180 // TODO: Add case when shared user id is added [b/28144775] 9181 } else { 9182 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9183 + pkg.packageName + " to old name " + origPackage.name); 9184 } 9185 break; 9186 } 9187 } 9188 } 9189 } 9190 9191 if (mTransferedPackages.contains(pkg.packageName)) { 9192 Slog.w(TAG, "Package " + pkg.packageName 9193 + " was transferred to another, but its .apk remains"); 9194 } 9195 9196 // See comments in nonMutatedPs declaration 9197 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9198 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9199 if (foundPs != null) { 9200 nonMutatedPs = new PackageSetting(foundPs); 9201 } 9202 } 9203 9204 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9205 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9206 if (foundPs != null) { 9207 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9208 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9209 } 9210 } 9211 9212 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9213 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9214 PackageManagerService.reportSettingsProblem(Log.WARN, 9215 "Package " + pkg.packageName + " shared user changed from " 9216 + (pkgSetting.sharedUser != null 9217 ? pkgSetting.sharedUser.name : "<nothing>") 9218 + " to " 9219 + (suid != null ? suid.name : "<nothing>") 9220 + "; replacing with new"); 9221 pkgSetting = null; 9222 } 9223 final PackageSetting oldPkgSetting = 9224 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9225 final PackageSetting disabledPkgSetting = 9226 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9227 9228 String[] usesStaticLibraries = null; 9229 if (pkg.usesStaticLibraries != null) { 9230 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9231 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9232 } 9233 9234 if (pkgSetting == null) { 9235 final String parentPackageName = (pkg.parentPackage != null) 9236 ? pkg.parentPackage.packageName : null; 9237 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9238 // REMOVE SharedUserSetting from method; update in a separate call 9239 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9240 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9241 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9242 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9243 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9244 true /*allowInstall*/, instantApp, parentPackageName, 9245 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9246 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9247 // SIDE EFFECTS; updates system state; move elsewhere 9248 if (origPackage != null) { 9249 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9250 } 9251 mSettings.addUserToSettingLPw(pkgSetting); 9252 } else { 9253 // REMOVE SharedUserSetting from method; update in a separate call. 9254 // 9255 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9256 // secondaryCpuAbi are not known at this point so we always update them 9257 // to null here, only to reset them at a later point. 9258 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9259 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9260 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9261 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9262 UserManagerService.getInstance(), usesStaticLibraries, 9263 pkg.usesStaticLibrariesVersions); 9264 } 9265 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9266 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9267 9268 // SIDE EFFECTS; modifies system state; move elsewhere 9269 if (pkgSetting.origPackage != null) { 9270 // If we are first transitioning from an original package, 9271 // fix up the new package's name now. We need to do this after 9272 // looking up the package under its new name, so getPackageLP 9273 // can take care of fiddling things correctly. 9274 pkg.setPackageName(origPackage.name); 9275 9276 // File a report about this. 9277 String msg = "New package " + pkgSetting.realName 9278 + " renamed to replace old package " + pkgSetting.name; 9279 reportSettingsProblem(Log.WARN, msg); 9280 9281 // Make a note of it. 9282 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9283 mTransferedPackages.add(origPackage.name); 9284 } 9285 9286 // No longer need to retain this. 9287 pkgSetting.origPackage = null; 9288 } 9289 9290 // SIDE EFFECTS; modifies system state; move elsewhere 9291 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9292 // Make a note of it. 9293 mTransferedPackages.add(pkg.packageName); 9294 } 9295 9296 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9297 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9298 } 9299 9300 if ((scanFlags & SCAN_BOOTING) == 0 9301 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9302 // Check all shared libraries and map to their actual file path. 9303 // We only do this here for apps not on a system dir, because those 9304 // are the only ones that can fail an install due to this. We 9305 // will take care of the system apps by updating all of their 9306 // library paths after the scan is done. Also during the initial 9307 // scan don't update any libs as we do this wholesale after all 9308 // apps are scanned to avoid dependency based scanning. 9309 updateSharedLibrariesLPr(pkg, null); 9310 } 9311 9312 if (mFoundPolicyFile) { 9313 SELinuxMMAC.assignSeInfoValue(pkg); 9314 } 9315 pkg.applicationInfo.uid = pkgSetting.appId; 9316 pkg.mExtras = pkgSetting; 9317 9318 9319 // Static shared libs have same package with different versions where 9320 // we internally use a synthetic package name to allow multiple versions 9321 // of the same package, therefore we need to compare signatures against 9322 // the package setting for the latest library version. 9323 PackageSetting signatureCheckPs = pkgSetting; 9324 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9325 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9326 if (libraryEntry != null) { 9327 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9328 } 9329 } 9330 9331 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9332 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9333 // We just determined the app is signed correctly, so bring 9334 // over the latest parsed certs. 9335 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9336 } else { 9337 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9338 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9339 "Package " + pkg.packageName + " upgrade keys do not match the " 9340 + "previously installed version"); 9341 } else { 9342 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9343 String msg = "System package " + pkg.packageName 9344 + " signature changed; retaining data."; 9345 reportSettingsProblem(Log.WARN, msg); 9346 } 9347 } 9348 } else { 9349 try { 9350 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9351 verifySignaturesLP(signatureCheckPs, pkg); 9352 // We just determined the app is signed correctly, so bring 9353 // over the latest parsed certs. 9354 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9355 } catch (PackageManagerException e) { 9356 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9357 throw e; 9358 } 9359 // The signature has changed, but this package is in the system 9360 // image... let's recover! 9361 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9362 // However... if this package is part of a shared user, but it 9363 // doesn't match the signature of the shared user, let's fail. 9364 // What this means is that you can't change the signatures 9365 // associated with an overall shared user, which doesn't seem all 9366 // that unreasonable. 9367 if (signatureCheckPs.sharedUser != null) { 9368 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9369 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9370 throw new PackageManagerException( 9371 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9372 "Signature mismatch for shared user: " 9373 + pkgSetting.sharedUser); 9374 } 9375 } 9376 // File a report about this. 9377 String msg = "System package " + pkg.packageName 9378 + " signature changed; retaining data."; 9379 reportSettingsProblem(Log.WARN, msg); 9380 } 9381 } 9382 9383 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9384 // This package wants to adopt ownership of permissions from 9385 // another package. 9386 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9387 final String origName = pkg.mAdoptPermissions.get(i); 9388 final PackageSetting orig = mSettings.getPackageLPr(origName); 9389 if (orig != null) { 9390 if (verifyPackageUpdateLPr(orig, pkg)) { 9391 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9392 + pkg.packageName); 9393 // SIDE EFFECTS; updates permissions system state; move elsewhere 9394 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9395 } 9396 } 9397 } 9398 } 9399 } 9400 9401 pkg.applicationInfo.processName = fixProcessName( 9402 pkg.applicationInfo.packageName, 9403 pkg.applicationInfo.processName); 9404 9405 if (pkg != mPlatformPackage) { 9406 // Get all of our default paths setup 9407 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9408 } 9409 9410 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9411 9412 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9413 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9414 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9415 derivePackageAbi( 9416 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9417 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9418 9419 // Some system apps still use directory structure for native libraries 9420 // in which case we might end up not detecting abi solely based on apk 9421 // structure. Try to detect abi based on directory structure. 9422 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9423 pkg.applicationInfo.primaryCpuAbi == null) { 9424 setBundledAppAbisAndRoots(pkg, pkgSetting); 9425 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9426 } 9427 } else { 9428 // This is not a first boot or an upgrade, don't bother deriving the 9429 // ABI during the scan. Instead, trust the value that was stored in the 9430 // package setting. 9431 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9432 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9433 9434 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9435 9436 if (DEBUG_ABI_SELECTION) { 9437 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9438 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9439 pkg.applicationInfo.secondaryCpuAbi); 9440 } 9441 } 9442 } else { 9443 if ((scanFlags & SCAN_MOVE) != 0) { 9444 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9445 // but we already have this packages package info in the PackageSetting. We just 9446 // use that and derive the native library path based on the new codepath. 9447 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9448 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9449 } 9450 9451 // Set native library paths again. For moves, the path will be updated based on the 9452 // ABIs we've determined above. For non-moves, the path will be updated based on the 9453 // ABIs we determined during compilation, but the path will depend on the final 9454 // package path (after the rename away from the stage path). 9455 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9456 } 9457 9458 // This is a special case for the "system" package, where the ABI is 9459 // dictated by the zygote configuration (and init.rc). We should keep track 9460 // of this ABI so that we can deal with "normal" applications that run under 9461 // the same UID correctly. 9462 if (mPlatformPackage == pkg) { 9463 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9464 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9465 } 9466 9467 // If there's a mismatch between the abi-override in the package setting 9468 // and the abiOverride specified for the install. Warn about this because we 9469 // would've already compiled the app without taking the package setting into 9470 // account. 9471 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9472 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9473 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9474 " for package " + pkg.packageName); 9475 } 9476 } 9477 9478 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9479 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9480 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9481 9482 // Copy the derived override back to the parsed package, so that we can 9483 // update the package settings accordingly. 9484 pkg.cpuAbiOverride = cpuAbiOverride; 9485 9486 if (DEBUG_ABI_SELECTION) { 9487 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9488 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9489 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9490 } 9491 9492 // Push the derived path down into PackageSettings so we know what to 9493 // clean up at uninstall time. 9494 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9495 9496 if (DEBUG_ABI_SELECTION) { 9497 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9498 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9499 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9500 } 9501 9502 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9503 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9504 // We don't do this here during boot because we can do it all 9505 // at once after scanning all existing packages. 9506 // 9507 // We also do this *before* we perform dexopt on this package, so that 9508 // we can avoid redundant dexopts, and also to make sure we've got the 9509 // code and package path correct. 9510 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9511 } 9512 9513 if (mFactoryTest && pkg.requestedPermissions.contains( 9514 android.Manifest.permission.FACTORY_TEST)) { 9515 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9516 } 9517 9518 if (isSystemApp(pkg)) { 9519 pkgSetting.isOrphaned = true; 9520 } 9521 9522 // Take care of first install / last update times. 9523 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9524 if (currentTime != 0) { 9525 if (pkgSetting.firstInstallTime == 0) { 9526 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9527 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9528 pkgSetting.lastUpdateTime = currentTime; 9529 } 9530 } else if (pkgSetting.firstInstallTime == 0) { 9531 // We need *something*. Take time time stamp of the file. 9532 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9533 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9534 if (scanFileTime != pkgSetting.timeStamp) { 9535 // A package on the system image has changed; consider this 9536 // to be an update. 9537 pkgSetting.lastUpdateTime = scanFileTime; 9538 } 9539 } 9540 pkgSetting.setTimeStamp(scanFileTime); 9541 9542 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9543 if (nonMutatedPs != null) { 9544 synchronized (mPackages) { 9545 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9546 } 9547 } 9548 } else { 9549 final int userId = user == null ? 0 : user.getIdentifier(); 9550 // Modify state for the given package setting 9551 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9552 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9553 if (pkgSetting.getInstantApp(userId)) { 9554 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9555 } 9556 } 9557 return pkg; 9558 } 9559 9560 /** 9561 * Applies policy to the parsed package based upon the given policy flags. 9562 * Ensures the package is in a good state. 9563 * <p> 9564 * Implementation detail: This method must NOT have any side effect. It would 9565 * ideally be static, but, it requires locks to read system state. 9566 */ 9567 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9568 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9569 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9570 if (pkg.applicationInfo.isDirectBootAware()) { 9571 // we're direct boot aware; set for all components 9572 for (PackageParser.Service s : pkg.services) { 9573 s.info.encryptionAware = s.info.directBootAware = true; 9574 } 9575 for (PackageParser.Provider p : pkg.providers) { 9576 p.info.encryptionAware = p.info.directBootAware = true; 9577 } 9578 for (PackageParser.Activity a : pkg.activities) { 9579 a.info.encryptionAware = a.info.directBootAware = true; 9580 } 9581 for (PackageParser.Activity r : pkg.receivers) { 9582 r.info.encryptionAware = r.info.directBootAware = true; 9583 } 9584 } 9585 } else { 9586 // Only allow system apps to be flagged as core apps. 9587 pkg.coreApp = false; 9588 // clear flags not applicable to regular apps 9589 pkg.applicationInfo.privateFlags &= 9590 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9591 pkg.applicationInfo.privateFlags &= 9592 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9593 } 9594 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9595 9596 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9597 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9598 } 9599 9600 if (!isSystemApp(pkg)) { 9601 // Only system apps can use these features. 9602 pkg.mOriginalPackages = null; 9603 pkg.mRealPackage = null; 9604 pkg.mAdoptPermissions = null; 9605 } 9606 } 9607 9608 /** 9609 * Asserts the parsed package is valid according to the given policy. If the 9610 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9611 * <p> 9612 * Implementation detail: This method must NOT have any side effects. It would 9613 * ideally be static, but, it requires locks to read system state. 9614 * 9615 * @throws PackageManagerException If the package fails any of the validation checks 9616 */ 9617 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9618 throws PackageManagerException { 9619 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9620 assertCodePolicy(pkg); 9621 } 9622 9623 if (pkg.applicationInfo.getCodePath() == null || 9624 pkg.applicationInfo.getResourcePath() == null) { 9625 // Bail out. The resource and code paths haven't been set. 9626 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9627 "Code and resource paths haven't been set correctly"); 9628 } 9629 9630 // Make sure we're not adding any bogus keyset info 9631 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9632 ksms.assertScannedPackageValid(pkg); 9633 9634 synchronized (mPackages) { 9635 // The special "android" package can only be defined once 9636 if (pkg.packageName.equals("android")) { 9637 if (mAndroidApplication != null) { 9638 Slog.w(TAG, "*************************************************"); 9639 Slog.w(TAG, "Core android package being redefined. Skipping."); 9640 Slog.w(TAG, " codePath=" + pkg.codePath); 9641 Slog.w(TAG, "*************************************************"); 9642 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9643 "Core android package being redefined. Skipping."); 9644 } 9645 } 9646 9647 // A package name must be unique; don't allow duplicates 9648 if (mPackages.containsKey(pkg.packageName)) { 9649 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9650 "Application package " + pkg.packageName 9651 + " already installed. Skipping duplicate."); 9652 } 9653 9654 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9655 // Static libs have a synthetic package name containing the version 9656 // but we still want the base name to be unique. 9657 if (mPackages.containsKey(pkg.manifestPackageName)) { 9658 throw new PackageManagerException( 9659 "Duplicate static shared lib provider package"); 9660 } 9661 9662 // Static shared libraries should have at least O target SDK 9663 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9664 throw new PackageManagerException( 9665 "Packages declaring static-shared libs must target O SDK or higher"); 9666 } 9667 9668 // Package declaring static a shared lib cannot be instant apps 9669 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9670 throw new PackageManagerException( 9671 "Packages declaring static-shared libs cannot be instant apps"); 9672 } 9673 9674 // Package declaring static a shared lib cannot be renamed since the package 9675 // name is synthetic and apps can't code around package manager internals. 9676 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9677 throw new PackageManagerException( 9678 "Packages declaring static-shared libs cannot be renamed"); 9679 } 9680 9681 // Package declaring static a shared lib cannot declare child packages 9682 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9683 throw new PackageManagerException( 9684 "Packages declaring static-shared libs cannot have child packages"); 9685 } 9686 9687 // Package declaring static a shared lib cannot declare dynamic libs 9688 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9689 throw new PackageManagerException( 9690 "Packages declaring static-shared libs cannot declare dynamic libs"); 9691 } 9692 9693 // Package declaring static a shared lib cannot declare shared users 9694 if (pkg.mSharedUserId != null) { 9695 throw new PackageManagerException( 9696 "Packages declaring static-shared libs cannot declare shared users"); 9697 } 9698 9699 // Static shared libs cannot declare activities 9700 if (!pkg.activities.isEmpty()) { 9701 throw new PackageManagerException( 9702 "Static shared libs cannot declare activities"); 9703 } 9704 9705 // Static shared libs cannot declare services 9706 if (!pkg.services.isEmpty()) { 9707 throw new PackageManagerException( 9708 "Static shared libs cannot declare services"); 9709 } 9710 9711 // Static shared libs cannot declare providers 9712 if (!pkg.providers.isEmpty()) { 9713 throw new PackageManagerException( 9714 "Static shared libs cannot declare content providers"); 9715 } 9716 9717 // Static shared libs cannot declare receivers 9718 if (!pkg.receivers.isEmpty()) { 9719 throw new PackageManagerException( 9720 "Static shared libs cannot declare broadcast receivers"); 9721 } 9722 9723 // Static shared libs cannot declare permission groups 9724 if (!pkg.permissionGroups.isEmpty()) { 9725 throw new PackageManagerException( 9726 "Static shared libs cannot declare permission groups"); 9727 } 9728 9729 // Static shared libs cannot declare permissions 9730 if (!pkg.permissions.isEmpty()) { 9731 throw new PackageManagerException( 9732 "Static shared libs cannot declare permissions"); 9733 } 9734 9735 // Static shared libs cannot declare protected broadcasts 9736 if (pkg.protectedBroadcasts != null) { 9737 throw new PackageManagerException( 9738 "Static shared libs cannot declare protected broadcasts"); 9739 } 9740 9741 // Static shared libs cannot be overlay targets 9742 if (pkg.mOverlayTarget != null) { 9743 throw new PackageManagerException( 9744 "Static shared libs cannot be overlay targets"); 9745 } 9746 9747 // The version codes must be ordered as lib versions 9748 int minVersionCode = Integer.MIN_VALUE; 9749 int maxVersionCode = Integer.MAX_VALUE; 9750 9751 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9752 pkg.staticSharedLibName); 9753 if (versionedLib != null) { 9754 final int versionCount = versionedLib.size(); 9755 for (int i = 0; i < versionCount; i++) { 9756 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9757 // TODO: We will change version code to long, so in the new API it is long 9758 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9759 .getVersionCode(); 9760 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9761 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9762 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9763 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9764 } else { 9765 minVersionCode = maxVersionCode = libVersionCode; 9766 break; 9767 } 9768 } 9769 } 9770 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9771 throw new PackageManagerException("Static shared" 9772 + " lib version codes must be ordered as lib versions"); 9773 } 9774 } 9775 9776 // Only privileged apps and updated privileged apps can add child packages. 9777 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9778 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9779 throw new PackageManagerException("Only privileged apps can add child " 9780 + "packages. Ignoring package " + pkg.packageName); 9781 } 9782 final int childCount = pkg.childPackages.size(); 9783 for (int i = 0; i < childCount; i++) { 9784 PackageParser.Package childPkg = pkg.childPackages.get(i); 9785 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9786 childPkg.packageName)) { 9787 throw new PackageManagerException("Can't override child of " 9788 + "another disabled app. Ignoring package " + pkg.packageName); 9789 } 9790 } 9791 } 9792 9793 // If we're only installing presumed-existing packages, require that the 9794 // scanned APK is both already known and at the path previously established 9795 // for it. Previously unknown packages we pick up normally, but if we have an 9796 // a priori expectation about this package's install presence, enforce it. 9797 // With a singular exception for new system packages. When an OTA contains 9798 // a new system package, we allow the codepath to change from a system location 9799 // to the user-installed location. If we don't allow this change, any newer, 9800 // user-installed version of the application will be ignored. 9801 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9802 if (mExpectingBetter.containsKey(pkg.packageName)) { 9803 logCriticalInfo(Log.WARN, 9804 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9805 } else { 9806 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9807 if (known != null) { 9808 if (DEBUG_PACKAGE_SCANNING) { 9809 Log.d(TAG, "Examining " + pkg.codePath 9810 + " and requiring known paths " + known.codePathString 9811 + " & " + known.resourcePathString); 9812 } 9813 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9814 || !pkg.applicationInfo.getResourcePath().equals( 9815 known.resourcePathString)) { 9816 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9817 "Application package " + pkg.packageName 9818 + " found at " + pkg.applicationInfo.getCodePath() 9819 + " but expected at " + known.codePathString 9820 + "; ignoring."); 9821 } 9822 } 9823 } 9824 } 9825 9826 // Verify that this new package doesn't have any content providers 9827 // that conflict with existing packages. Only do this if the 9828 // package isn't already installed, since we don't want to break 9829 // things that are installed. 9830 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9831 final int N = pkg.providers.size(); 9832 int i; 9833 for (i=0; i<N; i++) { 9834 PackageParser.Provider p = pkg.providers.get(i); 9835 if (p.info.authority != null) { 9836 String names[] = p.info.authority.split(";"); 9837 for (int j = 0; j < names.length; j++) { 9838 if (mProvidersByAuthority.containsKey(names[j])) { 9839 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9840 final String otherPackageName = 9841 ((other != null && other.getComponentName() != null) ? 9842 other.getComponentName().getPackageName() : "?"); 9843 throw new PackageManagerException( 9844 INSTALL_FAILED_CONFLICTING_PROVIDER, 9845 "Can't install because provider name " + names[j] 9846 + " (in package " + pkg.applicationInfo.packageName 9847 + ") is already used by " + otherPackageName); 9848 } 9849 } 9850 } 9851 } 9852 } 9853 } 9854 } 9855 9856 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9857 int type, String declaringPackageName, int declaringVersionCode) { 9858 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9859 if (versionedLib == null) { 9860 versionedLib = new SparseArray<>(); 9861 mSharedLibraries.put(name, versionedLib); 9862 if (type == SharedLibraryInfo.TYPE_STATIC) { 9863 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9864 } 9865 } else if (versionedLib.indexOfKey(version) >= 0) { 9866 return false; 9867 } 9868 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9869 version, type, declaringPackageName, declaringVersionCode); 9870 versionedLib.put(version, libEntry); 9871 return true; 9872 } 9873 9874 private boolean removeSharedLibraryLPw(String name, int version) { 9875 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9876 if (versionedLib == null) { 9877 return false; 9878 } 9879 final int libIdx = versionedLib.indexOfKey(version); 9880 if (libIdx < 0) { 9881 return false; 9882 } 9883 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9884 versionedLib.remove(version); 9885 if (versionedLib.size() <= 0) { 9886 mSharedLibraries.remove(name); 9887 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9888 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9889 .getPackageName()); 9890 } 9891 } 9892 return true; 9893 } 9894 9895 /** 9896 * Adds a scanned package to the system. When this method is finished, the package will 9897 * be available for query, resolution, etc... 9898 */ 9899 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9900 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9901 final String pkgName = pkg.packageName; 9902 if (mCustomResolverComponentName != null && 9903 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9904 setUpCustomResolverActivity(pkg); 9905 } 9906 9907 if (pkg.packageName.equals("android")) { 9908 synchronized (mPackages) { 9909 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9910 // Set up information for our fall-back user intent resolution activity. 9911 mPlatformPackage = pkg; 9912 pkg.mVersionCode = mSdkVersion; 9913 mAndroidApplication = pkg.applicationInfo; 9914 if (!mResolverReplaced) { 9915 mResolveActivity.applicationInfo = mAndroidApplication; 9916 mResolveActivity.name = ResolverActivity.class.getName(); 9917 mResolveActivity.packageName = mAndroidApplication.packageName; 9918 mResolveActivity.processName = "system:ui"; 9919 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9920 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9921 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9922 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9923 mResolveActivity.exported = true; 9924 mResolveActivity.enabled = true; 9925 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9926 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9927 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9928 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9929 | ActivityInfo.CONFIG_ORIENTATION 9930 | ActivityInfo.CONFIG_KEYBOARD 9931 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9932 mResolveInfo.activityInfo = mResolveActivity; 9933 mResolveInfo.priority = 0; 9934 mResolveInfo.preferredOrder = 0; 9935 mResolveInfo.match = 0; 9936 mResolveComponentName = new ComponentName( 9937 mAndroidApplication.packageName, mResolveActivity.name); 9938 } 9939 } 9940 } 9941 } 9942 9943 ArrayList<PackageParser.Package> clientLibPkgs = null; 9944 // writer 9945 synchronized (mPackages) { 9946 boolean hasStaticSharedLibs = false; 9947 9948 // Any app can add new static shared libraries 9949 if (pkg.staticSharedLibName != null) { 9950 // Static shared libs don't allow renaming as they have synthetic package 9951 // names to allow install of multiple versions, so use name from manifest. 9952 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9953 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9954 pkg.manifestPackageName, pkg.mVersionCode)) { 9955 hasStaticSharedLibs = true; 9956 } else { 9957 Slog.w(TAG, "Package " + pkg.packageName + " library " 9958 + pkg.staticSharedLibName + " already exists; skipping"); 9959 } 9960 // Static shared libs cannot be updated once installed since they 9961 // use synthetic package name which includes the version code, so 9962 // not need to update other packages's shared lib dependencies. 9963 } 9964 9965 if (!hasStaticSharedLibs 9966 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9967 // Only system apps can add new dynamic shared libraries. 9968 if (pkg.libraryNames != null) { 9969 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9970 String name = pkg.libraryNames.get(i); 9971 boolean allowed = false; 9972 if (pkg.isUpdatedSystemApp()) { 9973 // New library entries can only be added through the 9974 // system image. This is important to get rid of a lot 9975 // of nasty edge cases: for example if we allowed a non- 9976 // system update of the app to add a library, then uninstalling 9977 // the update would make the library go away, and assumptions 9978 // we made such as through app install filtering would now 9979 // have allowed apps on the device which aren't compatible 9980 // with it. Better to just have the restriction here, be 9981 // conservative, and create many fewer cases that can negatively 9982 // impact the user experience. 9983 final PackageSetting sysPs = mSettings 9984 .getDisabledSystemPkgLPr(pkg.packageName); 9985 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9986 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9987 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9988 allowed = true; 9989 break; 9990 } 9991 } 9992 } 9993 } else { 9994 allowed = true; 9995 } 9996 if (allowed) { 9997 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9998 SharedLibraryInfo.VERSION_UNDEFINED, 9999 SharedLibraryInfo.TYPE_DYNAMIC, 10000 pkg.packageName, pkg.mVersionCode)) { 10001 Slog.w(TAG, "Package " + pkg.packageName + " library " 10002 + name + " already exists; skipping"); 10003 } 10004 } else { 10005 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10006 + name + " that is not declared on system image; skipping"); 10007 } 10008 } 10009 10010 if ((scanFlags & SCAN_BOOTING) == 0) { 10011 // If we are not booting, we need to update any applications 10012 // that are clients of our shared library. If we are booting, 10013 // this will all be done once the scan is complete. 10014 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10015 } 10016 } 10017 } 10018 } 10019 10020 if ((scanFlags & SCAN_BOOTING) != 0) { 10021 // No apps can run during boot scan, so they don't need to be frozen 10022 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10023 // Caller asked to not kill app, so it's probably not frozen 10024 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10025 // Caller asked us to ignore frozen check for some reason; they 10026 // probably didn't know the package name 10027 } else { 10028 // We're doing major surgery on this package, so it better be frozen 10029 // right now to keep it from launching 10030 checkPackageFrozen(pkgName); 10031 } 10032 10033 // Also need to kill any apps that are dependent on the library. 10034 if (clientLibPkgs != null) { 10035 for (int i=0; i<clientLibPkgs.size(); i++) { 10036 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10037 killApplication(clientPkg.applicationInfo.packageName, 10038 clientPkg.applicationInfo.uid, "update lib"); 10039 } 10040 } 10041 10042 // writer 10043 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10044 10045 synchronized (mPackages) { 10046 // We don't expect installation to fail beyond this point 10047 10048 // Add the new setting to mSettings 10049 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10050 // Add the new setting to mPackages 10051 mPackages.put(pkg.applicationInfo.packageName, pkg); 10052 // Make sure we don't accidentally delete its data. 10053 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10054 while (iter.hasNext()) { 10055 PackageCleanItem item = iter.next(); 10056 if (pkgName.equals(item.packageName)) { 10057 iter.remove(); 10058 } 10059 } 10060 10061 // Add the package's KeySets to the global KeySetManagerService 10062 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10063 ksms.addScannedPackageLPw(pkg); 10064 10065 int N = pkg.providers.size(); 10066 StringBuilder r = null; 10067 int i; 10068 for (i=0; i<N; i++) { 10069 PackageParser.Provider p = pkg.providers.get(i); 10070 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10071 p.info.processName); 10072 mProviders.addProvider(p); 10073 p.syncable = p.info.isSyncable; 10074 if (p.info.authority != null) { 10075 String names[] = p.info.authority.split(";"); 10076 p.info.authority = null; 10077 for (int j = 0; j < names.length; j++) { 10078 if (j == 1 && p.syncable) { 10079 // We only want the first authority for a provider to possibly be 10080 // syncable, so if we already added this provider using a different 10081 // authority clear the syncable flag. We copy the provider before 10082 // changing it because the mProviders object contains a reference 10083 // to a provider that we don't want to change. 10084 // Only do this for the second authority since the resulting provider 10085 // object can be the same for all future authorities for this provider. 10086 p = new PackageParser.Provider(p); 10087 p.syncable = false; 10088 } 10089 if (!mProvidersByAuthority.containsKey(names[j])) { 10090 mProvidersByAuthority.put(names[j], p); 10091 if (p.info.authority == null) { 10092 p.info.authority = names[j]; 10093 } else { 10094 p.info.authority = p.info.authority + ";" + names[j]; 10095 } 10096 if (DEBUG_PACKAGE_SCANNING) { 10097 if (chatty) 10098 Log.d(TAG, "Registered content provider: " + names[j] 10099 + ", className = " + p.info.name + ", isSyncable = " 10100 + p.info.isSyncable); 10101 } 10102 } else { 10103 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10104 Slog.w(TAG, "Skipping provider name " + names[j] + 10105 " (in package " + pkg.applicationInfo.packageName + 10106 "): name already used by " 10107 + ((other != null && other.getComponentName() != null) 10108 ? other.getComponentName().getPackageName() : "?")); 10109 } 10110 } 10111 } 10112 if (chatty) { 10113 if (r == null) { 10114 r = new StringBuilder(256); 10115 } else { 10116 r.append(' '); 10117 } 10118 r.append(p.info.name); 10119 } 10120 } 10121 if (r != null) { 10122 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10123 } 10124 10125 N = pkg.services.size(); 10126 r = null; 10127 for (i=0; i<N; i++) { 10128 PackageParser.Service s = pkg.services.get(i); 10129 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10130 s.info.processName); 10131 mServices.addService(s); 10132 if (chatty) { 10133 if (r == null) { 10134 r = new StringBuilder(256); 10135 } else { 10136 r.append(' '); 10137 } 10138 r.append(s.info.name); 10139 } 10140 } 10141 if (r != null) { 10142 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10143 } 10144 10145 N = pkg.receivers.size(); 10146 r = null; 10147 for (i=0; i<N; i++) { 10148 PackageParser.Activity a = pkg.receivers.get(i); 10149 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10150 a.info.processName); 10151 mReceivers.addActivity(a, "receiver"); 10152 if (chatty) { 10153 if (r == null) { 10154 r = new StringBuilder(256); 10155 } else { 10156 r.append(' '); 10157 } 10158 r.append(a.info.name); 10159 } 10160 } 10161 if (r != null) { 10162 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10163 } 10164 10165 N = pkg.activities.size(); 10166 r = null; 10167 for (i=0; i<N; i++) { 10168 PackageParser.Activity a = pkg.activities.get(i); 10169 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10170 a.info.processName); 10171 mActivities.addActivity(a, "activity"); 10172 if (chatty) { 10173 if (r == null) { 10174 r = new StringBuilder(256); 10175 } else { 10176 r.append(' '); 10177 } 10178 r.append(a.info.name); 10179 } 10180 } 10181 if (r != null) { 10182 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10183 } 10184 10185 N = pkg.permissionGroups.size(); 10186 r = null; 10187 for (i=0; i<N; i++) { 10188 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10189 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10190 final String curPackageName = cur == null ? null : cur.info.packageName; 10191 // Dont allow ephemeral apps to define new permission groups. 10192 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10193 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10194 + pg.info.packageName 10195 + " ignored: instant apps cannot define new permission groups."); 10196 continue; 10197 } 10198 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10199 if (cur == null || isPackageUpdate) { 10200 mPermissionGroups.put(pg.info.name, pg); 10201 if (chatty) { 10202 if (r == null) { 10203 r = new StringBuilder(256); 10204 } else { 10205 r.append(' '); 10206 } 10207 if (isPackageUpdate) { 10208 r.append("UPD:"); 10209 } 10210 r.append(pg.info.name); 10211 } 10212 } else { 10213 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10214 + pg.info.packageName + " ignored: original from " 10215 + cur.info.packageName); 10216 if (chatty) { 10217 if (r == null) { 10218 r = new StringBuilder(256); 10219 } else { 10220 r.append(' '); 10221 } 10222 r.append("DUP:"); 10223 r.append(pg.info.name); 10224 } 10225 } 10226 } 10227 if (r != null) { 10228 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10229 } 10230 10231 N = pkg.permissions.size(); 10232 r = null; 10233 for (i=0; i<N; i++) { 10234 PackageParser.Permission p = pkg.permissions.get(i); 10235 10236 // Dont allow ephemeral apps to define new permissions. 10237 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10238 Slog.w(TAG, "Permission " + p.info.name + " from package " 10239 + p.info.packageName 10240 + " ignored: instant apps cannot define new permissions."); 10241 continue; 10242 } 10243 10244 // Assume by default that we did not install this permission into the system. 10245 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10246 10247 // Now that permission groups have a special meaning, we ignore permission 10248 // groups for legacy apps to prevent unexpected behavior. In particular, 10249 // permissions for one app being granted to someone just becase they happen 10250 // to be in a group defined by another app (before this had no implications). 10251 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10252 p.group = mPermissionGroups.get(p.info.group); 10253 // Warn for a permission in an unknown group. 10254 if (p.info.group != null && p.group == null) { 10255 Slog.w(TAG, "Permission " + p.info.name + " from package " 10256 + p.info.packageName + " in an unknown group " + p.info.group); 10257 } 10258 } 10259 10260 ArrayMap<String, BasePermission> permissionMap = 10261 p.tree ? mSettings.mPermissionTrees 10262 : mSettings.mPermissions; 10263 BasePermission bp = permissionMap.get(p.info.name); 10264 10265 // Allow system apps to redefine non-system permissions 10266 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10267 final boolean currentOwnerIsSystem = (bp.perm != null 10268 && isSystemApp(bp.perm.owner)); 10269 if (isSystemApp(p.owner)) { 10270 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10271 // It's a built-in permission and no owner, take ownership now 10272 bp.packageSetting = pkgSetting; 10273 bp.perm = p; 10274 bp.uid = pkg.applicationInfo.uid; 10275 bp.sourcePackage = p.info.packageName; 10276 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10277 } else if (!currentOwnerIsSystem) { 10278 String msg = "New decl " + p.owner + " of permission " 10279 + p.info.name + " is system; overriding " + bp.sourcePackage; 10280 reportSettingsProblem(Log.WARN, msg); 10281 bp = null; 10282 } 10283 } 10284 } 10285 10286 if (bp == null) { 10287 bp = new BasePermission(p.info.name, p.info.packageName, 10288 BasePermission.TYPE_NORMAL); 10289 permissionMap.put(p.info.name, bp); 10290 } 10291 10292 if (bp.perm == null) { 10293 if (bp.sourcePackage == null 10294 || bp.sourcePackage.equals(p.info.packageName)) { 10295 BasePermission tree = findPermissionTreeLP(p.info.name); 10296 if (tree == null 10297 || tree.sourcePackage.equals(p.info.packageName)) { 10298 bp.packageSetting = pkgSetting; 10299 bp.perm = p; 10300 bp.uid = pkg.applicationInfo.uid; 10301 bp.sourcePackage = p.info.packageName; 10302 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10303 if (chatty) { 10304 if (r == null) { 10305 r = new StringBuilder(256); 10306 } else { 10307 r.append(' '); 10308 } 10309 r.append(p.info.name); 10310 } 10311 } else { 10312 Slog.w(TAG, "Permission " + p.info.name + " from package " 10313 + p.info.packageName + " ignored: base tree " 10314 + tree.name + " is from package " 10315 + tree.sourcePackage); 10316 } 10317 } else { 10318 Slog.w(TAG, "Permission " + p.info.name + " from package " 10319 + p.info.packageName + " ignored: original from " 10320 + bp.sourcePackage); 10321 } 10322 } else if (chatty) { 10323 if (r == null) { 10324 r = new StringBuilder(256); 10325 } else { 10326 r.append(' '); 10327 } 10328 r.append("DUP:"); 10329 r.append(p.info.name); 10330 } 10331 if (bp.perm == p) { 10332 bp.protectionLevel = p.info.protectionLevel; 10333 } 10334 } 10335 10336 if (r != null) { 10337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10338 } 10339 10340 N = pkg.instrumentation.size(); 10341 r = null; 10342 for (i=0; i<N; i++) { 10343 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10344 a.info.packageName = pkg.applicationInfo.packageName; 10345 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10346 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10347 a.info.splitNames = pkg.splitNames; 10348 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10349 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10350 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10351 a.info.dataDir = pkg.applicationInfo.dataDir; 10352 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10353 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10354 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10355 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10356 mInstrumentation.put(a.getComponentName(), a); 10357 if (chatty) { 10358 if (r == null) { 10359 r = new StringBuilder(256); 10360 } else { 10361 r.append(' '); 10362 } 10363 r.append(a.info.name); 10364 } 10365 } 10366 if (r != null) { 10367 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10368 } 10369 10370 if (pkg.protectedBroadcasts != null) { 10371 N = pkg.protectedBroadcasts.size(); 10372 for (i=0; i<N; i++) { 10373 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10374 } 10375 } 10376 } 10377 10378 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10379 } 10380 10381 /** 10382 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10383 * is derived purely on the basis of the contents of {@code scanFile} and 10384 * {@code cpuAbiOverride}. 10385 * 10386 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10387 */ 10388 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10389 String cpuAbiOverride, boolean extractLibs, 10390 File appLib32InstallDir) 10391 throws PackageManagerException { 10392 // Give ourselves some initial paths; we'll come back for another 10393 // pass once we've determined ABI below. 10394 setNativeLibraryPaths(pkg, appLib32InstallDir); 10395 10396 // We would never need to extract libs for forward-locked and external packages, 10397 // since the container service will do it for us. We shouldn't attempt to 10398 // extract libs from system app when it was not updated. 10399 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10400 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10401 extractLibs = false; 10402 } 10403 10404 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10405 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10406 10407 NativeLibraryHelper.Handle handle = null; 10408 try { 10409 handle = NativeLibraryHelper.Handle.create(pkg); 10410 // TODO(multiArch): This can be null for apps that didn't go through the 10411 // usual installation process. We can calculate it again, like we 10412 // do during install time. 10413 // 10414 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10415 // unnecessary. 10416 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10417 10418 // Null out the abis so that they can be recalculated. 10419 pkg.applicationInfo.primaryCpuAbi = null; 10420 pkg.applicationInfo.secondaryCpuAbi = null; 10421 if (isMultiArch(pkg.applicationInfo)) { 10422 // Warn if we've set an abiOverride for multi-lib packages.. 10423 // By definition, we need to copy both 32 and 64 bit libraries for 10424 // such packages. 10425 if (pkg.cpuAbiOverride != null 10426 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10427 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10428 } 10429 10430 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10431 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10432 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10433 if (extractLibs) { 10434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10435 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10436 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10437 useIsaSpecificSubdirs); 10438 } else { 10439 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10440 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10441 } 10442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10443 } 10444 10445 maybeThrowExceptionForMultiArchCopy( 10446 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10447 10448 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10449 if (extractLibs) { 10450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10451 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10452 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10453 useIsaSpecificSubdirs); 10454 } else { 10455 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10456 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10457 } 10458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10459 } 10460 10461 maybeThrowExceptionForMultiArchCopy( 10462 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10463 10464 if (abi64 >= 0) { 10465 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10466 } 10467 10468 if (abi32 >= 0) { 10469 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10470 if (abi64 >= 0) { 10471 if (pkg.use32bitAbi) { 10472 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10473 pkg.applicationInfo.primaryCpuAbi = abi; 10474 } else { 10475 pkg.applicationInfo.secondaryCpuAbi = abi; 10476 } 10477 } else { 10478 pkg.applicationInfo.primaryCpuAbi = abi; 10479 } 10480 } 10481 10482 } else { 10483 String[] abiList = (cpuAbiOverride != null) ? 10484 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10485 10486 // Enable gross and lame hacks for apps that are built with old 10487 // SDK tools. We must scan their APKs for renderscript bitcode and 10488 // not launch them if it's present. Don't bother checking on devices 10489 // that don't have 64 bit support. 10490 boolean needsRenderScriptOverride = false; 10491 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10492 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10493 abiList = Build.SUPPORTED_32_BIT_ABIS; 10494 needsRenderScriptOverride = true; 10495 } 10496 10497 final int copyRet; 10498 if (extractLibs) { 10499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10500 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10501 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10502 } else { 10503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10504 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10505 } 10506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10507 10508 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10509 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10510 "Error unpackaging native libs for app, errorCode=" + copyRet); 10511 } 10512 10513 if (copyRet >= 0) { 10514 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10515 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10516 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10517 } else if (needsRenderScriptOverride) { 10518 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10519 } 10520 } 10521 } catch (IOException ioe) { 10522 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10523 } finally { 10524 IoUtils.closeQuietly(handle); 10525 } 10526 10527 // Now that we've calculated the ABIs and determined if it's an internal app, 10528 // we will go ahead and populate the nativeLibraryPath. 10529 setNativeLibraryPaths(pkg, appLib32InstallDir); 10530 } 10531 10532 /** 10533 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10534 * i.e, so that all packages can be run inside a single process if required. 10535 * 10536 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10537 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10538 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10539 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10540 * updating a package that belongs to a shared user. 10541 * 10542 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10543 * adds unnecessary complexity. 10544 */ 10545 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10546 PackageParser.Package scannedPackage) { 10547 String requiredInstructionSet = null; 10548 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10549 requiredInstructionSet = VMRuntime.getInstructionSet( 10550 scannedPackage.applicationInfo.primaryCpuAbi); 10551 } 10552 10553 PackageSetting requirer = null; 10554 for (PackageSetting ps : packagesForUser) { 10555 // If packagesForUser contains scannedPackage, we skip it. This will happen 10556 // when scannedPackage is an update of an existing package. Without this check, 10557 // we will never be able to change the ABI of any package belonging to a shared 10558 // user, even if it's compatible with other packages. 10559 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10560 if (ps.primaryCpuAbiString == null) { 10561 continue; 10562 } 10563 10564 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10565 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10566 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10567 // this but there's not much we can do. 10568 String errorMessage = "Instruction set mismatch, " 10569 + ((requirer == null) ? "[caller]" : requirer) 10570 + " requires " + requiredInstructionSet + " whereas " + ps 10571 + " requires " + instructionSet; 10572 Slog.w(TAG, errorMessage); 10573 } 10574 10575 if (requiredInstructionSet == null) { 10576 requiredInstructionSet = instructionSet; 10577 requirer = ps; 10578 } 10579 } 10580 } 10581 10582 if (requiredInstructionSet != null) { 10583 String adjustedAbi; 10584 if (requirer != null) { 10585 // requirer != null implies that either scannedPackage was null or that scannedPackage 10586 // did not require an ABI, in which case we have to adjust scannedPackage to match 10587 // the ABI of the set (which is the same as requirer's ABI) 10588 adjustedAbi = requirer.primaryCpuAbiString; 10589 if (scannedPackage != null) { 10590 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10591 } 10592 } else { 10593 // requirer == null implies that we're updating all ABIs in the set to 10594 // match scannedPackage. 10595 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10596 } 10597 10598 for (PackageSetting ps : packagesForUser) { 10599 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10600 if (ps.primaryCpuAbiString != null) { 10601 continue; 10602 } 10603 10604 ps.primaryCpuAbiString = adjustedAbi; 10605 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10606 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10607 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10608 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10609 + " (requirer=" 10610 + (requirer != null ? requirer.pkg : "null") 10611 + ", scannedPackage=" 10612 + (scannedPackage != null ? scannedPackage : "null") 10613 + ")"); 10614 try { 10615 mInstaller.rmdex(ps.codePathString, 10616 getDexCodeInstructionSet(getPreferredInstructionSet())); 10617 } catch (InstallerException ignored) { 10618 } 10619 } 10620 } 10621 } 10622 } 10623 } 10624 10625 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10626 synchronized (mPackages) { 10627 mResolverReplaced = true; 10628 // Set up information for custom user intent resolution activity. 10629 mResolveActivity.applicationInfo = pkg.applicationInfo; 10630 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10631 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10632 mResolveActivity.processName = pkg.applicationInfo.packageName; 10633 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10634 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10635 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10636 mResolveActivity.theme = 0; 10637 mResolveActivity.exported = true; 10638 mResolveActivity.enabled = true; 10639 mResolveInfo.activityInfo = mResolveActivity; 10640 mResolveInfo.priority = 0; 10641 mResolveInfo.preferredOrder = 0; 10642 mResolveInfo.match = 0; 10643 mResolveComponentName = mCustomResolverComponentName; 10644 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10645 mResolveComponentName); 10646 } 10647 } 10648 10649 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10650 if (installerActivity == null) { 10651 if (DEBUG_EPHEMERAL) { 10652 Slog.d(TAG, "Clear ephemeral installer activity"); 10653 } 10654 mInstantAppInstallerActivity = null; 10655 return; 10656 } 10657 10658 if (DEBUG_EPHEMERAL) { 10659 Slog.d(TAG, "Set ephemeral installer activity: " 10660 + installerActivity.getComponentName()); 10661 } 10662 // Set up information for ephemeral installer activity 10663 mInstantAppInstallerActivity = installerActivity; 10664 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10665 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10666 mInstantAppInstallerActivity.exported = true; 10667 mInstantAppInstallerActivity.enabled = true; 10668 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10669 mInstantAppInstallerInfo.priority = 0; 10670 mInstantAppInstallerInfo.preferredOrder = 1; 10671 mInstantAppInstallerInfo.isDefault = true; 10672 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10673 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10674 } 10675 10676 private static String calculateBundledApkRoot(final String codePathString) { 10677 final File codePath = new File(codePathString); 10678 final File codeRoot; 10679 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10680 codeRoot = Environment.getRootDirectory(); 10681 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10682 codeRoot = Environment.getOemDirectory(); 10683 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10684 codeRoot = Environment.getVendorDirectory(); 10685 } else { 10686 // Unrecognized code path; take its top real segment as the apk root: 10687 // e.g. /something/app/blah.apk => /something 10688 try { 10689 File f = codePath.getCanonicalFile(); 10690 File parent = f.getParentFile(); // non-null because codePath is a file 10691 File tmp; 10692 while ((tmp = parent.getParentFile()) != null) { 10693 f = parent; 10694 parent = tmp; 10695 } 10696 codeRoot = f; 10697 Slog.w(TAG, "Unrecognized code path " 10698 + codePath + " - using " + codeRoot); 10699 } catch (IOException e) { 10700 // Can't canonicalize the code path -- shenanigans? 10701 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10702 return Environment.getRootDirectory().getPath(); 10703 } 10704 } 10705 return codeRoot.getPath(); 10706 } 10707 10708 /** 10709 * Derive and set the location of native libraries for the given package, 10710 * which varies depending on where and how the package was installed. 10711 */ 10712 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10713 final ApplicationInfo info = pkg.applicationInfo; 10714 final String codePath = pkg.codePath; 10715 final File codeFile = new File(codePath); 10716 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10717 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10718 10719 info.nativeLibraryRootDir = null; 10720 info.nativeLibraryRootRequiresIsa = false; 10721 info.nativeLibraryDir = null; 10722 info.secondaryNativeLibraryDir = null; 10723 10724 if (isApkFile(codeFile)) { 10725 // Monolithic install 10726 if (bundledApp) { 10727 // If "/system/lib64/apkname" exists, assume that is the per-package 10728 // native library directory to use; otherwise use "/system/lib/apkname". 10729 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10730 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10731 getPrimaryInstructionSet(info)); 10732 10733 // This is a bundled system app so choose the path based on the ABI. 10734 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10735 // is just the default path. 10736 final String apkName = deriveCodePathName(codePath); 10737 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10738 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10739 apkName).getAbsolutePath(); 10740 10741 if (info.secondaryCpuAbi != null) { 10742 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10743 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10744 secondaryLibDir, apkName).getAbsolutePath(); 10745 } 10746 } else if (asecApp) { 10747 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10748 .getAbsolutePath(); 10749 } else { 10750 final String apkName = deriveCodePathName(codePath); 10751 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10752 .getAbsolutePath(); 10753 } 10754 10755 info.nativeLibraryRootRequiresIsa = false; 10756 info.nativeLibraryDir = info.nativeLibraryRootDir; 10757 } else { 10758 // Cluster install 10759 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10760 info.nativeLibraryRootRequiresIsa = true; 10761 10762 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10763 getPrimaryInstructionSet(info)).getAbsolutePath(); 10764 10765 if (info.secondaryCpuAbi != null) { 10766 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10767 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10768 } 10769 } 10770 } 10771 10772 /** 10773 * Calculate the abis and roots for a bundled app. These can uniquely 10774 * be determined from the contents of the system partition, i.e whether 10775 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10776 * of this information, and instead assume that the system was built 10777 * sensibly. 10778 */ 10779 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10780 PackageSetting pkgSetting) { 10781 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10782 10783 // If "/system/lib64/apkname" exists, assume that is the per-package 10784 // native library directory to use; otherwise use "/system/lib/apkname". 10785 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10786 setBundledAppAbi(pkg, apkRoot, apkName); 10787 // pkgSetting might be null during rescan following uninstall of updates 10788 // to a bundled app, so accommodate that possibility. The settings in 10789 // that case will be established later from the parsed package. 10790 // 10791 // If the settings aren't null, sync them up with what we've just derived. 10792 // note that apkRoot isn't stored in the package settings. 10793 if (pkgSetting != null) { 10794 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10795 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10796 } 10797 } 10798 10799 /** 10800 * Deduces the ABI of a bundled app and sets the relevant fields on the 10801 * parsed pkg object. 10802 * 10803 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10804 * under which system libraries are installed. 10805 * @param apkName the name of the installed package. 10806 */ 10807 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10808 final File codeFile = new File(pkg.codePath); 10809 10810 final boolean has64BitLibs; 10811 final boolean has32BitLibs; 10812 if (isApkFile(codeFile)) { 10813 // Monolithic install 10814 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10815 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10816 } else { 10817 // Cluster install 10818 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10819 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10820 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10821 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10822 has64BitLibs = (new File(rootDir, isa)).exists(); 10823 } else { 10824 has64BitLibs = false; 10825 } 10826 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10827 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10828 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10829 has32BitLibs = (new File(rootDir, isa)).exists(); 10830 } else { 10831 has32BitLibs = false; 10832 } 10833 } 10834 10835 if (has64BitLibs && !has32BitLibs) { 10836 // The package has 64 bit libs, but not 32 bit libs. Its primary 10837 // ABI should be 64 bit. We can safely assume here that the bundled 10838 // native libraries correspond to the most preferred ABI in the list. 10839 10840 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10841 pkg.applicationInfo.secondaryCpuAbi = null; 10842 } else if (has32BitLibs && !has64BitLibs) { 10843 // The package has 32 bit libs but not 64 bit libs. Its primary 10844 // ABI should be 32 bit. 10845 10846 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10847 pkg.applicationInfo.secondaryCpuAbi = null; 10848 } else if (has32BitLibs && has64BitLibs) { 10849 // The application has both 64 and 32 bit bundled libraries. We check 10850 // here that the app declares multiArch support, and warn if it doesn't. 10851 // 10852 // We will be lenient here and record both ABIs. The primary will be the 10853 // ABI that's higher on the list, i.e, a device that's configured to prefer 10854 // 64 bit apps will see a 64 bit primary ABI, 10855 10856 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10857 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10858 } 10859 10860 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10861 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10862 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10863 } else { 10864 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10865 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10866 } 10867 } else { 10868 pkg.applicationInfo.primaryCpuAbi = null; 10869 pkg.applicationInfo.secondaryCpuAbi = null; 10870 } 10871 } 10872 10873 private void killApplication(String pkgName, int appId, String reason) { 10874 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10875 } 10876 10877 private void killApplication(String pkgName, int appId, int userId, String reason) { 10878 // Request the ActivityManager to kill the process(only for existing packages) 10879 // so that we do not end up in a confused state while the user is still using the older 10880 // version of the application while the new one gets installed. 10881 final long token = Binder.clearCallingIdentity(); 10882 try { 10883 IActivityManager am = ActivityManager.getService(); 10884 if (am != null) { 10885 try { 10886 am.killApplication(pkgName, appId, userId, reason); 10887 } catch (RemoteException e) { 10888 } 10889 } 10890 } finally { 10891 Binder.restoreCallingIdentity(token); 10892 } 10893 } 10894 10895 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10896 // Remove the parent package setting 10897 PackageSetting ps = (PackageSetting) pkg.mExtras; 10898 if (ps != null) { 10899 removePackageLI(ps, chatty); 10900 } 10901 // Remove the child package setting 10902 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10903 for (int i = 0; i < childCount; i++) { 10904 PackageParser.Package childPkg = pkg.childPackages.get(i); 10905 ps = (PackageSetting) childPkg.mExtras; 10906 if (ps != null) { 10907 removePackageLI(ps, chatty); 10908 } 10909 } 10910 } 10911 10912 void removePackageLI(PackageSetting ps, boolean chatty) { 10913 if (DEBUG_INSTALL) { 10914 if (chatty) 10915 Log.d(TAG, "Removing package " + ps.name); 10916 } 10917 10918 // writer 10919 synchronized (mPackages) { 10920 mPackages.remove(ps.name); 10921 final PackageParser.Package pkg = ps.pkg; 10922 if (pkg != null) { 10923 cleanPackageDataStructuresLILPw(pkg, chatty); 10924 } 10925 } 10926 } 10927 10928 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10929 if (DEBUG_INSTALL) { 10930 if (chatty) 10931 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10932 } 10933 10934 // writer 10935 synchronized (mPackages) { 10936 // Remove the parent package 10937 mPackages.remove(pkg.applicationInfo.packageName); 10938 cleanPackageDataStructuresLILPw(pkg, chatty); 10939 10940 // Remove the child packages 10941 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10942 for (int i = 0; i < childCount; i++) { 10943 PackageParser.Package childPkg = pkg.childPackages.get(i); 10944 mPackages.remove(childPkg.applicationInfo.packageName); 10945 cleanPackageDataStructuresLILPw(childPkg, chatty); 10946 } 10947 } 10948 } 10949 10950 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10951 int N = pkg.providers.size(); 10952 StringBuilder r = null; 10953 int i; 10954 for (i=0; i<N; i++) { 10955 PackageParser.Provider p = pkg.providers.get(i); 10956 mProviders.removeProvider(p); 10957 if (p.info.authority == null) { 10958 10959 /* There was another ContentProvider with this authority when 10960 * this app was installed so this authority is null, 10961 * Ignore it as we don't have to unregister the provider. 10962 */ 10963 continue; 10964 } 10965 String names[] = p.info.authority.split(";"); 10966 for (int j = 0; j < names.length; j++) { 10967 if (mProvidersByAuthority.get(names[j]) == p) { 10968 mProvidersByAuthority.remove(names[j]); 10969 if (DEBUG_REMOVE) { 10970 if (chatty) 10971 Log.d(TAG, "Unregistered content provider: " + names[j] 10972 + ", className = " + p.info.name + ", isSyncable = " 10973 + p.info.isSyncable); 10974 } 10975 } 10976 } 10977 if (DEBUG_REMOVE && chatty) { 10978 if (r == null) { 10979 r = new StringBuilder(256); 10980 } else { 10981 r.append(' '); 10982 } 10983 r.append(p.info.name); 10984 } 10985 } 10986 if (r != null) { 10987 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10988 } 10989 10990 N = pkg.services.size(); 10991 r = null; 10992 for (i=0; i<N; i++) { 10993 PackageParser.Service s = pkg.services.get(i); 10994 mServices.removeService(s); 10995 if (chatty) { 10996 if (r == null) { 10997 r = new StringBuilder(256); 10998 } else { 10999 r.append(' '); 11000 } 11001 r.append(s.info.name); 11002 } 11003 } 11004 if (r != null) { 11005 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11006 } 11007 11008 N = pkg.receivers.size(); 11009 r = null; 11010 for (i=0; i<N; i++) { 11011 PackageParser.Activity a = pkg.receivers.get(i); 11012 mReceivers.removeActivity(a, "receiver"); 11013 if (DEBUG_REMOVE && chatty) { 11014 if (r == null) { 11015 r = new StringBuilder(256); 11016 } else { 11017 r.append(' '); 11018 } 11019 r.append(a.info.name); 11020 } 11021 } 11022 if (r != null) { 11023 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11024 } 11025 11026 N = pkg.activities.size(); 11027 r = null; 11028 for (i=0; i<N; i++) { 11029 PackageParser.Activity a = pkg.activities.get(i); 11030 mActivities.removeActivity(a, "activity"); 11031 if (DEBUG_REMOVE && chatty) { 11032 if (r == null) { 11033 r = new StringBuilder(256); 11034 } else { 11035 r.append(' '); 11036 } 11037 r.append(a.info.name); 11038 } 11039 } 11040 if (r != null) { 11041 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11042 } 11043 11044 N = pkg.permissions.size(); 11045 r = null; 11046 for (i=0; i<N; i++) { 11047 PackageParser.Permission p = pkg.permissions.get(i); 11048 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11049 if (bp == null) { 11050 bp = mSettings.mPermissionTrees.get(p.info.name); 11051 } 11052 if (bp != null && bp.perm == p) { 11053 bp.perm = null; 11054 if (DEBUG_REMOVE && chatty) { 11055 if (r == null) { 11056 r = new StringBuilder(256); 11057 } else { 11058 r.append(' '); 11059 } 11060 r.append(p.info.name); 11061 } 11062 } 11063 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11064 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11065 if (appOpPkgs != null) { 11066 appOpPkgs.remove(pkg.packageName); 11067 } 11068 } 11069 } 11070 if (r != null) { 11071 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11072 } 11073 11074 N = pkg.requestedPermissions.size(); 11075 r = null; 11076 for (i=0; i<N; i++) { 11077 String perm = pkg.requestedPermissions.get(i); 11078 BasePermission bp = mSettings.mPermissions.get(perm); 11079 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11080 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11081 if (appOpPkgs != null) { 11082 appOpPkgs.remove(pkg.packageName); 11083 if (appOpPkgs.isEmpty()) { 11084 mAppOpPermissionPackages.remove(perm); 11085 } 11086 } 11087 } 11088 } 11089 if (r != null) { 11090 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11091 } 11092 11093 N = pkg.instrumentation.size(); 11094 r = null; 11095 for (i=0; i<N; i++) { 11096 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11097 mInstrumentation.remove(a.getComponentName()); 11098 if (DEBUG_REMOVE && chatty) { 11099 if (r == null) { 11100 r = new StringBuilder(256); 11101 } else { 11102 r.append(' '); 11103 } 11104 r.append(a.info.name); 11105 } 11106 } 11107 if (r != null) { 11108 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11109 } 11110 11111 r = null; 11112 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11113 // Only system apps can hold shared libraries. 11114 if (pkg.libraryNames != null) { 11115 for (i = 0; i < pkg.libraryNames.size(); i++) { 11116 String name = pkg.libraryNames.get(i); 11117 if (removeSharedLibraryLPw(name, 0)) { 11118 if (DEBUG_REMOVE && chatty) { 11119 if (r == null) { 11120 r = new StringBuilder(256); 11121 } else { 11122 r.append(' '); 11123 } 11124 r.append(name); 11125 } 11126 } 11127 } 11128 } 11129 } 11130 11131 r = null; 11132 11133 // Any package can hold static shared libraries. 11134 if (pkg.staticSharedLibName != null) { 11135 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11136 if (DEBUG_REMOVE && chatty) { 11137 if (r == null) { 11138 r = new StringBuilder(256); 11139 } else { 11140 r.append(' '); 11141 } 11142 r.append(pkg.staticSharedLibName); 11143 } 11144 } 11145 } 11146 11147 if (r != null) { 11148 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11149 } 11150 } 11151 11152 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11153 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11154 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11155 return true; 11156 } 11157 } 11158 return false; 11159 } 11160 11161 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11162 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11163 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11164 11165 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11166 // Update the parent permissions 11167 updatePermissionsLPw(pkg.packageName, pkg, flags); 11168 // Update the child permissions 11169 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11170 for (int i = 0; i < childCount; i++) { 11171 PackageParser.Package childPkg = pkg.childPackages.get(i); 11172 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11173 } 11174 } 11175 11176 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11177 int flags) { 11178 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11179 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11180 } 11181 11182 private void updatePermissionsLPw(String changingPkg, 11183 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11184 // Make sure there are no dangling permission trees. 11185 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11186 while (it.hasNext()) { 11187 final BasePermission bp = it.next(); 11188 if (bp.packageSetting == null) { 11189 // We may not yet have parsed the package, so just see if 11190 // we still know about its settings. 11191 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11192 } 11193 if (bp.packageSetting == null) { 11194 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11195 + " from package " + bp.sourcePackage); 11196 it.remove(); 11197 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11198 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11199 Slog.i(TAG, "Removing old permission tree: " + bp.name 11200 + " from package " + bp.sourcePackage); 11201 flags |= UPDATE_PERMISSIONS_ALL; 11202 it.remove(); 11203 } 11204 } 11205 } 11206 11207 // Make sure all dynamic permissions have been assigned to a package, 11208 // and make sure there are no dangling permissions. 11209 it = mSettings.mPermissions.values().iterator(); 11210 while (it.hasNext()) { 11211 final BasePermission bp = it.next(); 11212 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11213 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11214 + bp.name + " pkg=" + bp.sourcePackage 11215 + " info=" + bp.pendingInfo); 11216 if (bp.packageSetting == null && bp.pendingInfo != null) { 11217 final BasePermission tree = findPermissionTreeLP(bp.name); 11218 if (tree != null && tree.perm != null) { 11219 bp.packageSetting = tree.packageSetting; 11220 bp.perm = new PackageParser.Permission(tree.perm.owner, 11221 new PermissionInfo(bp.pendingInfo)); 11222 bp.perm.info.packageName = tree.perm.info.packageName; 11223 bp.perm.info.name = bp.name; 11224 bp.uid = tree.uid; 11225 } 11226 } 11227 } 11228 if (bp.packageSetting == null) { 11229 // We may not yet have parsed the package, so just see if 11230 // we still know about its settings. 11231 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11232 } 11233 if (bp.packageSetting == null) { 11234 Slog.w(TAG, "Removing dangling permission: " + bp.name 11235 + " from package " + bp.sourcePackage); 11236 it.remove(); 11237 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11238 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11239 Slog.i(TAG, "Removing old permission: " + bp.name 11240 + " from package " + bp.sourcePackage); 11241 flags |= UPDATE_PERMISSIONS_ALL; 11242 it.remove(); 11243 } 11244 } 11245 } 11246 11247 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11248 // Now update the permissions for all packages, in particular 11249 // replace the granted permissions of the system packages. 11250 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11251 for (PackageParser.Package pkg : mPackages.values()) { 11252 if (pkg != pkgInfo) { 11253 // Only replace for packages on requested volume 11254 final String volumeUuid = getVolumeUuidForPackage(pkg); 11255 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11256 && Objects.equals(replaceVolumeUuid, volumeUuid); 11257 grantPermissionsLPw(pkg, replace, changingPkg); 11258 } 11259 } 11260 } 11261 11262 if (pkgInfo != null) { 11263 // Only replace for packages on requested volume 11264 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11265 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11266 && Objects.equals(replaceVolumeUuid, volumeUuid); 11267 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11268 } 11269 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11270 } 11271 11272 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11273 String packageOfInterest) { 11274 // IMPORTANT: There are two types of permissions: install and runtime. 11275 // Install time permissions are granted when the app is installed to 11276 // all device users and users added in the future. Runtime permissions 11277 // are granted at runtime explicitly to specific users. Normal and signature 11278 // protected permissions are install time permissions. Dangerous permissions 11279 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11280 // otherwise they are runtime permissions. This function does not manage 11281 // runtime permissions except for the case an app targeting Lollipop MR1 11282 // being upgraded to target a newer SDK, in which case dangerous permissions 11283 // are transformed from install time to runtime ones. 11284 11285 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11286 if (ps == null) { 11287 return; 11288 } 11289 11290 PermissionsState permissionsState = ps.getPermissionsState(); 11291 PermissionsState origPermissions = permissionsState; 11292 11293 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11294 11295 boolean runtimePermissionsRevoked = false; 11296 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11297 11298 boolean changedInstallPermission = false; 11299 11300 if (replace) { 11301 ps.installPermissionsFixed = false; 11302 if (!ps.isSharedUser()) { 11303 origPermissions = new PermissionsState(permissionsState); 11304 permissionsState.reset(); 11305 } else { 11306 // We need to know only about runtime permission changes since the 11307 // calling code always writes the install permissions state but 11308 // the runtime ones are written only if changed. The only cases of 11309 // changed runtime permissions here are promotion of an install to 11310 // runtime and revocation of a runtime from a shared user. 11311 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11312 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11313 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11314 runtimePermissionsRevoked = true; 11315 } 11316 } 11317 } 11318 11319 permissionsState.setGlobalGids(mGlobalGids); 11320 11321 final int N = pkg.requestedPermissions.size(); 11322 for (int i=0; i<N; i++) { 11323 final String name = pkg.requestedPermissions.get(i); 11324 final BasePermission bp = mSettings.mPermissions.get(name); 11325 11326 if (DEBUG_INSTALL) { 11327 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11328 } 11329 11330 if (bp == null || bp.packageSetting == null) { 11331 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11332 Slog.w(TAG, "Unknown permission " + name 11333 + " in package " + pkg.packageName); 11334 } 11335 continue; 11336 } 11337 11338 11339 // Limit ephemeral apps to ephemeral allowed permissions. 11340 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11341 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11342 + pkg.packageName); 11343 continue; 11344 } 11345 11346 final String perm = bp.name; 11347 boolean allowedSig = false; 11348 int grant = GRANT_DENIED; 11349 11350 // Keep track of app op permissions. 11351 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11352 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11353 if (pkgs == null) { 11354 pkgs = new ArraySet<>(); 11355 mAppOpPermissionPackages.put(bp.name, pkgs); 11356 } 11357 pkgs.add(pkg.packageName); 11358 } 11359 11360 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11361 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11362 >= Build.VERSION_CODES.M; 11363 switch (level) { 11364 case PermissionInfo.PROTECTION_NORMAL: { 11365 // For all apps normal permissions are install time ones. 11366 grant = GRANT_INSTALL; 11367 } break; 11368 11369 case PermissionInfo.PROTECTION_DANGEROUS: { 11370 // If a permission review is required for legacy apps we represent 11371 // their permissions as always granted runtime ones since we need 11372 // to keep the review required permission flag per user while an 11373 // install permission's state is shared across all users. 11374 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11375 // For legacy apps dangerous permissions are install time ones. 11376 grant = GRANT_INSTALL; 11377 } else if (origPermissions.hasInstallPermission(bp.name)) { 11378 // For legacy apps that became modern, install becomes runtime. 11379 grant = GRANT_UPGRADE; 11380 } else if (mPromoteSystemApps 11381 && isSystemApp(ps) 11382 && mExistingSystemPackages.contains(ps.name)) { 11383 // For legacy system apps, install becomes runtime. 11384 // We cannot check hasInstallPermission() for system apps since those 11385 // permissions were granted implicitly and not persisted pre-M. 11386 grant = GRANT_UPGRADE; 11387 } else { 11388 // For modern apps keep runtime permissions unchanged. 11389 grant = GRANT_RUNTIME; 11390 } 11391 } break; 11392 11393 case PermissionInfo.PROTECTION_SIGNATURE: { 11394 // For all apps signature permissions are install time ones. 11395 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11396 if (allowedSig) { 11397 grant = GRANT_INSTALL; 11398 } 11399 } break; 11400 } 11401 11402 if (DEBUG_INSTALL) { 11403 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11404 } 11405 11406 if (grant != GRANT_DENIED) { 11407 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11408 // If this is an existing, non-system package, then 11409 // we can't add any new permissions to it. 11410 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11411 // Except... if this is a permission that was added 11412 // to the platform (note: need to only do this when 11413 // updating the platform). 11414 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11415 grant = GRANT_DENIED; 11416 } 11417 } 11418 } 11419 11420 switch (grant) { 11421 case GRANT_INSTALL: { 11422 // Revoke this as runtime permission to handle the case of 11423 // a runtime permission being downgraded to an install one. 11424 // Also in permission review mode we keep dangerous permissions 11425 // for legacy apps 11426 for (int userId : UserManagerService.getInstance().getUserIds()) { 11427 if (origPermissions.getRuntimePermissionState( 11428 bp.name, userId) != null) { 11429 // Revoke the runtime permission and clear the flags. 11430 origPermissions.revokeRuntimePermission(bp, userId); 11431 origPermissions.updatePermissionFlags(bp, userId, 11432 PackageManager.MASK_PERMISSION_FLAGS, 0); 11433 // If we revoked a permission permission, we have to write. 11434 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11435 changedRuntimePermissionUserIds, userId); 11436 } 11437 } 11438 // Grant an install permission. 11439 if (permissionsState.grantInstallPermission(bp) != 11440 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11441 changedInstallPermission = true; 11442 } 11443 } break; 11444 11445 case GRANT_RUNTIME: { 11446 // Grant previously granted runtime permissions. 11447 for (int userId : UserManagerService.getInstance().getUserIds()) { 11448 PermissionState permissionState = origPermissions 11449 .getRuntimePermissionState(bp.name, userId); 11450 int flags = permissionState != null 11451 ? permissionState.getFlags() : 0; 11452 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11453 // Don't propagate the permission in a permission review mode if 11454 // the former was revoked, i.e. marked to not propagate on upgrade. 11455 // Note that in a permission review mode install permissions are 11456 // represented as constantly granted runtime ones since we need to 11457 // keep a per user state associated with the permission. Also the 11458 // revoke on upgrade flag is no longer applicable and is reset. 11459 final boolean revokeOnUpgrade = (flags & PackageManager 11460 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11461 if (revokeOnUpgrade) { 11462 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11463 // Since we changed the flags, we have to write. 11464 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11465 changedRuntimePermissionUserIds, userId); 11466 } 11467 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11468 if (permissionsState.grantRuntimePermission(bp, userId) == 11469 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11470 // If we cannot put the permission as it was, 11471 // we have to write. 11472 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11473 changedRuntimePermissionUserIds, userId); 11474 } 11475 } 11476 11477 // If the app supports runtime permissions no need for a review. 11478 if (mPermissionReviewRequired 11479 && appSupportsRuntimePermissions 11480 && (flags & PackageManager 11481 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11482 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11483 // Since we changed the flags, we have to write. 11484 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11485 changedRuntimePermissionUserIds, userId); 11486 } 11487 } else if (mPermissionReviewRequired 11488 && !appSupportsRuntimePermissions) { 11489 // For legacy apps that need a permission review, every new 11490 // runtime permission is granted but it is pending a review. 11491 // We also need to review only platform defined runtime 11492 // permissions as these are the only ones the platform knows 11493 // how to disable the API to simulate revocation as legacy 11494 // apps don't expect to run with revoked permissions. 11495 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11496 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11497 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11498 // We changed the flags, hence have to write. 11499 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11500 changedRuntimePermissionUserIds, userId); 11501 } 11502 } 11503 if (permissionsState.grantRuntimePermission(bp, userId) 11504 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11505 // We changed the permission, hence have to write. 11506 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11507 changedRuntimePermissionUserIds, userId); 11508 } 11509 } 11510 // Propagate the permission flags. 11511 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11512 } 11513 } break; 11514 11515 case GRANT_UPGRADE: { 11516 // Grant runtime permissions for a previously held install permission. 11517 PermissionState permissionState = origPermissions 11518 .getInstallPermissionState(bp.name); 11519 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11520 11521 if (origPermissions.revokeInstallPermission(bp) 11522 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11523 // We will be transferring the permission flags, so clear them. 11524 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11525 PackageManager.MASK_PERMISSION_FLAGS, 0); 11526 changedInstallPermission = true; 11527 } 11528 11529 // If the permission is not to be promoted to runtime we ignore it and 11530 // also its other flags as they are not applicable to install permissions. 11531 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11532 for (int userId : currentUserIds) { 11533 if (permissionsState.grantRuntimePermission(bp, userId) != 11534 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11535 // Transfer the permission flags. 11536 permissionsState.updatePermissionFlags(bp, userId, 11537 flags, flags); 11538 // If we granted the permission, we have to write. 11539 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11540 changedRuntimePermissionUserIds, userId); 11541 } 11542 } 11543 } 11544 } break; 11545 11546 default: { 11547 if (packageOfInterest == null 11548 || packageOfInterest.equals(pkg.packageName)) { 11549 Slog.w(TAG, "Not granting permission " + perm 11550 + " to package " + pkg.packageName 11551 + " because it was previously installed without"); 11552 } 11553 } break; 11554 } 11555 } else { 11556 if (permissionsState.revokeInstallPermission(bp) != 11557 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11558 // Also drop the permission flags. 11559 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11560 PackageManager.MASK_PERMISSION_FLAGS, 0); 11561 changedInstallPermission = true; 11562 Slog.i(TAG, "Un-granting permission " + perm 11563 + " from package " + pkg.packageName 11564 + " (protectionLevel=" + bp.protectionLevel 11565 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11566 + ")"); 11567 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11568 // Don't print warning for app op permissions, since it is fine for them 11569 // not to be granted, there is a UI for the user to decide. 11570 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11571 Slog.w(TAG, "Not granting permission " + perm 11572 + " to package " + pkg.packageName 11573 + " (protectionLevel=" + bp.protectionLevel 11574 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11575 + ")"); 11576 } 11577 } 11578 } 11579 } 11580 11581 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11582 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11583 // This is the first that we have heard about this package, so the 11584 // permissions we have now selected are fixed until explicitly 11585 // changed. 11586 ps.installPermissionsFixed = true; 11587 } 11588 11589 // Persist the runtime permissions state for users with changes. If permissions 11590 // were revoked because no app in the shared user declares them we have to 11591 // write synchronously to avoid losing runtime permissions state. 11592 for (int userId : changedRuntimePermissionUserIds) { 11593 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11594 } 11595 } 11596 11597 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11598 boolean allowed = false; 11599 final int NP = PackageParser.NEW_PERMISSIONS.length; 11600 for (int ip=0; ip<NP; ip++) { 11601 final PackageParser.NewPermissionInfo npi 11602 = PackageParser.NEW_PERMISSIONS[ip]; 11603 if (npi.name.equals(perm) 11604 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11605 allowed = true; 11606 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11607 + pkg.packageName); 11608 break; 11609 } 11610 } 11611 return allowed; 11612 } 11613 11614 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11615 BasePermission bp, PermissionsState origPermissions) { 11616 boolean privilegedPermission = (bp.protectionLevel 11617 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11618 boolean privappPermissionsDisable = 11619 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11620 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11621 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11622 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11623 && !platformPackage && platformPermission) { 11624 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11625 .getPrivAppPermissions(pkg.packageName); 11626 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11627 if (!whitelisted) { 11628 Slog.w(TAG, "Privileged permission " + perm + " for package " 11629 + pkg.packageName + " - not in privapp-permissions whitelist"); 11630 // Only report violations for apps on system image 11631 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11632 if (mPrivappPermissionsViolations == null) { 11633 mPrivappPermissionsViolations = new ArraySet<>(); 11634 } 11635 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11636 } 11637 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11638 return false; 11639 } 11640 } 11641 } 11642 boolean allowed = (compareSignatures( 11643 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11644 == PackageManager.SIGNATURE_MATCH) 11645 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11646 == PackageManager.SIGNATURE_MATCH); 11647 if (!allowed && privilegedPermission) { 11648 if (isSystemApp(pkg)) { 11649 // For updated system applications, a system permission 11650 // is granted only if it had been defined by the original application. 11651 if (pkg.isUpdatedSystemApp()) { 11652 final PackageSetting sysPs = mSettings 11653 .getDisabledSystemPkgLPr(pkg.packageName); 11654 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11655 // If the original was granted this permission, we take 11656 // that grant decision as read and propagate it to the 11657 // update. 11658 if (sysPs.isPrivileged()) { 11659 allowed = true; 11660 } 11661 } else { 11662 // The system apk may have been updated with an older 11663 // version of the one on the data partition, but which 11664 // granted a new system permission that it didn't have 11665 // before. In this case we do want to allow the app to 11666 // now get the new permission if the ancestral apk is 11667 // privileged to get it. 11668 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11669 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11670 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11671 allowed = true; 11672 break; 11673 } 11674 } 11675 } 11676 // Also if a privileged parent package on the system image or any of 11677 // its children requested a privileged permission, the updated child 11678 // packages can also get the permission. 11679 if (pkg.parentPackage != null) { 11680 final PackageSetting disabledSysParentPs = mSettings 11681 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11682 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11683 && disabledSysParentPs.isPrivileged()) { 11684 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11685 allowed = true; 11686 } else if (disabledSysParentPs.pkg.childPackages != null) { 11687 final int count = disabledSysParentPs.pkg.childPackages.size(); 11688 for (int i = 0; i < count; i++) { 11689 PackageParser.Package disabledSysChildPkg = 11690 disabledSysParentPs.pkg.childPackages.get(i); 11691 if (isPackageRequestingPermission(disabledSysChildPkg, 11692 perm)) { 11693 allowed = true; 11694 break; 11695 } 11696 } 11697 } 11698 } 11699 } 11700 } 11701 } else { 11702 allowed = isPrivilegedApp(pkg); 11703 } 11704 } 11705 } 11706 if (!allowed) { 11707 if (!allowed && (bp.protectionLevel 11708 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11709 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11710 // If this was a previously normal/dangerous permission that got moved 11711 // to a system permission as part of the runtime permission redesign, then 11712 // we still want to blindly grant it to old apps. 11713 allowed = true; 11714 } 11715 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11716 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11717 // If this permission is to be granted to the system installer and 11718 // this app is an installer, then it gets the permission. 11719 allowed = true; 11720 } 11721 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11722 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11723 // If this permission is to be granted to the system verifier and 11724 // this app is a verifier, then it gets the permission. 11725 allowed = true; 11726 } 11727 if (!allowed && (bp.protectionLevel 11728 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11729 && isSystemApp(pkg)) { 11730 // Any pre-installed system app is allowed to get this permission. 11731 allowed = true; 11732 } 11733 if (!allowed && (bp.protectionLevel 11734 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11735 // For development permissions, a development permission 11736 // is granted only if it was already granted. 11737 allowed = origPermissions.hasInstallPermission(perm); 11738 } 11739 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11740 && pkg.packageName.equals(mSetupWizardPackage)) { 11741 // If this permission is to be granted to the system setup wizard and 11742 // this app is a setup wizard, then it gets the permission. 11743 allowed = true; 11744 } 11745 } 11746 return allowed; 11747 } 11748 11749 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11750 final int permCount = pkg.requestedPermissions.size(); 11751 for (int j = 0; j < permCount; j++) { 11752 String requestedPermission = pkg.requestedPermissions.get(j); 11753 if (permission.equals(requestedPermission)) { 11754 return true; 11755 } 11756 } 11757 return false; 11758 } 11759 11760 final class ActivityIntentResolver 11761 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11762 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11763 boolean defaultOnly, int userId) { 11764 if (!sUserManager.exists(userId)) return null; 11765 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11766 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11767 } 11768 11769 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11770 int userId) { 11771 if (!sUserManager.exists(userId)) return null; 11772 mFlags = flags; 11773 return super.queryIntent(intent, resolvedType, 11774 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11775 userId); 11776 } 11777 11778 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11779 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11780 if (!sUserManager.exists(userId)) return null; 11781 if (packageActivities == null) { 11782 return null; 11783 } 11784 mFlags = flags; 11785 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11786 final int N = packageActivities.size(); 11787 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11788 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11789 11790 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11791 for (int i = 0; i < N; ++i) { 11792 intentFilters = packageActivities.get(i).intents; 11793 if (intentFilters != null && intentFilters.size() > 0) { 11794 PackageParser.ActivityIntentInfo[] array = 11795 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11796 intentFilters.toArray(array); 11797 listCut.add(array); 11798 } 11799 } 11800 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11801 } 11802 11803 /** 11804 * Finds a privileged activity that matches the specified activity names. 11805 */ 11806 private PackageParser.Activity findMatchingActivity( 11807 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11808 for (PackageParser.Activity sysActivity : activityList) { 11809 if (sysActivity.info.name.equals(activityInfo.name)) { 11810 return sysActivity; 11811 } 11812 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11813 return sysActivity; 11814 } 11815 if (sysActivity.info.targetActivity != null) { 11816 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11817 return sysActivity; 11818 } 11819 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11820 return sysActivity; 11821 } 11822 } 11823 } 11824 return null; 11825 } 11826 11827 public class IterGenerator<E> { 11828 public Iterator<E> generate(ActivityIntentInfo info) { 11829 return null; 11830 } 11831 } 11832 11833 public class ActionIterGenerator extends IterGenerator<String> { 11834 @Override 11835 public Iterator<String> generate(ActivityIntentInfo info) { 11836 return info.actionsIterator(); 11837 } 11838 } 11839 11840 public class CategoriesIterGenerator extends IterGenerator<String> { 11841 @Override 11842 public Iterator<String> generate(ActivityIntentInfo info) { 11843 return info.categoriesIterator(); 11844 } 11845 } 11846 11847 public class SchemesIterGenerator extends IterGenerator<String> { 11848 @Override 11849 public Iterator<String> generate(ActivityIntentInfo info) { 11850 return info.schemesIterator(); 11851 } 11852 } 11853 11854 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11855 @Override 11856 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11857 return info.authoritiesIterator(); 11858 } 11859 } 11860 11861 /** 11862 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11863 * MODIFIED. Do not pass in a list that should not be changed. 11864 */ 11865 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11866 IterGenerator<T> generator, Iterator<T> searchIterator) { 11867 // loop through the set of actions; every one must be found in the intent filter 11868 while (searchIterator.hasNext()) { 11869 // we must have at least one filter in the list to consider a match 11870 if (intentList.size() == 0) { 11871 break; 11872 } 11873 11874 final T searchAction = searchIterator.next(); 11875 11876 // loop through the set of intent filters 11877 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11878 while (intentIter.hasNext()) { 11879 final ActivityIntentInfo intentInfo = intentIter.next(); 11880 boolean selectionFound = false; 11881 11882 // loop through the intent filter's selection criteria; at least one 11883 // of them must match the searched criteria 11884 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11885 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11886 final T intentSelection = intentSelectionIter.next(); 11887 if (intentSelection != null && intentSelection.equals(searchAction)) { 11888 selectionFound = true; 11889 break; 11890 } 11891 } 11892 11893 // the selection criteria wasn't found in this filter's set; this filter 11894 // is not a potential match 11895 if (!selectionFound) { 11896 intentIter.remove(); 11897 } 11898 } 11899 } 11900 } 11901 11902 private boolean isProtectedAction(ActivityIntentInfo filter) { 11903 final Iterator<String> actionsIter = filter.actionsIterator(); 11904 while (actionsIter != null && actionsIter.hasNext()) { 11905 final String filterAction = actionsIter.next(); 11906 if (PROTECTED_ACTIONS.contains(filterAction)) { 11907 return true; 11908 } 11909 } 11910 return false; 11911 } 11912 11913 /** 11914 * Adjusts the priority of the given intent filter according to policy. 11915 * <p> 11916 * <ul> 11917 * <li>The priority for non privileged applications is capped to '0'</li> 11918 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11919 * <li>The priority for unbundled updates to privileged applications is capped to the 11920 * priority defined on the system partition</li> 11921 * </ul> 11922 * <p> 11923 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11924 * allowed to obtain any priority on any action. 11925 */ 11926 private void adjustPriority( 11927 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11928 // nothing to do; priority is fine as-is 11929 if (intent.getPriority() <= 0) { 11930 return; 11931 } 11932 11933 final ActivityInfo activityInfo = intent.activity.info; 11934 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11935 11936 final boolean privilegedApp = 11937 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11938 if (!privilegedApp) { 11939 // non-privileged applications can never define a priority >0 11940 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11941 + " package: " + applicationInfo.packageName 11942 + " activity: " + intent.activity.className 11943 + " origPrio: " + intent.getPriority()); 11944 intent.setPriority(0); 11945 return; 11946 } 11947 11948 if (systemActivities == null) { 11949 // the system package is not disabled; we're parsing the system partition 11950 if (isProtectedAction(intent)) { 11951 if (mDeferProtectedFilters) { 11952 // We can't deal with these just yet. No component should ever obtain a 11953 // >0 priority for a protected actions, with ONE exception -- the setup 11954 // wizard. The setup wizard, however, cannot be known until we're able to 11955 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11956 // until all intent filters have been processed. Chicken, meet egg. 11957 // Let the filter temporarily have a high priority and rectify the 11958 // priorities after all system packages have been scanned. 11959 mProtectedFilters.add(intent); 11960 if (DEBUG_FILTERS) { 11961 Slog.i(TAG, "Protected action; save for later;" 11962 + " package: " + applicationInfo.packageName 11963 + " activity: " + intent.activity.className 11964 + " origPrio: " + intent.getPriority()); 11965 } 11966 return; 11967 } else { 11968 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11969 Slog.i(TAG, "No setup wizard;" 11970 + " All protected intents capped to priority 0"); 11971 } 11972 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11973 if (DEBUG_FILTERS) { 11974 Slog.i(TAG, "Found setup wizard;" 11975 + " allow priority " + intent.getPriority() + ";" 11976 + " package: " + intent.activity.info.packageName 11977 + " activity: " + intent.activity.className 11978 + " priority: " + intent.getPriority()); 11979 } 11980 // setup wizard gets whatever it wants 11981 return; 11982 } 11983 Slog.w(TAG, "Protected action; cap priority to 0;" 11984 + " package: " + intent.activity.info.packageName 11985 + " activity: " + intent.activity.className 11986 + " origPrio: " + intent.getPriority()); 11987 intent.setPriority(0); 11988 return; 11989 } 11990 } 11991 // privileged apps on the system image get whatever priority they request 11992 return; 11993 } 11994 11995 // privileged app unbundled update ... try to find the same activity 11996 final PackageParser.Activity foundActivity = 11997 findMatchingActivity(systemActivities, activityInfo); 11998 if (foundActivity == null) { 11999 // this is a new activity; it cannot obtain >0 priority 12000 if (DEBUG_FILTERS) { 12001 Slog.i(TAG, "New activity; cap priority to 0;" 12002 + " package: " + applicationInfo.packageName 12003 + " activity: " + intent.activity.className 12004 + " origPrio: " + intent.getPriority()); 12005 } 12006 intent.setPriority(0); 12007 return; 12008 } 12009 12010 // found activity, now check for filter equivalence 12011 12012 // a shallow copy is enough; we modify the list, not its contents 12013 final List<ActivityIntentInfo> intentListCopy = 12014 new ArrayList<>(foundActivity.intents); 12015 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12016 12017 // find matching action subsets 12018 final Iterator<String> actionsIterator = intent.actionsIterator(); 12019 if (actionsIterator != null) { 12020 getIntentListSubset( 12021 intentListCopy, new ActionIterGenerator(), actionsIterator); 12022 if (intentListCopy.size() == 0) { 12023 // no more intents to match; we're not equivalent 12024 if (DEBUG_FILTERS) { 12025 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12026 + " package: " + applicationInfo.packageName 12027 + " activity: " + intent.activity.className 12028 + " origPrio: " + intent.getPriority()); 12029 } 12030 intent.setPriority(0); 12031 return; 12032 } 12033 } 12034 12035 // find matching category subsets 12036 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12037 if (categoriesIterator != null) { 12038 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12039 categoriesIterator); 12040 if (intentListCopy.size() == 0) { 12041 // no more intents to match; we're not equivalent 12042 if (DEBUG_FILTERS) { 12043 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12044 + " package: " + applicationInfo.packageName 12045 + " activity: " + intent.activity.className 12046 + " origPrio: " + intent.getPriority()); 12047 } 12048 intent.setPriority(0); 12049 return; 12050 } 12051 } 12052 12053 // find matching schemes subsets 12054 final Iterator<String> schemesIterator = intent.schemesIterator(); 12055 if (schemesIterator != null) { 12056 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12057 schemesIterator); 12058 if (intentListCopy.size() == 0) { 12059 // no more intents to match; we're not equivalent 12060 if (DEBUG_FILTERS) { 12061 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12062 + " package: " + applicationInfo.packageName 12063 + " activity: " + intent.activity.className 12064 + " origPrio: " + intent.getPriority()); 12065 } 12066 intent.setPriority(0); 12067 return; 12068 } 12069 } 12070 12071 // find matching authorities subsets 12072 final Iterator<IntentFilter.AuthorityEntry> 12073 authoritiesIterator = intent.authoritiesIterator(); 12074 if (authoritiesIterator != null) { 12075 getIntentListSubset(intentListCopy, 12076 new AuthoritiesIterGenerator(), 12077 authoritiesIterator); 12078 if (intentListCopy.size() == 0) { 12079 // no more intents to match; we're not equivalent 12080 if (DEBUG_FILTERS) { 12081 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12082 + " package: " + applicationInfo.packageName 12083 + " activity: " + intent.activity.className 12084 + " origPrio: " + intent.getPriority()); 12085 } 12086 intent.setPriority(0); 12087 return; 12088 } 12089 } 12090 12091 // we found matching filter(s); app gets the max priority of all intents 12092 int cappedPriority = 0; 12093 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12094 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12095 } 12096 if (intent.getPriority() > cappedPriority) { 12097 if (DEBUG_FILTERS) { 12098 Slog.i(TAG, "Found matching filter(s);" 12099 + " cap priority to " + cappedPriority + ";" 12100 + " package: " + applicationInfo.packageName 12101 + " activity: " + intent.activity.className 12102 + " origPrio: " + intent.getPriority()); 12103 } 12104 intent.setPriority(cappedPriority); 12105 return; 12106 } 12107 // all this for nothing; the requested priority was <= what was on the system 12108 } 12109 12110 public final void addActivity(PackageParser.Activity a, String type) { 12111 mActivities.put(a.getComponentName(), a); 12112 if (DEBUG_SHOW_INFO) 12113 Log.v( 12114 TAG, " " + type + " " + 12115 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12116 if (DEBUG_SHOW_INFO) 12117 Log.v(TAG, " Class=" + a.info.name); 12118 final int NI = a.intents.size(); 12119 for (int j=0; j<NI; j++) { 12120 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12121 if ("activity".equals(type)) { 12122 final PackageSetting ps = 12123 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12124 final List<PackageParser.Activity> systemActivities = 12125 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12126 adjustPriority(systemActivities, intent); 12127 } 12128 if (DEBUG_SHOW_INFO) { 12129 Log.v(TAG, " IntentFilter:"); 12130 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12131 } 12132 if (!intent.debugCheck()) { 12133 Log.w(TAG, "==> For Activity " + a.info.name); 12134 } 12135 addFilter(intent); 12136 } 12137 } 12138 12139 public final void removeActivity(PackageParser.Activity a, String type) { 12140 mActivities.remove(a.getComponentName()); 12141 if (DEBUG_SHOW_INFO) { 12142 Log.v(TAG, " " + type + " " 12143 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12144 : a.info.name) + ":"); 12145 Log.v(TAG, " Class=" + a.info.name); 12146 } 12147 final int NI = a.intents.size(); 12148 for (int j=0; j<NI; j++) { 12149 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12150 if (DEBUG_SHOW_INFO) { 12151 Log.v(TAG, " IntentFilter:"); 12152 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12153 } 12154 removeFilter(intent); 12155 } 12156 } 12157 12158 @Override 12159 protected boolean allowFilterResult( 12160 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12161 ActivityInfo filterAi = filter.activity.info; 12162 for (int i=dest.size()-1; i>=0; i--) { 12163 ActivityInfo destAi = dest.get(i).activityInfo; 12164 if (destAi.name == filterAi.name 12165 && destAi.packageName == filterAi.packageName) { 12166 return false; 12167 } 12168 } 12169 return true; 12170 } 12171 12172 @Override 12173 protected ActivityIntentInfo[] newArray(int size) { 12174 return new ActivityIntentInfo[size]; 12175 } 12176 12177 @Override 12178 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12179 if (!sUserManager.exists(userId)) return true; 12180 PackageParser.Package p = filter.activity.owner; 12181 if (p != null) { 12182 PackageSetting ps = (PackageSetting)p.mExtras; 12183 if (ps != null) { 12184 // System apps are never considered stopped for purposes of 12185 // filtering, because there may be no way for the user to 12186 // actually re-launch them. 12187 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12188 && ps.getStopped(userId); 12189 } 12190 } 12191 return false; 12192 } 12193 12194 @Override 12195 protected boolean isPackageForFilter(String packageName, 12196 PackageParser.ActivityIntentInfo info) { 12197 return packageName.equals(info.activity.owner.packageName); 12198 } 12199 12200 @Override 12201 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12202 int match, int userId) { 12203 if (!sUserManager.exists(userId)) return null; 12204 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12205 return null; 12206 } 12207 final PackageParser.Activity activity = info.activity; 12208 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12209 if (ps == null) { 12210 return null; 12211 } 12212 final PackageUserState userState = ps.readUserState(userId); 12213 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12214 userState, userId); 12215 if (ai == null) { 12216 return null; 12217 } 12218 final boolean matchVisibleToInstantApp = 12219 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12220 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12221 // throw out filters that aren't visible to ephemeral apps 12222 if (matchVisibleToInstantApp 12223 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12224 return null; 12225 } 12226 // throw out ephemeral filters if we're not explicitly requesting them 12227 if (!isInstantApp && userState.instantApp) { 12228 return null; 12229 } 12230 // throw out instant app filters if updates are available; will trigger 12231 // instant app resolution 12232 if (userState.instantApp && ps.isUpdateAvailable()) { 12233 return null; 12234 } 12235 final ResolveInfo res = new ResolveInfo(); 12236 res.activityInfo = ai; 12237 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12238 res.filter = info; 12239 } 12240 if (info != null) { 12241 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12242 } 12243 res.priority = info.getPriority(); 12244 res.preferredOrder = activity.owner.mPreferredOrder; 12245 //System.out.println("Result: " + res.activityInfo.className + 12246 // " = " + res.priority); 12247 res.match = match; 12248 res.isDefault = info.hasDefault; 12249 res.labelRes = info.labelRes; 12250 res.nonLocalizedLabel = info.nonLocalizedLabel; 12251 if (userNeedsBadging(userId)) { 12252 res.noResourceId = true; 12253 } else { 12254 res.icon = info.icon; 12255 } 12256 res.iconResourceId = info.icon; 12257 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12258 res.instantAppAvailable = userState.instantApp; 12259 return res; 12260 } 12261 12262 @Override 12263 protected void sortResults(List<ResolveInfo> results) { 12264 Collections.sort(results, mResolvePrioritySorter); 12265 } 12266 12267 @Override 12268 protected void dumpFilter(PrintWriter out, String prefix, 12269 PackageParser.ActivityIntentInfo filter) { 12270 out.print(prefix); out.print( 12271 Integer.toHexString(System.identityHashCode(filter.activity))); 12272 out.print(' '); 12273 filter.activity.printComponentShortName(out); 12274 out.print(" filter "); 12275 out.println(Integer.toHexString(System.identityHashCode(filter))); 12276 } 12277 12278 @Override 12279 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12280 return filter.activity; 12281 } 12282 12283 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12284 PackageParser.Activity activity = (PackageParser.Activity)label; 12285 out.print(prefix); out.print( 12286 Integer.toHexString(System.identityHashCode(activity))); 12287 out.print(' '); 12288 activity.printComponentShortName(out); 12289 if (count > 1) { 12290 out.print(" ("); out.print(count); out.print(" filters)"); 12291 } 12292 out.println(); 12293 } 12294 12295 // Keys are String (activity class name), values are Activity. 12296 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12297 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12298 private int mFlags; 12299 } 12300 12301 private final class ServiceIntentResolver 12302 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12303 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12304 boolean defaultOnly, int userId) { 12305 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12306 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12307 } 12308 12309 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12310 int userId) { 12311 if (!sUserManager.exists(userId)) return null; 12312 mFlags = flags; 12313 return super.queryIntent(intent, resolvedType, 12314 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12315 userId); 12316 } 12317 12318 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12319 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12320 if (!sUserManager.exists(userId)) return null; 12321 if (packageServices == null) { 12322 return null; 12323 } 12324 mFlags = flags; 12325 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12326 final int N = packageServices.size(); 12327 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12328 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12329 12330 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12331 for (int i = 0; i < N; ++i) { 12332 intentFilters = packageServices.get(i).intents; 12333 if (intentFilters != null && intentFilters.size() > 0) { 12334 PackageParser.ServiceIntentInfo[] array = 12335 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12336 intentFilters.toArray(array); 12337 listCut.add(array); 12338 } 12339 } 12340 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12341 } 12342 12343 public final void addService(PackageParser.Service s) { 12344 mServices.put(s.getComponentName(), s); 12345 if (DEBUG_SHOW_INFO) { 12346 Log.v(TAG, " " 12347 + (s.info.nonLocalizedLabel != null 12348 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12349 Log.v(TAG, " Class=" + s.info.name); 12350 } 12351 final int NI = s.intents.size(); 12352 int j; 12353 for (j=0; j<NI; j++) { 12354 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12355 if (DEBUG_SHOW_INFO) { 12356 Log.v(TAG, " IntentFilter:"); 12357 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12358 } 12359 if (!intent.debugCheck()) { 12360 Log.w(TAG, "==> For Service " + s.info.name); 12361 } 12362 addFilter(intent); 12363 } 12364 } 12365 12366 public final void removeService(PackageParser.Service s) { 12367 mServices.remove(s.getComponentName()); 12368 if (DEBUG_SHOW_INFO) { 12369 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12370 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12371 Log.v(TAG, " Class=" + s.info.name); 12372 } 12373 final int NI = s.intents.size(); 12374 int j; 12375 for (j=0; j<NI; j++) { 12376 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12377 if (DEBUG_SHOW_INFO) { 12378 Log.v(TAG, " IntentFilter:"); 12379 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12380 } 12381 removeFilter(intent); 12382 } 12383 } 12384 12385 @Override 12386 protected boolean allowFilterResult( 12387 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12388 ServiceInfo filterSi = filter.service.info; 12389 for (int i=dest.size()-1; i>=0; i--) { 12390 ServiceInfo destAi = dest.get(i).serviceInfo; 12391 if (destAi.name == filterSi.name 12392 && destAi.packageName == filterSi.packageName) { 12393 return false; 12394 } 12395 } 12396 return true; 12397 } 12398 12399 @Override 12400 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12401 return new PackageParser.ServiceIntentInfo[size]; 12402 } 12403 12404 @Override 12405 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12406 if (!sUserManager.exists(userId)) return true; 12407 PackageParser.Package p = filter.service.owner; 12408 if (p != null) { 12409 PackageSetting ps = (PackageSetting)p.mExtras; 12410 if (ps != null) { 12411 // System apps are never considered stopped for purposes of 12412 // filtering, because there may be no way for the user to 12413 // actually re-launch them. 12414 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12415 && ps.getStopped(userId); 12416 } 12417 } 12418 return false; 12419 } 12420 12421 @Override 12422 protected boolean isPackageForFilter(String packageName, 12423 PackageParser.ServiceIntentInfo info) { 12424 return packageName.equals(info.service.owner.packageName); 12425 } 12426 12427 @Override 12428 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12429 int match, int userId) { 12430 if (!sUserManager.exists(userId)) return null; 12431 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12432 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12433 return null; 12434 } 12435 final PackageParser.Service service = info.service; 12436 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12437 if (ps == null) { 12438 return null; 12439 } 12440 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12441 ps.readUserState(userId), userId); 12442 if (si == null) { 12443 return null; 12444 } 12445 final ResolveInfo res = new ResolveInfo(); 12446 res.serviceInfo = si; 12447 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12448 res.filter = filter; 12449 } 12450 res.priority = info.getPriority(); 12451 res.preferredOrder = service.owner.mPreferredOrder; 12452 res.match = match; 12453 res.isDefault = info.hasDefault; 12454 res.labelRes = info.labelRes; 12455 res.nonLocalizedLabel = info.nonLocalizedLabel; 12456 res.icon = info.icon; 12457 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12458 return res; 12459 } 12460 12461 @Override 12462 protected void sortResults(List<ResolveInfo> results) { 12463 Collections.sort(results, mResolvePrioritySorter); 12464 } 12465 12466 @Override 12467 protected void dumpFilter(PrintWriter out, String prefix, 12468 PackageParser.ServiceIntentInfo filter) { 12469 out.print(prefix); out.print( 12470 Integer.toHexString(System.identityHashCode(filter.service))); 12471 out.print(' '); 12472 filter.service.printComponentShortName(out); 12473 out.print(" filter "); 12474 out.println(Integer.toHexString(System.identityHashCode(filter))); 12475 } 12476 12477 @Override 12478 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12479 return filter.service; 12480 } 12481 12482 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12483 PackageParser.Service service = (PackageParser.Service)label; 12484 out.print(prefix); out.print( 12485 Integer.toHexString(System.identityHashCode(service))); 12486 out.print(' '); 12487 service.printComponentShortName(out); 12488 if (count > 1) { 12489 out.print(" ("); out.print(count); out.print(" filters)"); 12490 } 12491 out.println(); 12492 } 12493 12494// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12495// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12496// final List<ResolveInfo> retList = Lists.newArrayList(); 12497// while (i.hasNext()) { 12498// final ResolveInfo resolveInfo = (ResolveInfo) i; 12499// if (isEnabledLP(resolveInfo.serviceInfo)) { 12500// retList.add(resolveInfo); 12501// } 12502// } 12503// return retList; 12504// } 12505 12506 // Keys are String (activity class name), values are Activity. 12507 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12508 = new ArrayMap<ComponentName, PackageParser.Service>(); 12509 private int mFlags; 12510 } 12511 12512 private final class ProviderIntentResolver 12513 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12514 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12515 boolean defaultOnly, int userId) { 12516 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12517 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12518 } 12519 12520 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12521 int userId) { 12522 if (!sUserManager.exists(userId)) 12523 return null; 12524 mFlags = flags; 12525 return super.queryIntent(intent, resolvedType, 12526 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12527 userId); 12528 } 12529 12530 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12531 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12532 if (!sUserManager.exists(userId)) 12533 return null; 12534 if (packageProviders == null) { 12535 return null; 12536 } 12537 mFlags = flags; 12538 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12539 final int N = packageProviders.size(); 12540 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12541 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12542 12543 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12544 for (int i = 0; i < N; ++i) { 12545 intentFilters = packageProviders.get(i).intents; 12546 if (intentFilters != null && intentFilters.size() > 0) { 12547 PackageParser.ProviderIntentInfo[] array = 12548 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12549 intentFilters.toArray(array); 12550 listCut.add(array); 12551 } 12552 } 12553 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12554 } 12555 12556 public final void addProvider(PackageParser.Provider p) { 12557 if (mProviders.containsKey(p.getComponentName())) { 12558 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12559 return; 12560 } 12561 12562 mProviders.put(p.getComponentName(), p); 12563 if (DEBUG_SHOW_INFO) { 12564 Log.v(TAG, " " 12565 + (p.info.nonLocalizedLabel != null 12566 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12567 Log.v(TAG, " Class=" + p.info.name); 12568 } 12569 final int NI = p.intents.size(); 12570 int j; 12571 for (j = 0; j < NI; j++) { 12572 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12573 if (DEBUG_SHOW_INFO) { 12574 Log.v(TAG, " IntentFilter:"); 12575 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12576 } 12577 if (!intent.debugCheck()) { 12578 Log.w(TAG, "==> For Provider " + p.info.name); 12579 } 12580 addFilter(intent); 12581 } 12582 } 12583 12584 public final void removeProvider(PackageParser.Provider p) { 12585 mProviders.remove(p.getComponentName()); 12586 if (DEBUG_SHOW_INFO) { 12587 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12588 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12589 Log.v(TAG, " Class=" + p.info.name); 12590 } 12591 final int NI = p.intents.size(); 12592 int j; 12593 for (j = 0; j < NI; j++) { 12594 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12595 if (DEBUG_SHOW_INFO) { 12596 Log.v(TAG, " IntentFilter:"); 12597 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12598 } 12599 removeFilter(intent); 12600 } 12601 } 12602 12603 @Override 12604 protected boolean allowFilterResult( 12605 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12606 ProviderInfo filterPi = filter.provider.info; 12607 for (int i = dest.size() - 1; i >= 0; i--) { 12608 ProviderInfo destPi = dest.get(i).providerInfo; 12609 if (destPi.name == filterPi.name 12610 && destPi.packageName == filterPi.packageName) { 12611 return false; 12612 } 12613 } 12614 return true; 12615 } 12616 12617 @Override 12618 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12619 return new PackageParser.ProviderIntentInfo[size]; 12620 } 12621 12622 @Override 12623 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12624 if (!sUserManager.exists(userId)) 12625 return true; 12626 PackageParser.Package p = filter.provider.owner; 12627 if (p != null) { 12628 PackageSetting ps = (PackageSetting) p.mExtras; 12629 if (ps != null) { 12630 // System apps are never considered stopped for purposes of 12631 // filtering, because there may be no way for the user to 12632 // actually re-launch them. 12633 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12634 && ps.getStopped(userId); 12635 } 12636 } 12637 return false; 12638 } 12639 12640 @Override 12641 protected boolean isPackageForFilter(String packageName, 12642 PackageParser.ProviderIntentInfo info) { 12643 return packageName.equals(info.provider.owner.packageName); 12644 } 12645 12646 @Override 12647 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12648 int match, int userId) { 12649 if (!sUserManager.exists(userId)) 12650 return null; 12651 final PackageParser.ProviderIntentInfo info = filter; 12652 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12653 return null; 12654 } 12655 final PackageParser.Provider provider = info.provider; 12656 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12657 if (ps == null) { 12658 return null; 12659 } 12660 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12661 ps.readUserState(userId), userId); 12662 if (pi == null) { 12663 return null; 12664 } 12665 final ResolveInfo res = new ResolveInfo(); 12666 res.providerInfo = pi; 12667 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12668 res.filter = filter; 12669 } 12670 res.priority = info.getPriority(); 12671 res.preferredOrder = provider.owner.mPreferredOrder; 12672 res.match = match; 12673 res.isDefault = info.hasDefault; 12674 res.labelRes = info.labelRes; 12675 res.nonLocalizedLabel = info.nonLocalizedLabel; 12676 res.icon = info.icon; 12677 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12678 return res; 12679 } 12680 12681 @Override 12682 protected void sortResults(List<ResolveInfo> results) { 12683 Collections.sort(results, mResolvePrioritySorter); 12684 } 12685 12686 @Override 12687 protected void dumpFilter(PrintWriter out, String prefix, 12688 PackageParser.ProviderIntentInfo filter) { 12689 out.print(prefix); 12690 out.print( 12691 Integer.toHexString(System.identityHashCode(filter.provider))); 12692 out.print(' '); 12693 filter.provider.printComponentShortName(out); 12694 out.print(" filter "); 12695 out.println(Integer.toHexString(System.identityHashCode(filter))); 12696 } 12697 12698 @Override 12699 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12700 return filter.provider; 12701 } 12702 12703 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12704 PackageParser.Provider provider = (PackageParser.Provider)label; 12705 out.print(prefix); out.print( 12706 Integer.toHexString(System.identityHashCode(provider))); 12707 out.print(' '); 12708 provider.printComponentShortName(out); 12709 if (count > 1) { 12710 out.print(" ("); out.print(count); out.print(" filters)"); 12711 } 12712 out.println(); 12713 } 12714 12715 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12716 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12717 private int mFlags; 12718 } 12719 12720 static final class EphemeralIntentResolver 12721 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12722 /** 12723 * The result that has the highest defined order. Ordering applies on a 12724 * per-package basis. Mapping is from package name to Pair of order and 12725 * EphemeralResolveInfo. 12726 * <p> 12727 * NOTE: This is implemented as a field variable for convenience and efficiency. 12728 * By having a field variable, we're able to track filter ordering as soon as 12729 * a non-zero order is defined. Otherwise, multiple loops across the result set 12730 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12731 * this needs to be contained entirely within {@link #filterResults}. 12732 */ 12733 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12734 12735 @Override 12736 protected AuxiliaryResolveInfo[] newArray(int size) { 12737 return new AuxiliaryResolveInfo[size]; 12738 } 12739 12740 @Override 12741 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12742 return true; 12743 } 12744 12745 @Override 12746 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12747 int userId) { 12748 if (!sUserManager.exists(userId)) { 12749 return null; 12750 } 12751 final String packageName = responseObj.resolveInfo.getPackageName(); 12752 final Integer order = responseObj.getOrder(); 12753 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12754 mOrderResult.get(packageName); 12755 // ordering is enabled and this item's order isn't high enough 12756 if (lastOrderResult != null && lastOrderResult.first >= order) { 12757 return null; 12758 } 12759 final InstantAppResolveInfo res = responseObj.resolveInfo; 12760 if (order > 0) { 12761 // non-zero order, enable ordering 12762 mOrderResult.put(packageName, new Pair<>(order, res)); 12763 } 12764 return responseObj; 12765 } 12766 12767 @Override 12768 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12769 // only do work if ordering is enabled [most of the time it won't be] 12770 if (mOrderResult.size() == 0) { 12771 return; 12772 } 12773 int resultSize = results.size(); 12774 for (int i = 0; i < resultSize; i++) { 12775 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12776 final String packageName = info.getPackageName(); 12777 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12778 if (savedInfo == null) { 12779 // package doesn't having ordering 12780 continue; 12781 } 12782 if (savedInfo.second == info) { 12783 // circled back to the highest ordered item; remove from order list 12784 mOrderResult.remove(savedInfo); 12785 if (mOrderResult.size() == 0) { 12786 // no more ordered items 12787 break; 12788 } 12789 continue; 12790 } 12791 // item has a worse order, remove it from the result list 12792 results.remove(i); 12793 resultSize--; 12794 i--; 12795 } 12796 } 12797 } 12798 12799 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12800 new Comparator<ResolveInfo>() { 12801 public int compare(ResolveInfo r1, ResolveInfo r2) { 12802 int v1 = r1.priority; 12803 int v2 = r2.priority; 12804 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12805 if (v1 != v2) { 12806 return (v1 > v2) ? -1 : 1; 12807 } 12808 v1 = r1.preferredOrder; 12809 v2 = r2.preferredOrder; 12810 if (v1 != v2) { 12811 return (v1 > v2) ? -1 : 1; 12812 } 12813 if (r1.isDefault != r2.isDefault) { 12814 return r1.isDefault ? -1 : 1; 12815 } 12816 v1 = r1.match; 12817 v2 = r2.match; 12818 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12819 if (v1 != v2) { 12820 return (v1 > v2) ? -1 : 1; 12821 } 12822 if (r1.system != r2.system) { 12823 return r1.system ? -1 : 1; 12824 } 12825 if (r1.activityInfo != null) { 12826 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12827 } 12828 if (r1.serviceInfo != null) { 12829 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12830 } 12831 if (r1.providerInfo != null) { 12832 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12833 } 12834 return 0; 12835 } 12836 }; 12837 12838 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12839 new Comparator<ProviderInfo>() { 12840 public int compare(ProviderInfo p1, ProviderInfo p2) { 12841 final int v1 = p1.initOrder; 12842 final int v2 = p2.initOrder; 12843 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12844 } 12845 }; 12846 12847 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12848 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12849 final int[] userIds) { 12850 mHandler.post(new Runnable() { 12851 @Override 12852 public void run() { 12853 try { 12854 final IActivityManager am = ActivityManager.getService(); 12855 if (am == null) return; 12856 final int[] resolvedUserIds; 12857 if (userIds == null) { 12858 resolvedUserIds = am.getRunningUserIds(); 12859 } else { 12860 resolvedUserIds = userIds; 12861 } 12862 for (int id : resolvedUserIds) { 12863 final Intent intent = new Intent(action, 12864 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12865 if (extras != null) { 12866 intent.putExtras(extras); 12867 } 12868 if (targetPkg != null) { 12869 intent.setPackage(targetPkg); 12870 } 12871 // Modify the UID when posting to other users 12872 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12873 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12874 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12875 intent.putExtra(Intent.EXTRA_UID, uid); 12876 } 12877 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12878 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12879 if (DEBUG_BROADCASTS) { 12880 RuntimeException here = new RuntimeException("here"); 12881 here.fillInStackTrace(); 12882 Slog.d(TAG, "Sending to user " + id + ": " 12883 + intent.toShortString(false, true, false, false) 12884 + " " + intent.getExtras(), here); 12885 } 12886 am.broadcastIntent(null, intent, null, finishedReceiver, 12887 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12888 null, finishedReceiver != null, false, id); 12889 } 12890 } catch (RemoteException ex) { 12891 } 12892 } 12893 }); 12894 } 12895 12896 /** 12897 * Check if the external storage media is available. This is true if there 12898 * is a mounted external storage medium or if the external storage is 12899 * emulated. 12900 */ 12901 private boolean isExternalMediaAvailable() { 12902 return mMediaMounted || Environment.isExternalStorageEmulated(); 12903 } 12904 12905 @Override 12906 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12907 // writer 12908 synchronized (mPackages) { 12909 if (!isExternalMediaAvailable()) { 12910 // If the external storage is no longer mounted at this point, 12911 // the caller may not have been able to delete all of this 12912 // packages files and can not delete any more. Bail. 12913 return null; 12914 } 12915 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12916 if (lastPackage != null) { 12917 pkgs.remove(lastPackage); 12918 } 12919 if (pkgs.size() > 0) { 12920 return pkgs.get(0); 12921 } 12922 } 12923 return null; 12924 } 12925 12926 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12927 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12928 userId, andCode ? 1 : 0, packageName); 12929 if (mSystemReady) { 12930 msg.sendToTarget(); 12931 } else { 12932 if (mPostSystemReadyMessages == null) { 12933 mPostSystemReadyMessages = new ArrayList<>(); 12934 } 12935 mPostSystemReadyMessages.add(msg); 12936 } 12937 } 12938 12939 void startCleaningPackages() { 12940 // reader 12941 if (!isExternalMediaAvailable()) { 12942 return; 12943 } 12944 synchronized (mPackages) { 12945 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12946 return; 12947 } 12948 } 12949 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12950 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12951 IActivityManager am = ActivityManager.getService(); 12952 if (am != null) { 12953 try { 12954 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12955 UserHandle.USER_SYSTEM); 12956 } catch (RemoteException e) { 12957 } 12958 } 12959 } 12960 12961 @Override 12962 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12963 int installFlags, String installerPackageName, int userId) { 12964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12965 12966 final int callingUid = Binder.getCallingUid(); 12967 enforceCrossUserPermission(callingUid, userId, 12968 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12969 12970 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12971 try { 12972 if (observer != null) { 12973 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12974 } 12975 } catch (RemoteException re) { 12976 } 12977 return; 12978 } 12979 12980 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12981 installFlags |= PackageManager.INSTALL_FROM_ADB; 12982 12983 } else { 12984 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12985 // about installerPackageName. 12986 12987 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12988 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12989 } 12990 12991 UserHandle user; 12992 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12993 user = UserHandle.ALL; 12994 } else { 12995 user = new UserHandle(userId); 12996 } 12997 12998 // Only system components can circumvent runtime permissions when installing. 12999 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13000 && mContext.checkCallingOrSelfPermission(Manifest.permission 13001 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13002 throw new SecurityException("You need the " 13003 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13004 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13005 } 13006 13007 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13008 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13009 throw new IllegalArgumentException( 13010 "New installs into ASEC containers no longer supported"); 13011 } 13012 13013 final File originFile = new File(originPath); 13014 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13015 13016 final Message msg = mHandler.obtainMessage(INIT_COPY); 13017 final VerificationInfo verificationInfo = new VerificationInfo( 13018 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13019 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13020 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13021 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13022 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13023 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13024 msg.obj = params; 13025 13026 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13027 System.identityHashCode(msg.obj)); 13028 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13029 System.identityHashCode(msg.obj)); 13030 13031 mHandler.sendMessage(msg); 13032 } 13033 13034 13035 /** 13036 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13037 * it is acting on behalf on an enterprise or the user). 13038 * 13039 * Note that the ordering of the conditionals in this method is important. The checks we perform 13040 * are as follows, in this order: 13041 * 13042 * 1) If the install is being performed by a system app, we can trust the app to have set the 13043 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13044 * what it is. 13045 * 2) If the install is being performed by a device or profile owner app, the install reason 13046 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13047 * set the install reason correctly. If the app targets an older SDK version where install 13048 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13049 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13050 * 3) In all other cases, the install is being performed by a regular app that is neither part 13051 * of the system nor a device or profile owner. We have no reason to believe that this app is 13052 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13053 * set to enterprise policy and if so, change it to unknown instead. 13054 */ 13055 private int fixUpInstallReason(String installerPackageName, int installerUid, 13056 int installReason) { 13057 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13058 == PERMISSION_GRANTED) { 13059 // If the install is being performed by a system app, we trust that app to have set the 13060 // install reason correctly. 13061 return installReason; 13062 } 13063 13064 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13065 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13066 if (dpm != null) { 13067 ComponentName owner = null; 13068 try { 13069 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13070 if (owner == null) { 13071 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13072 } 13073 } catch (RemoteException e) { 13074 } 13075 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13076 // If the install is being performed by a device or profile owner, the install 13077 // reason should be enterprise policy. 13078 return PackageManager.INSTALL_REASON_POLICY; 13079 } 13080 } 13081 13082 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13083 // If the install is being performed by a regular app (i.e. neither system app nor 13084 // device or profile owner), we have no reason to believe that the app is acting on 13085 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13086 // change it to unknown instead. 13087 return PackageManager.INSTALL_REASON_UNKNOWN; 13088 } 13089 13090 // If the install is being performed by a regular app and the install reason was set to any 13091 // value but enterprise policy, leave the install reason unchanged. 13092 return installReason; 13093 } 13094 13095 void installStage(String packageName, File stagedDir, String stagedCid, 13096 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13097 String installerPackageName, int installerUid, UserHandle user, 13098 Certificate[][] certificates) { 13099 if (DEBUG_EPHEMERAL) { 13100 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13101 Slog.d(TAG, "Ephemeral install of " + packageName); 13102 } 13103 } 13104 final VerificationInfo verificationInfo = new VerificationInfo( 13105 sessionParams.originatingUri, sessionParams.referrerUri, 13106 sessionParams.originatingUid, installerUid); 13107 13108 final OriginInfo origin; 13109 if (stagedDir != null) { 13110 origin = OriginInfo.fromStagedFile(stagedDir); 13111 } else { 13112 origin = OriginInfo.fromStagedContainer(stagedCid); 13113 } 13114 13115 final Message msg = mHandler.obtainMessage(INIT_COPY); 13116 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13117 sessionParams.installReason); 13118 final InstallParams params = new InstallParams(origin, null, observer, 13119 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13120 verificationInfo, user, sessionParams.abiOverride, 13121 sessionParams.grantedRuntimePermissions, certificates, installReason); 13122 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13123 msg.obj = params; 13124 13125 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13126 System.identityHashCode(msg.obj)); 13127 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13128 System.identityHashCode(msg.obj)); 13129 13130 mHandler.sendMessage(msg); 13131 } 13132 13133 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13134 int userId) { 13135 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13136 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13137 } 13138 13139 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13140 int appId, int... userIds) { 13141 if (ArrayUtils.isEmpty(userIds)) { 13142 return; 13143 } 13144 Bundle extras = new Bundle(1); 13145 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13146 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13147 13148 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13149 packageName, extras, 0, null, null, userIds); 13150 if (isSystem) { 13151 mHandler.post(() -> { 13152 for (int userId : userIds) { 13153 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13154 } 13155 } 13156 ); 13157 } 13158 } 13159 13160 /** 13161 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13162 * automatically without needing an explicit launch. 13163 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13164 */ 13165 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13166 // If user is not running, the app didn't miss any broadcast 13167 if (!mUserManagerInternal.isUserRunning(userId)) { 13168 return; 13169 } 13170 final IActivityManager am = ActivityManager.getService(); 13171 try { 13172 // Deliver LOCKED_BOOT_COMPLETED first 13173 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13174 .setPackage(packageName); 13175 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13176 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13177 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13178 13179 // Deliver BOOT_COMPLETED only if user is unlocked 13180 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13181 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13182 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13183 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13184 } 13185 } catch (RemoteException e) { 13186 throw e.rethrowFromSystemServer(); 13187 } 13188 } 13189 13190 @Override 13191 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13192 int userId) { 13193 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13194 PackageSetting pkgSetting; 13195 final int uid = Binder.getCallingUid(); 13196 enforceCrossUserPermission(uid, userId, 13197 true /* requireFullPermission */, true /* checkShell */, 13198 "setApplicationHiddenSetting for user " + userId); 13199 13200 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13201 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13202 return false; 13203 } 13204 13205 long callingId = Binder.clearCallingIdentity(); 13206 try { 13207 boolean sendAdded = false; 13208 boolean sendRemoved = false; 13209 // writer 13210 synchronized (mPackages) { 13211 pkgSetting = mSettings.mPackages.get(packageName); 13212 if (pkgSetting == null) { 13213 return false; 13214 } 13215 // Do not allow "android" is being disabled 13216 if ("android".equals(packageName)) { 13217 Slog.w(TAG, "Cannot hide package: android"); 13218 return false; 13219 } 13220 // Cannot hide static shared libs as they are considered 13221 // a part of the using app (emulating static linking). Also 13222 // static libs are installed always on internal storage. 13223 PackageParser.Package pkg = mPackages.get(packageName); 13224 if (pkg != null && pkg.staticSharedLibName != null) { 13225 Slog.w(TAG, "Cannot hide package: " + packageName 13226 + " providing static shared library: " 13227 + pkg.staticSharedLibName); 13228 return false; 13229 } 13230 // Only allow protected packages to hide themselves. 13231 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13232 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13233 Slog.w(TAG, "Not hiding protected package: " + packageName); 13234 return false; 13235 } 13236 13237 if (pkgSetting.getHidden(userId) != hidden) { 13238 pkgSetting.setHidden(hidden, userId); 13239 mSettings.writePackageRestrictionsLPr(userId); 13240 if (hidden) { 13241 sendRemoved = true; 13242 } else { 13243 sendAdded = true; 13244 } 13245 } 13246 } 13247 if (sendAdded) { 13248 sendPackageAddedForUser(packageName, pkgSetting, userId); 13249 return true; 13250 } 13251 if (sendRemoved) { 13252 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13253 "hiding pkg"); 13254 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13255 return true; 13256 } 13257 } finally { 13258 Binder.restoreCallingIdentity(callingId); 13259 } 13260 return false; 13261 } 13262 13263 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13264 int userId) { 13265 final PackageRemovedInfo info = new PackageRemovedInfo(); 13266 info.removedPackage = packageName; 13267 info.removedUsers = new int[] {userId}; 13268 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13269 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13270 } 13271 13272 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13273 if (pkgList.length > 0) { 13274 Bundle extras = new Bundle(1); 13275 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13276 13277 sendPackageBroadcast( 13278 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13279 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13280 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13281 new int[] {userId}); 13282 } 13283 } 13284 13285 /** 13286 * Returns true if application is not found or there was an error. Otherwise it returns 13287 * the hidden state of the package for the given user. 13288 */ 13289 @Override 13290 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13291 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13293 true /* requireFullPermission */, false /* checkShell */, 13294 "getApplicationHidden for user " + userId); 13295 PackageSetting pkgSetting; 13296 long callingId = Binder.clearCallingIdentity(); 13297 try { 13298 // writer 13299 synchronized (mPackages) { 13300 pkgSetting = mSettings.mPackages.get(packageName); 13301 if (pkgSetting == null) { 13302 return true; 13303 } 13304 return pkgSetting.getHidden(userId); 13305 } 13306 } finally { 13307 Binder.restoreCallingIdentity(callingId); 13308 } 13309 } 13310 13311 /** 13312 * @hide 13313 */ 13314 @Override 13315 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13316 int installReason) { 13317 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13318 null); 13319 PackageSetting pkgSetting; 13320 final int uid = Binder.getCallingUid(); 13321 enforceCrossUserPermission(uid, userId, 13322 true /* requireFullPermission */, true /* checkShell */, 13323 "installExistingPackage for user " + userId); 13324 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13325 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13326 } 13327 13328 long callingId = Binder.clearCallingIdentity(); 13329 try { 13330 boolean installed = false; 13331 final boolean instantApp = 13332 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13333 final boolean fullApp = 13334 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13335 13336 // writer 13337 synchronized (mPackages) { 13338 pkgSetting = mSettings.mPackages.get(packageName); 13339 if (pkgSetting == null) { 13340 return PackageManager.INSTALL_FAILED_INVALID_URI; 13341 } 13342 if (!pkgSetting.getInstalled(userId)) { 13343 pkgSetting.setInstalled(true, userId); 13344 pkgSetting.setHidden(false, userId); 13345 pkgSetting.setInstallReason(installReason, userId); 13346 mSettings.writePackageRestrictionsLPr(userId); 13347 mSettings.writeKernelMappingLPr(pkgSetting); 13348 installed = true; 13349 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13350 // upgrade app from instant to full; we don't allow app downgrade 13351 installed = true; 13352 } 13353 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13354 } 13355 13356 if (installed) { 13357 if (pkgSetting.pkg != null) { 13358 synchronized (mInstallLock) { 13359 // We don't need to freeze for a brand new install 13360 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13361 } 13362 } 13363 sendPackageAddedForUser(packageName, pkgSetting, userId); 13364 synchronized (mPackages) { 13365 updateSequenceNumberLP(packageName, new int[]{ userId }); 13366 } 13367 } 13368 } finally { 13369 Binder.restoreCallingIdentity(callingId); 13370 } 13371 13372 return PackageManager.INSTALL_SUCCEEDED; 13373 } 13374 13375 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13376 boolean instantApp, boolean fullApp) { 13377 // no state specified; do nothing 13378 if (!instantApp && !fullApp) { 13379 return; 13380 } 13381 if (userId != UserHandle.USER_ALL) { 13382 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13383 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13384 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13385 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13386 } 13387 } else { 13388 for (int currentUserId : sUserManager.getUserIds()) { 13389 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13390 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13391 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13392 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13393 } 13394 } 13395 } 13396 } 13397 13398 boolean isUserRestricted(int userId, String restrictionKey) { 13399 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13400 if (restrictions.getBoolean(restrictionKey, false)) { 13401 Log.w(TAG, "User is restricted: " + restrictionKey); 13402 return true; 13403 } 13404 return false; 13405 } 13406 13407 @Override 13408 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13409 int userId) { 13410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13411 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13412 true /* requireFullPermission */, true /* checkShell */, 13413 "setPackagesSuspended for user " + userId); 13414 13415 if (ArrayUtils.isEmpty(packageNames)) { 13416 return packageNames; 13417 } 13418 13419 // List of package names for whom the suspended state has changed. 13420 List<String> changedPackages = new ArrayList<>(packageNames.length); 13421 // List of package names for whom the suspended state is not set as requested in this 13422 // method. 13423 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13424 long callingId = Binder.clearCallingIdentity(); 13425 try { 13426 for (int i = 0; i < packageNames.length; i++) { 13427 String packageName = packageNames[i]; 13428 boolean changed = false; 13429 final int appId; 13430 synchronized (mPackages) { 13431 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13432 if (pkgSetting == null) { 13433 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13434 + "\". Skipping suspending/un-suspending."); 13435 unactionedPackages.add(packageName); 13436 continue; 13437 } 13438 appId = pkgSetting.appId; 13439 if (pkgSetting.getSuspended(userId) != suspended) { 13440 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13441 unactionedPackages.add(packageName); 13442 continue; 13443 } 13444 pkgSetting.setSuspended(suspended, userId); 13445 mSettings.writePackageRestrictionsLPr(userId); 13446 changed = true; 13447 changedPackages.add(packageName); 13448 } 13449 } 13450 13451 if (changed && suspended) { 13452 killApplication(packageName, UserHandle.getUid(userId, appId), 13453 "suspending package"); 13454 } 13455 } 13456 } finally { 13457 Binder.restoreCallingIdentity(callingId); 13458 } 13459 13460 if (!changedPackages.isEmpty()) { 13461 sendPackagesSuspendedForUser(changedPackages.toArray( 13462 new String[changedPackages.size()]), userId, suspended); 13463 } 13464 13465 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13466 } 13467 13468 @Override 13469 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13470 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13471 true /* requireFullPermission */, false /* checkShell */, 13472 "isPackageSuspendedForUser for user " + userId); 13473 synchronized (mPackages) { 13474 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13475 if (pkgSetting == null) { 13476 throw new IllegalArgumentException("Unknown target package: " + packageName); 13477 } 13478 return pkgSetting.getSuspended(userId); 13479 } 13480 } 13481 13482 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13483 if (isPackageDeviceAdmin(packageName, userId)) { 13484 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13485 + "\": has an active device admin"); 13486 return false; 13487 } 13488 13489 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13490 if (packageName.equals(activeLauncherPackageName)) { 13491 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13492 + "\": contains the active launcher"); 13493 return false; 13494 } 13495 13496 if (packageName.equals(mRequiredInstallerPackage)) { 13497 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13498 + "\": required for package installation"); 13499 return false; 13500 } 13501 13502 if (packageName.equals(mRequiredUninstallerPackage)) { 13503 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13504 + "\": required for package uninstallation"); 13505 return false; 13506 } 13507 13508 if (packageName.equals(mRequiredVerifierPackage)) { 13509 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13510 + "\": required for package verification"); 13511 return false; 13512 } 13513 13514 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13515 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13516 + "\": is the default dialer"); 13517 return false; 13518 } 13519 13520 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13521 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13522 + "\": protected package"); 13523 return false; 13524 } 13525 13526 // Cannot suspend static shared libs as they are considered 13527 // a part of the using app (emulating static linking). Also 13528 // static libs are installed always on internal storage. 13529 PackageParser.Package pkg = mPackages.get(packageName); 13530 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13531 Slog.w(TAG, "Cannot suspend package: " + packageName 13532 + " providing static shared library: " 13533 + pkg.staticSharedLibName); 13534 return false; 13535 } 13536 13537 return true; 13538 } 13539 13540 private String getActiveLauncherPackageName(int userId) { 13541 Intent intent = new Intent(Intent.ACTION_MAIN); 13542 intent.addCategory(Intent.CATEGORY_HOME); 13543 ResolveInfo resolveInfo = resolveIntent( 13544 intent, 13545 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13546 PackageManager.MATCH_DEFAULT_ONLY, 13547 userId); 13548 13549 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13550 } 13551 13552 private String getDefaultDialerPackageName(int userId) { 13553 synchronized (mPackages) { 13554 return mSettings.getDefaultDialerPackageNameLPw(userId); 13555 } 13556 } 13557 13558 @Override 13559 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13560 mContext.enforceCallingOrSelfPermission( 13561 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13562 "Only package verification agents can verify applications"); 13563 13564 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13565 final PackageVerificationResponse response = new PackageVerificationResponse( 13566 verificationCode, Binder.getCallingUid()); 13567 msg.arg1 = id; 13568 msg.obj = response; 13569 mHandler.sendMessage(msg); 13570 } 13571 13572 @Override 13573 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13574 long millisecondsToDelay) { 13575 mContext.enforceCallingOrSelfPermission( 13576 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13577 "Only package verification agents can extend verification timeouts"); 13578 13579 final PackageVerificationState state = mPendingVerification.get(id); 13580 final PackageVerificationResponse response = new PackageVerificationResponse( 13581 verificationCodeAtTimeout, Binder.getCallingUid()); 13582 13583 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13584 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13585 } 13586 if (millisecondsToDelay < 0) { 13587 millisecondsToDelay = 0; 13588 } 13589 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13590 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13591 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13592 } 13593 13594 if ((state != null) && !state.timeoutExtended()) { 13595 state.extendTimeout(); 13596 13597 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13598 msg.arg1 = id; 13599 msg.obj = response; 13600 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13601 } 13602 } 13603 13604 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13605 int verificationCode, UserHandle user) { 13606 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13607 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13608 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13609 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13610 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13611 13612 mContext.sendBroadcastAsUser(intent, user, 13613 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13614 } 13615 13616 private ComponentName matchComponentForVerifier(String packageName, 13617 List<ResolveInfo> receivers) { 13618 ActivityInfo targetReceiver = null; 13619 13620 final int NR = receivers.size(); 13621 for (int i = 0; i < NR; i++) { 13622 final ResolveInfo info = receivers.get(i); 13623 if (info.activityInfo == null) { 13624 continue; 13625 } 13626 13627 if (packageName.equals(info.activityInfo.packageName)) { 13628 targetReceiver = info.activityInfo; 13629 break; 13630 } 13631 } 13632 13633 if (targetReceiver == null) { 13634 return null; 13635 } 13636 13637 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13638 } 13639 13640 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13641 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13642 if (pkgInfo.verifiers.length == 0) { 13643 return null; 13644 } 13645 13646 final int N = pkgInfo.verifiers.length; 13647 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13648 for (int i = 0; i < N; i++) { 13649 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13650 13651 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13652 receivers); 13653 if (comp == null) { 13654 continue; 13655 } 13656 13657 final int verifierUid = getUidForVerifier(verifierInfo); 13658 if (verifierUid == -1) { 13659 continue; 13660 } 13661 13662 if (DEBUG_VERIFY) { 13663 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13664 + " with the correct signature"); 13665 } 13666 sufficientVerifiers.add(comp); 13667 verificationState.addSufficientVerifier(verifierUid); 13668 } 13669 13670 return sufficientVerifiers; 13671 } 13672 13673 private int getUidForVerifier(VerifierInfo verifierInfo) { 13674 synchronized (mPackages) { 13675 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13676 if (pkg == null) { 13677 return -1; 13678 } else if (pkg.mSignatures.length != 1) { 13679 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13680 + " has more than one signature; ignoring"); 13681 return -1; 13682 } 13683 13684 /* 13685 * If the public key of the package's signature does not match 13686 * our expected public key, then this is a different package and 13687 * we should skip. 13688 */ 13689 13690 final byte[] expectedPublicKey; 13691 try { 13692 final Signature verifierSig = pkg.mSignatures[0]; 13693 final PublicKey publicKey = verifierSig.getPublicKey(); 13694 expectedPublicKey = publicKey.getEncoded(); 13695 } catch (CertificateException e) { 13696 return -1; 13697 } 13698 13699 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13700 13701 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13702 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13703 + " does not have the expected public key; ignoring"); 13704 return -1; 13705 } 13706 13707 return pkg.applicationInfo.uid; 13708 } 13709 } 13710 13711 @Override 13712 public void finishPackageInstall(int token, boolean didLaunch) { 13713 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13714 13715 if (DEBUG_INSTALL) { 13716 Slog.v(TAG, "BM finishing package install for " + token); 13717 } 13718 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13719 13720 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13721 mHandler.sendMessage(msg); 13722 } 13723 13724 /** 13725 * Get the verification agent timeout. 13726 * 13727 * @return verification timeout in milliseconds 13728 */ 13729 private long getVerificationTimeout() { 13730 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13731 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13732 DEFAULT_VERIFICATION_TIMEOUT); 13733 } 13734 13735 /** 13736 * Get the default verification agent response code. 13737 * 13738 * @return default verification response code 13739 */ 13740 private int getDefaultVerificationResponse() { 13741 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13742 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13743 DEFAULT_VERIFICATION_RESPONSE); 13744 } 13745 13746 /** 13747 * Check whether or not package verification has been enabled. 13748 * 13749 * @return true if verification should be performed 13750 */ 13751 private boolean isVerificationEnabled(int userId, int installFlags) { 13752 if (!DEFAULT_VERIFY_ENABLE) { 13753 return false; 13754 } 13755 13756 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13757 13758 // Check if installing from ADB 13759 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13760 // Do not run verification in a test harness environment 13761 if (ActivityManager.isRunningInTestHarness()) { 13762 return false; 13763 } 13764 if (ensureVerifyAppsEnabled) { 13765 return true; 13766 } 13767 // Check if the developer does not want package verification for ADB installs 13768 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13769 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13770 return false; 13771 } 13772 } 13773 13774 if (ensureVerifyAppsEnabled) { 13775 return true; 13776 } 13777 13778 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13779 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13780 } 13781 13782 @Override 13783 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13784 throws RemoteException { 13785 mContext.enforceCallingOrSelfPermission( 13786 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13787 "Only intentfilter verification agents can verify applications"); 13788 13789 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13790 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13791 Binder.getCallingUid(), verificationCode, failedDomains); 13792 msg.arg1 = id; 13793 msg.obj = response; 13794 mHandler.sendMessage(msg); 13795 } 13796 13797 @Override 13798 public int getIntentVerificationStatus(String packageName, int userId) { 13799 synchronized (mPackages) { 13800 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13801 } 13802 } 13803 13804 @Override 13805 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13806 mContext.enforceCallingOrSelfPermission( 13807 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13808 13809 boolean result = false; 13810 synchronized (mPackages) { 13811 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13812 } 13813 if (result) { 13814 scheduleWritePackageRestrictionsLocked(userId); 13815 } 13816 return result; 13817 } 13818 13819 @Override 13820 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13821 String packageName) { 13822 synchronized (mPackages) { 13823 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13824 } 13825 } 13826 13827 @Override 13828 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13829 if (TextUtils.isEmpty(packageName)) { 13830 return ParceledListSlice.emptyList(); 13831 } 13832 synchronized (mPackages) { 13833 PackageParser.Package pkg = mPackages.get(packageName); 13834 if (pkg == null || pkg.activities == null) { 13835 return ParceledListSlice.emptyList(); 13836 } 13837 final int count = pkg.activities.size(); 13838 ArrayList<IntentFilter> result = new ArrayList<>(); 13839 for (int n=0; n<count; n++) { 13840 PackageParser.Activity activity = pkg.activities.get(n); 13841 if (activity.intents != null && activity.intents.size() > 0) { 13842 result.addAll(activity.intents); 13843 } 13844 } 13845 return new ParceledListSlice<>(result); 13846 } 13847 } 13848 13849 @Override 13850 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13851 mContext.enforceCallingOrSelfPermission( 13852 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13853 13854 synchronized (mPackages) { 13855 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13856 if (packageName != null) { 13857 result |= updateIntentVerificationStatus(packageName, 13858 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13859 userId); 13860 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13861 packageName, userId); 13862 } 13863 return result; 13864 } 13865 } 13866 13867 @Override 13868 public String getDefaultBrowserPackageName(int userId) { 13869 synchronized (mPackages) { 13870 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13871 } 13872 } 13873 13874 /** 13875 * Get the "allow unknown sources" setting. 13876 * 13877 * @return the current "allow unknown sources" setting 13878 */ 13879 private int getUnknownSourcesSettings() { 13880 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13881 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13882 -1); 13883 } 13884 13885 @Override 13886 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13887 final int uid = Binder.getCallingUid(); 13888 // writer 13889 synchronized (mPackages) { 13890 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13891 if (targetPackageSetting == null) { 13892 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13893 } 13894 13895 PackageSetting installerPackageSetting; 13896 if (installerPackageName != null) { 13897 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13898 if (installerPackageSetting == null) { 13899 throw new IllegalArgumentException("Unknown installer package: " 13900 + installerPackageName); 13901 } 13902 } else { 13903 installerPackageSetting = null; 13904 } 13905 13906 Signature[] callerSignature; 13907 Object obj = mSettings.getUserIdLPr(uid); 13908 if (obj != null) { 13909 if (obj instanceof SharedUserSetting) { 13910 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13911 } else if (obj instanceof PackageSetting) { 13912 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13913 } else { 13914 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13915 } 13916 } else { 13917 throw new SecurityException("Unknown calling UID: " + uid); 13918 } 13919 13920 // Verify: can't set installerPackageName to a package that is 13921 // not signed with the same cert as the caller. 13922 if (installerPackageSetting != null) { 13923 if (compareSignatures(callerSignature, 13924 installerPackageSetting.signatures.mSignatures) 13925 != PackageManager.SIGNATURE_MATCH) { 13926 throw new SecurityException( 13927 "Caller does not have same cert as new installer package " 13928 + installerPackageName); 13929 } 13930 } 13931 13932 // Verify: if target already has an installer package, it must 13933 // be signed with the same cert as the caller. 13934 if (targetPackageSetting.installerPackageName != null) { 13935 PackageSetting setting = mSettings.mPackages.get( 13936 targetPackageSetting.installerPackageName); 13937 // If the currently set package isn't valid, then it's always 13938 // okay to change it. 13939 if (setting != null) { 13940 if (compareSignatures(callerSignature, 13941 setting.signatures.mSignatures) 13942 != PackageManager.SIGNATURE_MATCH) { 13943 throw new SecurityException( 13944 "Caller does not have same cert as old installer package " 13945 + targetPackageSetting.installerPackageName); 13946 } 13947 } 13948 } 13949 13950 // Okay! 13951 targetPackageSetting.installerPackageName = installerPackageName; 13952 if (installerPackageName != null) { 13953 mSettings.mInstallerPackages.add(installerPackageName); 13954 } 13955 scheduleWriteSettingsLocked(); 13956 } 13957 } 13958 13959 @Override 13960 public void setApplicationCategoryHint(String packageName, int categoryHint, 13961 String callerPackageName) { 13962 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13963 callerPackageName); 13964 synchronized (mPackages) { 13965 PackageSetting ps = mSettings.mPackages.get(packageName); 13966 if (ps == null) { 13967 throw new IllegalArgumentException("Unknown target package " + packageName); 13968 } 13969 13970 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13971 throw new IllegalArgumentException("Calling package " + callerPackageName 13972 + " is not installer for " + packageName); 13973 } 13974 13975 if (ps.categoryHint != categoryHint) { 13976 ps.categoryHint = categoryHint; 13977 scheduleWriteSettingsLocked(); 13978 } 13979 } 13980 } 13981 13982 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13983 // Queue up an async operation since the package installation may take a little while. 13984 mHandler.post(new Runnable() { 13985 public void run() { 13986 mHandler.removeCallbacks(this); 13987 // Result object to be returned 13988 PackageInstalledInfo res = new PackageInstalledInfo(); 13989 res.setReturnCode(currentStatus); 13990 res.uid = -1; 13991 res.pkg = null; 13992 res.removedInfo = null; 13993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13994 args.doPreInstall(res.returnCode); 13995 synchronized (mInstallLock) { 13996 installPackageTracedLI(args, res); 13997 } 13998 args.doPostInstall(res.returnCode, res.uid); 13999 } 14000 14001 // A restore should be performed at this point if (a) the install 14002 // succeeded, (b) the operation is not an update, and (c) the new 14003 // package has not opted out of backup participation. 14004 final boolean update = res.removedInfo != null 14005 && res.removedInfo.removedPackage != null; 14006 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14007 boolean doRestore = !update 14008 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14009 14010 // Set up the post-install work request bookkeeping. This will be used 14011 // and cleaned up by the post-install event handling regardless of whether 14012 // there's a restore pass performed. Token values are >= 1. 14013 int token; 14014 if (mNextInstallToken < 0) mNextInstallToken = 1; 14015 token = mNextInstallToken++; 14016 14017 PostInstallData data = new PostInstallData(args, res); 14018 mRunningInstalls.put(token, data); 14019 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14020 14021 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14022 // Pass responsibility to the Backup Manager. It will perform a 14023 // restore if appropriate, then pass responsibility back to the 14024 // Package Manager to run the post-install observer callbacks 14025 // and broadcasts. 14026 IBackupManager bm = IBackupManager.Stub.asInterface( 14027 ServiceManager.getService(Context.BACKUP_SERVICE)); 14028 if (bm != null) { 14029 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14030 + " to BM for possible restore"); 14031 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14032 try { 14033 // TODO: http://b/22388012 14034 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14035 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14036 } else { 14037 doRestore = false; 14038 } 14039 } catch (RemoteException e) { 14040 // can't happen; the backup manager is local 14041 } catch (Exception e) { 14042 Slog.e(TAG, "Exception trying to enqueue restore", e); 14043 doRestore = false; 14044 } 14045 } else { 14046 Slog.e(TAG, "Backup Manager not found!"); 14047 doRestore = false; 14048 } 14049 } 14050 14051 if (!doRestore) { 14052 // No restore possible, or the Backup Manager was mysteriously not 14053 // available -- just fire the post-install work request directly. 14054 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14055 14056 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14057 14058 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14059 mHandler.sendMessage(msg); 14060 } 14061 } 14062 }); 14063 } 14064 14065 /** 14066 * Callback from PackageSettings whenever an app is first transitioned out of the 14067 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14068 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14069 * here whether the app is the target of an ongoing install, and only send the 14070 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14071 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14072 * handling. 14073 */ 14074 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14075 // Serialize this with the rest of the install-process message chain. In the 14076 // restore-at-install case, this Runnable will necessarily run before the 14077 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14078 // are coherent. In the non-restore case, the app has already completed install 14079 // and been launched through some other means, so it is not in a problematic 14080 // state for observers to see the FIRST_LAUNCH signal. 14081 mHandler.post(new Runnable() { 14082 @Override 14083 public void run() { 14084 for (int i = 0; i < mRunningInstalls.size(); i++) { 14085 final PostInstallData data = mRunningInstalls.valueAt(i); 14086 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14087 continue; 14088 } 14089 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14090 // right package; but is it for the right user? 14091 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14092 if (userId == data.res.newUsers[uIndex]) { 14093 if (DEBUG_BACKUP) { 14094 Slog.i(TAG, "Package " + pkgName 14095 + " being restored so deferring FIRST_LAUNCH"); 14096 } 14097 return; 14098 } 14099 } 14100 } 14101 } 14102 // didn't find it, so not being restored 14103 if (DEBUG_BACKUP) { 14104 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14105 } 14106 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14107 } 14108 }); 14109 } 14110 14111 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14112 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14113 installerPkg, null, userIds); 14114 } 14115 14116 private abstract class HandlerParams { 14117 private static final int MAX_RETRIES = 4; 14118 14119 /** 14120 * Number of times startCopy() has been attempted and had a non-fatal 14121 * error. 14122 */ 14123 private int mRetries = 0; 14124 14125 /** User handle for the user requesting the information or installation. */ 14126 private final UserHandle mUser; 14127 String traceMethod; 14128 int traceCookie; 14129 14130 HandlerParams(UserHandle user) { 14131 mUser = user; 14132 } 14133 14134 UserHandle getUser() { 14135 return mUser; 14136 } 14137 14138 HandlerParams setTraceMethod(String traceMethod) { 14139 this.traceMethod = traceMethod; 14140 return this; 14141 } 14142 14143 HandlerParams setTraceCookie(int traceCookie) { 14144 this.traceCookie = traceCookie; 14145 return this; 14146 } 14147 14148 final boolean startCopy() { 14149 boolean res; 14150 try { 14151 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14152 14153 if (++mRetries > MAX_RETRIES) { 14154 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14155 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14156 handleServiceError(); 14157 return false; 14158 } else { 14159 handleStartCopy(); 14160 res = true; 14161 } 14162 } catch (RemoteException e) { 14163 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14164 mHandler.sendEmptyMessage(MCS_RECONNECT); 14165 res = false; 14166 } 14167 handleReturnCode(); 14168 return res; 14169 } 14170 14171 final void serviceError() { 14172 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14173 handleServiceError(); 14174 handleReturnCode(); 14175 } 14176 14177 abstract void handleStartCopy() throws RemoteException; 14178 abstract void handleServiceError(); 14179 abstract void handleReturnCode(); 14180 } 14181 14182 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14183 for (File path : paths) { 14184 try { 14185 mcs.clearDirectory(path.getAbsolutePath()); 14186 } catch (RemoteException e) { 14187 } 14188 } 14189 } 14190 14191 static class OriginInfo { 14192 /** 14193 * Location where install is coming from, before it has been 14194 * copied/renamed into place. This could be a single monolithic APK 14195 * file, or a cluster directory. This location may be untrusted. 14196 */ 14197 final File file; 14198 final String cid; 14199 14200 /** 14201 * Flag indicating that {@link #file} or {@link #cid} has already been 14202 * staged, meaning downstream users don't need to defensively copy the 14203 * contents. 14204 */ 14205 final boolean staged; 14206 14207 /** 14208 * Flag indicating that {@link #file} or {@link #cid} is an already 14209 * installed app that is being moved. 14210 */ 14211 final boolean existing; 14212 14213 final String resolvedPath; 14214 final File resolvedFile; 14215 14216 static OriginInfo fromNothing() { 14217 return new OriginInfo(null, null, false, false); 14218 } 14219 14220 static OriginInfo fromUntrustedFile(File file) { 14221 return new OriginInfo(file, null, false, false); 14222 } 14223 14224 static OriginInfo fromExistingFile(File file) { 14225 return new OriginInfo(file, null, false, true); 14226 } 14227 14228 static OriginInfo fromStagedFile(File file) { 14229 return new OriginInfo(file, null, true, false); 14230 } 14231 14232 static OriginInfo fromStagedContainer(String cid) { 14233 return new OriginInfo(null, cid, true, false); 14234 } 14235 14236 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14237 this.file = file; 14238 this.cid = cid; 14239 this.staged = staged; 14240 this.existing = existing; 14241 14242 if (cid != null) { 14243 resolvedPath = PackageHelper.getSdDir(cid); 14244 resolvedFile = new File(resolvedPath); 14245 } else if (file != null) { 14246 resolvedPath = file.getAbsolutePath(); 14247 resolvedFile = file; 14248 } else { 14249 resolvedPath = null; 14250 resolvedFile = null; 14251 } 14252 } 14253 } 14254 14255 static class MoveInfo { 14256 final int moveId; 14257 final String fromUuid; 14258 final String toUuid; 14259 final String packageName; 14260 final String dataAppName; 14261 final int appId; 14262 final String seinfo; 14263 final int targetSdkVersion; 14264 14265 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14266 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14267 this.moveId = moveId; 14268 this.fromUuid = fromUuid; 14269 this.toUuid = toUuid; 14270 this.packageName = packageName; 14271 this.dataAppName = dataAppName; 14272 this.appId = appId; 14273 this.seinfo = seinfo; 14274 this.targetSdkVersion = targetSdkVersion; 14275 } 14276 } 14277 14278 static class VerificationInfo { 14279 /** A constant used to indicate that a uid value is not present. */ 14280 public static final int NO_UID = -1; 14281 14282 /** URI referencing where the package was downloaded from. */ 14283 final Uri originatingUri; 14284 14285 /** HTTP referrer URI associated with the originatingURI. */ 14286 final Uri referrer; 14287 14288 /** UID of the application that the install request originated from. */ 14289 final int originatingUid; 14290 14291 /** UID of application requesting the install */ 14292 final int installerUid; 14293 14294 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14295 this.originatingUri = originatingUri; 14296 this.referrer = referrer; 14297 this.originatingUid = originatingUid; 14298 this.installerUid = installerUid; 14299 } 14300 } 14301 14302 class InstallParams extends HandlerParams { 14303 final OriginInfo origin; 14304 final MoveInfo move; 14305 final IPackageInstallObserver2 observer; 14306 int installFlags; 14307 final String installerPackageName; 14308 final String volumeUuid; 14309 private InstallArgs mArgs; 14310 private int mRet; 14311 final String packageAbiOverride; 14312 final String[] grantedRuntimePermissions; 14313 final VerificationInfo verificationInfo; 14314 final Certificate[][] certificates; 14315 final int installReason; 14316 14317 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14318 int installFlags, String installerPackageName, String volumeUuid, 14319 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14320 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14321 super(user); 14322 this.origin = origin; 14323 this.move = move; 14324 this.observer = observer; 14325 this.installFlags = installFlags; 14326 this.installerPackageName = installerPackageName; 14327 this.volumeUuid = volumeUuid; 14328 this.verificationInfo = verificationInfo; 14329 this.packageAbiOverride = packageAbiOverride; 14330 this.grantedRuntimePermissions = grantedPermissions; 14331 this.certificates = certificates; 14332 this.installReason = installReason; 14333 } 14334 14335 @Override 14336 public String toString() { 14337 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14338 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14339 } 14340 14341 private int installLocationPolicy(PackageInfoLite pkgLite) { 14342 String packageName = pkgLite.packageName; 14343 int installLocation = pkgLite.installLocation; 14344 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14345 // reader 14346 synchronized (mPackages) { 14347 // Currently installed package which the new package is attempting to replace or 14348 // null if no such package is installed. 14349 PackageParser.Package installedPkg = mPackages.get(packageName); 14350 // Package which currently owns the data which the new package will own if installed. 14351 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14352 // will be null whereas dataOwnerPkg will contain information about the package 14353 // which was uninstalled while keeping its data. 14354 PackageParser.Package dataOwnerPkg = installedPkg; 14355 if (dataOwnerPkg == null) { 14356 PackageSetting ps = mSettings.mPackages.get(packageName); 14357 if (ps != null) { 14358 dataOwnerPkg = ps.pkg; 14359 } 14360 } 14361 14362 if (dataOwnerPkg != null) { 14363 // If installed, the package will get access to data left on the device by its 14364 // predecessor. As a security measure, this is permited only if this is not a 14365 // version downgrade or if the predecessor package is marked as debuggable and 14366 // a downgrade is explicitly requested. 14367 // 14368 // On debuggable platform builds, downgrades are permitted even for 14369 // non-debuggable packages to make testing easier. Debuggable platform builds do 14370 // not offer security guarantees and thus it's OK to disable some security 14371 // mechanisms to make debugging/testing easier on those builds. However, even on 14372 // debuggable builds downgrades of packages are permitted only if requested via 14373 // installFlags. This is because we aim to keep the behavior of debuggable 14374 // platform builds as close as possible to the behavior of non-debuggable 14375 // platform builds. 14376 final boolean downgradeRequested = 14377 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14378 final boolean packageDebuggable = 14379 (dataOwnerPkg.applicationInfo.flags 14380 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14381 final boolean downgradePermitted = 14382 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14383 if (!downgradePermitted) { 14384 try { 14385 checkDowngrade(dataOwnerPkg, pkgLite); 14386 } catch (PackageManagerException e) { 14387 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14388 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14389 } 14390 } 14391 } 14392 14393 if (installedPkg != null) { 14394 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14395 // Check for updated system application. 14396 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14397 if (onSd) { 14398 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14399 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14400 } 14401 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14402 } else { 14403 if (onSd) { 14404 // Install flag overrides everything. 14405 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14406 } 14407 // If current upgrade specifies particular preference 14408 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14409 // Application explicitly specified internal. 14410 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14411 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14412 // App explictly prefers external. Let policy decide 14413 } else { 14414 // Prefer previous location 14415 if (isExternal(installedPkg)) { 14416 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14417 } 14418 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14419 } 14420 } 14421 } else { 14422 // Invalid install. Return error code 14423 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14424 } 14425 } 14426 } 14427 // All the special cases have been taken care of. 14428 // Return result based on recommended install location. 14429 if (onSd) { 14430 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14431 } 14432 return pkgLite.recommendedInstallLocation; 14433 } 14434 14435 /* 14436 * Invoke remote method to get package information and install 14437 * location values. Override install location based on default 14438 * policy if needed and then create install arguments based 14439 * on the install location. 14440 */ 14441 public void handleStartCopy() throws RemoteException { 14442 int ret = PackageManager.INSTALL_SUCCEEDED; 14443 14444 // If we're already staged, we've firmly committed to an install location 14445 if (origin.staged) { 14446 if (origin.file != null) { 14447 installFlags |= PackageManager.INSTALL_INTERNAL; 14448 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14449 } else if (origin.cid != null) { 14450 installFlags |= PackageManager.INSTALL_EXTERNAL; 14451 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14452 } else { 14453 throw new IllegalStateException("Invalid stage location"); 14454 } 14455 } 14456 14457 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14458 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14459 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14460 PackageInfoLite pkgLite = null; 14461 14462 if (onInt && onSd) { 14463 // Check if both bits are set. 14464 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14465 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14466 } else if (onSd && ephemeral) { 14467 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14468 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14469 } else { 14470 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14471 packageAbiOverride); 14472 14473 if (DEBUG_EPHEMERAL && ephemeral) { 14474 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14475 } 14476 14477 /* 14478 * If we have too little free space, try to free cache 14479 * before giving up. 14480 */ 14481 if (!origin.staged && pkgLite.recommendedInstallLocation 14482 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14483 // TODO: focus freeing disk space on the target device 14484 final StorageManager storage = StorageManager.from(mContext); 14485 final long lowThreshold = storage.getStorageLowBytes( 14486 Environment.getDataDirectory()); 14487 14488 final long sizeBytes = mContainerService.calculateInstalledSize( 14489 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14490 14491 try { 14492 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14493 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14494 installFlags, packageAbiOverride); 14495 } catch (InstallerException e) { 14496 Slog.w(TAG, "Failed to free cache", e); 14497 } 14498 14499 /* 14500 * The cache free must have deleted the file we 14501 * downloaded to install. 14502 * 14503 * TODO: fix the "freeCache" call to not delete 14504 * the file we care about. 14505 */ 14506 if (pkgLite.recommendedInstallLocation 14507 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14508 pkgLite.recommendedInstallLocation 14509 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14510 } 14511 } 14512 } 14513 14514 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14515 int loc = pkgLite.recommendedInstallLocation; 14516 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14517 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14518 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14519 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14520 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14521 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14522 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14523 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14524 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14525 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14526 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14527 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14528 } else { 14529 // Override with defaults if needed. 14530 loc = installLocationPolicy(pkgLite); 14531 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14532 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14533 } else if (!onSd && !onInt) { 14534 // Override install location with flags 14535 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14536 // Set the flag to install on external media. 14537 installFlags |= PackageManager.INSTALL_EXTERNAL; 14538 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14539 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14540 if (DEBUG_EPHEMERAL) { 14541 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14542 } 14543 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14544 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14545 |PackageManager.INSTALL_INTERNAL); 14546 } else { 14547 // Make sure the flag for installing on external 14548 // media is unset 14549 installFlags |= PackageManager.INSTALL_INTERNAL; 14550 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14551 } 14552 } 14553 } 14554 } 14555 14556 final InstallArgs args = createInstallArgs(this); 14557 mArgs = args; 14558 14559 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14560 // TODO: http://b/22976637 14561 // Apps installed for "all" users use the device owner to verify the app 14562 UserHandle verifierUser = getUser(); 14563 if (verifierUser == UserHandle.ALL) { 14564 verifierUser = UserHandle.SYSTEM; 14565 } 14566 14567 /* 14568 * Determine if we have any installed package verifiers. If we 14569 * do, then we'll defer to them to verify the packages. 14570 */ 14571 final int requiredUid = mRequiredVerifierPackage == null ? -1 14572 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14573 verifierUser.getIdentifier()); 14574 if (!origin.existing && requiredUid != -1 14575 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14576 final Intent verification = new Intent( 14577 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14578 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14579 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14580 PACKAGE_MIME_TYPE); 14581 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14582 14583 // Query all live verifiers based on current user state 14584 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14585 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14586 14587 if (DEBUG_VERIFY) { 14588 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14589 + verification.toString() + " with " + pkgLite.verifiers.length 14590 + " optional verifiers"); 14591 } 14592 14593 final int verificationId = mPendingVerificationToken++; 14594 14595 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14596 14597 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14598 installerPackageName); 14599 14600 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14601 installFlags); 14602 14603 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14604 pkgLite.packageName); 14605 14606 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14607 pkgLite.versionCode); 14608 14609 if (verificationInfo != null) { 14610 if (verificationInfo.originatingUri != null) { 14611 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14612 verificationInfo.originatingUri); 14613 } 14614 if (verificationInfo.referrer != null) { 14615 verification.putExtra(Intent.EXTRA_REFERRER, 14616 verificationInfo.referrer); 14617 } 14618 if (verificationInfo.originatingUid >= 0) { 14619 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14620 verificationInfo.originatingUid); 14621 } 14622 if (verificationInfo.installerUid >= 0) { 14623 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14624 verificationInfo.installerUid); 14625 } 14626 } 14627 14628 final PackageVerificationState verificationState = new PackageVerificationState( 14629 requiredUid, args); 14630 14631 mPendingVerification.append(verificationId, verificationState); 14632 14633 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14634 receivers, verificationState); 14635 14636 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14637 final long idleDuration = getVerificationTimeout(); 14638 14639 /* 14640 * If any sufficient verifiers were listed in the package 14641 * manifest, attempt to ask them. 14642 */ 14643 if (sufficientVerifiers != null) { 14644 final int N = sufficientVerifiers.size(); 14645 if (N == 0) { 14646 Slog.i(TAG, "Additional verifiers required, but none installed."); 14647 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14648 } else { 14649 for (int i = 0; i < N; i++) { 14650 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14651 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14652 verifierComponent.getPackageName(), idleDuration, 14653 verifierUser.getIdentifier(), false, "package verifier"); 14654 14655 final Intent sufficientIntent = new Intent(verification); 14656 sufficientIntent.setComponent(verifierComponent); 14657 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14658 } 14659 } 14660 } 14661 14662 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14663 mRequiredVerifierPackage, receivers); 14664 if (ret == PackageManager.INSTALL_SUCCEEDED 14665 && mRequiredVerifierPackage != null) { 14666 Trace.asyncTraceBegin( 14667 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14668 /* 14669 * Send the intent to the required verification agent, 14670 * but only start the verification timeout after the 14671 * target BroadcastReceivers have run. 14672 */ 14673 verification.setComponent(requiredVerifierComponent); 14674 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14675 mRequiredVerifierPackage, idleDuration, 14676 verifierUser.getIdentifier(), false, "package verifier"); 14677 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14678 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14679 new BroadcastReceiver() { 14680 @Override 14681 public void onReceive(Context context, Intent intent) { 14682 final Message msg = mHandler 14683 .obtainMessage(CHECK_PENDING_VERIFICATION); 14684 msg.arg1 = verificationId; 14685 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14686 } 14687 }, null, 0, null, null); 14688 14689 /* 14690 * We don't want the copy to proceed until verification 14691 * succeeds, so null out this field. 14692 */ 14693 mArgs = null; 14694 } 14695 } else { 14696 /* 14697 * No package verification is enabled, so immediately start 14698 * the remote call to initiate copy using temporary file. 14699 */ 14700 ret = args.copyApk(mContainerService, true); 14701 } 14702 } 14703 14704 mRet = ret; 14705 } 14706 14707 @Override 14708 void handleReturnCode() { 14709 // If mArgs is null, then MCS couldn't be reached. When it 14710 // reconnects, it will try again to install. At that point, this 14711 // will succeed. 14712 if (mArgs != null) { 14713 processPendingInstall(mArgs, mRet); 14714 } 14715 } 14716 14717 @Override 14718 void handleServiceError() { 14719 mArgs = createInstallArgs(this); 14720 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14721 } 14722 14723 public boolean isForwardLocked() { 14724 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14725 } 14726 } 14727 14728 /** 14729 * Used during creation of InstallArgs 14730 * 14731 * @param installFlags package installation flags 14732 * @return true if should be installed on external storage 14733 */ 14734 private static boolean installOnExternalAsec(int installFlags) { 14735 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14736 return false; 14737 } 14738 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14739 return true; 14740 } 14741 return false; 14742 } 14743 14744 /** 14745 * Used during creation of InstallArgs 14746 * 14747 * @param installFlags package installation flags 14748 * @return true if should be installed as forward locked 14749 */ 14750 private static boolean installForwardLocked(int installFlags) { 14751 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14752 } 14753 14754 private InstallArgs createInstallArgs(InstallParams params) { 14755 if (params.move != null) { 14756 return new MoveInstallArgs(params); 14757 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14758 return new AsecInstallArgs(params); 14759 } else { 14760 return new FileInstallArgs(params); 14761 } 14762 } 14763 14764 /** 14765 * Create args that describe an existing installed package. Typically used 14766 * when cleaning up old installs, or used as a move source. 14767 */ 14768 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14769 String resourcePath, String[] instructionSets) { 14770 final boolean isInAsec; 14771 if (installOnExternalAsec(installFlags)) { 14772 /* Apps on SD card are always in ASEC containers. */ 14773 isInAsec = true; 14774 } else if (installForwardLocked(installFlags) 14775 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14776 /* 14777 * Forward-locked apps are only in ASEC containers if they're the 14778 * new style 14779 */ 14780 isInAsec = true; 14781 } else { 14782 isInAsec = false; 14783 } 14784 14785 if (isInAsec) { 14786 return new AsecInstallArgs(codePath, instructionSets, 14787 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14788 } else { 14789 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14790 } 14791 } 14792 14793 static abstract class InstallArgs { 14794 /** @see InstallParams#origin */ 14795 final OriginInfo origin; 14796 /** @see InstallParams#move */ 14797 final MoveInfo move; 14798 14799 final IPackageInstallObserver2 observer; 14800 // Always refers to PackageManager flags only 14801 final int installFlags; 14802 final String installerPackageName; 14803 final String volumeUuid; 14804 final UserHandle user; 14805 final String abiOverride; 14806 final String[] installGrantPermissions; 14807 /** If non-null, drop an async trace when the install completes */ 14808 final String traceMethod; 14809 final int traceCookie; 14810 final Certificate[][] certificates; 14811 final int installReason; 14812 14813 // The list of instruction sets supported by this app. This is currently 14814 // only used during the rmdex() phase to clean up resources. We can get rid of this 14815 // if we move dex files under the common app path. 14816 /* nullable */ String[] instructionSets; 14817 14818 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14819 int installFlags, String installerPackageName, String volumeUuid, 14820 UserHandle user, String[] instructionSets, 14821 String abiOverride, String[] installGrantPermissions, 14822 String traceMethod, int traceCookie, Certificate[][] certificates, 14823 int installReason) { 14824 this.origin = origin; 14825 this.move = move; 14826 this.installFlags = installFlags; 14827 this.observer = observer; 14828 this.installerPackageName = installerPackageName; 14829 this.volumeUuid = volumeUuid; 14830 this.user = user; 14831 this.instructionSets = instructionSets; 14832 this.abiOverride = abiOverride; 14833 this.installGrantPermissions = installGrantPermissions; 14834 this.traceMethod = traceMethod; 14835 this.traceCookie = traceCookie; 14836 this.certificates = certificates; 14837 this.installReason = installReason; 14838 } 14839 14840 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14841 abstract int doPreInstall(int status); 14842 14843 /** 14844 * Rename package into final resting place. All paths on the given 14845 * scanned package should be updated to reflect the rename. 14846 */ 14847 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14848 abstract int doPostInstall(int status, int uid); 14849 14850 /** @see PackageSettingBase#codePathString */ 14851 abstract String getCodePath(); 14852 /** @see PackageSettingBase#resourcePathString */ 14853 abstract String getResourcePath(); 14854 14855 // Need installer lock especially for dex file removal. 14856 abstract void cleanUpResourcesLI(); 14857 abstract boolean doPostDeleteLI(boolean delete); 14858 14859 /** 14860 * Called before the source arguments are copied. This is used mostly 14861 * for MoveParams when it needs to read the source file to put it in the 14862 * destination. 14863 */ 14864 int doPreCopy() { 14865 return PackageManager.INSTALL_SUCCEEDED; 14866 } 14867 14868 /** 14869 * Called after the source arguments are copied. This is used mostly for 14870 * MoveParams when it needs to read the source file to put it in the 14871 * destination. 14872 */ 14873 int doPostCopy(int uid) { 14874 return PackageManager.INSTALL_SUCCEEDED; 14875 } 14876 14877 protected boolean isFwdLocked() { 14878 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14879 } 14880 14881 protected boolean isExternalAsec() { 14882 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14883 } 14884 14885 protected boolean isEphemeral() { 14886 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14887 } 14888 14889 UserHandle getUser() { 14890 return user; 14891 } 14892 } 14893 14894 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14895 if (!allCodePaths.isEmpty()) { 14896 if (instructionSets == null) { 14897 throw new IllegalStateException("instructionSet == null"); 14898 } 14899 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14900 for (String codePath : allCodePaths) { 14901 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14902 try { 14903 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14904 } catch (InstallerException ignored) { 14905 } 14906 } 14907 } 14908 } 14909 } 14910 14911 /** 14912 * Logic to handle installation of non-ASEC applications, including copying 14913 * and renaming logic. 14914 */ 14915 class FileInstallArgs extends InstallArgs { 14916 private File codeFile; 14917 private File resourceFile; 14918 14919 // Example topology: 14920 // /data/app/com.example/base.apk 14921 // /data/app/com.example/split_foo.apk 14922 // /data/app/com.example/lib/arm/libfoo.so 14923 // /data/app/com.example/lib/arm64/libfoo.so 14924 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14925 14926 /** New install */ 14927 FileInstallArgs(InstallParams params) { 14928 super(params.origin, params.move, params.observer, params.installFlags, 14929 params.installerPackageName, params.volumeUuid, 14930 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14931 params.grantedRuntimePermissions, 14932 params.traceMethod, params.traceCookie, params.certificates, 14933 params.installReason); 14934 if (isFwdLocked()) { 14935 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14936 } 14937 } 14938 14939 /** Existing install */ 14940 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14941 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14942 null, null, null, 0, null /*certificates*/, 14943 PackageManager.INSTALL_REASON_UNKNOWN); 14944 this.codeFile = (codePath != null) ? new File(codePath) : null; 14945 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14946 } 14947 14948 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14949 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14950 try { 14951 return doCopyApk(imcs, temp); 14952 } finally { 14953 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14954 } 14955 } 14956 14957 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14958 if (origin.staged) { 14959 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14960 codeFile = origin.file; 14961 resourceFile = origin.file; 14962 return PackageManager.INSTALL_SUCCEEDED; 14963 } 14964 14965 try { 14966 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14967 final File tempDir = 14968 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14969 codeFile = tempDir; 14970 resourceFile = tempDir; 14971 } catch (IOException e) { 14972 Slog.w(TAG, "Failed to create copy file: " + e); 14973 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14974 } 14975 14976 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14977 @Override 14978 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14979 if (!FileUtils.isValidExtFilename(name)) { 14980 throw new IllegalArgumentException("Invalid filename: " + name); 14981 } 14982 try { 14983 final File file = new File(codeFile, name); 14984 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14985 O_RDWR | O_CREAT, 0644); 14986 Os.chmod(file.getAbsolutePath(), 0644); 14987 return new ParcelFileDescriptor(fd); 14988 } catch (ErrnoException e) { 14989 throw new RemoteException("Failed to open: " + e.getMessage()); 14990 } 14991 } 14992 }; 14993 14994 int ret = PackageManager.INSTALL_SUCCEEDED; 14995 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14996 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14997 Slog.e(TAG, "Failed to copy package"); 14998 return ret; 14999 } 15000 15001 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15002 NativeLibraryHelper.Handle handle = null; 15003 try { 15004 handle = NativeLibraryHelper.Handle.create(codeFile); 15005 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15006 abiOverride); 15007 } catch (IOException e) { 15008 Slog.e(TAG, "Copying native libraries failed", e); 15009 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15010 } finally { 15011 IoUtils.closeQuietly(handle); 15012 } 15013 15014 return ret; 15015 } 15016 15017 int doPreInstall(int status) { 15018 if (status != PackageManager.INSTALL_SUCCEEDED) { 15019 cleanUp(); 15020 } 15021 return status; 15022 } 15023 15024 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15025 if (status != PackageManager.INSTALL_SUCCEEDED) { 15026 cleanUp(); 15027 return false; 15028 } 15029 15030 final File targetDir = codeFile.getParentFile(); 15031 final File beforeCodeFile = codeFile; 15032 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15033 15034 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15035 try { 15036 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15037 } catch (ErrnoException e) { 15038 Slog.w(TAG, "Failed to rename", e); 15039 return false; 15040 } 15041 15042 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15043 Slog.w(TAG, "Failed to restorecon"); 15044 return false; 15045 } 15046 15047 // Reflect the rename internally 15048 codeFile = afterCodeFile; 15049 resourceFile = afterCodeFile; 15050 15051 // Reflect the rename in scanned details 15052 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15053 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15054 afterCodeFile, pkg.baseCodePath)); 15055 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15056 afterCodeFile, pkg.splitCodePaths)); 15057 15058 // Reflect the rename in app info 15059 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15060 pkg.setApplicationInfoCodePath(pkg.codePath); 15061 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15062 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15063 pkg.setApplicationInfoResourcePath(pkg.codePath); 15064 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15065 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15066 15067 return true; 15068 } 15069 15070 int doPostInstall(int status, int uid) { 15071 if (status != PackageManager.INSTALL_SUCCEEDED) { 15072 cleanUp(); 15073 } 15074 return status; 15075 } 15076 15077 @Override 15078 String getCodePath() { 15079 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15080 } 15081 15082 @Override 15083 String getResourcePath() { 15084 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15085 } 15086 15087 private boolean cleanUp() { 15088 if (codeFile == null || !codeFile.exists()) { 15089 return false; 15090 } 15091 15092 removeCodePathLI(codeFile); 15093 15094 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15095 resourceFile.delete(); 15096 } 15097 15098 return true; 15099 } 15100 15101 void cleanUpResourcesLI() { 15102 // Try enumerating all code paths before deleting 15103 List<String> allCodePaths = Collections.EMPTY_LIST; 15104 if (codeFile != null && codeFile.exists()) { 15105 try { 15106 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15107 allCodePaths = pkg.getAllCodePaths(); 15108 } catch (PackageParserException e) { 15109 // Ignored; we tried our best 15110 } 15111 } 15112 15113 cleanUp(); 15114 removeDexFiles(allCodePaths, instructionSets); 15115 } 15116 15117 boolean doPostDeleteLI(boolean delete) { 15118 // XXX err, shouldn't we respect the delete flag? 15119 cleanUpResourcesLI(); 15120 return true; 15121 } 15122 } 15123 15124 private boolean isAsecExternal(String cid) { 15125 final String asecPath = PackageHelper.getSdFilesystem(cid); 15126 return !asecPath.startsWith(mAsecInternalPath); 15127 } 15128 15129 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15130 PackageManagerException { 15131 if (copyRet < 0) { 15132 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15133 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15134 throw new PackageManagerException(copyRet, message); 15135 } 15136 } 15137 } 15138 15139 /** 15140 * Extract the StorageManagerService "container ID" from the full code path of an 15141 * .apk. 15142 */ 15143 static String cidFromCodePath(String fullCodePath) { 15144 int eidx = fullCodePath.lastIndexOf("/"); 15145 String subStr1 = fullCodePath.substring(0, eidx); 15146 int sidx = subStr1.lastIndexOf("/"); 15147 return subStr1.substring(sidx+1, eidx); 15148 } 15149 15150 /** 15151 * Logic to handle installation of ASEC applications, including copying and 15152 * renaming logic. 15153 */ 15154 class AsecInstallArgs extends InstallArgs { 15155 static final String RES_FILE_NAME = "pkg.apk"; 15156 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15157 15158 String cid; 15159 String packagePath; 15160 String resourcePath; 15161 15162 /** New install */ 15163 AsecInstallArgs(InstallParams params) { 15164 super(params.origin, params.move, params.observer, params.installFlags, 15165 params.installerPackageName, params.volumeUuid, 15166 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15167 params.grantedRuntimePermissions, 15168 params.traceMethod, params.traceCookie, params.certificates, 15169 params.installReason); 15170 } 15171 15172 /** Existing install */ 15173 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15174 boolean isExternal, boolean isForwardLocked) { 15175 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15176 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15177 instructionSets, null, null, null, 0, null /*certificates*/, 15178 PackageManager.INSTALL_REASON_UNKNOWN); 15179 // Hackily pretend we're still looking at a full code path 15180 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15181 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15182 } 15183 15184 // Extract cid from fullCodePath 15185 int eidx = fullCodePath.lastIndexOf("/"); 15186 String subStr1 = fullCodePath.substring(0, eidx); 15187 int sidx = subStr1.lastIndexOf("/"); 15188 cid = subStr1.substring(sidx+1, eidx); 15189 setMountPath(subStr1); 15190 } 15191 15192 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15193 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15194 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15195 instructionSets, null, null, null, 0, null /*certificates*/, 15196 PackageManager.INSTALL_REASON_UNKNOWN); 15197 this.cid = cid; 15198 setMountPath(PackageHelper.getSdDir(cid)); 15199 } 15200 15201 void createCopyFile() { 15202 cid = mInstallerService.allocateExternalStageCidLegacy(); 15203 } 15204 15205 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15206 if (origin.staged && origin.cid != null) { 15207 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15208 cid = origin.cid; 15209 setMountPath(PackageHelper.getSdDir(cid)); 15210 return PackageManager.INSTALL_SUCCEEDED; 15211 } 15212 15213 if (temp) { 15214 createCopyFile(); 15215 } else { 15216 /* 15217 * Pre-emptively destroy the container since it's destroyed if 15218 * copying fails due to it existing anyway. 15219 */ 15220 PackageHelper.destroySdDir(cid); 15221 } 15222 15223 final String newMountPath = imcs.copyPackageToContainer( 15224 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15225 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15226 15227 if (newMountPath != null) { 15228 setMountPath(newMountPath); 15229 return PackageManager.INSTALL_SUCCEEDED; 15230 } else { 15231 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15232 } 15233 } 15234 15235 @Override 15236 String getCodePath() { 15237 return packagePath; 15238 } 15239 15240 @Override 15241 String getResourcePath() { 15242 return resourcePath; 15243 } 15244 15245 int doPreInstall(int status) { 15246 if (status != PackageManager.INSTALL_SUCCEEDED) { 15247 // Destroy container 15248 PackageHelper.destroySdDir(cid); 15249 } else { 15250 boolean mounted = PackageHelper.isContainerMounted(cid); 15251 if (!mounted) { 15252 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15253 Process.SYSTEM_UID); 15254 if (newMountPath != null) { 15255 setMountPath(newMountPath); 15256 } else { 15257 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15258 } 15259 } 15260 } 15261 return status; 15262 } 15263 15264 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15265 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15266 String newMountPath = null; 15267 if (PackageHelper.isContainerMounted(cid)) { 15268 // Unmount the container 15269 if (!PackageHelper.unMountSdDir(cid)) { 15270 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15271 return false; 15272 } 15273 } 15274 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15275 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15276 " which might be stale. Will try to clean up."); 15277 // Clean up the stale container and proceed to recreate. 15278 if (!PackageHelper.destroySdDir(newCacheId)) { 15279 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15280 return false; 15281 } 15282 // Successfully cleaned up stale container. Try to rename again. 15283 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15284 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15285 + " inspite of cleaning it up."); 15286 return false; 15287 } 15288 } 15289 if (!PackageHelper.isContainerMounted(newCacheId)) { 15290 Slog.w(TAG, "Mounting container " + newCacheId); 15291 newMountPath = PackageHelper.mountSdDir(newCacheId, 15292 getEncryptKey(), Process.SYSTEM_UID); 15293 } else { 15294 newMountPath = PackageHelper.getSdDir(newCacheId); 15295 } 15296 if (newMountPath == null) { 15297 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15298 return false; 15299 } 15300 Log.i(TAG, "Succesfully renamed " + cid + 15301 " to " + newCacheId + 15302 " at new path: " + newMountPath); 15303 cid = newCacheId; 15304 15305 final File beforeCodeFile = new File(packagePath); 15306 setMountPath(newMountPath); 15307 final File afterCodeFile = new File(packagePath); 15308 15309 // Reflect the rename in scanned details 15310 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15311 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15312 afterCodeFile, pkg.baseCodePath)); 15313 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15314 afterCodeFile, pkg.splitCodePaths)); 15315 15316 // Reflect the rename in app info 15317 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15318 pkg.setApplicationInfoCodePath(pkg.codePath); 15319 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15320 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15321 pkg.setApplicationInfoResourcePath(pkg.codePath); 15322 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15323 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15324 15325 return true; 15326 } 15327 15328 private void setMountPath(String mountPath) { 15329 final File mountFile = new File(mountPath); 15330 15331 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15332 if (monolithicFile.exists()) { 15333 packagePath = monolithicFile.getAbsolutePath(); 15334 if (isFwdLocked()) { 15335 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15336 } else { 15337 resourcePath = packagePath; 15338 } 15339 } else { 15340 packagePath = mountFile.getAbsolutePath(); 15341 resourcePath = packagePath; 15342 } 15343 } 15344 15345 int doPostInstall(int status, int uid) { 15346 if (status != PackageManager.INSTALL_SUCCEEDED) { 15347 cleanUp(); 15348 } else { 15349 final int groupOwner; 15350 final String protectedFile; 15351 if (isFwdLocked()) { 15352 groupOwner = UserHandle.getSharedAppGid(uid); 15353 protectedFile = RES_FILE_NAME; 15354 } else { 15355 groupOwner = -1; 15356 protectedFile = null; 15357 } 15358 15359 if (uid < Process.FIRST_APPLICATION_UID 15360 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15361 Slog.e(TAG, "Failed to finalize " + cid); 15362 PackageHelper.destroySdDir(cid); 15363 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15364 } 15365 15366 boolean mounted = PackageHelper.isContainerMounted(cid); 15367 if (!mounted) { 15368 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15369 } 15370 } 15371 return status; 15372 } 15373 15374 private void cleanUp() { 15375 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15376 15377 // Destroy secure container 15378 PackageHelper.destroySdDir(cid); 15379 } 15380 15381 private List<String> getAllCodePaths() { 15382 final File codeFile = new File(getCodePath()); 15383 if (codeFile != null && codeFile.exists()) { 15384 try { 15385 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15386 return pkg.getAllCodePaths(); 15387 } catch (PackageParserException e) { 15388 // Ignored; we tried our best 15389 } 15390 } 15391 return Collections.EMPTY_LIST; 15392 } 15393 15394 void cleanUpResourcesLI() { 15395 // Enumerate all code paths before deleting 15396 cleanUpResourcesLI(getAllCodePaths()); 15397 } 15398 15399 private void cleanUpResourcesLI(List<String> allCodePaths) { 15400 cleanUp(); 15401 removeDexFiles(allCodePaths, instructionSets); 15402 } 15403 15404 String getPackageName() { 15405 return getAsecPackageName(cid); 15406 } 15407 15408 boolean doPostDeleteLI(boolean delete) { 15409 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15410 final List<String> allCodePaths = getAllCodePaths(); 15411 boolean mounted = PackageHelper.isContainerMounted(cid); 15412 if (mounted) { 15413 // Unmount first 15414 if (PackageHelper.unMountSdDir(cid)) { 15415 mounted = false; 15416 } 15417 } 15418 if (!mounted && delete) { 15419 cleanUpResourcesLI(allCodePaths); 15420 } 15421 return !mounted; 15422 } 15423 15424 @Override 15425 int doPreCopy() { 15426 if (isFwdLocked()) { 15427 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15428 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15429 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15430 } 15431 } 15432 15433 return PackageManager.INSTALL_SUCCEEDED; 15434 } 15435 15436 @Override 15437 int doPostCopy(int uid) { 15438 if (isFwdLocked()) { 15439 if (uid < Process.FIRST_APPLICATION_UID 15440 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15441 RES_FILE_NAME)) { 15442 Slog.e(TAG, "Failed to finalize " + cid); 15443 PackageHelper.destroySdDir(cid); 15444 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15445 } 15446 } 15447 15448 return PackageManager.INSTALL_SUCCEEDED; 15449 } 15450 } 15451 15452 /** 15453 * Logic to handle movement of existing installed applications. 15454 */ 15455 class MoveInstallArgs extends InstallArgs { 15456 private File codeFile; 15457 private File resourceFile; 15458 15459 /** New install */ 15460 MoveInstallArgs(InstallParams params) { 15461 super(params.origin, params.move, params.observer, params.installFlags, 15462 params.installerPackageName, params.volumeUuid, 15463 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15464 params.grantedRuntimePermissions, 15465 params.traceMethod, params.traceCookie, params.certificates, 15466 params.installReason); 15467 } 15468 15469 int copyApk(IMediaContainerService imcs, boolean temp) { 15470 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15471 + move.fromUuid + " to " + move.toUuid); 15472 synchronized (mInstaller) { 15473 try { 15474 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15475 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15476 } catch (InstallerException e) { 15477 Slog.w(TAG, "Failed to move app", e); 15478 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15479 } 15480 } 15481 15482 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15483 resourceFile = codeFile; 15484 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15485 15486 return PackageManager.INSTALL_SUCCEEDED; 15487 } 15488 15489 int doPreInstall(int status) { 15490 if (status != PackageManager.INSTALL_SUCCEEDED) { 15491 cleanUp(move.toUuid); 15492 } 15493 return status; 15494 } 15495 15496 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15497 if (status != PackageManager.INSTALL_SUCCEEDED) { 15498 cleanUp(move.toUuid); 15499 return false; 15500 } 15501 15502 // Reflect the move in app info 15503 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15504 pkg.setApplicationInfoCodePath(pkg.codePath); 15505 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15506 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15507 pkg.setApplicationInfoResourcePath(pkg.codePath); 15508 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15509 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15510 15511 return true; 15512 } 15513 15514 int doPostInstall(int status, int uid) { 15515 if (status == PackageManager.INSTALL_SUCCEEDED) { 15516 cleanUp(move.fromUuid); 15517 } else { 15518 cleanUp(move.toUuid); 15519 } 15520 return status; 15521 } 15522 15523 @Override 15524 String getCodePath() { 15525 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15526 } 15527 15528 @Override 15529 String getResourcePath() { 15530 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15531 } 15532 15533 private boolean cleanUp(String volumeUuid) { 15534 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15535 move.dataAppName); 15536 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15537 final int[] userIds = sUserManager.getUserIds(); 15538 synchronized (mInstallLock) { 15539 // Clean up both app data and code 15540 // All package moves are frozen until finished 15541 for (int userId : userIds) { 15542 try { 15543 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15544 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15545 } catch (InstallerException e) { 15546 Slog.w(TAG, String.valueOf(e)); 15547 } 15548 } 15549 removeCodePathLI(codeFile); 15550 } 15551 return true; 15552 } 15553 15554 void cleanUpResourcesLI() { 15555 throw new UnsupportedOperationException(); 15556 } 15557 15558 boolean doPostDeleteLI(boolean delete) { 15559 throw new UnsupportedOperationException(); 15560 } 15561 } 15562 15563 static String getAsecPackageName(String packageCid) { 15564 int idx = packageCid.lastIndexOf("-"); 15565 if (idx == -1) { 15566 return packageCid; 15567 } 15568 return packageCid.substring(0, idx); 15569 } 15570 15571 // Utility method used to create code paths based on package name and available index. 15572 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15573 String idxStr = ""; 15574 int idx = 1; 15575 // Fall back to default value of idx=1 if prefix is not 15576 // part of oldCodePath 15577 if (oldCodePath != null) { 15578 String subStr = oldCodePath; 15579 // Drop the suffix right away 15580 if (suffix != null && subStr.endsWith(suffix)) { 15581 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15582 } 15583 // If oldCodePath already contains prefix find out the 15584 // ending index to either increment or decrement. 15585 int sidx = subStr.lastIndexOf(prefix); 15586 if (sidx != -1) { 15587 subStr = subStr.substring(sidx + prefix.length()); 15588 if (subStr != null) { 15589 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15590 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15591 } 15592 try { 15593 idx = Integer.parseInt(subStr); 15594 if (idx <= 1) { 15595 idx++; 15596 } else { 15597 idx--; 15598 } 15599 } catch(NumberFormatException e) { 15600 } 15601 } 15602 } 15603 } 15604 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15605 return prefix + idxStr; 15606 } 15607 15608 private File getNextCodePath(File targetDir, String packageName) { 15609 File result; 15610 SecureRandom random = new SecureRandom(); 15611 byte[] bytes = new byte[16]; 15612 do { 15613 random.nextBytes(bytes); 15614 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15615 result = new File(targetDir, packageName + "-" + suffix); 15616 } while (result.exists()); 15617 return result; 15618 } 15619 15620 // Utility method that returns the relative package path with respect 15621 // to the installation directory. Like say for /data/data/com.test-1.apk 15622 // string com.test-1 is returned. 15623 static String deriveCodePathName(String codePath) { 15624 if (codePath == null) { 15625 return null; 15626 } 15627 final File codeFile = new File(codePath); 15628 final String name = codeFile.getName(); 15629 if (codeFile.isDirectory()) { 15630 return name; 15631 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15632 final int lastDot = name.lastIndexOf('.'); 15633 return name.substring(0, lastDot); 15634 } else { 15635 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15636 return null; 15637 } 15638 } 15639 15640 static class PackageInstalledInfo { 15641 String name; 15642 int uid; 15643 // The set of users that originally had this package installed. 15644 int[] origUsers; 15645 // The set of users that now have this package installed. 15646 int[] newUsers; 15647 PackageParser.Package pkg; 15648 int returnCode; 15649 String returnMsg; 15650 PackageRemovedInfo removedInfo; 15651 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15652 15653 public void setError(int code, String msg) { 15654 setReturnCode(code); 15655 setReturnMessage(msg); 15656 Slog.w(TAG, msg); 15657 } 15658 15659 public void setError(String msg, PackageParserException e) { 15660 setReturnCode(e.error); 15661 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15662 Slog.w(TAG, msg, e); 15663 } 15664 15665 public void setError(String msg, PackageManagerException e) { 15666 returnCode = e.error; 15667 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15668 Slog.w(TAG, msg, e); 15669 } 15670 15671 public void setReturnCode(int returnCode) { 15672 this.returnCode = returnCode; 15673 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15674 for (int i = 0; i < childCount; i++) { 15675 addedChildPackages.valueAt(i).returnCode = returnCode; 15676 } 15677 } 15678 15679 private void setReturnMessage(String returnMsg) { 15680 this.returnMsg = returnMsg; 15681 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15682 for (int i = 0; i < childCount; i++) { 15683 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15684 } 15685 } 15686 15687 // In some error cases we want to convey more info back to the observer 15688 String origPackage; 15689 String origPermission; 15690 } 15691 15692 /* 15693 * Install a non-existing package. 15694 */ 15695 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15696 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15697 PackageInstalledInfo res, int installReason) { 15698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15699 15700 // Remember this for later, in case we need to rollback this install 15701 String pkgName = pkg.packageName; 15702 15703 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15704 15705 synchronized(mPackages) { 15706 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15707 if (renamedPackage != null) { 15708 // A package with the same name is already installed, though 15709 // it has been renamed to an older name. The package we 15710 // are trying to install should be installed as an update to 15711 // the existing one, but that has not been requested, so bail. 15712 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15713 + " without first uninstalling package running as " 15714 + renamedPackage); 15715 return; 15716 } 15717 if (mPackages.containsKey(pkgName)) { 15718 // Don't allow installation over an existing package with the same name. 15719 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15720 + " without first uninstalling."); 15721 return; 15722 } 15723 } 15724 15725 try { 15726 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15727 System.currentTimeMillis(), user); 15728 15729 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15730 15731 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15732 prepareAppDataAfterInstallLIF(newPackage); 15733 15734 } else { 15735 // Remove package from internal structures, but keep around any 15736 // data that might have already existed 15737 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15738 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15739 } 15740 } catch (PackageManagerException e) { 15741 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15742 } 15743 15744 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15745 } 15746 15747 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15748 // Can't rotate keys during boot or if sharedUser. 15749 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15750 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15751 return false; 15752 } 15753 // app is using upgradeKeySets; make sure all are valid 15754 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15755 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15756 for (int i = 0; i < upgradeKeySets.length; i++) { 15757 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15758 Slog.wtf(TAG, "Package " 15759 + (oldPs.name != null ? oldPs.name : "<null>") 15760 + " contains upgrade-key-set reference to unknown key-set: " 15761 + upgradeKeySets[i] 15762 + " reverting to signatures check."); 15763 return false; 15764 } 15765 } 15766 return true; 15767 } 15768 15769 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15770 // Upgrade keysets are being used. Determine if new package has a superset of the 15771 // required keys. 15772 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15773 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15774 for (int i = 0; i < upgradeKeySets.length; i++) { 15775 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15776 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15777 return true; 15778 } 15779 } 15780 return false; 15781 } 15782 15783 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15784 try (DigestInputStream digestStream = 15785 new DigestInputStream(new FileInputStream(file), digest)) { 15786 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15787 } 15788 } 15789 15790 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15791 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15792 int installReason) { 15793 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15794 15795 final PackageParser.Package oldPackage; 15796 final String pkgName = pkg.packageName; 15797 final int[] allUsers; 15798 final int[] installedUsers; 15799 15800 synchronized(mPackages) { 15801 oldPackage = mPackages.get(pkgName); 15802 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15803 15804 // don't allow upgrade to target a release SDK from a pre-release SDK 15805 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15806 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15807 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15808 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15809 if (oldTargetsPreRelease 15810 && !newTargetsPreRelease 15811 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15812 Slog.w(TAG, "Can't install package targeting released sdk"); 15813 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15814 return; 15815 } 15816 15817 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15818 15819 // verify signatures are valid 15820 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15821 if (!checkUpgradeKeySetLP(ps, pkg)) { 15822 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15823 "New package not signed by keys specified by upgrade-keysets: " 15824 + pkgName); 15825 return; 15826 } 15827 } else { 15828 // default to original signature matching 15829 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15830 != PackageManager.SIGNATURE_MATCH) { 15831 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15832 "New package has a different signature: " + pkgName); 15833 return; 15834 } 15835 } 15836 15837 // don't allow a system upgrade unless the upgrade hash matches 15838 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15839 byte[] digestBytes = null; 15840 try { 15841 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15842 updateDigest(digest, new File(pkg.baseCodePath)); 15843 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15844 for (String path : pkg.splitCodePaths) { 15845 updateDigest(digest, new File(path)); 15846 } 15847 } 15848 digestBytes = digest.digest(); 15849 } catch (NoSuchAlgorithmException | IOException e) { 15850 res.setError(INSTALL_FAILED_INVALID_APK, 15851 "Could not compute hash: " + pkgName); 15852 return; 15853 } 15854 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15855 res.setError(INSTALL_FAILED_INVALID_APK, 15856 "New package fails restrict-update check: " + pkgName); 15857 return; 15858 } 15859 // retain upgrade restriction 15860 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15861 } 15862 15863 // Check for shared user id changes 15864 String invalidPackageName = 15865 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15866 if (invalidPackageName != null) { 15867 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15868 "Package " + invalidPackageName + " tried to change user " 15869 + oldPackage.mSharedUserId); 15870 return; 15871 } 15872 15873 // In case of rollback, remember per-user/profile install state 15874 allUsers = sUserManager.getUserIds(); 15875 installedUsers = ps.queryInstalledUsers(allUsers, true); 15876 15877 // don't allow an upgrade from full to ephemeral 15878 if (isInstantApp) { 15879 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15880 for (int currentUser : allUsers) { 15881 if (!ps.getInstantApp(currentUser)) { 15882 // can't downgrade from full to instant 15883 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15884 + " for user: " + currentUser); 15885 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15886 return; 15887 } 15888 } 15889 } else if (!ps.getInstantApp(user.getIdentifier())) { 15890 // can't downgrade from full to instant 15891 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15892 + " for user: " + user.getIdentifier()); 15893 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15894 return; 15895 } 15896 } 15897 } 15898 15899 // Update what is removed 15900 res.removedInfo = new PackageRemovedInfo(); 15901 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15902 res.removedInfo.removedPackage = oldPackage.packageName; 15903 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15904 res.removedInfo.isUpdate = true; 15905 res.removedInfo.origUsers = installedUsers; 15906 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15907 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15908 for (int i = 0; i < installedUsers.length; i++) { 15909 final int userId = installedUsers[i]; 15910 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15911 } 15912 15913 final int childCount = (oldPackage.childPackages != null) 15914 ? oldPackage.childPackages.size() : 0; 15915 for (int i = 0; i < childCount; i++) { 15916 boolean childPackageUpdated = false; 15917 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15918 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15919 if (res.addedChildPackages != null) { 15920 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15921 if (childRes != null) { 15922 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15923 childRes.removedInfo.removedPackage = childPkg.packageName; 15924 childRes.removedInfo.isUpdate = true; 15925 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15926 childPackageUpdated = true; 15927 } 15928 } 15929 if (!childPackageUpdated) { 15930 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15931 childRemovedRes.removedPackage = childPkg.packageName; 15932 childRemovedRes.isUpdate = false; 15933 childRemovedRes.dataRemoved = true; 15934 synchronized (mPackages) { 15935 if (childPs != null) { 15936 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15937 } 15938 } 15939 if (res.removedInfo.removedChildPackages == null) { 15940 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15941 } 15942 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15943 } 15944 } 15945 15946 boolean sysPkg = (isSystemApp(oldPackage)); 15947 if (sysPkg) { 15948 // Set the system/privileged flags as needed 15949 final boolean privileged = 15950 (oldPackage.applicationInfo.privateFlags 15951 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15952 final int systemPolicyFlags = policyFlags 15953 | PackageParser.PARSE_IS_SYSTEM 15954 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15955 15956 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15957 user, allUsers, installerPackageName, res, installReason); 15958 } else { 15959 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15960 user, allUsers, installerPackageName, res, installReason); 15961 } 15962 } 15963 15964 public List<String> getPreviousCodePaths(String packageName) { 15965 final PackageSetting ps = mSettings.mPackages.get(packageName); 15966 final List<String> result = new ArrayList<String>(); 15967 if (ps != null && ps.oldCodePaths != null) { 15968 result.addAll(ps.oldCodePaths); 15969 } 15970 return result; 15971 } 15972 15973 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15974 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15975 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15976 int installReason) { 15977 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15978 + deletedPackage); 15979 15980 String pkgName = deletedPackage.packageName; 15981 boolean deletedPkg = true; 15982 boolean addedPkg = false; 15983 boolean updatedSettings = false; 15984 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15985 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15986 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15987 15988 final long origUpdateTime = (pkg.mExtras != null) 15989 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15990 15991 // First delete the existing package while retaining the data directory 15992 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15993 res.removedInfo, true, pkg)) { 15994 // If the existing package wasn't successfully deleted 15995 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15996 deletedPkg = false; 15997 } else { 15998 // Successfully deleted the old package; proceed with replace. 15999 16000 // If deleted package lived in a container, give users a chance to 16001 // relinquish resources before killing. 16002 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16003 if (DEBUG_INSTALL) { 16004 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16005 } 16006 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16007 final ArrayList<String> pkgList = new ArrayList<String>(1); 16008 pkgList.add(deletedPackage.applicationInfo.packageName); 16009 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16010 } 16011 16012 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16013 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16014 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16015 16016 try { 16017 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16018 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16019 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16020 installReason); 16021 16022 // Update the in-memory copy of the previous code paths. 16023 PackageSetting ps = mSettings.mPackages.get(pkgName); 16024 if (!killApp) { 16025 if (ps.oldCodePaths == null) { 16026 ps.oldCodePaths = new ArraySet<>(); 16027 } 16028 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16029 if (deletedPackage.splitCodePaths != null) { 16030 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16031 } 16032 } else { 16033 ps.oldCodePaths = null; 16034 } 16035 if (ps.childPackageNames != null) { 16036 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16037 final String childPkgName = ps.childPackageNames.get(i); 16038 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16039 childPs.oldCodePaths = ps.oldCodePaths; 16040 } 16041 } 16042 // set instant app status, but, only if it's explicitly specified 16043 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16044 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16045 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16046 prepareAppDataAfterInstallLIF(newPackage); 16047 addedPkg = true; 16048 mDexManager.notifyPackageUpdated(newPackage.packageName, 16049 newPackage.baseCodePath, newPackage.splitCodePaths); 16050 } catch (PackageManagerException e) { 16051 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16052 } 16053 } 16054 16055 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16056 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16057 16058 // Revert all internal state mutations and added folders for the failed install 16059 if (addedPkg) { 16060 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16061 res.removedInfo, true, null); 16062 } 16063 16064 // Restore the old package 16065 if (deletedPkg) { 16066 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16067 File restoreFile = new File(deletedPackage.codePath); 16068 // Parse old package 16069 boolean oldExternal = isExternal(deletedPackage); 16070 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16071 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16072 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16073 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16074 try { 16075 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16076 null); 16077 } catch (PackageManagerException e) { 16078 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16079 + e.getMessage()); 16080 return; 16081 } 16082 16083 synchronized (mPackages) { 16084 // Ensure the installer package name up to date 16085 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16086 16087 // Update permissions for restored package 16088 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16089 16090 mSettings.writeLPr(); 16091 } 16092 16093 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16094 } 16095 } else { 16096 synchronized (mPackages) { 16097 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16098 if (ps != null) { 16099 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16100 if (res.removedInfo.removedChildPackages != null) { 16101 final int childCount = res.removedInfo.removedChildPackages.size(); 16102 // Iterate in reverse as we may modify the collection 16103 for (int i = childCount - 1; i >= 0; i--) { 16104 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16105 if (res.addedChildPackages.containsKey(childPackageName)) { 16106 res.removedInfo.removedChildPackages.removeAt(i); 16107 } else { 16108 PackageRemovedInfo childInfo = res.removedInfo 16109 .removedChildPackages.valueAt(i); 16110 childInfo.removedForAllUsers = mPackages.get( 16111 childInfo.removedPackage) == null; 16112 } 16113 } 16114 } 16115 } 16116 } 16117 } 16118 } 16119 16120 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16121 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16122 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16123 int installReason) { 16124 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16125 + ", old=" + deletedPackage); 16126 16127 final boolean disabledSystem; 16128 16129 // Remove existing system package 16130 removePackageLI(deletedPackage, true); 16131 16132 synchronized (mPackages) { 16133 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16134 } 16135 if (!disabledSystem) { 16136 // We didn't need to disable the .apk as a current system package, 16137 // which means we are replacing another update that is already 16138 // installed. We need to make sure to delete the older one's .apk. 16139 res.removedInfo.args = createInstallArgsForExisting(0, 16140 deletedPackage.applicationInfo.getCodePath(), 16141 deletedPackage.applicationInfo.getResourcePath(), 16142 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16143 } else { 16144 res.removedInfo.args = null; 16145 } 16146 16147 // Successfully disabled the old package. Now proceed with re-installation 16148 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16149 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16150 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16151 16152 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16153 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16154 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16155 16156 PackageParser.Package newPackage = null; 16157 try { 16158 // Add the package to the internal data structures 16159 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16160 16161 // Set the update and install times 16162 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16163 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16164 System.currentTimeMillis()); 16165 16166 // Update the package dynamic state if succeeded 16167 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16168 // Now that the install succeeded make sure we remove data 16169 // directories for any child package the update removed. 16170 final int deletedChildCount = (deletedPackage.childPackages != null) 16171 ? deletedPackage.childPackages.size() : 0; 16172 final int newChildCount = (newPackage.childPackages != null) 16173 ? newPackage.childPackages.size() : 0; 16174 for (int i = 0; i < deletedChildCount; i++) { 16175 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16176 boolean childPackageDeleted = true; 16177 for (int j = 0; j < newChildCount; j++) { 16178 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16179 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16180 childPackageDeleted = false; 16181 break; 16182 } 16183 } 16184 if (childPackageDeleted) { 16185 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16186 deletedChildPkg.packageName); 16187 if (ps != null && res.removedInfo.removedChildPackages != null) { 16188 PackageRemovedInfo removedChildRes = res.removedInfo 16189 .removedChildPackages.get(deletedChildPkg.packageName); 16190 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16191 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16192 } 16193 } 16194 } 16195 16196 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16197 installReason); 16198 prepareAppDataAfterInstallLIF(newPackage); 16199 16200 mDexManager.notifyPackageUpdated(newPackage.packageName, 16201 newPackage.baseCodePath, newPackage.splitCodePaths); 16202 } 16203 } catch (PackageManagerException e) { 16204 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16205 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16206 } 16207 16208 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16209 // Re installation failed. Restore old information 16210 // Remove new pkg information 16211 if (newPackage != null) { 16212 removeInstalledPackageLI(newPackage, true); 16213 } 16214 // Add back the old system package 16215 try { 16216 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16217 } catch (PackageManagerException e) { 16218 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16219 } 16220 16221 synchronized (mPackages) { 16222 if (disabledSystem) { 16223 enableSystemPackageLPw(deletedPackage); 16224 } 16225 16226 // Ensure the installer package name up to date 16227 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16228 16229 // Update permissions for restored package 16230 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16231 16232 mSettings.writeLPr(); 16233 } 16234 16235 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16236 + " after failed upgrade"); 16237 } 16238 } 16239 16240 /** 16241 * Checks whether the parent or any of the child packages have a change shared 16242 * user. For a package to be a valid update the shred users of the parent and 16243 * the children should match. We may later support changing child shared users. 16244 * @param oldPkg The updated package. 16245 * @param newPkg The update package. 16246 * @return The shared user that change between the versions. 16247 */ 16248 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16249 PackageParser.Package newPkg) { 16250 // Check parent shared user 16251 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16252 return newPkg.packageName; 16253 } 16254 // Check child shared users 16255 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16256 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16257 for (int i = 0; i < newChildCount; i++) { 16258 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16259 // If this child was present, did it have the same shared user? 16260 for (int j = 0; j < oldChildCount; j++) { 16261 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16262 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16263 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16264 return newChildPkg.packageName; 16265 } 16266 } 16267 } 16268 return null; 16269 } 16270 16271 private void removeNativeBinariesLI(PackageSetting ps) { 16272 // Remove the lib path for the parent package 16273 if (ps != null) { 16274 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16275 // Remove the lib path for the child packages 16276 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16277 for (int i = 0; i < childCount; i++) { 16278 PackageSetting childPs = null; 16279 synchronized (mPackages) { 16280 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16281 } 16282 if (childPs != null) { 16283 NativeLibraryHelper.removeNativeBinariesLI(childPs 16284 .legacyNativeLibraryPathString); 16285 } 16286 } 16287 } 16288 } 16289 16290 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16291 // Enable the parent package 16292 mSettings.enableSystemPackageLPw(pkg.packageName); 16293 // Enable the child packages 16294 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16295 for (int i = 0; i < childCount; i++) { 16296 PackageParser.Package childPkg = pkg.childPackages.get(i); 16297 mSettings.enableSystemPackageLPw(childPkg.packageName); 16298 } 16299 } 16300 16301 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16302 PackageParser.Package newPkg) { 16303 // Disable the parent package (parent always replaced) 16304 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16305 // Disable the child packages 16306 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16307 for (int i = 0; i < childCount; i++) { 16308 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16309 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16310 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16311 } 16312 return disabled; 16313 } 16314 16315 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16316 String installerPackageName) { 16317 // Enable the parent package 16318 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16319 // Enable the child packages 16320 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16321 for (int i = 0; i < childCount; i++) { 16322 PackageParser.Package childPkg = pkg.childPackages.get(i); 16323 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16324 } 16325 } 16326 16327 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16328 // Collect all used permissions in the UID 16329 ArraySet<String> usedPermissions = new ArraySet<>(); 16330 final int packageCount = su.packages.size(); 16331 for (int i = 0; i < packageCount; i++) { 16332 PackageSetting ps = su.packages.valueAt(i); 16333 if (ps.pkg == null) { 16334 continue; 16335 } 16336 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16337 for (int j = 0; j < requestedPermCount; j++) { 16338 String permission = ps.pkg.requestedPermissions.get(j); 16339 BasePermission bp = mSettings.mPermissions.get(permission); 16340 if (bp != null) { 16341 usedPermissions.add(permission); 16342 } 16343 } 16344 } 16345 16346 PermissionsState permissionsState = su.getPermissionsState(); 16347 // Prune install permissions 16348 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16349 final int installPermCount = installPermStates.size(); 16350 for (int i = installPermCount - 1; i >= 0; i--) { 16351 PermissionState permissionState = installPermStates.get(i); 16352 if (!usedPermissions.contains(permissionState.getName())) { 16353 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16354 if (bp != null) { 16355 permissionsState.revokeInstallPermission(bp); 16356 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16357 PackageManager.MASK_PERMISSION_FLAGS, 0); 16358 } 16359 } 16360 } 16361 16362 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16363 16364 // Prune runtime permissions 16365 for (int userId : allUserIds) { 16366 List<PermissionState> runtimePermStates = permissionsState 16367 .getRuntimePermissionStates(userId); 16368 final int runtimePermCount = runtimePermStates.size(); 16369 for (int i = runtimePermCount - 1; i >= 0; i--) { 16370 PermissionState permissionState = runtimePermStates.get(i); 16371 if (!usedPermissions.contains(permissionState.getName())) { 16372 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16373 if (bp != null) { 16374 permissionsState.revokeRuntimePermission(bp, userId); 16375 permissionsState.updatePermissionFlags(bp, userId, 16376 PackageManager.MASK_PERMISSION_FLAGS, 0); 16377 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16378 runtimePermissionChangedUserIds, userId); 16379 } 16380 } 16381 } 16382 } 16383 16384 return runtimePermissionChangedUserIds; 16385 } 16386 16387 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16388 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16389 // Update the parent package setting 16390 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16391 res, user, installReason); 16392 // Update the child packages setting 16393 final int childCount = (newPackage.childPackages != null) 16394 ? newPackage.childPackages.size() : 0; 16395 for (int i = 0; i < childCount; i++) { 16396 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16397 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16398 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16399 childRes.origUsers, childRes, user, installReason); 16400 } 16401 } 16402 16403 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16404 String installerPackageName, int[] allUsers, int[] installedForUsers, 16405 PackageInstalledInfo res, UserHandle user, int installReason) { 16406 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16407 16408 String pkgName = newPackage.packageName; 16409 synchronized (mPackages) { 16410 //write settings. the installStatus will be incomplete at this stage. 16411 //note that the new package setting would have already been 16412 //added to mPackages. It hasn't been persisted yet. 16413 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16414 // TODO: Remove this write? It's also written at the end of this method 16415 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16416 mSettings.writeLPr(); 16417 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16418 } 16419 16420 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16421 synchronized (mPackages) { 16422 updatePermissionsLPw(newPackage.packageName, newPackage, 16423 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16424 ? UPDATE_PERMISSIONS_ALL : 0)); 16425 // For system-bundled packages, we assume that installing an upgraded version 16426 // of the package implies that the user actually wants to run that new code, 16427 // so we enable the package. 16428 PackageSetting ps = mSettings.mPackages.get(pkgName); 16429 final int userId = user.getIdentifier(); 16430 if (ps != null) { 16431 if (isSystemApp(newPackage)) { 16432 if (DEBUG_INSTALL) { 16433 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16434 } 16435 // Enable system package for requested users 16436 if (res.origUsers != null) { 16437 for (int origUserId : res.origUsers) { 16438 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16439 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16440 origUserId, installerPackageName); 16441 } 16442 } 16443 } 16444 // Also convey the prior install/uninstall state 16445 if (allUsers != null && installedForUsers != null) { 16446 for (int currentUserId : allUsers) { 16447 final boolean installed = ArrayUtils.contains( 16448 installedForUsers, currentUserId); 16449 if (DEBUG_INSTALL) { 16450 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16451 } 16452 ps.setInstalled(installed, currentUserId); 16453 } 16454 // these install state changes will be persisted in the 16455 // upcoming call to mSettings.writeLPr(). 16456 } 16457 } 16458 // It's implied that when a user requests installation, they want the app to be 16459 // installed and enabled. 16460 if (userId != UserHandle.USER_ALL) { 16461 ps.setInstalled(true, userId); 16462 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16463 } 16464 16465 // When replacing an existing package, preserve the original install reason for all 16466 // users that had the package installed before. 16467 final Set<Integer> previousUserIds = new ArraySet<>(); 16468 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16469 final int installReasonCount = res.removedInfo.installReasons.size(); 16470 for (int i = 0; i < installReasonCount; i++) { 16471 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16472 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16473 ps.setInstallReason(previousInstallReason, previousUserId); 16474 previousUserIds.add(previousUserId); 16475 } 16476 } 16477 16478 // Set install reason for users that are having the package newly installed. 16479 if (userId == UserHandle.USER_ALL) { 16480 for (int currentUserId : sUserManager.getUserIds()) { 16481 if (!previousUserIds.contains(currentUserId)) { 16482 ps.setInstallReason(installReason, currentUserId); 16483 } 16484 } 16485 } else if (!previousUserIds.contains(userId)) { 16486 ps.setInstallReason(installReason, userId); 16487 } 16488 mSettings.writeKernelMappingLPr(ps); 16489 } 16490 res.name = pkgName; 16491 res.uid = newPackage.applicationInfo.uid; 16492 res.pkg = newPackage; 16493 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16494 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16495 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16496 //to update install status 16497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16498 mSettings.writeLPr(); 16499 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16500 } 16501 16502 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16503 } 16504 16505 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16506 try { 16507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16508 installPackageLI(args, res); 16509 } finally { 16510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16511 } 16512 } 16513 16514 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16515 final int installFlags = args.installFlags; 16516 final String installerPackageName = args.installerPackageName; 16517 final String volumeUuid = args.volumeUuid; 16518 final File tmpPackageFile = new File(args.getCodePath()); 16519 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16520 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16521 || (args.volumeUuid != null)); 16522 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16523 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16524 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16525 boolean replace = false; 16526 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16527 if (args.move != null) { 16528 // moving a complete application; perform an initial scan on the new install location 16529 scanFlags |= SCAN_INITIAL; 16530 } 16531 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16532 scanFlags |= SCAN_DONT_KILL_APP; 16533 } 16534 if (instantApp) { 16535 scanFlags |= SCAN_AS_INSTANT_APP; 16536 } 16537 if (fullApp) { 16538 scanFlags |= SCAN_AS_FULL_APP; 16539 } 16540 16541 // Result object to be returned 16542 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16543 16544 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16545 16546 // Sanity check 16547 if (instantApp && (forwardLocked || onExternal)) { 16548 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16549 + " external=" + onExternal); 16550 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16551 return; 16552 } 16553 16554 // Retrieve PackageSettings and parse package 16555 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16556 | PackageParser.PARSE_ENFORCE_CODE 16557 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16558 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16559 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16560 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16561 PackageParser pp = new PackageParser(); 16562 pp.setSeparateProcesses(mSeparateProcesses); 16563 pp.setDisplayMetrics(mMetrics); 16564 pp.setCallback(mPackageParserCallback); 16565 16566 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16567 final PackageParser.Package pkg; 16568 try { 16569 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16570 } catch (PackageParserException e) { 16571 res.setError("Failed parse during installPackageLI", e); 16572 return; 16573 } finally { 16574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16575 } 16576 16577 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16578 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16579 Slog.w(TAG, "Instant app package " + pkg.packageName 16580 + " does not target O, this will be a fatal error."); 16581 // STOPSHIP: Make this a fatal error 16582 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16583 } 16584 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16585 Slog.w(TAG, "Instant app package " + pkg.packageName 16586 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16587 // STOPSHIP: Make this a fatal error 16588 pkg.applicationInfo.targetSandboxVersion = 2; 16589 } 16590 16591 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16592 // Static shared libraries have synthetic package names 16593 renameStaticSharedLibraryPackage(pkg); 16594 16595 // No static shared libs on external storage 16596 if (onExternal) { 16597 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16598 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16599 "Packages declaring static-shared libs cannot be updated"); 16600 return; 16601 } 16602 } 16603 16604 // If we are installing a clustered package add results for the children 16605 if (pkg.childPackages != null) { 16606 synchronized (mPackages) { 16607 final int childCount = pkg.childPackages.size(); 16608 for (int i = 0; i < childCount; i++) { 16609 PackageParser.Package childPkg = pkg.childPackages.get(i); 16610 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16611 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16612 childRes.pkg = childPkg; 16613 childRes.name = childPkg.packageName; 16614 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16615 if (childPs != null) { 16616 childRes.origUsers = childPs.queryInstalledUsers( 16617 sUserManager.getUserIds(), true); 16618 } 16619 if ((mPackages.containsKey(childPkg.packageName))) { 16620 childRes.removedInfo = new PackageRemovedInfo(); 16621 childRes.removedInfo.removedPackage = childPkg.packageName; 16622 } 16623 if (res.addedChildPackages == null) { 16624 res.addedChildPackages = new ArrayMap<>(); 16625 } 16626 res.addedChildPackages.put(childPkg.packageName, childRes); 16627 } 16628 } 16629 } 16630 16631 // If package doesn't declare API override, mark that we have an install 16632 // time CPU ABI override. 16633 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16634 pkg.cpuAbiOverride = args.abiOverride; 16635 } 16636 16637 String pkgName = res.name = pkg.packageName; 16638 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16639 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16640 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16641 return; 16642 } 16643 } 16644 16645 try { 16646 // either use what we've been given or parse directly from the APK 16647 if (args.certificates != null) { 16648 try { 16649 PackageParser.populateCertificates(pkg, args.certificates); 16650 } catch (PackageParserException e) { 16651 // there was something wrong with the certificates we were given; 16652 // try to pull them from the APK 16653 PackageParser.collectCertificates(pkg, parseFlags); 16654 } 16655 } else { 16656 PackageParser.collectCertificates(pkg, parseFlags); 16657 } 16658 } catch (PackageParserException e) { 16659 res.setError("Failed collect during installPackageLI", e); 16660 return; 16661 } 16662 16663 // Get rid of all references to package scan path via parser. 16664 pp = null; 16665 String oldCodePath = null; 16666 boolean systemApp = false; 16667 synchronized (mPackages) { 16668 // Check if installing already existing package 16669 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16670 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16671 if (pkg.mOriginalPackages != null 16672 && pkg.mOriginalPackages.contains(oldName) 16673 && mPackages.containsKey(oldName)) { 16674 // This package is derived from an original package, 16675 // and this device has been updating from that original 16676 // name. We must continue using the original name, so 16677 // rename the new package here. 16678 pkg.setPackageName(oldName); 16679 pkgName = pkg.packageName; 16680 replace = true; 16681 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16682 + oldName + " pkgName=" + pkgName); 16683 } else if (mPackages.containsKey(pkgName)) { 16684 // This package, under its official name, already exists 16685 // on the device; we should replace it. 16686 replace = true; 16687 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16688 } 16689 16690 // Child packages are installed through the parent package 16691 if (pkg.parentPackage != null) { 16692 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16693 "Package " + pkg.packageName + " is child of package " 16694 + pkg.parentPackage.parentPackage + ". Child packages " 16695 + "can be updated only through the parent package."); 16696 return; 16697 } 16698 16699 if (replace) { 16700 // Prevent apps opting out from runtime permissions 16701 PackageParser.Package oldPackage = mPackages.get(pkgName); 16702 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16703 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16704 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16705 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16706 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16707 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16708 + " doesn't support runtime permissions but the old" 16709 + " target SDK " + oldTargetSdk + " does."); 16710 return; 16711 } 16712 // Prevent apps from downgrading their targetSandbox. 16713 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16714 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16715 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16716 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16717 "Package " + pkg.packageName + " new target sandbox " 16718 + newTargetSandbox + " is incompatible with the previous value of" 16719 + oldTargetSandbox + "."); 16720 return; 16721 } 16722 16723 // Prevent installing of child packages 16724 if (oldPackage.parentPackage != null) { 16725 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16726 "Package " + pkg.packageName + " is child of package " 16727 + oldPackage.parentPackage + ". Child packages " 16728 + "can be updated only through the parent package."); 16729 return; 16730 } 16731 } 16732 } 16733 16734 PackageSetting ps = mSettings.mPackages.get(pkgName); 16735 if (ps != null) { 16736 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16737 16738 // Static shared libs have same package with different versions where 16739 // we internally use a synthetic package name to allow multiple versions 16740 // of the same package, therefore we need to compare signatures against 16741 // the package setting for the latest library version. 16742 PackageSetting signatureCheckPs = ps; 16743 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16744 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16745 if (libraryEntry != null) { 16746 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16747 } 16748 } 16749 16750 // Quick sanity check that we're signed correctly if updating; 16751 // we'll check this again later when scanning, but we want to 16752 // bail early here before tripping over redefined permissions. 16753 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16754 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16755 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16756 + pkg.packageName + " upgrade keys do not match the " 16757 + "previously installed version"); 16758 return; 16759 } 16760 } else { 16761 try { 16762 verifySignaturesLP(signatureCheckPs, pkg); 16763 } catch (PackageManagerException e) { 16764 res.setError(e.error, e.getMessage()); 16765 return; 16766 } 16767 } 16768 16769 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16770 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16771 systemApp = (ps.pkg.applicationInfo.flags & 16772 ApplicationInfo.FLAG_SYSTEM) != 0; 16773 } 16774 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16775 } 16776 16777 int N = pkg.permissions.size(); 16778 for (int i = N-1; i >= 0; i--) { 16779 PackageParser.Permission perm = pkg.permissions.get(i); 16780 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16781 16782 // Don't allow anyone but the platform to define ephemeral permissions. 16783 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16784 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16785 Slog.w(TAG, "Package " + pkg.packageName 16786 + " attempting to delcare ephemeral permission " 16787 + perm.info.name + "; Removing ephemeral."); 16788 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16789 } 16790 // Check whether the newly-scanned package wants to define an already-defined perm 16791 if (bp != null) { 16792 // If the defining package is signed with our cert, it's okay. This 16793 // also includes the "updating the same package" case, of course. 16794 // "updating same package" could also involve key-rotation. 16795 final boolean sigsOk; 16796 if (bp.sourcePackage.equals(pkg.packageName) 16797 && (bp.packageSetting instanceof PackageSetting) 16798 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16799 scanFlags))) { 16800 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16801 } else { 16802 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16803 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16804 } 16805 if (!sigsOk) { 16806 // If the owning package is the system itself, we log but allow 16807 // install to proceed; we fail the install on all other permission 16808 // redefinitions. 16809 if (!bp.sourcePackage.equals("android")) { 16810 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16811 + pkg.packageName + " attempting to redeclare permission " 16812 + perm.info.name + " already owned by " + bp.sourcePackage); 16813 res.origPermission = perm.info.name; 16814 res.origPackage = bp.sourcePackage; 16815 return; 16816 } else { 16817 Slog.w(TAG, "Package " + pkg.packageName 16818 + " attempting to redeclare system permission " 16819 + perm.info.name + "; ignoring new declaration"); 16820 pkg.permissions.remove(i); 16821 } 16822 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16823 // Prevent apps to change protection level to dangerous from any other 16824 // type as this would allow a privilege escalation where an app adds a 16825 // normal/signature permission in other app's group and later redefines 16826 // it as dangerous leading to the group auto-grant. 16827 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16828 == PermissionInfo.PROTECTION_DANGEROUS) { 16829 if (bp != null && !bp.isRuntime()) { 16830 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16831 + "non-runtime permission " + perm.info.name 16832 + " to runtime; keeping old protection level"); 16833 perm.info.protectionLevel = bp.protectionLevel; 16834 } 16835 } 16836 } 16837 } 16838 } 16839 } 16840 16841 if (systemApp) { 16842 if (onExternal) { 16843 // Abort update; system app can't be replaced with app on sdcard 16844 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16845 "Cannot install updates to system apps on sdcard"); 16846 return; 16847 } else if (instantApp) { 16848 // Abort update; system app can't be replaced with an instant app 16849 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16850 "Cannot update a system app with an instant app"); 16851 return; 16852 } 16853 } 16854 16855 if (args.move != null) { 16856 // We did an in-place move, so dex is ready to roll 16857 scanFlags |= SCAN_NO_DEX; 16858 scanFlags |= SCAN_MOVE; 16859 16860 synchronized (mPackages) { 16861 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16862 if (ps == null) { 16863 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16864 "Missing settings for moved package " + pkgName); 16865 } 16866 16867 // We moved the entire application as-is, so bring over the 16868 // previously derived ABI information. 16869 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16870 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16871 } 16872 16873 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16874 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16875 scanFlags |= SCAN_NO_DEX; 16876 16877 try { 16878 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16879 args.abiOverride : pkg.cpuAbiOverride); 16880 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16881 true /*extractLibs*/, mAppLib32InstallDir); 16882 } catch (PackageManagerException pme) { 16883 Slog.e(TAG, "Error deriving application ABI", pme); 16884 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16885 return; 16886 } 16887 16888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16889 // Do not run PackageDexOptimizer through the local performDexOpt 16890 // method because `pkg` may not be in `mPackages` yet. 16891 // 16892 // Also, don't fail application installs if the dexopt step fails. 16893 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16894 null /* instructionSets */, false /* checkProfiles */, 16895 getCompilerFilterForReason(REASON_INSTALL), 16896 getOrCreateCompilerPackageStats(pkg), 16897 mDexManager.isUsedByOtherApps(pkg.packageName)); 16898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16899 16900 // Notify BackgroundDexOptService that the package has been changed. 16901 // If this is an update of a package which used to fail to compile, 16902 // BDOS will remove it from its blacklist. 16903 // TODO: Layering violation 16904 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16905 } 16906 16907 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16908 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16909 return; 16910 } 16911 16912 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16913 16914 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16915 "installPackageLI")) { 16916 if (replace) { 16917 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16918 // Static libs have a synthetic package name containing the version 16919 // and cannot be updated as an update would get a new package name, 16920 // unless this is the exact same version code which is useful for 16921 // development. 16922 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16923 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16924 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16925 + "static-shared libs cannot be updated"); 16926 return; 16927 } 16928 } 16929 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16930 installerPackageName, res, args.installReason); 16931 } else { 16932 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16933 args.user, installerPackageName, volumeUuid, res, args.installReason); 16934 } 16935 } 16936 synchronized (mPackages) { 16937 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16938 if (ps != null) { 16939 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16940 ps.setUpdateAvailable(false /*updateAvailable*/); 16941 } 16942 16943 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16944 for (int i = 0; i < childCount; i++) { 16945 PackageParser.Package childPkg = pkg.childPackages.get(i); 16946 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16947 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16948 if (childPs != null) { 16949 childRes.newUsers = childPs.queryInstalledUsers( 16950 sUserManager.getUserIds(), true); 16951 } 16952 } 16953 16954 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16955 updateSequenceNumberLP(pkgName, res.newUsers); 16956 updateInstantAppInstallerLocked(); 16957 } 16958 } 16959 } 16960 16961 private void startIntentFilterVerifications(int userId, boolean replacing, 16962 PackageParser.Package pkg) { 16963 if (mIntentFilterVerifierComponent == null) { 16964 Slog.w(TAG, "No IntentFilter verification will not be done as " 16965 + "there is no IntentFilterVerifier available!"); 16966 return; 16967 } 16968 16969 final int verifierUid = getPackageUid( 16970 mIntentFilterVerifierComponent.getPackageName(), 16971 MATCH_DEBUG_TRIAGED_MISSING, 16972 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16973 16974 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16975 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16976 mHandler.sendMessage(msg); 16977 16978 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16979 for (int i = 0; i < childCount; i++) { 16980 PackageParser.Package childPkg = pkg.childPackages.get(i); 16981 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16982 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16983 mHandler.sendMessage(msg); 16984 } 16985 } 16986 16987 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16988 PackageParser.Package pkg) { 16989 int size = pkg.activities.size(); 16990 if (size == 0) { 16991 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16992 "No activity, so no need to verify any IntentFilter!"); 16993 return; 16994 } 16995 16996 final boolean hasDomainURLs = hasDomainURLs(pkg); 16997 if (!hasDomainURLs) { 16998 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16999 "No domain URLs, so no need to verify any IntentFilter!"); 17000 return; 17001 } 17002 17003 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17004 + " if any IntentFilter from the " + size 17005 + " Activities needs verification ..."); 17006 17007 int count = 0; 17008 final String packageName = pkg.packageName; 17009 17010 synchronized (mPackages) { 17011 // If this is a new install and we see that we've already run verification for this 17012 // package, we have nothing to do: it means the state was restored from backup. 17013 if (!replacing) { 17014 IntentFilterVerificationInfo ivi = 17015 mSettings.getIntentFilterVerificationLPr(packageName); 17016 if (ivi != null) { 17017 if (DEBUG_DOMAIN_VERIFICATION) { 17018 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17019 + ivi.getStatusString()); 17020 } 17021 return; 17022 } 17023 } 17024 17025 // If any filters need to be verified, then all need to be. 17026 boolean needToVerify = false; 17027 for (PackageParser.Activity a : pkg.activities) { 17028 for (ActivityIntentInfo filter : a.intents) { 17029 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17030 if (DEBUG_DOMAIN_VERIFICATION) { 17031 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17032 } 17033 needToVerify = true; 17034 break; 17035 } 17036 } 17037 } 17038 17039 if (needToVerify) { 17040 final int verificationId = mIntentFilterVerificationToken++; 17041 for (PackageParser.Activity a : pkg.activities) { 17042 for (ActivityIntentInfo filter : a.intents) { 17043 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17044 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17045 "Verification needed for IntentFilter:" + filter.toString()); 17046 mIntentFilterVerifier.addOneIntentFilterVerification( 17047 verifierUid, userId, verificationId, filter, packageName); 17048 count++; 17049 } 17050 } 17051 } 17052 } 17053 } 17054 17055 if (count > 0) { 17056 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17057 + " IntentFilter verification" + (count > 1 ? "s" : "") 17058 + " for userId:" + userId); 17059 mIntentFilterVerifier.startVerifications(userId); 17060 } else { 17061 if (DEBUG_DOMAIN_VERIFICATION) { 17062 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17063 } 17064 } 17065 } 17066 17067 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17068 final ComponentName cn = filter.activity.getComponentName(); 17069 final String packageName = cn.getPackageName(); 17070 17071 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17072 packageName); 17073 if (ivi == null) { 17074 return true; 17075 } 17076 int status = ivi.getStatus(); 17077 switch (status) { 17078 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17079 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17080 return true; 17081 17082 default: 17083 // Nothing to do 17084 return false; 17085 } 17086 } 17087 17088 private static boolean isMultiArch(ApplicationInfo info) { 17089 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17090 } 17091 17092 private static boolean isExternal(PackageParser.Package pkg) { 17093 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17094 } 17095 17096 private static boolean isExternal(PackageSetting ps) { 17097 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17098 } 17099 17100 private static boolean isSystemApp(PackageParser.Package pkg) { 17101 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17102 } 17103 17104 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17105 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17106 } 17107 17108 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17109 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17110 } 17111 17112 private static boolean isSystemApp(PackageSetting ps) { 17113 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17114 } 17115 17116 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17117 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17118 } 17119 17120 private int packageFlagsToInstallFlags(PackageSetting ps) { 17121 int installFlags = 0; 17122 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17123 // This existing package was an external ASEC install when we have 17124 // the external flag without a UUID 17125 installFlags |= PackageManager.INSTALL_EXTERNAL; 17126 } 17127 if (ps.isForwardLocked()) { 17128 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17129 } 17130 return installFlags; 17131 } 17132 17133 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17134 if (isExternal(pkg)) { 17135 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17136 return StorageManager.UUID_PRIMARY_PHYSICAL; 17137 } else { 17138 return pkg.volumeUuid; 17139 } 17140 } else { 17141 return StorageManager.UUID_PRIVATE_INTERNAL; 17142 } 17143 } 17144 17145 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17146 if (isExternal(pkg)) { 17147 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17148 return mSettings.getExternalVersion(); 17149 } else { 17150 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17151 } 17152 } else { 17153 return mSettings.getInternalVersion(); 17154 } 17155 } 17156 17157 private void deleteTempPackageFiles() { 17158 final FilenameFilter filter = new FilenameFilter() { 17159 public boolean accept(File dir, String name) { 17160 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17161 } 17162 }; 17163 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17164 file.delete(); 17165 } 17166 } 17167 17168 @Override 17169 public void deletePackageAsUser(String packageName, int versionCode, 17170 IPackageDeleteObserver observer, int userId, int flags) { 17171 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17172 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17173 } 17174 17175 @Override 17176 public void deletePackageVersioned(VersionedPackage versionedPackage, 17177 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17178 mContext.enforceCallingOrSelfPermission( 17179 android.Manifest.permission.DELETE_PACKAGES, null); 17180 Preconditions.checkNotNull(versionedPackage); 17181 Preconditions.checkNotNull(observer); 17182 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17183 PackageManager.VERSION_CODE_HIGHEST, 17184 Integer.MAX_VALUE, "versionCode must be >= -1"); 17185 17186 final String packageName = versionedPackage.getPackageName(); 17187 // TODO: We will change version code to long, so in the new API it is long 17188 final int versionCode = (int) versionedPackage.getVersionCode(); 17189 final String internalPackageName; 17190 synchronized (mPackages) { 17191 // Normalize package name to handle renamed packages and static libs 17192 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17193 // TODO: We will change version code to long, so in the new API it is long 17194 (int) versionedPackage.getVersionCode()); 17195 } 17196 17197 final int uid = Binder.getCallingUid(); 17198 if (!isOrphaned(internalPackageName) 17199 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17200 try { 17201 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17202 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17203 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17204 observer.onUserActionRequired(intent); 17205 } catch (RemoteException re) { 17206 } 17207 return; 17208 } 17209 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17210 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17211 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17212 mContext.enforceCallingOrSelfPermission( 17213 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17214 "deletePackage for user " + userId); 17215 } 17216 17217 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17218 try { 17219 observer.onPackageDeleted(packageName, 17220 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17221 } catch (RemoteException re) { 17222 } 17223 return; 17224 } 17225 17226 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17227 try { 17228 observer.onPackageDeleted(packageName, 17229 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17230 } catch (RemoteException re) { 17231 } 17232 return; 17233 } 17234 17235 if (DEBUG_REMOVE) { 17236 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17237 + " deleteAllUsers: " + deleteAllUsers + " version=" 17238 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17239 ? "VERSION_CODE_HIGHEST" : versionCode)); 17240 } 17241 // Queue up an async operation since the package deletion may take a little while. 17242 mHandler.post(new Runnable() { 17243 public void run() { 17244 mHandler.removeCallbacks(this); 17245 int returnCode; 17246 if (!deleteAllUsers) { 17247 returnCode = deletePackageX(internalPackageName, versionCode, 17248 userId, deleteFlags); 17249 } else { 17250 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17251 internalPackageName, users); 17252 // If nobody is blocking uninstall, proceed with delete for all users 17253 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17254 returnCode = deletePackageX(internalPackageName, versionCode, 17255 userId, deleteFlags); 17256 } else { 17257 // Otherwise uninstall individually for users with blockUninstalls=false 17258 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17259 for (int userId : users) { 17260 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17261 returnCode = deletePackageX(internalPackageName, versionCode, 17262 userId, userFlags); 17263 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17264 Slog.w(TAG, "Package delete failed for user " + userId 17265 + ", returnCode " + returnCode); 17266 } 17267 } 17268 } 17269 // The app has only been marked uninstalled for certain users. 17270 // We still need to report that delete was blocked 17271 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17272 } 17273 } 17274 try { 17275 observer.onPackageDeleted(packageName, returnCode, null); 17276 } catch (RemoteException e) { 17277 Log.i(TAG, "Observer no longer exists."); 17278 } //end catch 17279 } //end run 17280 }); 17281 } 17282 17283 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17284 if (pkg.staticSharedLibName != null) { 17285 return pkg.manifestPackageName; 17286 } 17287 return pkg.packageName; 17288 } 17289 17290 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17291 // Handle renamed packages 17292 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17293 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17294 17295 // Is this a static library? 17296 SparseArray<SharedLibraryEntry> versionedLib = 17297 mStaticLibsByDeclaringPackage.get(packageName); 17298 if (versionedLib == null || versionedLib.size() <= 0) { 17299 return packageName; 17300 } 17301 17302 // Figure out which lib versions the caller can see 17303 SparseIntArray versionsCallerCanSee = null; 17304 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17305 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17306 && callingAppId != Process.ROOT_UID) { 17307 versionsCallerCanSee = new SparseIntArray(); 17308 String libName = versionedLib.valueAt(0).info.getName(); 17309 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17310 if (uidPackages != null) { 17311 for (String uidPackage : uidPackages) { 17312 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17313 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17314 if (libIdx >= 0) { 17315 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17316 versionsCallerCanSee.append(libVersion, libVersion); 17317 } 17318 } 17319 } 17320 } 17321 17322 // Caller can see nothing - done 17323 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17324 return packageName; 17325 } 17326 17327 // Find the version the caller can see and the app version code 17328 SharedLibraryEntry highestVersion = null; 17329 final int versionCount = versionedLib.size(); 17330 for (int i = 0; i < versionCount; i++) { 17331 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17332 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17333 libEntry.info.getVersion()) < 0) { 17334 continue; 17335 } 17336 // TODO: We will change version code to long, so in the new API it is long 17337 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17338 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17339 if (libVersionCode == versionCode) { 17340 return libEntry.apk; 17341 } 17342 } else if (highestVersion == null) { 17343 highestVersion = libEntry; 17344 } else if (libVersionCode > highestVersion.info 17345 .getDeclaringPackage().getVersionCode()) { 17346 highestVersion = libEntry; 17347 } 17348 } 17349 17350 if (highestVersion != null) { 17351 return highestVersion.apk; 17352 } 17353 17354 return packageName; 17355 } 17356 17357 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17358 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17359 || callingUid == Process.SYSTEM_UID) { 17360 return true; 17361 } 17362 final int callingUserId = UserHandle.getUserId(callingUid); 17363 // If the caller installed the pkgName, then allow it to silently uninstall. 17364 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17365 return true; 17366 } 17367 17368 // Allow package verifier to silently uninstall. 17369 if (mRequiredVerifierPackage != null && 17370 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17371 return true; 17372 } 17373 17374 // Allow package uninstaller to silently uninstall. 17375 if (mRequiredUninstallerPackage != null && 17376 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17377 return true; 17378 } 17379 17380 // Allow storage manager to silently uninstall. 17381 if (mStorageManagerPackage != null && 17382 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17383 return true; 17384 } 17385 return false; 17386 } 17387 17388 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17389 int[] result = EMPTY_INT_ARRAY; 17390 for (int userId : userIds) { 17391 if (getBlockUninstallForUser(packageName, userId)) { 17392 result = ArrayUtils.appendInt(result, userId); 17393 } 17394 } 17395 return result; 17396 } 17397 17398 @Override 17399 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17400 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17401 } 17402 17403 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17404 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17405 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17406 try { 17407 if (dpm != null) { 17408 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17409 /* callingUserOnly =*/ false); 17410 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17411 : deviceOwnerComponentName.getPackageName(); 17412 // Does the package contains the device owner? 17413 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17414 // this check is probably not needed, since DO should be registered as a device 17415 // admin on some user too. (Original bug for this: b/17657954) 17416 if (packageName.equals(deviceOwnerPackageName)) { 17417 return true; 17418 } 17419 // Does it contain a device admin for any user? 17420 int[] users; 17421 if (userId == UserHandle.USER_ALL) { 17422 users = sUserManager.getUserIds(); 17423 } else { 17424 users = new int[]{userId}; 17425 } 17426 for (int i = 0; i < users.length; ++i) { 17427 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17428 return true; 17429 } 17430 } 17431 } 17432 } catch (RemoteException e) { 17433 } 17434 return false; 17435 } 17436 17437 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17438 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17439 } 17440 17441 /** 17442 * This method is an internal method that could be get invoked either 17443 * to delete an installed package or to clean up a failed installation. 17444 * After deleting an installed package, a broadcast is sent to notify any 17445 * listeners that the package has been removed. For cleaning up a failed 17446 * installation, the broadcast is not necessary since the package's 17447 * installation wouldn't have sent the initial broadcast either 17448 * The key steps in deleting a package are 17449 * deleting the package information in internal structures like mPackages, 17450 * deleting the packages base directories through installd 17451 * updating mSettings to reflect current status 17452 * persisting settings for later use 17453 * sending a broadcast if necessary 17454 */ 17455 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17456 final PackageRemovedInfo info = new PackageRemovedInfo(); 17457 final boolean res; 17458 17459 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17460 ? UserHandle.USER_ALL : userId; 17461 17462 if (isPackageDeviceAdmin(packageName, removeUser)) { 17463 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17464 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17465 } 17466 17467 PackageSetting uninstalledPs = null; 17468 PackageParser.Package pkg = null; 17469 17470 // for the uninstall-updates case and restricted profiles, remember the per- 17471 // user handle installed state 17472 int[] allUsers; 17473 synchronized (mPackages) { 17474 uninstalledPs = mSettings.mPackages.get(packageName); 17475 if (uninstalledPs == null) { 17476 Slog.w(TAG, "Not removing non-existent package " + packageName); 17477 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17478 } 17479 17480 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17481 && uninstalledPs.versionCode != versionCode) { 17482 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17483 + uninstalledPs.versionCode + " != " + versionCode); 17484 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17485 } 17486 17487 // Static shared libs can be declared by any package, so let us not 17488 // allow removing a package if it provides a lib others depend on. 17489 pkg = mPackages.get(packageName); 17490 if (pkg != null && pkg.staticSharedLibName != null) { 17491 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17492 pkg.staticSharedLibVersion); 17493 if (libEntry != null) { 17494 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17495 libEntry.info, 0, userId); 17496 if (!ArrayUtils.isEmpty(libClientPackages)) { 17497 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17498 + " hosting lib " + libEntry.info.getName() + " version " 17499 + libEntry.info.getVersion() + " used by " + libClientPackages); 17500 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17501 } 17502 } 17503 } 17504 17505 allUsers = sUserManager.getUserIds(); 17506 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17507 } 17508 17509 final int freezeUser; 17510 if (isUpdatedSystemApp(uninstalledPs) 17511 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17512 // We're downgrading a system app, which will apply to all users, so 17513 // freeze them all during the downgrade 17514 freezeUser = UserHandle.USER_ALL; 17515 } else { 17516 freezeUser = removeUser; 17517 } 17518 17519 synchronized (mInstallLock) { 17520 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17521 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17522 deleteFlags, "deletePackageX")) { 17523 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17524 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17525 } 17526 synchronized (mPackages) { 17527 if (res) { 17528 if (pkg != null) { 17529 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17530 } 17531 updateSequenceNumberLP(packageName, info.removedUsers); 17532 updateInstantAppInstallerLocked(); 17533 } 17534 } 17535 } 17536 17537 if (res) { 17538 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17539 info.sendPackageRemovedBroadcasts(killApp); 17540 info.sendSystemPackageUpdatedBroadcasts(); 17541 info.sendSystemPackageAppearedBroadcasts(); 17542 } 17543 // Force a gc here. 17544 Runtime.getRuntime().gc(); 17545 // Delete the resources here after sending the broadcast to let 17546 // other processes clean up before deleting resources. 17547 if (info.args != null) { 17548 synchronized (mInstallLock) { 17549 info.args.doPostDeleteLI(true); 17550 } 17551 } 17552 17553 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17554 } 17555 17556 class PackageRemovedInfo { 17557 String removedPackage; 17558 int uid = -1; 17559 int removedAppId = -1; 17560 int[] origUsers; 17561 int[] removedUsers = null; 17562 SparseArray<Integer> installReasons; 17563 boolean isRemovedPackageSystemUpdate = false; 17564 boolean isUpdate; 17565 boolean dataRemoved; 17566 boolean removedForAllUsers; 17567 boolean isStaticSharedLib; 17568 // Clean up resources deleted packages. 17569 InstallArgs args = null; 17570 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17571 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17572 17573 void sendPackageRemovedBroadcasts(boolean killApp) { 17574 sendPackageRemovedBroadcastInternal(killApp); 17575 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17576 for (int i = 0; i < childCount; i++) { 17577 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17578 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17579 } 17580 } 17581 17582 void sendSystemPackageUpdatedBroadcasts() { 17583 if (isRemovedPackageSystemUpdate) { 17584 sendSystemPackageUpdatedBroadcastsInternal(); 17585 final int childCount = (removedChildPackages != null) 17586 ? removedChildPackages.size() : 0; 17587 for (int i = 0; i < childCount; i++) { 17588 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17589 if (childInfo.isRemovedPackageSystemUpdate) { 17590 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17591 } 17592 } 17593 } 17594 } 17595 17596 void sendSystemPackageAppearedBroadcasts() { 17597 final int packageCount = (appearedChildPackages != null) 17598 ? appearedChildPackages.size() : 0; 17599 for (int i = 0; i < packageCount; i++) { 17600 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17601 sendPackageAddedForNewUsers(installedInfo.name, true, 17602 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17603 } 17604 } 17605 17606 private void sendSystemPackageUpdatedBroadcastsInternal() { 17607 Bundle extras = new Bundle(2); 17608 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17609 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17610 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17611 extras, 0, null, null, null); 17612 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17613 extras, 0, null, null, null); 17614 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17615 null, 0, removedPackage, null, null); 17616 } 17617 17618 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17619 // Don't send static shared library removal broadcasts as these 17620 // libs are visible only the the apps that depend on them an one 17621 // cannot remove the library if it has a dependency. 17622 if (isStaticSharedLib) { 17623 return; 17624 } 17625 Bundle extras = new Bundle(2); 17626 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17627 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17628 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17629 if (isUpdate || isRemovedPackageSystemUpdate) { 17630 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17631 } 17632 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17633 if (removedPackage != null) { 17634 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17635 extras, 0, null, null, removedUsers); 17636 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17637 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17638 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17639 null, null, removedUsers); 17640 } 17641 } 17642 if (removedAppId >= 0) { 17643 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17644 removedUsers); 17645 } 17646 } 17647 } 17648 17649 /* 17650 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17651 * flag is not set, the data directory is removed as well. 17652 * make sure this flag is set for partially installed apps. If not its meaningless to 17653 * delete a partially installed application. 17654 */ 17655 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17656 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17657 String packageName = ps.name; 17658 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17659 // Retrieve object to delete permissions for shared user later on 17660 final PackageParser.Package deletedPkg; 17661 final PackageSetting deletedPs; 17662 // reader 17663 synchronized (mPackages) { 17664 deletedPkg = mPackages.get(packageName); 17665 deletedPs = mSettings.mPackages.get(packageName); 17666 if (outInfo != null) { 17667 outInfo.removedPackage = packageName; 17668 outInfo.isStaticSharedLib = deletedPkg != null 17669 && deletedPkg.staticSharedLibName != null; 17670 outInfo.removedUsers = deletedPs != null 17671 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17672 : null; 17673 } 17674 } 17675 17676 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17677 17678 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17679 final PackageParser.Package resolvedPkg; 17680 if (deletedPkg != null) { 17681 resolvedPkg = deletedPkg; 17682 } else { 17683 // We don't have a parsed package when it lives on an ejected 17684 // adopted storage device, so fake something together 17685 resolvedPkg = new PackageParser.Package(ps.name); 17686 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17687 } 17688 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17689 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17690 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17691 if (outInfo != null) { 17692 outInfo.dataRemoved = true; 17693 } 17694 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17695 } 17696 17697 int removedAppId = -1; 17698 17699 // writer 17700 synchronized (mPackages) { 17701 boolean installedStateChanged = false; 17702 if (deletedPs != null) { 17703 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17704 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17705 clearDefaultBrowserIfNeeded(packageName); 17706 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17707 removedAppId = mSettings.removePackageLPw(packageName); 17708 if (outInfo != null) { 17709 outInfo.removedAppId = removedAppId; 17710 } 17711 updatePermissionsLPw(deletedPs.name, null, 0); 17712 if (deletedPs.sharedUser != null) { 17713 // Remove permissions associated with package. Since runtime 17714 // permissions are per user we have to kill the removed package 17715 // or packages running under the shared user of the removed 17716 // package if revoking the permissions requested only by the removed 17717 // package is successful and this causes a change in gids. 17718 for (int userId : UserManagerService.getInstance().getUserIds()) { 17719 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17720 userId); 17721 if (userIdToKill == UserHandle.USER_ALL 17722 || userIdToKill >= UserHandle.USER_SYSTEM) { 17723 // If gids changed for this user, kill all affected packages. 17724 mHandler.post(new Runnable() { 17725 @Override 17726 public void run() { 17727 // This has to happen with no lock held. 17728 killApplication(deletedPs.name, deletedPs.appId, 17729 KILL_APP_REASON_GIDS_CHANGED); 17730 } 17731 }); 17732 break; 17733 } 17734 } 17735 } 17736 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17737 } 17738 // make sure to preserve per-user disabled state if this removal was just 17739 // a downgrade of a system app to the factory package 17740 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17741 if (DEBUG_REMOVE) { 17742 Slog.d(TAG, "Propagating install state across downgrade"); 17743 } 17744 for (int userId : allUserHandles) { 17745 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17746 if (DEBUG_REMOVE) { 17747 Slog.d(TAG, " user " + userId + " => " + installed); 17748 } 17749 if (installed != ps.getInstalled(userId)) { 17750 installedStateChanged = true; 17751 } 17752 ps.setInstalled(installed, userId); 17753 } 17754 } 17755 } 17756 // can downgrade to reader 17757 if (writeSettings) { 17758 // Save settings now 17759 mSettings.writeLPr(); 17760 } 17761 if (installedStateChanged) { 17762 mSettings.writeKernelMappingLPr(ps); 17763 } 17764 } 17765 if (removedAppId != -1) { 17766 // A user ID was deleted here. Go through all users and remove it 17767 // from KeyStore. 17768 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17769 } 17770 } 17771 17772 static boolean locationIsPrivileged(File path) { 17773 try { 17774 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17775 .getCanonicalPath(); 17776 return path.getCanonicalPath().startsWith(privilegedAppDir); 17777 } catch (IOException e) { 17778 Slog.e(TAG, "Unable to access code path " + path); 17779 } 17780 return false; 17781 } 17782 17783 /* 17784 * Tries to delete system package. 17785 */ 17786 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17787 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17788 boolean writeSettings) { 17789 if (deletedPs.parentPackageName != null) { 17790 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17791 return false; 17792 } 17793 17794 final boolean applyUserRestrictions 17795 = (allUserHandles != null) && (outInfo.origUsers != null); 17796 final PackageSetting disabledPs; 17797 // Confirm if the system package has been updated 17798 // An updated system app can be deleted. This will also have to restore 17799 // the system pkg from system partition 17800 // reader 17801 synchronized (mPackages) { 17802 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17803 } 17804 17805 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17806 + " disabledPs=" + disabledPs); 17807 17808 if (disabledPs == null) { 17809 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17810 return false; 17811 } else if (DEBUG_REMOVE) { 17812 Slog.d(TAG, "Deleting system pkg from data partition"); 17813 } 17814 17815 if (DEBUG_REMOVE) { 17816 if (applyUserRestrictions) { 17817 Slog.d(TAG, "Remembering install states:"); 17818 for (int userId : allUserHandles) { 17819 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17820 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17821 } 17822 } 17823 } 17824 17825 // Delete the updated package 17826 outInfo.isRemovedPackageSystemUpdate = true; 17827 if (outInfo.removedChildPackages != null) { 17828 final int childCount = (deletedPs.childPackageNames != null) 17829 ? deletedPs.childPackageNames.size() : 0; 17830 for (int i = 0; i < childCount; i++) { 17831 String childPackageName = deletedPs.childPackageNames.get(i); 17832 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17833 .contains(childPackageName)) { 17834 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17835 childPackageName); 17836 if (childInfo != null) { 17837 childInfo.isRemovedPackageSystemUpdate = true; 17838 } 17839 } 17840 } 17841 } 17842 17843 if (disabledPs.versionCode < deletedPs.versionCode) { 17844 // Delete data for downgrades 17845 flags &= ~PackageManager.DELETE_KEEP_DATA; 17846 } else { 17847 // Preserve data by setting flag 17848 flags |= PackageManager.DELETE_KEEP_DATA; 17849 } 17850 17851 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17852 outInfo, writeSettings, disabledPs.pkg); 17853 if (!ret) { 17854 return false; 17855 } 17856 17857 // writer 17858 synchronized (mPackages) { 17859 // Reinstate the old system package 17860 enableSystemPackageLPw(disabledPs.pkg); 17861 // Remove any native libraries from the upgraded package. 17862 removeNativeBinariesLI(deletedPs); 17863 } 17864 17865 // Install the system package 17866 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17867 int parseFlags = mDefParseFlags 17868 | PackageParser.PARSE_MUST_BE_APK 17869 | PackageParser.PARSE_IS_SYSTEM 17870 | PackageParser.PARSE_IS_SYSTEM_DIR; 17871 if (locationIsPrivileged(disabledPs.codePath)) { 17872 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17873 } 17874 17875 final PackageParser.Package newPkg; 17876 try { 17877 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17878 0 /* currentTime */, null); 17879 } catch (PackageManagerException e) { 17880 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17881 + e.getMessage()); 17882 return false; 17883 } 17884 17885 try { 17886 // update shared libraries for the newly re-installed system package 17887 updateSharedLibrariesLPr(newPkg, null); 17888 } catch (PackageManagerException e) { 17889 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17890 } 17891 17892 prepareAppDataAfterInstallLIF(newPkg); 17893 17894 // writer 17895 synchronized (mPackages) { 17896 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17897 17898 // Propagate the permissions state as we do not want to drop on the floor 17899 // runtime permissions. The update permissions method below will take 17900 // care of removing obsolete permissions and grant install permissions. 17901 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17902 updatePermissionsLPw(newPkg.packageName, newPkg, 17903 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17904 17905 if (applyUserRestrictions) { 17906 boolean installedStateChanged = false; 17907 if (DEBUG_REMOVE) { 17908 Slog.d(TAG, "Propagating install state across reinstall"); 17909 } 17910 for (int userId : allUserHandles) { 17911 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17912 if (DEBUG_REMOVE) { 17913 Slog.d(TAG, " user " + userId + " => " + installed); 17914 } 17915 if (installed != ps.getInstalled(userId)) { 17916 installedStateChanged = true; 17917 } 17918 ps.setInstalled(installed, userId); 17919 17920 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17921 } 17922 // Regardless of writeSettings we need to ensure that this restriction 17923 // state propagation is persisted 17924 mSettings.writeAllUsersPackageRestrictionsLPr(); 17925 if (installedStateChanged) { 17926 mSettings.writeKernelMappingLPr(ps); 17927 } 17928 } 17929 // can downgrade to reader here 17930 if (writeSettings) { 17931 mSettings.writeLPr(); 17932 } 17933 } 17934 return true; 17935 } 17936 17937 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17938 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17939 PackageRemovedInfo outInfo, boolean writeSettings, 17940 PackageParser.Package replacingPackage) { 17941 synchronized (mPackages) { 17942 if (outInfo != null) { 17943 outInfo.uid = ps.appId; 17944 } 17945 17946 if (outInfo != null && outInfo.removedChildPackages != null) { 17947 final int childCount = (ps.childPackageNames != null) 17948 ? ps.childPackageNames.size() : 0; 17949 for (int i = 0; i < childCount; i++) { 17950 String childPackageName = ps.childPackageNames.get(i); 17951 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17952 if (childPs == null) { 17953 return false; 17954 } 17955 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17956 childPackageName); 17957 if (childInfo != null) { 17958 childInfo.uid = childPs.appId; 17959 } 17960 } 17961 } 17962 } 17963 17964 // Delete package data from internal structures and also remove data if flag is set 17965 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17966 17967 // Delete the child packages data 17968 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17969 for (int i = 0; i < childCount; i++) { 17970 PackageSetting childPs; 17971 synchronized (mPackages) { 17972 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17973 } 17974 if (childPs != null) { 17975 PackageRemovedInfo childOutInfo = (outInfo != null 17976 && outInfo.removedChildPackages != null) 17977 ? outInfo.removedChildPackages.get(childPs.name) : null; 17978 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17979 && (replacingPackage != null 17980 && !replacingPackage.hasChildPackage(childPs.name)) 17981 ? flags & ~DELETE_KEEP_DATA : flags; 17982 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17983 deleteFlags, writeSettings); 17984 } 17985 } 17986 17987 // Delete application code and resources only for parent packages 17988 if (ps.parentPackageName == null) { 17989 if (deleteCodeAndResources && (outInfo != null)) { 17990 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17991 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17992 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17993 } 17994 } 17995 17996 return true; 17997 } 17998 17999 @Override 18000 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18001 int userId) { 18002 mContext.enforceCallingOrSelfPermission( 18003 android.Manifest.permission.DELETE_PACKAGES, null); 18004 synchronized (mPackages) { 18005 PackageSetting ps = mSettings.mPackages.get(packageName); 18006 if (ps == null) { 18007 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18008 return false; 18009 } 18010 // Cannot block uninstall of static shared libs as they are 18011 // considered a part of the using app (emulating static linking). 18012 // Also static libs are installed always on internal storage. 18013 PackageParser.Package pkg = mPackages.get(packageName); 18014 if (pkg != null && pkg.staticSharedLibName != null) { 18015 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18016 + " providing static shared library: " + pkg.staticSharedLibName); 18017 return false; 18018 } 18019 if (!ps.getInstalled(userId)) { 18020 // Can't block uninstall for an app that is not installed or enabled. 18021 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18022 return false; 18023 } 18024 ps.setBlockUninstall(blockUninstall, userId); 18025 mSettings.writePackageRestrictionsLPr(userId); 18026 } 18027 return true; 18028 } 18029 18030 @Override 18031 public boolean getBlockUninstallForUser(String packageName, int userId) { 18032 synchronized (mPackages) { 18033 PackageSetting ps = mSettings.mPackages.get(packageName); 18034 if (ps == null) { 18035 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18036 return false; 18037 } 18038 return ps.getBlockUninstall(userId); 18039 } 18040 } 18041 18042 @Override 18043 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18044 int callingUid = Binder.getCallingUid(); 18045 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18046 throw new SecurityException( 18047 "setRequiredForSystemUser can only be run by the system or root"); 18048 } 18049 synchronized (mPackages) { 18050 PackageSetting ps = mSettings.mPackages.get(packageName); 18051 if (ps == null) { 18052 Log.w(TAG, "Package doesn't exist: " + packageName); 18053 return false; 18054 } 18055 if (systemUserApp) { 18056 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18057 } else { 18058 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18059 } 18060 mSettings.writeLPr(); 18061 } 18062 return true; 18063 } 18064 18065 /* 18066 * This method handles package deletion in general 18067 */ 18068 private boolean deletePackageLIF(String packageName, UserHandle user, 18069 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18070 PackageRemovedInfo outInfo, boolean writeSettings, 18071 PackageParser.Package replacingPackage) { 18072 if (packageName == null) { 18073 Slog.w(TAG, "Attempt to delete null packageName."); 18074 return false; 18075 } 18076 18077 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18078 18079 PackageSetting ps; 18080 synchronized (mPackages) { 18081 ps = mSettings.mPackages.get(packageName); 18082 if (ps == null) { 18083 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18084 return false; 18085 } 18086 18087 if (ps.parentPackageName != null && (!isSystemApp(ps) 18088 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18089 if (DEBUG_REMOVE) { 18090 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18091 + ((user == null) ? UserHandle.USER_ALL : user)); 18092 } 18093 final int removedUserId = (user != null) ? user.getIdentifier() 18094 : UserHandle.USER_ALL; 18095 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18096 return false; 18097 } 18098 markPackageUninstalledForUserLPw(ps, user); 18099 scheduleWritePackageRestrictionsLocked(user); 18100 return true; 18101 } 18102 } 18103 18104 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18105 && user.getIdentifier() != UserHandle.USER_ALL)) { 18106 // The caller is asking that the package only be deleted for a single 18107 // user. To do this, we just mark its uninstalled state and delete 18108 // its data. If this is a system app, we only allow this to happen if 18109 // they have set the special DELETE_SYSTEM_APP which requests different 18110 // semantics than normal for uninstalling system apps. 18111 markPackageUninstalledForUserLPw(ps, user); 18112 18113 if (!isSystemApp(ps)) { 18114 // Do not uninstall the APK if an app should be cached 18115 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18116 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18117 // Other user still have this package installed, so all 18118 // we need to do is clear this user's data and save that 18119 // it is uninstalled. 18120 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18121 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18122 return false; 18123 } 18124 scheduleWritePackageRestrictionsLocked(user); 18125 return true; 18126 } else { 18127 // We need to set it back to 'installed' so the uninstall 18128 // broadcasts will be sent correctly. 18129 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18130 ps.setInstalled(true, user.getIdentifier()); 18131 mSettings.writeKernelMappingLPr(ps); 18132 } 18133 } else { 18134 // This is a system app, so we assume that the 18135 // other users still have this package installed, so all 18136 // we need to do is clear this user's data and save that 18137 // it is uninstalled. 18138 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18139 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18140 return false; 18141 } 18142 scheduleWritePackageRestrictionsLocked(user); 18143 return true; 18144 } 18145 } 18146 18147 // If we are deleting a composite package for all users, keep track 18148 // of result for each child. 18149 if (ps.childPackageNames != null && outInfo != null) { 18150 synchronized (mPackages) { 18151 final int childCount = ps.childPackageNames.size(); 18152 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18153 for (int i = 0; i < childCount; i++) { 18154 String childPackageName = ps.childPackageNames.get(i); 18155 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18156 childInfo.removedPackage = childPackageName; 18157 outInfo.removedChildPackages.put(childPackageName, childInfo); 18158 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18159 if (childPs != null) { 18160 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18161 } 18162 } 18163 } 18164 } 18165 18166 boolean ret = false; 18167 if (isSystemApp(ps)) { 18168 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18169 // When an updated system application is deleted we delete the existing resources 18170 // as well and fall back to existing code in system partition 18171 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18172 } else { 18173 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18174 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18175 outInfo, writeSettings, replacingPackage); 18176 } 18177 18178 // Take a note whether we deleted the package for all users 18179 if (outInfo != null) { 18180 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18181 if (outInfo.removedChildPackages != null) { 18182 synchronized (mPackages) { 18183 final int childCount = outInfo.removedChildPackages.size(); 18184 for (int i = 0; i < childCount; i++) { 18185 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18186 if (childInfo != null) { 18187 childInfo.removedForAllUsers = mPackages.get( 18188 childInfo.removedPackage) == null; 18189 } 18190 } 18191 } 18192 } 18193 // If we uninstalled an update to a system app there may be some 18194 // child packages that appeared as they are declared in the system 18195 // app but were not declared in the update. 18196 if (isSystemApp(ps)) { 18197 synchronized (mPackages) { 18198 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18199 final int childCount = (updatedPs.childPackageNames != null) 18200 ? updatedPs.childPackageNames.size() : 0; 18201 for (int i = 0; i < childCount; i++) { 18202 String childPackageName = updatedPs.childPackageNames.get(i); 18203 if (outInfo.removedChildPackages == null 18204 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18205 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18206 if (childPs == null) { 18207 continue; 18208 } 18209 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18210 installRes.name = childPackageName; 18211 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18212 installRes.pkg = mPackages.get(childPackageName); 18213 installRes.uid = childPs.pkg.applicationInfo.uid; 18214 if (outInfo.appearedChildPackages == null) { 18215 outInfo.appearedChildPackages = new ArrayMap<>(); 18216 } 18217 outInfo.appearedChildPackages.put(childPackageName, installRes); 18218 } 18219 } 18220 } 18221 } 18222 } 18223 18224 return ret; 18225 } 18226 18227 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18228 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18229 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18230 for (int nextUserId : userIds) { 18231 if (DEBUG_REMOVE) { 18232 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18233 } 18234 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18235 false /*installed*/, 18236 true /*stopped*/, 18237 true /*notLaunched*/, 18238 false /*hidden*/, 18239 false /*suspended*/, 18240 false /*instantApp*/, 18241 null /*lastDisableAppCaller*/, 18242 null /*enabledComponents*/, 18243 null /*disabledComponents*/, 18244 false /*blockUninstall*/, 18245 ps.readUserState(nextUserId).domainVerificationStatus, 18246 0, PackageManager.INSTALL_REASON_UNKNOWN); 18247 } 18248 mSettings.writeKernelMappingLPr(ps); 18249 } 18250 18251 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18252 PackageRemovedInfo outInfo) { 18253 final PackageParser.Package pkg; 18254 synchronized (mPackages) { 18255 pkg = mPackages.get(ps.name); 18256 } 18257 18258 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18259 : new int[] {userId}; 18260 for (int nextUserId : userIds) { 18261 if (DEBUG_REMOVE) { 18262 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18263 + nextUserId); 18264 } 18265 18266 destroyAppDataLIF(pkg, userId, 18267 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18268 destroyAppProfilesLIF(pkg, userId); 18269 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18270 schedulePackageCleaning(ps.name, nextUserId, false); 18271 synchronized (mPackages) { 18272 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18273 scheduleWritePackageRestrictionsLocked(nextUserId); 18274 } 18275 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18276 } 18277 } 18278 18279 if (outInfo != null) { 18280 outInfo.removedPackage = ps.name; 18281 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18282 outInfo.removedAppId = ps.appId; 18283 outInfo.removedUsers = userIds; 18284 } 18285 18286 return true; 18287 } 18288 18289 private final class ClearStorageConnection implements ServiceConnection { 18290 IMediaContainerService mContainerService; 18291 18292 @Override 18293 public void onServiceConnected(ComponentName name, IBinder service) { 18294 synchronized (this) { 18295 mContainerService = IMediaContainerService.Stub 18296 .asInterface(Binder.allowBlocking(service)); 18297 notifyAll(); 18298 } 18299 } 18300 18301 @Override 18302 public void onServiceDisconnected(ComponentName name) { 18303 } 18304 } 18305 18306 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18307 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18308 18309 final boolean mounted; 18310 if (Environment.isExternalStorageEmulated()) { 18311 mounted = true; 18312 } else { 18313 final String status = Environment.getExternalStorageState(); 18314 18315 mounted = status.equals(Environment.MEDIA_MOUNTED) 18316 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18317 } 18318 18319 if (!mounted) { 18320 return; 18321 } 18322 18323 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18324 int[] users; 18325 if (userId == UserHandle.USER_ALL) { 18326 users = sUserManager.getUserIds(); 18327 } else { 18328 users = new int[] { userId }; 18329 } 18330 final ClearStorageConnection conn = new ClearStorageConnection(); 18331 if (mContext.bindServiceAsUser( 18332 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18333 try { 18334 for (int curUser : users) { 18335 long timeout = SystemClock.uptimeMillis() + 5000; 18336 synchronized (conn) { 18337 long now; 18338 while (conn.mContainerService == null && 18339 (now = SystemClock.uptimeMillis()) < timeout) { 18340 try { 18341 conn.wait(timeout - now); 18342 } catch (InterruptedException e) { 18343 } 18344 } 18345 } 18346 if (conn.mContainerService == null) { 18347 return; 18348 } 18349 18350 final UserEnvironment userEnv = new UserEnvironment(curUser); 18351 clearDirectory(conn.mContainerService, 18352 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18353 if (allData) { 18354 clearDirectory(conn.mContainerService, 18355 userEnv.buildExternalStorageAppDataDirs(packageName)); 18356 clearDirectory(conn.mContainerService, 18357 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18358 } 18359 } 18360 } finally { 18361 mContext.unbindService(conn); 18362 } 18363 } 18364 } 18365 18366 @Override 18367 public void clearApplicationProfileData(String packageName) { 18368 enforceSystemOrRoot("Only the system can clear all profile data"); 18369 18370 final PackageParser.Package pkg; 18371 synchronized (mPackages) { 18372 pkg = mPackages.get(packageName); 18373 } 18374 18375 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18376 synchronized (mInstallLock) { 18377 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18378 } 18379 } 18380 } 18381 18382 @Override 18383 public void clearApplicationUserData(final String packageName, 18384 final IPackageDataObserver observer, final int userId) { 18385 mContext.enforceCallingOrSelfPermission( 18386 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18387 18388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18389 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18390 18391 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18392 throw new SecurityException("Cannot clear data for a protected package: " 18393 + packageName); 18394 } 18395 // Queue up an async operation since the package deletion may take a little while. 18396 mHandler.post(new Runnable() { 18397 public void run() { 18398 mHandler.removeCallbacks(this); 18399 final boolean succeeded; 18400 try (PackageFreezer freezer = freezePackage(packageName, 18401 "clearApplicationUserData")) { 18402 synchronized (mInstallLock) { 18403 succeeded = clearApplicationUserDataLIF(packageName, userId); 18404 } 18405 clearExternalStorageDataSync(packageName, userId, true); 18406 synchronized (mPackages) { 18407 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18408 packageName, userId); 18409 } 18410 } 18411 if (succeeded) { 18412 // invoke DeviceStorageMonitor's update method to clear any notifications 18413 DeviceStorageMonitorInternal dsm = LocalServices 18414 .getService(DeviceStorageMonitorInternal.class); 18415 if (dsm != null) { 18416 dsm.checkMemory(); 18417 } 18418 } 18419 if(observer != null) { 18420 try { 18421 observer.onRemoveCompleted(packageName, succeeded); 18422 } catch (RemoteException e) { 18423 Log.i(TAG, "Observer no longer exists."); 18424 } 18425 } //end if observer 18426 } //end run 18427 }); 18428 } 18429 18430 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18431 if (packageName == null) { 18432 Slog.w(TAG, "Attempt to delete null packageName."); 18433 return false; 18434 } 18435 18436 // Try finding details about the requested package 18437 PackageParser.Package pkg; 18438 synchronized (mPackages) { 18439 pkg = mPackages.get(packageName); 18440 if (pkg == null) { 18441 final PackageSetting ps = mSettings.mPackages.get(packageName); 18442 if (ps != null) { 18443 pkg = ps.pkg; 18444 } 18445 } 18446 18447 if (pkg == null) { 18448 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18449 return false; 18450 } 18451 18452 PackageSetting ps = (PackageSetting) pkg.mExtras; 18453 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18454 } 18455 18456 clearAppDataLIF(pkg, userId, 18457 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18458 18459 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18460 removeKeystoreDataIfNeeded(userId, appId); 18461 18462 UserManagerInternal umInternal = getUserManagerInternal(); 18463 final int flags; 18464 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18465 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18466 } else if (umInternal.isUserRunning(userId)) { 18467 flags = StorageManager.FLAG_STORAGE_DE; 18468 } else { 18469 flags = 0; 18470 } 18471 prepareAppDataContentsLIF(pkg, userId, flags); 18472 18473 return true; 18474 } 18475 18476 /** 18477 * Reverts user permission state changes (permissions and flags) in 18478 * all packages for a given user. 18479 * 18480 * @param userId The device user for which to do a reset. 18481 */ 18482 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18483 final int packageCount = mPackages.size(); 18484 for (int i = 0; i < packageCount; i++) { 18485 PackageParser.Package pkg = mPackages.valueAt(i); 18486 PackageSetting ps = (PackageSetting) pkg.mExtras; 18487 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18488 } 18489 } 18490 18491 private void resetNetworkPolicies(int userId) { 18492 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18493 } 18494 18495 /** 18496 * Reverts user permission state changes (permissions and flags). 18497 * 18498 * @param ps The package for which to reset. 18499 * @param userId The device user for which to do a reset. 18500 */ 18501 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18502 final PackageSetting ps, final int userId) { 18503 if (ps.pkg == null) { 18504 return; 18505 } 18506 18507 // These are flags that can change base on user actions. 18508 final int userSettableMask = FLAG_PERMISSION_USER_SET 18509 | FLAG_PERMISSION_USER_FIXED 18510 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18511 | FLAG_PERMISSION_REVIEW_REQUIRED; 18512 18513 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18514 | FLAG_PERMISSION_POLICY_FIXED; 18515 18516 boolean writeInstallPermissions = false; 18517 boolean writeRuntimePermissions = false; 18518 18519 final int permissionCount = ps.pkg.requestedPermissions.size(); 18520 for (int i = 0; i < permissionCount; i++) { 18521 String permission = ps.pkg.requestedPermissions.get(i); 18522 18523 BasePermission bp = mSettings.mPermissions.get(permission); 18524 if (bp == null) { 18525 continue; 18526 } 18527 18528 // If shared user we just reset the state to which only this app contributed. 18529 if (ps.sharedUser != null) { 18530 boolean used = false; 18531 final int packageCount = ps.sharedUser.packages.size(); 18532 for (int j = 0; j < packageCount; j++) { 18533 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18534 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18535 && pkg.pkg.requestedPermissions.contains(permission)) { 18536 used = true; 18537 break; 18538 } 18539 } 18540 if (used) { 18541 continue; 18542 } 18543 } 18544 18545 PermissionsState permissionsState = ps.getPermissionsState(); 18546 18547 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18548 18549 // Always clear the user settable flags. 18550 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18551 bp.name) != null; 18552 // If permission review is enabled and this is a legacy app, mark the 18553 // permission as requiring a review as this is the initial state. 18554 int flags = 0; 18555 if (mPermissionReviewRequired 18556 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18557 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18558 } 18559 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18560 if (hasInstallState) { 18561 writeInstallPermissions = true; 18562 } else { 18563 writeRuntimePermissions = true; 18564 } 18565 } 18566 18567 // Below is only runtime permission handling. 18568 if (!bp.isRuntime()) { 18569 continue; 18570 } 18571 18572 // Never clobber system or policy. 18573 if ((oldFlags & policyOrSystemFlags) != 0) { 18574 continue; 18575 } 18576 18577 // If this permission was granted by default, make sure it is. 18578 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18579 if (permissionsState.grantRuntimePermission(bp, userId) 18580 != PERMISSION_OPERATION_FAILURE) { 18581 writeRuntimePermissions = true; 18582 } 18583 // If permission review is enabled the permissions for a legacy apps 18584 // are represented as constantly granted runtime ones, so don't revoke. 18585 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18586 // Otherwise, reset the permission. 18587 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18588 switch (revokeResult) { 18589 case PERMISSION_OPERATION_SUCCESS: 18590 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18591 writeRuntimePermissions = true; 18592 final int appId = ps.appId; 18593 mHandler.post(new Runnable() { 18594 @Override 18595 public void run() { 18596 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18597 } 18598 }); 18599 } break; 18600 } 18601 } 18602 } 18603 18604 // Synchronously write as we are taking permissions away. 18605 if (writeRuntimePermissions) { 18606 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18607 } 18608 18609 // Synchronously write as we are taking permissions away. 18610 if (writeInstallPermissions) { 18611 mSettings.writeLPr(); 18612 } 18613 } 18614 18615 /** 18616 * Remove entries from the keystore daemon. Will only remove it if the 18617 * {@code appId} is valid. 18618 */ 18619 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18620 if (appId < 0) { 18621 return; 18622 } 18623 18624 final KeyStore keyStore = KeyStore.getInstance(); 18625 if (keyStore != null) { 18626 if (userId == UserHandle.USER_ALL) { 18627 for (final int individual : sUserManager.getUserIds()) { 18628 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18629 } 18630 } else { 18631 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18632 } 18633 } else { 18634 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18635 } 18636 } 18637 18638 @Override 18639 public void deleteApplicationCacheFiles(final String packageName, 18640 final IPackageDataObserver observer) { 18641 final int userId = UserHandle.getCallingUserId(); 18642 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18643 } 18644 18645 @Override 18646 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18647 final IPackageDataObserver observer) { 18648 mContext.enforceCallingOrSelfPermission( 18649 android.Manifest.permission.DELETE_CACHE_FILES, null); 18650 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18651 /* requireFullPermission= */ true, /* checkShell= */ false, 18652 "delete application cache files"); 18653 18654 final PackageParser.Package pkg; 18655 synchronized (mPackages) { 18656 pkg = mPackages.get(packageName); 18657 } 18658 18659 // Queue up an async operation since the package deletion may take a little while. 18660 mHandler.post(new Runnable() { 18661 public void run() { 18662 synchronized (mInstallLock) { 18663 final int flags = StorageManager.FLAG_STORAGE_DE 18664 | StorageManager.FLAG_STORAGE_CE; 18665 // We're only clearing cache files, so we don't care if the 18666 // app is unfrozen and still able to run 18667 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18668 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18669 } 18670 clearExternalStorageDataSync(packageName, userId, false); 18671 if (observer != null) { 18672 try { 18673 observer.onRemoveCompleted(packageName, true); 18674 } catch (RemoteException e) { 18675 Log.i(TAG, "Observer no longer exists."); 18676 } 18677 } 18678 } 18679 }); 18680 } 18681 18682 @Override 18683 public void getPackageSizeInfo(final String packageName, int userHandle, 18684 final IPackageStatsObserver observer) { 18685 throw new UnsupportedOperationException( 18686 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18687 } 18688 18689 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18690 final PackageSetting ps; 18691 synchronized (mPackages) { 18692 ps = mSettings.mPackages.get(packageName); 18693 if (ps == null) { 18694 Slog.w(TAG, "Failed to find settings for " + packageName); 18695 return false; 18696 } 18697 } 18698 18699 final String[] packageNames = { packageName }; 18700 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18701 final String[] codePaths = { ps.codePathString }; 18702 18703 try { 18704 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18705 ps.appId, ceDataInodes, codePaths, stats); 18706 18707 // For now, ignore code size of packages on system partition 18708 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18709 stats.codeSize = 0; 18710 } 18711 18712 // External clients expect these to be tracked separately 18713 stats.dataSize -= stats.cacheSize; 18714 18715 } catch (InstallerException e) { 18716 Slog.w(TAG, String.valueOf(e)); 18717 return false; 18718 } 18719 18720 return true; 18721 } 18722 18723 private int getUidTargetSdkVersionLockedLPr(int uid) { 18724 Object obj = mSettings.getUserIdLPr(uid); 18725 if (obj instanceof SharedUserSetting) { 18726 final SharedUserSetting sus = (SharedUserSetting) obj; 18727 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18728 final Iterator<PackageSetting> it = sus.packages.iterator(); 18729 while (it.hasNext()) { 18730 final PackageSetting ps = it.next(); 18731 if (ps.pkg != null) { 18732 int v = ps.pkg.applicationInfo.targetSdkVersion; 18733 if (v < vers) vers = v; 18734 } 18735 } 18736 return vers; 18737 } else if (obj instanceof PackageSetting) { 18738 final PackageSetting ps = (PackageSetting) obj; 18739 if (ps.pkg != null) { 18740 return ps.pkg.applicationInfo.targetSdkVersion; 18741 } 18742 } 18743 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18744 } 18745 18746 @Override 18747 public void addPreferredActivity(IntentFilter filter, int match, 18748 ComponentName[] set, ComponentName activity, int userId) { 18749 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18750 "Adding preferred"); 18751 } 18752 18753 private void addPreferredActivityInternal(IntentFilter filter, int match, 18754 ComponentName[] set, ComponentName activity, boolean always, int userId, 18755 String opname) { 18756 // writer 18757 int callingUid = Binder.getCallingUid(); 18758 enforceCrossUserPermission(callingUid, userId, 18759 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18760 if (filter.countActions() == 0) { 18761 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18762 return; 18763 } 18764 synchronized (mPackages) { 18765 if (mContext.checkCallingOrSelfPermission( 18766 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18767 != PackageManager.PERMISSION_GRANTED) { 18768 if (getUidTargetSdkVersionLockedLPr(callingUid) 18769 < Build.VERSION_CODES.FROYO) { 18770 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18771 + callingUid); 18772 return; 18773 } 18774 mContext.enforceCallingOrSelfPermission( 18775 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18776 } 18777 18778 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18779 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18780 + userId + ":"); 18781 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18782 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18783 scheduleWritePackageRestrictionsLocked(userId); 18784 postPreferredActivityChangedBroadcast(userId); 18785 } 18786 } 18787 18788 private void postPreferredActivityChangedBroadcast(int userId) { 18789 mHandler.post(() -> { 18790 final IActivityManager am = ActivityManager.getService(); 18791 if (am == null) { 18792 return; 18793 } 18794 18795 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18796 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18797 try { 18798 am.broadcastIntent(null, intent, null, null, 18799 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18800 null, false, false, userId); 18801 } catch (RemoteException e) { 18802 } 18803 }); 18804 } 18805 18806 @Override 18807 public void replacePreferredActivity(IntentFilter filter, int match, 18808 ComponentName[] set, ComponentName activity, int userId) { 18809 if (filter.countActions() != 1) { 18810 throw new IllegalArgumentException( 18811 "replacePreferredActivity expects filter to have only 1 action."); 18812 } 18813 if (filter.countDataAuthorities() != 0 18814 || filter.countDataPaths() != 0 18815 || filter.countDataSchemes() > 1 18816 || filter.countDataTypes() != 0) { 18817 throw new IllegalArgumentException( 18818 "replacePreferredActivity expects filter to have no data authorities, " + 18819 "paths, or types; and at most one scheme."); 18820 } 18821 18822 final int callingUid = Binder.getCallingUid(); 18823 enforceCrossUserPermission(callingUid, userId, 18824 true /* requireFullPermission */, false /* checkShell */, 18825 "replace preferred activity"); 18826 synchronized (mPackages) { 18827 if (mContext.checkCallingOrSelfPermission( 18828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18829 != PackageManager.PERMISSION_GRANTED) { 18830 if (getUidTargetSdkVersionLockedLPr(callingUid) 18831 < Build.VERSION_CODES.FROYO) { 18832 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18833 + Binder.getCallingUid()); 18834 return; 18835 } 18836 mContext.enforceCallingOrSelfPermission( 18837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18838 } 18839 18840 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18841 if (pir != null) { 18842 // Get all of the existing entries that exactly match this filter. 18843 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18844 if (existing != null && existing.size() == 1) { 18845 PreferredActivity cur = existing.get(0); 18846 if (DEBUG_PREFERRED) { 18847 Slog.i(TAG, "Checking replace of preferred:"); 18848 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18849 if (!cur.mPref.mAlways) { 18850 Slog.i(TAG, " -- CUR; not mAlways!"); 18851 } else { 18852 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18853 Slog.i(TAG, " -- CUR: mSet=" 18854 + Arrays.toString(cur.mPref.mSetComponents)); 18855 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18856 Slog.i(TAG, " -- NEW: mMatch=" 18857 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18858 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18859 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18860 } 18861 } 18862 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18863 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18864 && cur.mPref.sameSet(set)) { 18865 // Setting the preferred activity to what it happens to be already 18866 if (DEBUG_PREFERRED) { 18867 Slog.i(TAG, "Replacing with same preferred activity " 18868 + cur.mPref.mShortComponent + " for user " 18869 + userId + ":"); 18870 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18871 } 18872 return; 18873 } 18874 } 18875 18876 if (existing != null) { 18877 if (DEBUG_PREFERRED) { 18878 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18879 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18880 } 18881 for (int i = 0; i < existing.size(); i++) { 18882 PreferredActivity pa = existing.get(i); 18883 if (DEBUG_PREFERRED) { 18884 Slog.i(TAG, "Removing existing preferred activity " 18885 + pa.mPref.mComponent + ":"); 18886 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18887 } 18888 pir.removeFilter(pa); 18889 } 18890 } 18891 } 18892 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18893 "Replacing preferred"); 18894 } 18895 } 18896 18897 @Override 18898 public void clearPackagePreferredActivities(String packageName) { 18899 final int uid = Binder.getCallingUid(); 18900 // writer 18901 synchronized (mPackages) { 18902 PackageParser.Package pkg = mPackages.get(packageName); 18903 if (pkg == null || pkg.applicationInfo.uid != uid) { 18904 if (mContext.checkCallingOrSelfPermission( 18905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18906 != PackageManager.PERMISSION_GRANTED) { 18907 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18908 < Build.VERSION_CODES.FROYO) { 18909 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18910 + Binder.getCallingUid()); 18911 return; 18912 } 18913 mContext.enforceCallingOrSelfPermission( 18914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18915 } 18916 } 18917 18918 int user = UserHandle.getCallingUserId(); 18919 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18920 scheduleWritePackageRestrictionsLocked(user); 18921 } 18922 } 18923 } 18924 18925 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18926 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18927 ArrayList<PreferredActivity> removed = null; 18928 boolean changed = false; 18929 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18930 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18931 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18932 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18933 continue; 18934 } 18935 Iterator<PreferredActivity> it = pir.filterIterator(); 18936 while (it.hasNext()) { 18937 PreferredActivity pa = it.next(); 18938 // Mark entry for removal only if it matches the package name 18939 // and the entry is of type "always". 18940 if (packageName == null || 18941 (pa.mPref.mComponent.getPackageName().equals(packageName) 18942 && pa.mPref.mAlways)) { 18943 if (removed == null) { 18944 removed = new ArrayList<PreferredActivity>(); 18945 } 18946 removed.add(pa); 18947 } 18948 } 18949 if (removed != null) { 18950 for (int j=0; j<removed.size(); j++) { 18951 PreferredActivity pa = removed.get(j); 18952 pir.removeFilter(pa); 18953 } 18954 changed = true; 18955 } 18956 } 18957 if (changed) { 18958 postPreferredActivityChangedBroadcast(userId); 18959 } 18960 return changed; 18961 } 18962 18963 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18964 private void clearIntentFilterVerificationsLPw(int userId) { 18965 final int packageCount = mPackages.size(); 18966 for (int i = 0; i < packageCount; i++) { 18967 PackageParser.Package pkg = mPackages.valueAt(i); 18968 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18969 } 18970 } 18971 18972 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18973 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18974 if (userId == UserHandle.USER_ALL) { 18975 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18976 sUserManager.getUserIds())) { 18977 for (int oneUserId : sUserManager.getUserIds()) { 18978 scheduleWritePackageRestrictionsLocked(oneUserId); 18979 } 18980 } 18981 } else { 18982 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18983 scheduleWritePackageRestrictionsLocked(userId); 18984 } 18985 } 18986 } 18987 18988 void clearDefaultBrowserIfNeeded(String packageName) { 18989 for (int oneUserId : sUserManager.getUserIds()) { 18990 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18991 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18992 if (packageName.equals(defaultBrowserPackageName)) { 18993 setDefaultBrowserPackageName(null, oneUserId); 18994 } 18995 } 18996 } 18997 18998 @Override 18999 public void resetApplicationPreferences(int userId) { 19000 mContext.enforceCallingOrSelfPermission( 19001 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19002 final long identity = Binder.clearCallingIdentity(); 19003 // writer 19004 try { 19005 synchronized (mPackages) { 19006 clearPackagePreferredActivitiesLPw(null, userId); 19007 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19008 // TODO: We have to reset the default SMS and Phone. This requires 19009 // significant refactoring to keep all default apps in the package 19010 // manager (cleaner but more work) or have the services provide 19011 // callbacks to the package manager to request a default app reset. 19012 applyFactoryDefaultBrowserLPw(userId); 19013 clearIntentFilterVerificationsLPw(userId); 19014 primeDomainVerificationsLPw(userId); 19015 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19016 scheduleWritePackageRestrictionsLocked(userId); 19017 } 19018 resetNetworkPolicies(userId); 19019 } finally { 19020 Binder.restoreCallingIdentity(identity); 19021 } 19022 } 19023 19024 @Override 19025 public int getPreferredActivities(List<IntentFilter> outFilters, 19026 List<ComponentName> outActivities, String packageName) { 19027 19028 int num = 0; 19029 final int userId = UserHandle.getCallingUserId(); 19030 // reader 19031 synchronized (mPackages) { 19032 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19033 if (pir != null) { 19034 final Iterator<PreferredActivity> it = pir.filterIterator(); 19035 while (it.hasNext()) { 19036 final PreferredActivity pa = it.next(); 19037 if (packageName == null 19038 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19039 && pa.mPref.mAlways)) { 19040 if (outFilters != null) { 19041 outFilters.add(new IntentFilter(pa)); 19042 } 19043 if (outActivities != null) { 19044 outActivities.add(pa.mPref.mComponent); 19045 } 19046 } 19047 } 19048 } 19049 } 19050 19051 return num; 19052 } 19053 19054 @Override 19055 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19056 int userId) { 19057 int callingUid = Binder.getCallingUid(); 19058 if (callingUid != Process.SYSTEM_UID) { 19059 throw new SecurityException( 19060 "addPersistentPreferredActivity can only be run by the system"); 19061 } 19062 if (filter.countActions() == 0) { 19063 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19064 return; 19065 } 19066 synchronized (mPackages) { 19067 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19068 ":"); 19069 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19070 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19071 new PersistentPreferredActivity(filter, activity)); 19072 scheduleWritePackageRestrictionsLocked(userId); 19073 postPreferredActivityChangedBroadcast(userId); 19074 } 19075 } 19076 19077 @Override 19078 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19079 int callingUid = Binder.getCallingUid(); 19080 if (callingUid != Process.SYSTEM_UID) { 19081 throw new SecurityException( 19082 "clearPackagePersistentPreferredActivities can only be run by the system"); 19083 } 19084 ArrayList<PersistentPreferredActivity> removed = null; 19085 boolean changed = false; 19086 synchronized (mPackages) { 19087 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19088 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19089 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19090 .valueAt(i); 19091 if (userId != thisUserId) { 19092 continue; 19093 } 19094 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19095 while (it.hasNext()) { 19096 PersistentPreferredActivity ppa = it.next(); 19097 // Mark entry for removal only if it matches the package name. 19098 if (ppa.mComponent.getPackageName().equals(packageName)) { 19099 if (removed == null) { 19100 removed = new ArrayList<PersistentPreferredActivity>(); 19101 } 19102 removed.add(ppa); 19103 } 19104 } 19105 if (removed != null) { 19106 for (int j=0; j<removed.size(); j++) { 19107 PersistentPreferredActivity ppa = removed.get(j); 19108 ppir.removeFilter(ppa); 19109 } 19110 changed = true; 19111 } 19112 } 19113 19114 if (changed) { 19115 scheduleWritePackageRestrictionsLocked(userId); 19116 postPreferredActivityChangedBroadcast(userId); 19117 } 19118 } 19119 } 19120 19121 /** 19122 * Common machinery for picking apart a restored XML blob and passing 19123 * it to a caller-supplied functor to be applied to the running system. 19124 */ 19125 private void restoreFromXml(XmlPullParser parser, int userId, 19126 String expectedStartTag, BlobXmlRestorer functor) 19127 throws IOException, XmlPullParserException { 19128 int type; 19129 while ((type = parser.next()) != XmlPullParser.START_TAG 19130 && type != XmlPullParser.END_DOCUMENT) { 19131 } 19132 if (type != XmlPullParser.START_TAG) { 19133 // oops didn't find a start tag?! 19134 if (DEBUG_BACKUP) { 19135 Slog.e(TAG, "Didn't find start tag during restore"); 19136 } 19137 return; 19138 } 19139Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19140 // this is supposed to be TAG_PREFERRED_BACKUP 19141 if (!expectedStartTag.equals(parser.getName())) { 19142 if (DEBUG_BACKUP) { 19143 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19144 } 19145 return; 19146 } 19147 19148 // skip interfering stuff, then we're aligned with the backing implementation 19149 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19150Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19151 functor.apply(parser, userId); 19152 } 19153 19154 private interface BlobXmlRestorer { 19155 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19156 } 19157 19158 /** 19159 * Non-Binder method, support for the backup/restore mechanism: write the 19160 * full set of preferred activities in its canonical XML format. Returns the 19161 * XML output as a byte array, or null if there is none. 19162 */ 19163 @Override 19164 public byte[] getPreferredActivityBackup(int userId) { 19165 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19166 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19167 } 19168 19169 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19170 try { 19171 final XmlSerializer serializer = new FastXmlSerializer(); 19172 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19173 serializer.startDocument(null, true); 19174 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19175 19176 synchronized (mPackages) { 19177 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19178 } 19179 19180 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19181 serializer.endDocument(); 19182 serializer.flush(); 19183 } catch (Exception e) { 19184 if (DEBUG_BACKUP) { 19185 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19186 } 19187 return null; 19188 } 19189 19190 return dataStream.toByteArray(); 19191 } 19192 19193 @Override 19194 public void restorePreferredActivities(byte[] backup, int userId) { 19195 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19196 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19197 } 19198 19199 try { 19200 final XmlPullParser parser = Xml.newPullParser(); 19201 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19202 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19203 new BlobXmlRestorer() { 19204 @Override 19205 public void apply(XmlPullParser parser, int userId) 19206 throws XmlPullParserException, IOException { 19207 synchronized (mPackages) { 19208 mSettings.readPreferredActivitiesLPw(parser, userId); 19209 } 19210 } 19211 } ); 19212 } catch (Exception e) { 19213 if (DEBUG_BACKUP) { 19214 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19215 } 19216 } 19217 } 19218 19219 /** 19220 * Non-Binder method, support for the backup/restore mechanism: write the 19221 * default browser (etc) settings in its canonical XML format. Returns the default 19222 * browser XML representation as a byte array, or null if there is none. 19223 */ 19224 @Override 19225 public byte[] getDefaultAppsBackup(int userId) { 19226 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19227 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19228 } 19229 19230 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19231 try { 19232 final XmlSerializer serializer = new FastXmlSerializer(); 19233 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19234 serializer.startDocument(null, true); 19235 serializer.startTag(null, TAG_DEFAULT_APPS); 19236 19237 synchronized (mPackages) { 19238 mSettings.writeDefaultAppsLPr(serializer, userId); 19239 } 19240 19241 serializer.endTag(null, TAG_DEFAULT_APPS); 19242 serializer.endDocument(); 19243 serializer.flush(); 19244 } catch (Exception e) { 19245 if (DEBUG_BACKUP) { 19246 Slog.e(TAG, "Unable to write default apps for backup", e); 19247 } 19248 return null; 19249 } 19250 19251 return dataStream.toByteArray(); 19252 } 19253 19254 @Override 19255 public void restoreDefaultApps(byte[] backup, int userId) { 19256 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19257 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19258 } 19259 19260 try { 19261 final XmlPullParser parser = Xml.newPullParser(); 19262 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19263 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19264 new BlobXmlRestorer() { 19265 @Override 19266 public void apply(XmlPullParser parser, int userId) 19267 throws XmlPullParserException, IOException { 19268 synchronized (mPackages) { 19269 mSettings.readDefaultAppsLPw(parser, userId); 19270 } 19271 } 19272 } ); 19273 } catch (Exception e) { 19274 if (DEBUG_BACKUP) { 19275 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19276 } 19277 } 19278 } 19279 19280 @Override 19281 public byte[] getIntentFilterVerificationBackup(int userId) { 19282 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19283 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19284 } 19285 19286 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19287 try { 19288 final XmlSerializer serializer = new FastXmlSerializer(); 19289 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19290 serializer.startDocument(null, true); 19291 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19292 19293 synchronized (mPackages) { 19294 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19295 } 19296 19297 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19298 serializer.endDocument(); 19299 serializer.flush(); 19300 } catch (Exception e) { 19301 if (DEBUG_BACKUP) { 19302 Slog.e(TAG, "Unable to write default apps for backup", e); 19303 } 19304 return null; 19305 } 19306 19307 return dataStream.toByteArray(); 19308 } 19309 19310 @Override 19311 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19312 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19313 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19314 } 19315 19316 try { 19317 final XmlPullParser parser = Xml.newPullParser(); 19318 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19319 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19320 new BlobXmlRestorer() { 19321 @Override 19322 public void apply(XmlPullParser parser, int userId) 19323 throws XmlPullParserException, IOException { 19324 synchronized (mPackages) { 19325 mSettings.readAllDomainVerificationsLPr(parser, userId); 19326 mSettings.writeLPr(); 19327 } 19328 } 19329 } ); 19330 } catch (Exception e) { 19331 if (DEBUG_BACKUP) { 19332 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19333 } 19334 } 19335 } 19336 19337 @Override 19338 public byte[] getPermissionGrantBackup(int userId) { 19339 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19340 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19341 } 19342 19343 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19344 try { 19345 final XmlSerializer serializer = new FastXmlSerializer(); 19346 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19347 serializer.startDocument(null, true); 19348 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19349 19350 synchronized (mPackages) { 19351 serializeRuntimePermissionGrantsLPr(serializer, userId); 19352 } 19353 19354 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19355 serializer.endDocument(); 19356 serializer.flush(); 19357 } catch (Exception e) { 19358 if (DEBUG_BACKUP) { 19359 Slog.e(TAG, "Unable to write default apps for backup", e); 19360 } 19361 return null; 19362 } 19363 19364 return dataStream.toByteArray(); 19365 } 19366 19367 @Override 19368 public void restorePermissionGrants(byte[] backup, int userId) { 19369 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19370 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19371 } 19372 19373 try { 19374 final XmlPullParser parser = Xml.newPullParser(); 19375 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19376 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19377 new BlobXmlRestorer() { 19378 @Override 19379 public void apply(XmlPullParser parser, int userId) 19380 throws XmlPullParserException, IOException { 19381 synchronized (mPackages) { 19382 processRestoredPermissionGrantsLPr(parser, userId); 19383 } 19384 } 19385 } ); 19386 } catch (Exception e) { 19387 if (DEBUG_BACKUP) { 19388 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19389 } 19390 } 19391 } 19392 19393 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19394 throws IOException { 19395 serializer.startTag(null, TAG_ALL_GRANTS); 19396 19397 final int N = mSettings.mPackages.size(); 19398 for (int i = 0; i < N; i++) { 19399 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19400 boolean pkgGrantsKnown = false; 19401 19402 PermissionsState packagePerms = ps.getPermissionsState(); 19403 19404 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19405 final int grantFlags = state.getFlags(); 19406 // only look at grants that are not system/policy fixed 19407 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19408 final boolean isGranted = state.isGranted(); 19409 // And only back up the user-twiddled state bits 19410 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19411 final String packageName = mSettings.mPackages.keyAt(i); 19412 if (!pkgGrantsKnown) { 19413 serializer.startTag(null, TAG_GRANT); 19414 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19415 pkgGrantsKnown = true; 19416 } 19417 19418 final boolean userSet = 19419 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19420 final boolean userFixed = 19421 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19422 final boolean revoke = 19423 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19424 19425 serializer.startTag(null, TAG_PERMISSION); 19426 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19427 if (isGranted) { 19428 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19429 } 19430 if (userSet) { 19431 serializer.attribute(null, ATTR_USER_SET, "true"); 19432 } 19433 if (userFixed) { 19434 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19435 } 19436 if (revoke) { 19437 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19438 } 19439 serializer.endTag(null, TAG_PERMISSION); 19440 } 19441 } 19442 } 19443 19444 if (pkgGrantsKnown) { 19445 serializer.endTag(null, TAG_GRANT); 19446 } 19447 } 19448 19449 serializer.endTag(null, TAG_ALL_GRANTS); 19450 } 19451 19452 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19453 throws XmlPullParserException, IOException { 19454 String pkgName = null; 19455 int outerDepth = parser.getDepth(); 19456 int type; 19457 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19458 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19459 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19460 continue; 19461 } 19462 19463 final String tagName = parser.getName(); 19464 if (tagName.equals(TAG_GRANT)) { 19465 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19466 if (DEBUG_BACKUP) { 19467 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19468 } 19469 } else if (tagName.equals(TAG_PERMISSION)) { 19470 19471 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19472 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19473 19474 int newFlagSet = 0; 19475 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19476 newFlagSet |= FLAG_PERMISSION_USER_SET; 19477 } 19478 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19479 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19480 } 19481 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19482 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19483 } 19484 if (DEBUG_BACKUP) { 19485 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19486 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19487 } 19488 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19489 if (ps != null) { 19490 // Already installed so we apply the grant immediately 19491 if (DEBUG_BACKUP) { 19492 Slog.v(TAG, " + already installed; applying"); 19493 } 19494 PermissionsState perms = ps.getPermissionsState(); 19495 BasePermission bp = mSettings.mPermissions.get(permName); 19496 if (bp != null) { 19497 if (isGranted) { 19498 perms.grantRuntimePermission(bp, userId); 19499 } 19500 if (newFlagSet != 0) { 19501 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19502 } 19503 } 19504 } else { 19505 // Need to wait for post-restore install to apply the grant 19506 if (DEBUG_BACKUP) { 19507 Slog.v(TAG, " - not yet installed; saving for later"); 19508 } 19509 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19510 isGranted, newFlagSet, userId); 19511 } 19512 } else { 19513 PackageManagerService.reportSettingsProblem(Log.WARN, 19514 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19515 XmlUtils.skipCurrentTag(parser); 19516 } 19517 } 19518 19519 scheduleWriteSettingsLocked(); 19520 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19521 } 19522 19523 @Override 19524 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19525 int sourceUserId, int targetUserId, int flags) { 19526 mContext.enforceCallingOrSelfPermission( 19527 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19528 int callingUid = Binder.getCallingUid(); 19529 enforceOwnerRights(ownerPackage, callingUid); 19530 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19531 if (intentFilter.countActions() == 0) { 19532 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19533 return; 19534 } 19535 synchronized (mPackages) { 19536 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19537 ownerPackage, targetUserId, flags); 19538 CrossProfileIntentResolver resolver = 19539 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19540 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19541 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19542 if (existing != null) { 19543 int size = existing.size(); 19544 for (int i = 0; i < size; i++) { 19545 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19546 return; 19547 } 19548 } 19549 } 19550 resolver.addFilter(newFilter); 19551 scheduleWritePackageRestrictionsLocked(sourceUserId); 19552 } 19553 } 19554 19555 @Override 19556 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19557 mContext.enforceCallingOrSelfPermission( 19558 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19559 int callingUid = Binder.getCallingUid(); 19560 enforceOwnerRights(ownerPackage, callingUid); 19561 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19562 synchronized (mPackages) { 19563 CrossProfileIntentResolver resolver = 19564 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19565 ArraySet<CrossProfileIntentFilter> set = 19566 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19567 for (CrossProfileIntentFilter filter : set) { 19568 if (filter.getOwnerPackage().equals(ownerPackage)) { 19569 resolver.removeFilter(filter); 19570 } 19571 } 19572 scheduleWritePackageRestrictionsLocked(sourceUserId); 19573 } 19574 } 19575 19576 // Enforcing that callingUid is owning pkg on userId 19577 private void enforceOwnerRights(String pkg, int callingUid) { 19578 // The system owns everything. 19579 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19580 return; 19581 } 19582 int callingUserId = UserHandle.getUserId(callingUid); 19583 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19584 if (pi == null) { 19585 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19586 + callingUserId); 19587 } 19588 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19589 throw new SecurityException("Calling uid " + callingUid 19590 + " does not own package " + pkg); 19591 } 19592 } 19593 19594 @Override 19595 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19596 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19597 } 19598 19599 /** 19600 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19601 * then reports the most likely home activity or null if there are more than one. 19602 */ 19603 public ComponentName getDefaultHomeActivity(int userId) { 19604 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19605 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19606 if (cn != null) { 19607 return cn; 19608 } 19609 19610 // Find the launcher with the highest priority and return that component if there are no 19611 // other home activity with the same priority. 19612 int lastPriority = Integer.MIN_VALUE; 19613 ComponentName lastComponent = null; 19614 final int size = allHomeCandidates.size(); 19615 for (int i = 0; i < size; i++) { 19616 final ResolveInfo ri = allHomeCandidates.get(i); 19617 if (ri.priority > lastPriority) { 19618 lastComponent = ri.activityInfo.getComponentName(); 19619 lastPriority = ri.priority; 19620 } else if (ri.priority == lastPriority) { 19621 // Two components found with same priority. 19622 lastComponent = null; 19623 } 19624 } 19625 return lastComponent; 19626 } 19627 19628 private Intent getHomeIntent() { 19629 Intent intent = new Intent(Intent.ACTION_MAIN); 19630 intent.addCategory(Intent.CATEGORY_HOME); 19631 intent.addCategory(Intent.CATEGORY_DEFAULT); 19632 return intent; 19633 } 19634 19635 private IntentFilter getHomeFilter() { 19636 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19637 filter.addCategory(Intent.CATEGORY_HOME); 19638 filter.addCategory(Intent.CATEGORY_DEFAULT); 19639 return filter; 19640 } 19641 19642 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19643 int userId) { 19644 Intent intent = getHomeIntent(); 19645 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19646 PackageManager.GET_META_DATA, userId); 19647 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19648 true, false, false, userId); 19649 19650 allHomeCandidates.clear(); 19651 if (list != null) { 19652 for (ResolveInfo ri : list) { 19653 allHomeCandidates.add(ri); 19654 } 19655 } 19656 return (preferred == null || preferred.activityInfo == null) 19657 ? null 19658 : new ComponentName(preferred.activityInfo.packageName, 19659 preferred.activityInfo.name); 19660 } 19661 19662 @Override 19663 public void setHomeActivity(ComponentName comp, int userId) { 19664 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19665 getHomeActivitiesAsUser(homeActivities, userId); 19666 19667 boolean found = false; 19668 19669 final int size = homeActivities.size(); 19670 final ComponentName[] set = new ComponentName[size]; 19671 for (int i = 0; i < size; i++) { 19672 final ResolveInfo candidate = homeActivities.get(i); 19673 final ActivityInfo info = candidate.activityInfo; 19674 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19675 set[i] = activityName; 19676 if (!found && activityName.equals(comp)) { 19677 found = true; 19678 } 19679 } 19680 if (!found) { 19681 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19682 + userId); 19683 } 19684 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19685 set, comp, userId); 19686 } 19687 19688 private @Nullable String getSetupWizardPackageName() { 19689 final Intent intent = new Intent(Intent.ACTION_MAIN); 19690 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19691 19692 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19693 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19694 | MATCH_DISABLED_COMPONENTS, 19695 UserHandle.myUserId()); 19696 if (matches.size() == 1) { 19697 return matches.get(0).getComponentInfo().packageName; 19698 } else { 19699 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19700 + ": matches=" + matches); 19701 return null; 19702 } 19703 } 19704 19705 private @Nullable String getStorageManagerPackageName() { 19706 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19707 19708 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19709 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19710 | MATCH_DISABLED_COMPONENTS, 19711 UserHandle.myUserId()); 19712 if (matches.size() == 1) { 19713 return matches.get(0).getComponentInfo().packageName; 19714 } else { 19715 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19716 + matches.size() + ": matches=" + matches); 19717 return null; 19718 } 19719 } 19720 19721 @Override 19722 public void setApplicationEnabledSetting(String appPackageName, 19723 int newState, int flags, int userId, String callingPackage) { 19724 if (!sUserManager.exists(userId)) return; 19725 if (callingPackage == null) { 19726 callingPackage = Integer.toString(Binder.getCallingUid()); 19727 } 19728 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19729 } 19730 19731 @Override 19732 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19733 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19734 synchronized (mPackages) { 19735 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19736 if (pkgSetting != null) { 19737 pkgSetting.setUpdateAvailable(updateAvailable); 19738 } 19739 } 19740 } 19741 19742 @Override 19743 public void setComponentEnabledSetting(ComponentName componentName, 19744 int newState, int flags, int userId) { 19745 if (!sUserManager.exists(userId)) return; 19746 setEnabledSetting(componentName.getPackageName(), 19747 componentName.getClassName(), newState, flags, userId, null); 19748 } 19749 19750 private void setEnabledSetting(final String packageName, String className, int newState, 19751 final int flags, int userId, String callingPackage) { 19752 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19753 || newState == COMPONENT_ENABLED_STATE_ENABLED 19754 || newState == COMPONENT_ENABLED_STATE_DISABLED 19755 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19756 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19757 throw new IllegalArgumentException("Invalid new component state: " 19758 + newState); 19759 } 19760 PackageSetting pkgSetting; 19761 final int uid = Binder.getCallingUid(); 19762 final int permission; 19763 if (uid == Process.SYSTEM_UID) { 19764 permission = PackageManager.PERMISSION_GRANTED; 19765 } else { 19766 permission = mContext.checkCallingOrSelfPermission( 19767 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19768 } 19769 enforceCrossUserPermission(uid, userId, 19770 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19771 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19772 boolean sendNow = false; 19773 boolean isApp = (className == null); 19774 String componentName = isApp ? packageName : className; 19775 int packageUid = -1; 19776 ArrayList<String> components; 19777 19778 // writer 19779 synchronized (mPackages) { 19780 pkgSetting = mSettings.mPackages.get(packageName); 19781 if (pkgSetting == null) { 19782 if (className == null) { 19783 throw new IllegalArgumentException("Unknown package: " + packageName); 19784 } 19785 throw new IllegalArgumentException( 19786 "Unknown component: " + packageName + "/" + className); 19787 } 19788 } 19789 19790 // Limit who can change which apps 19791 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19792 // Don't allow apps that don't have permission to modify other apps 19793 if (!allowedByPermission) { 19794 throw new SecurityException( 19795 "Permission Denial: attempt to change component state from pid=" 19796 + Binder.getCallingPid() 19797 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19798 } 19799 // Don't allow changing protected packages. 19800 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19801 throw new SecurityException("Cannot disable a protected package: " + packageName); 19802 } 19803 } 19804 19805 synchronized (mPackages) { 19806 if (uid == Process.SHELL_UID 19807 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19808 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19809 // unless it is a test package. 19810 int oldState = pkgSetting.getEnabled(userId); 19811 if (className == null 19812 && 19813 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19814 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19815 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19816 && 19817 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19818 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19819 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19820 // ok 19821 } else { 19822 throw new SecurityException( 19823 "Shell cannot change component state for " + packageName + "/" 19824 + className + " to " + newState); 19825 } 19826 } 19827 if (className == null) { 19828 // We're dealing with an application/package level state change 19829 if (pkgSetting.getEnabled(userId) == newState) { 19830 // Nothing to do 19831 return; 19832 } 19833 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19834 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19835 // Don't care about who enables an app. 19836 callingPackage = null; 19837 } 19838 pkgSetting.setEnabled(newState, userId, callingPackage); 19839 // pkgSetting.pkg.mSetEnabled = newState; 19840 } else { 19841 // We're dealing with a component level state change 19842 // First, verify that this is a valid class name. 19843 PackageParser.Package pkg = pkgSetting.pkg; 19844 if (pkg == null || !pkg.hasComponentClassName(className)) { 19845 if (pkg != null && 19846 pkg.applicationInfo.targetSdkVersion >= 19847 Build.VERSION_CODES.JELLY_BEAN) { 19848 throw new IllegalArgumentException("Component class " + className 19849 + " does not exist in " + packageName); 19850 } else { 19851 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19852 + className + " does not exist in " + packageName); 19853 } 19854 } 19855 switch (newState) { 19856 case COMPONENT_ENABLED_STATE_ENABLED: 19857 if (!pkgSetting.enableComponentLPw(className, userId)) { 19858 return; 19859 } 19860 break; 19861 case COMPONENT_ENABLED_STATE_DISABLED: 19862 if (!pkgSetting.disableComponentLPw(className, userId)) { 19863 return; 19864 } 19865 break; 19866 case COMPONENT_ENABLED_STATE_DEFAULT: 19867 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19868 return; 19869 } 19870 break; 19871 default: 19872 Slog.e(TAG, "Invalid new component state: " + newState); 19873 return; 19874 } 19875 } 19876 scheduleWritePackageRestrictionsLocked(userId); 19877 updateSequenceNumberLP(packageName, new int[] { userId }); 19878 final long callingId = Binder.clearCallingIdentity(); 19879 try { 19880 updateInstantAppInstallerLocked(); 19881 } finally { 19882 Binder.restoreCallingIdentity(callingId); 19883 } 19884 components = mPendingBroadcasts.get(userId, packageName); 19885 final boolean newPackage = components == null; 19886 if (newPackage) { 19887 components = new ArrayList<String>(); 19888 } 19889 if (!components.contains(componentName)) { 19890 components.add(componentName); 19891 } 19892 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19893 sendNow = true; 19894 // Purge entry from pending broadcast list if another one exists already 19895 // since we are sending one right away. 19896 mPendingBroadcasts.remove(userId, packageName); 19897 } else { 19898 if (newPackage) { 19899 mPendingBroadcasts.put(userId, packageName, components); 19900 } 19901 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19902 // Schedule a message 19903 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19904 } 19905 } 19906 } 19907 19908 long callingId = Binder.clearCallingIdentity(); 19909 try { 19910 if (sendNow) { 19911 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19912 sendPackageChangedBroadcast(packageName, 19913 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19914 } 19915 } finally { 19916 Binder.restoreCallingIdentity(callingId); 19917 } 19918 } 19919 19920 @Override 19921 public void flushPackageRestrictionsAsUser(int userId) { 19922 if (!sUserManager.exists(userId)) { 19923 return; 19924 } 19925 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19926 false /* checkShell */, "flushPackageRestrictions"); 19927 synchronized (mPackages) { 19928 mSettings.writePackageRestrictionsLPr(userId); 19929 mDirtyUsers.remove(userId); 19930 if (mDirtyUsers.isEmpty()) { 19931 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19932 } 19933 } 19934 } 19935 19936 private void sendPackageChangedBroadcast(String packageName, 19937 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19938 if (DEBUG_INSTALL) 19939 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19940 + componentNames); 19941 Bundle extras = new Bundle(4); 19942 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19943 String nameList[] = new String[componentNames.size()]; 19944 componentNames.toArray(nameList); 19945 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19946 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19947 extras.putInt(Intent.EXTRA_UID, packageUid); 19948 // If this is not reporting a change of the overall package, then only send it 19949 // to registered receivers. We don't want to launch a swath of apps for every 19950 // little component state change. 19951 final int flags = !componentNames.contains(packageName) 19952 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19953 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19954 new int[] {UserHandle.getUserId(packageUid)}); 19955 } 19956 19957 @Override 19958 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19959 if (!sUserManager.exists(userId)) return; 19960 final int uid = Binder.getCallingUid(); 19961 final int permission = mContext.checkCallingOrSelfPermission( 19962 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19963 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19964 enforceCrossUserPermission(uid, userId, 19965 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19966 // writer 19967 synchronized (mPackages) { 19968 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19969 allowedByPermission, uid, userId)) { 19970 scheduleWritePackageRestrictionsLocked(userId); 19971 } 19972 } 19973 } 19974 19975 @Override 19976 public String getInstallerPackageName(String packageName) { 19977 // reader 19978 synchronized (mPackages) { 19979 return mSettings.getInstallerPackageNameLPr(packageName); 19980 } 19981 } 19982 19983 public boolean isOrphaned(String packageName) { 19984 // reader 19985 synchronized (mPackages) { 19986 return mSettings.isOrphaned(packageName); 19987 } 19988 } 19989 19990 @Override 19991 public int getApplicationEnabledSetting(String packageName, int userId) { 19992 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19993 int uid = Binder.getCallingUid(); 19994 enforceCrossUserPermission(uid, userId, 19995 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19996 // reader 19997 synchronized (mPackages) { 19998 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19999 } 20000 } 20001 20002 @Override 20003 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20004 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20005 int uid = Binder.getCallingUid(); 20006 enforceCrossUserPermission(uid, userId, 20007 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20008 // reader 20009 synchronized (mPackages) { 20010 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20011 } 20012 } 20013 20014 @Override 20015 public void enterSafeMode() { 20016 enforceSystemOrRoot("Only the system can request entering safe mode"); 20017 20018 if (!mSystemReady) { 20019 mSafeMode = true; 20020 } 20021 } 20022 20023 @Override 20024 public void systemReady() { 20025 mSystemReady = true; 20026 20027 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20028 // disabled after already being started. 20029 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20030 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20031 20032 // Read the compatibilty setting when the system is ready. 20033 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20034 mContext.getContentResolver(), 20035 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20036 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20037 if (DEBUG_SETTINGS) { 20038 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20039 } 20040 20041 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20042 20043 synchronized (mPackages) { 20044 // Verify that all of the preferred activity components actually 20045 // exist. It is possible for applications to be updated and at 20046 // that point remove a previously declared activity component that 20047 // had been set as a preferred activity. We try to clean this up 20048 // the next time we encounter that preferred activity, but it is 20049 // possible for the user flow to never be able to return to that 20050 // situation so here we do a sanity check to make sure we haven't 20051 // left any junk around. 20052 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20053 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20054 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20055 removed.clear(); 20056 for (PreferredActivity pa : pir.filterSet()) { 20057 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20058 removed.add(pa); 20059 } 20060 } 20061 if (removed.size() > 0) { 20062 for (int r=0; r<removed.size(); r++) { 20063 PreferredActivity pa = removed.get(r); 20064 Slog.w(TAG, "Removing dangling preferred activity: " 20065 + pa.mPref.mComponent); 20066 pir.removeFilter(pa); 20067 } 20068 mSettings.writePackageRestrictionsLPr( 20069 mSettings.mPreferredActivities.keyAt(i)); 20070 } 20071 } 20072 20073 for (int userId : UserManagerService.getInstance().getUserIds()) { 20074 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20075 grantPermissionsUserIds = ArrayUtils.appendInt( 20076 grantPermissionsUserIds, userId); 20077 } 20078 } 20079 } 20080 sUserManager.systemReady(); 20081 20082 // If we upgraded grant all default permissions before kicking off. 20083 for (int userId : grantPermissionsUserIds) { 20084 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20085 } 20086 20087 // If we did not grant default permissions, we preload from this the 20088 // default permission exceptions lazily to ensure we don't hit the 20089 // disk on a new user creation. 20090 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20091 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20092 } 20093 20094 // Kick off any messages waiting for system ready 20095 if (mPostSystemReadyMessages != null) { 20096 for (Message msg : mPostSystemReadyMessages) { 20097 msg.sendToTarget(); 20098 } 20099 mPostSystemReadyMessages = null; 20100 } 20101 20102 // Watch for external volumes that come and go over time 20103 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20104 storage.registerListener(mStorageListener); 20105 20106 mInstallerService.systemReady(); 20107 mPackageDexOptimizer.systemReady(); 20108 20109 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20110 StorageManagerInternal.class); 20111 StorageManagerInternal.addExternalStoragePolicy( 20112 new StorageManagerInternal.ExternalStorageMountPolicy() { 20113 @Override 20114 public int getMountMode(int uid, String packageName) { 20115 if (Process.isIsolated(uid)) { 20116 return Zygote.MOUNT_EXTERNAL_NONE; 20117 } 20118 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20119 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20120 } 20121 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20122 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20123 } 20124 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20125 return Zygote.MOUNT_EXTERNAL_READ; 20126 } 20127 return Zygote.MOUNT_EXTERNAL_WRITE; 20128 } 20129 20130 @Override 20131 public boolean hasExternalStorage(int uid, String packageName) { 20132 return true; 20133 } 20134 }); 20135 20136 // Now that we're mostly running, clean up stale users and apps 20137 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20138 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20139 20140 if (mPrivappPermissionsViolations != null) { 20141 Slog.wtf(TAG,"Signature|privileged permissions not in " 20142 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20143 mPrivappPermissionsViolations = null; 20144 } 20145 } 20146 20147 public void waitForAppDataPrepared() { 20148 if (mPrepareAppDataFuture == null) { 20149 return; 20150 } 20151 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20152 mPrepareAppDataFuture = null; 20153 } 20154 20155 @Override 20156 public boolean isSafeMode() { 20157 return mSafeMode; 20158 } 20159 20160 @Override 20161 public boolean hasSystemUidErrors() { 20162 return mHasSystemUidErrors; 20163 } 20164 20165 static String arrayToString(int[] array) { 20166 StringBuffer buf = new StringBuffer(128); 20167 buf.append('['); 20168 if (array != null) { 20169 for (int i=0; i<array.length; i++) { 20170 if (i > 0) buf.append(", "); 20171 buf.append(array[i]); 20172 } 20173 } 20174 buf.append(']'); 20175 return buf.toString(); 20176 } 20177 20178 static class DumpState { 20179 public static final int DUMP_LIBS = 1 << 0; 20180 public static final int DUMP_FEATURES = 1 << 1; 20181 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20182 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20183 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20184 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20185 public static final int DUMP_PERMISSIONS = 1 << 6; 20186 public static final int DUMP_PACKAGES = 1 << 7; 20187 public static final int DUMP_SHARED_USERS = 1 << 8; 20188 public static final int DUMP_MESSAGES = 1 << 9; 20189 public static final int DUMP_PROVIDERS = 1 << 10; 20190 public static final int DUMP_VERIFIERS = 1 << 11; 20191 public static final int DUMP_PREFERRED = 1 << 12; 20192 public static final int DUMP_PREFERRED_XML = 1 << 13; 20193 public static final int DUMP_KEYSETS = 1 << 14; 20194 public static final int DUMP_VERSION = 1 << 15; 20195 public static final int DUMP_INSTALLS = 1 << 16; 20196 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20197 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20198 public static final int DUMP_FROZEN = 1 << 19; 20199 public static final int DUMP_DEXOPT = 1 << 20; 20200 public static final int DUMP_COMPILER_STATS = 1 << 21; 20201 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20202 20203 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20204 20205 private int mTypes; 20206 20207 private int mOptions; 20208 20209 private boolean mTitlePrinted; 20210 20211 private SharedUserSetting mSharedUser; 20212 20213 public boolean isDumping(int type) { 20214 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20215 return true; 20216 } 20217 20218 return (mTypes & type) != 0; 20219 } 20220 20221 public void setDump(int type) { 20222 mTypes |= type; 20223 } 20224 20225 public boolean isOptionEnabled(int option) { 20226 return (mOptions & option) != 0; 20227 } 20228 20229 public void setOptionEnabled(int option) { 20230 mOptions |= option; 20231 } 20232 20233 public boolean onTitlePrinted() { 20234 final boolean printed = mTitlePrinted; 20235 mTitlePrinted = true; 20236 return printed; 20237 } 20238 20239 public boolean getTitlePrinted() { 20240 return mTitlePrinted; 20241 } 20242 20243 public void setTitlePrinted(boolean enabled) { 20244 mTitlePrinted = enabled; 20245 } 20246 20247 public SharedUserSetting getSharedUser() { 20248 return mSharedUser; 20249 } 20250 20251 public void setSharedUser(SharedUserSetting user) { 20252 mSharedUser = user; 20253 } 20254 } 20255 20256 @Override 20257 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20258 FileDescriptor err, String[] args, ShellCallback callback, 20259 ResultReceiver resultReceiver) { 20260 (new PackageManagerShellCommand(this)).exec( 20261 this, in, out, err, args, callback, resultReceiver); 20262 } 20263 20264 @Override 20265 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20266 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20267 != PackageManager.PERMISSION_GRANTED) { 20268 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20269 + Binder.getCallingPid() 20270 + ", uid=" + Binder.getCallingUid() 20271 + " without permission " 20272 + android.Manifest.permission.DUMP); 20273 return; 20274 } 20275 20276 DumpState dumpState = new DumpState(); 20277 boolean fullPreferred = false; 20278 boolean checkin = false; 20279 20280 String packageName = null; 20281 ArraySet<String> permissionNames = null; 20282 20283 int opti = 0; 20284 while (opti < args.length) { 20285 String opt = args[opti]; 20286 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20287 break; 20288 } 20289 opti++; 20290 20291 if ("-a".equals(opt)) { 20292 // Right now we only know how to print all. 20293 } else if ("-h".equals(opt)) { 20294 pw.println("Package manager dump options:"); 20295 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20296 pw.println(" --checkin: dump for a checkin"); 20297 pw.println(" -f: print details of intent filters"); 20298 pw.println(" -h: print this help"); 20299 pw.println(" cmd may be one of:"); 20300 pw.println(" l[ibraries]: list known shared libraries"); 20301 pw.println(" f[eatures]: list device features"); 20302 pw.println(" k[eysets]: print known keysets"); 20303 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20304 pw.println(" perm[issions]: dump permissions"); 20305 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20306 pw.println(" pref[erred]: print preferred package settings"); 20307 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20308 pw.println(" prov[iders]: dump content providers"); 20309 pw.println(" p[ackages]: dump installed packages"); 20310 pw.println(" s[hared-users]: dump shared user IDs"); 20311 pw.println(" m[essages]: print collected runtime messages"); 20312 pw.println(" v[erifiers]: print package verifier info"); 20313 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20314 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20315 pw.println(" version: print database version info"); 20316 pw.println(" write: write current settings now"); 20317 pw.println(" installs: details about install sessions"); 20318 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20319 pw.println(" dexopt: dump dexopt state"); 20320 pw.println(" compiler-stats: dump compiler statistics"); 20321 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20322 pw.println(" <package.name>: info about given package"); 20323 return; 20324 } else if ("--checkin".equals(opt)) { 20325 checkin = true; 20326 } else if ("-f".equals(opt)) { 20327 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20328 } else if ("--proto".equals(opt)) { 20329 dumpProto(fd); 20330 return; 20331 } else { 20332 pw.println("Unknown argument: " + opt + "; use -h for help"); 20333 } 20334 } 20335 20336 // Is the caller requesting to dump a particular piece of data? 20337 if (opti < args.length) { 20338 String cmd = args[opti]; 20339 opti++; 20340 // Is this a package name? 20341 if ("android".equals(cmd) || cmd.contains(".")) { 20342 packageName = cmd; 20343 // When dumping a single package, we always dump all of its 20344 // filter information since the amount of data will be reasonable. 20345 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20346 } else if ("check-permission".equals(cmd)) { 20347 if (opti >= args.length) { 20348 pw.println("Error: check-permission missing permission argument"); 20349 return; 20350 } 20351 String perm = args[opti]; 20352 opti++; 20353 if (opti >= args.length) { 20354 pw.println("Error: check-permission missing package argument"); 20355 return; 20356 } 20357 20358 String pkg = args[opti]; 20359 opti++; 20360 int user = UserHandle.getUserId(Binder.getCallingUid()); 20361 if (opti < args.length) { 20362 try { 20363 user = Integer.parseInt(args[opti]); 20364 } catch (NumberFormatException e) { 20365 pw.println("Error: check-permission user argument is not a number: " 20366 + args[opti]); 20367 return; 20368 } 20369 } 20370 20371 // Normalize package name to handle renamed packages and static libs 20372 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20373 20374 pw.println(checkPermission(perm, pkg, user)); 20375 return; 20376 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20377 dumpState.setDump(DumpState.DUMP_LIBS); 20378 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20379 dumpState.setDump(DumpState.DUMP_FEATURES); 20380 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20381 if (opti >= args.length) { 20382 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20383 | DumpState.DUMP_SERVICE_RESOLVERS 20384 | DumpState.DUMP_RECEIVER_RESOLVERS 20385 | DumpState.DUMP_CONTENT_RESOLVERS); 20386 } else { 20387 while (opti < args.length) { 20388 String name = args[opti]; 20389 if ("a".equals(name) || "activity".equals(name)) { 20390 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20391 } else if ("s".equals(name) || "service".equals(name)) { 20392 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20393 } else if ("r".equals(name) || "receiver".equals(name)) { 20394 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20395 } else if ("c".equals(name) || "content".equals(name)) { 20396 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20397 } else { 20398 pw.println("Error: unknown resolver table type: " + name); 20399 return; 20400 } 20401 opti++; 20402 } 20403 } 20404 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20405 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20406 } else if ("permission".equals(cmd)) { 20407 if (opti >= args.length) { 20408 pw.println("Error: permission requires permission name"); 20409 return; 20410 } 20411 permissionNames = new ArraySet<>(); 20412 while (opti < args.length) { 20413 permissionNames.add(args[opti]); 20414 opti++; 20415 } 20416 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20417 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20418 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20419 dumpState.setDump(DumpState.DUMP_PREFERRED); 20420 } else if ("preferred-xml".equals(cmd)) { 20421 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20422 if (opti < args.length && "--full".equals(args[opti])) { 20423 fullPreferred = true; 20424 opti++; 20425 } 20426 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20427 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20428 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20429 dumpState.setDump(DumpState.DUMP_PACKAGES); 20430 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20431 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20432 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20433 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20434 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20435 dumpState.setDump(DumpState.DUMP_MESSAGES); 20436 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20437 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20438 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20439 || "intent-filter-verifiers".equals(cmd)) { 20440 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20441 } else if ("version".equals(cmd)) { 20442 dumpState.setDump(DumpState.DUMP_VERSION); 20443 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20444 dumpState.setDump(DumpState.DUMP_KEYSETS); 20445 } else if ("installs".equals(cmd)) { 20446 dumpState.setDump(DumpState.DUMP_INSTALLS); 20447 } else if ("frozen".equals(cmd)) { 20448 dumpState.setDump(DumpState.DUMP_FROZEN); 20449 } else if ("dexopt".equals(cmd)) { 20450 dumpState.setDump(DumpState.DUMP_DEXOPT); 20451 } else if ("compiler-stats".equals(cmd)) { 20452 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20453 } else if ("enabled-overlays".equals(cmd)) { 20454 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20455 } else if ("write".equals(cmd)) { 20456 synchronized (mPackages) { 20457 mSettings.writeLPr(); 20458 pw.println("Settings written."); 20459 return; 20460 } 20461 } 20462 } 20463 20464 if (checkin) { 20465 pw.println("vers,1"); 20466 } 20467 20468 // reader 20469 synchronized (mPackages) { 20470 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20471 if (!checkin) { 20472 if (dumpState.onTitlePrinted()) 20473 pw.println(); 20474 pw.println("Database versions:"); 20475 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20476 } 20477 } 20478 20479 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20480 if (!checkin) { 20481 if (dumpState.onTitlePrinted()) 20482 pw.println(); 20483 pw.println("Verifiers:"); 20484 pw.print(" Required: "); 20485 pw.print(mRequiredVerifierPackage); 20486 pw.print(" (uid="); 20487 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20488 UserHandle.USER_SYSTEM)); 20489 pw.println(")"); 20490 } else if (mRequiredVerifierPackage != null) { 20491 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20492 pw.print(","); 20493 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20494 UserHandle.USER_SYSTEM)); 20495 } 20496 } 20497 20498 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20499 packageName == null) { 20500 if (mIntentFilterVerifierComponent != null) { 20501 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20502 if (!checkin) { 20503 if (dumpState.onTitlePrinted()) 20504 pw.println(); 20505 pw.println("Intent Filter Verifier:"); 20506 pw.print(" Using: "); 20507 pw.print(verifierPackageName); 20508 pw.print(" (uid="); 20509 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20510 UserHandle.USER_SYSTEM)); 20511 pw.println(")"); 20512 } else if (verifierPackageName != null) { 20513 pw.print("ifv,"); pw.print(verifierPackageName); 20514 pw.print(","); 20515 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20516 UserHandle.USER_SYSTEM)); 20517 } 20518 } else { 20519 pw.println(); 20520 pw.println("No Intent Filter Verifier available!"); 20521 } 20522 } 20523 20524 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20525 boolean printedHeader = false; 20526 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20527 while (it.hasNext()) { 20528 String libName = it.next(); 20529 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20530 if (versionedLib == null) { 20531 continue; 20532 } 20533 final int versionCount = versionedLib.size(); 20534 for (int i = 0; i < versionCount; i++) { 20535 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20536 if (!checkin) { 20537 if (!printedHeader) { 20538 if (dumpState.onTitlePrinted()) 20539 pw.println(); 20540 pw.println("Libraries:"); 20541 printedHeader = true; 20542 } 20543 pw.print(" "); 20544 } else { 20545 pw.print("lib,"); 20546 } 20547 pw.print(libEntry.info.getName()); 20548 if (libEntry.info.isStatic()) { 20549 pw.print(" version=" + libEntry.info.getVersion()); 20550 } 20551 if (!checkin) { 20552 pw.print(" -> "); 20553 } 20554 if (libEntry.path != null) { 20555 pw.print(" (jar) "); 20556 pw.print(libEntry.path); 20557 } else { 20558 pw.print(" (apk) "); 20559 pw.print(libEntry.apk); 20560 } 20561 pw.println(); 20562 } 20563 } 20564 } 20565 20566 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20567 if (dumpState.onTitlePrinted()) 20568 pw.println(); 20569 if (!checkin) { 20570 pw.println("Features:"); 20571 } 20572 20573 synchronized (mAvailableFeatures) { 20574 for (FeatureInfo feat : mAvailableFeatures.values()) { 20575 if (checkin) { 20576 pw.print("feat,"); 20577 pw.print(feat.name); 20578 pw.print(","); 20579 pw.println(feat.version); 20580 } else { 20581 pw.print(" "); 20582 pw.print(feat.name); 20583 if (feat.version > 0) { 20584 pw.print(" version="); 20585 pw.print(feat.version); 20586 } 20587 pw.println(); 20588 } 20589 } 20590 } 20591 } 20592 20593 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20594 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20595 : "Activity Resolver Table:", " ", packageName, 20596 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20597 dumpState.setTitlePrinted(true); 20598 } 20599 } 20600 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20601 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20602 : "Receiver Resolver Table:", " ", packageName, 20603 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20604 dumpState.setTitlePrinted(true); 20605 } 20606 } 20607 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20608 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20609 : "Service Resolver Table:", " ", packageName, 20610 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20611 dumpState.setTitlePrinted(true); 20612 } 20613 } 20614 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20615 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20616 : "Provider Resolver Table:", " ", packageName, 20617 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20618 dumpState.setTitlePrinted(true); 20619 } 20620 } 20621 20622 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20623 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20624 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20625 int user = mSettings.mPreferredActivities.keyAt(i); 20626 if (pir.dump(pw, 20627 dumpState.getTitlePrinted() 20628 ? "\nPreferred Activities User " + user + ":" 20629 : "Preferred Activities User " + user + ":", " ", 20630 packageName, true, false)) { 20631 dumpState.setTitlePrinted(true); 20632 } 20633 } 20634 } 20635 20636 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20637 pw.flush(); 20638 FileOutputStream fout = new FileOutputStream(fd); 20639 BufferedOutputStream str = new BufferedOutputStream(fout); 20640 XmlSerializer serializer = new FastXmlSerializer(); 20641 try { 20642 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20643 serializer.startDocument(null, true); 20644 serializer.setFeature( 20645 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20646 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20647 serializer.endDocument(); 20648 serializer.flush(); 20649 } catch (IllegalArgumentException e) { 20650 pw.println("Failed writing: " + e); 20651 } catch (IllegalStateException e) { 20652 pw.println("Failed writing: " + e); 20653 } catch (IOException e) { 20654 pw.println("Failed writing: " + e); 20655 } 20656 } 20657 20658 if (!checkin 20659 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20660 && packageName == null) { 20661 pw.println(); 20662 int count = mSettings.mPackages.size(); 20663 if (count == 0) { 20664 pw.println("No applications!"); 20665 pw.println(); 20666 } else { 20667 final String prefix = " "; 20668 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20669 if (allPackageSettings.size() == 0) { 20670 pw.println("No domain preferred apps!"); 20671 pw.println(); 20672 } else { 20673 pw.println("App verification status:"); 20674 pw.println(); 20675 count = 0; 20676 for (PackageSetting ps : allPackageSettings) { 20677 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20678 if (ivi == null || ivi.getPackageName() == null) continue; 20679 pw.println(prefix + "Package: " + ivi.getPackageName()); 20680 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20681 pw.println(prefix + "Status: " + ivi.getStatusString()); 20682 pw.println(); 20683 count++; 20684 } 20685 if (count == 0) { 20686 pw.println(prefix + "No app verification established."); 20687 pw.println(); 20688 } 20689 for (int userId : sUserManager.getUserIds()) { 20690 pw.println("App linkages for user " + userId + ":"); 20691 pw.println(); 20692 count = 0; 20693 for (PackageSetting ps : allPackageSettings) { 20694 final long status = ps.getDomainVerificationStatusForUser(userId); 20695 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20696 && !DEBUG_DOMAIN_VERIFICATION) { 20697 continue; 20698 } 20699 pw.println(prefix + "Package: " + ps.name); 20700 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20701 String statusStr = IntentFilterVerificationInfo. 20702 getStatusStringFromValue(status); 20703 pw.println(prefix + "Status: " + statusStr); 20704 pw.println(); 20705 count++; 20706 } 20707 if (count == 0) { 20708 pw.println(prefix + "No configured app linkages."); 20709 pw.println(); 20710 } 20711 } 20712 } 20713 } 20714 } 20715 20716 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20717 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20718 if (packageName == null && permissionNames == null) { 20719 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20720 if (iperm == 0) { 20721 if (dumpState.onTitlePrinted()) 20722 pw.println(); 20723 pw.println("AppOp Permissions:"); 20724 } 20725 pw.print(" AppOp Permission "); 20726 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20727 pw.println(":"); 20728 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20729 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20730 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20731 } 20732 } 20733 } 20734 } 20735 20736 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20737 boolean printedSomething = false; 20738 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20739 if (packageName != null && !packageName.equals(p.info.packageName)) { 20740 continue; 20741 } 20742 if (!printedSomething) { 20743 if (dumpState.onTitlePrinted()) 20744 pw.println(); 20745 pw.println("Registered ContentProviders:"); 20746 printedSomething = true; 20747 } 20748 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20749 pw.print(" "); pw.println(p.toString()); 20750 } 20751 printedSomething = false; 20752 for (Map.Entry<String, PackageParser.Provider> entry : 20753 mProvidersByAuthority.entrySet()) { 20754 PackageParser.Provider p = entry.getValue(); 20755 if (packageName != null && !packageName.equals(p.info.packageName)) { 20756 continue; 20757 } 20758 if (!printedSomething) { 20759 if (dumpState.onTitlePrinted()) 20760 pw.println(); 20761 pw.println("ContentProvider Authorities:"); 20762 printedSomething = true; 20763 } 20764 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20765 pw.print(" "); pw.println(p.toString()); 20766 if (p.info != null && p.info.applicationInfo != null) { 20767 final String appInfo = p.info.applicationInfo.toString(); 20768 pw.print(" applicationInfo="); pw.println(appInfo); 20769 } 20770 } 20771 } 20772 20773 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20774 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20775 } 20776 20777 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20778 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20779 } 20780 20781 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20782 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20783 } 20784 20785 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20786 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20787 } 20788 20789 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20790 // XXX should handle packageName != null by dumping only install data that 20791 // the given package is involved with. 20792 if (dumpState.onTitlePrinted()) pw.println(); 20793 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20794 } 20795 20796 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20797 // XXX should handle packageName != null by dumping only install data that 20798 // the given package is involved with. 20799 if (dumpState.onTitlePrinted()) pw.println(); 20800 20801 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20802 ipw.println(); 20803 ipw.println("Frozen packages:"); 20804 ipw.increaseIndent(); 20805 if (mFrozenPackages.size() == 0) { 20806 ipw.println("(none)"); 20807 } else { 20808 for (int i = 0; i < mFrozenPackages.size(); i++) { 20809 ipw.println(mFrozenPackages.valueAt(i)); 20810 } 20811 } 20812 ipw.decreaseIndent(); 20813 } 20814 20815 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20816 if (dumpState.onTitlePrinted()) pw.println(); 20817 dumpDexoptStateLPr(pw, packageName); 20818 } 20819 20820 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20821 if (dumpState.onTitlePrinted()) pw.println(); 20822 dumpCompilerStatsLPr(pw, packageName); 20823 } 20824 20825 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20826 if (dumpState.onTitlePrinted()) pw.println(); 20827 dumpEnabledOverlaysLPr(pw); 20828 } 20829 20830 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20831 if (dumpState.onTitlePrinted()) pw.println(); 20832 mSettings.dumpReadMessagesLPr(pw, dumpState); 20833 20834 pw.println(); 20835 pw.println("Package warning messages:"); 20836 BufferedReader in = null; 20837 String line = null; 20838 try { 20839 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20840 while ((line = in.readLine()) != null) { 20841 if (line.contains("ignored: updated version")) continue; 20842 pw.println(line); 20843 } 20844 } catch (IOException ignored) { 20845 } finally { 20846 IoUtils.closeQuietly(in); 20847 } 20848 } 20849 20850 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20851 BufferedReader in = null; 20852 String line = null; 20853 try { 20854 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20855 while ((line = in.readLine()) != null) { 20856 if (line.contains("ignored: updated version")) continue; 20857 pw.print("msg,"); 20858 pw.println(line); 20859 } 20860 } catch (IOException ignored) { 20861 } finally { 20862 IoUtils.closeQuietly(in); 20863 } 20864 } 20865 } 20866 } 20867 20868 private void dumpProto(FileDescriptor fd) { 20869 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20870 20871 synchronized (mPackages) { 20872 final long requiredVerifierPackageToken = 20873 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20874 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20875 proto.write( 20876 PackageServiceDumpProto.PackageShortProto.UID, 20877 getPackageUid( 20878 mRequiredVerifierPackage, 20879 MATCH_DEBUG_TRIAGED_MISSING, 20880 UserHandle.USER_SYSTEM)); 20881 proto.end(requiredVerifierPackageToken); 20882 20883 if (mIntentFilterVerifierComponent != null) { 20884 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20885 final long verifierPackageToken = 20886 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20887 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20888 proto.write( 20889 PackageServiceDumpProto.PackageShortProto.UID, 20890 getPackageUid( 20891 verifierPackageName, 20892 MATCH_DEBUG_TRIAGED_MISSING, 20893 UserHandle.USER_SYSTEM)); 20894 proto.end(verifierPackageToken); 20895 } 20896 20897 dumpSharedLibrariesProto(proto); 20898 dumpFeaturesProto(proto); 20899 mSettings.dumpPackagesProto(proto); 20900 mSettings.dumpSharedUsersProto(proto); 20901 dumpMessagesProto(proto); 20902 } 20903 proto.flush(); 20904 } 20905 20906 private void dumpMessagesProto(ProtoOutputStream proto) { 20907 BufferedReader in = null; 20908 String line = null; 20909 try { 20910 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20911 while ((line = in.readLine()) != null) { 20912 if (line.contains("ignored: updated version")) continue; 20913 proto.write(PackageServiceDumpProto.MESSAGES, line); 20914 } 20915 } catch (IOException ignored) { 20916 } finally { 20917 IoUtils.closeQuietly(in); 20918 } 20919 } 20920 20921 private void dumpFeaturesProto(ProtoOutputStream proto) { 20922 synchronized (mAvailableFeatures) { 20923 final int count = mAvailableFeatures.size(); 20924 for (int i = 0; i < count; i++) { 20925 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20926 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20927 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20928 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20929 proto.end(featureToken); 20930 } 20931 } 20932 } 20933 20934 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20935 final int count = mSharedLibraries.size(); 20936 for (int i = 0; i < count; i++) { 20937 final String libName = mSharedLibraries.keyAt(i); 20938 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20939 if (versionedLib == null) { 20940 continue; 20941 } 20942 final int versionCount = versionedLib.size(); 20943 for (int j = 0; j < versionCount; j++) { 20944 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20945 final long sharedLibraryToken = 20946 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20947 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20948 final boolean isJar = (libEntry.path != null); 20949 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20950 if (isJar) { 20951 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20952 } else { 20953 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20954 } 20955 proto.end(sharedLibraryToken); 20956 } 20957 } 20958 } 20959 20960 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20961 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20962 ipw.println(); 20963 ipw.println("Dexopt state:"); 20964 ipw.increaseIndent(); 20965 Collection<PackageParser.Package> packages = null; 20966 if (packageName != null) { 20967 PackageParser.Package targetPackage = mPackages.get(packageName); 20968 if (targetPackage != null) { 20969 packages = Collections.singletonList(targetPackage); 20970 } else { 20971 ipw.println("Unable to find package: " + packageName); 20972 return; 20973 } 20974 } else { 20975 packages = mPackages.values(); 20976 } 20977 20978 for (PackageParser.Package pkg : packages) { 20979 ipw.println("[" + pkg.packageName + "]"); 20980 ipw.increaseIndent(); 20981 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20982 ipw.decreaseIndent(); 20983 } 20984 } 20985 20986 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20987 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20988 ipw.println(); 20989 ipw.println("Compiler stats:"); 20990 ipw.increaseIndent(); 20991 Collection<PackageParser.Package> packages = null; 20992 if (packageName != null) { 20993 PackageParser.Package targetPackage = mPackages.get(packageName); 20994 if (targetPackage != null) { 20995 packages = Collections.singletonList(targetPackage); 20996 } else { 20997 ipw.println("Unable to find package: " + packageName); 20998 return; 20999 } 21000 } else { 21001 packages = mPackages.values(); 21002 } 21003 21004 for (PackageParser.Package pkg : packages) { 21005 ipw.println("[" + pkg.packageName + "]"); 21006 ipw.increaseIndent(); 21007 21008 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21009 if (stats == null) { 21010 ipw.println("(No recorded stats)"); 21011 } else { 21012 stats.dump(ipw); 21013 } 21014 ipw.decreaseIndent(); 21015 } 21016 } 21017 21018 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21019 pw.println("Enabled overlay paths:"); 21020 final int N = mEnabledOverlayPaths.size(); 21021 for (int i = 0; i < N; i++) { 21022 final int userId = mEnabledOverlayPaths.keyAt(i); 21023 pw.println(String.format(" User %d:", userId)); 21024 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21025 mEnabledOverlayPaths.valueAt(i); 21026 final int M = userSpecificOverlays.size(); 21027 for (int j = 0; j < M; j++) { 21028 final String targetPackageName = userSpecificOverlays.keyAt(j); 21029 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21030 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21031 } 21032 } 21033 } 21034 21035 private String dumpDomainString(String packageName) { 21036 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21037 .getList(); 21038 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21039 21040 ArraySet<String> result = new ArraySet<>(); 21041 if (iviList.size() > 0) { 21042 for (IntentFilterVerificationInfo ivi : iviList) { 21043 for (String host : ivi.getDomains()) { 21044 result.add(host); 21045 } 21046 } 21047 } 21048 if (filters != null && filters.size() > 0) { 21049 for (IntentFilter filter : filters) { 21050 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21051 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21052 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21053 result.addAll(filter.getHostsList()); 21054 } 21055 } 21056 } 21057 21058 StringBuilder sb = new StringBuilder(result.size() * 16); 21059 for (String domain : result) { 21060 if (sb.length() > 0) sb.append(" "); 21061 sb.append(domain); 21062 } 21063 return sb.toString(); 21064 } 21065 21066 // ------- apps on sdcard specific code ------- 21067 static final boolean DEBUG_SD_INSTALL = false; 21068 21069 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21070 21071 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21072 21073 private boolean mMediaMounted = false; 21074 21075 static String getEncryptKey() { 21076 try { 21077 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21078 SD_ENCRYPTION_KEYSTORE_NAME); 21079 if (sdEncKey == null) { 21080 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21081 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21082 if (sdEncKey == null) { 21083 Slog.e(TAG, "Failed to create encryption keys"); 21084 return null; 21085 } 21086 } 21087 return sdEncKey; 21088 } catch (NoSuchAlgorithmException nsae) { 21089 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21090 return null; 21091 } catch (IOException ioe) { 21092 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21093 return null; 21094 } 21095 } 21096 21097 /* 21098 * Update media status on PackageManager. 21099 */ 21100 @Override 21101 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21102 int callingUid = Binder.getCallingUid(); 21103 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21104 throw new SecurityException("Media status can only be updated by the system"); 21105 } 21106 // reader; this apparently protects mMediaMounted, but should probably 21107 // be a different lock in that case. 21108 synchronized (mPackages) { 21109 Log.i(TAG, "Updating external media status from " 21110 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21111 + (mediaStatus ? "mounted" : "unmounted")); 21112 if (DEBUG_SD_INSTALL) 21113 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21114 + ", mMediaMounted=" + mMediaMounted); 21115 if (mediaStatus == mMediaMounted) { 21116 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21117 : 0, -1); 21118 mHandler.sendMessage(msg); 21119 return; 21120 } 21121 mMediaMounted = mediaStatus; 21122 } 21123 // Queue up an async operation since the package installation may take a 21124 // little while. 21125 mHandler.post(new Runnable() { 21126 public void run() { 21127 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21128 } 21129 }); 21130 } 21131 21132 /** 21133 * Called by StorageManagerService when the initial ASECs to scan are available. 21134 * Should block until all the ASEC containers are finished being scanned. 21135 */ 21136 public void scanAvailableAsecs() { 21137 updateExternalMediaStatusInner(true, false, false); 21138 } 21139 21140 /* 21141 * Collect information of applications on external media, map them against 21142 * existing containers and update information based on current mount status. 21143 * Please note that we always have to report status if reportStatus has been 21144 * set to true especially when unloading packages. 21145 */ 21146 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21147 boolean externalStorage) { 21148 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21149 int[] uidArr = EmptyArray.INT; 21150 21151 final String[] list = PackageHelper.getSecureContainerList(); 21152 if (ArrayUtils.isEmpty(list)) { 21153 Log.i(TAG, "No secure containers found"); 21154 } else { 21155 // Process list of secure containers and categorize them 21156 // as active or stale based on their package internal state. 21157 21158 // reader 21159 synchronized (mPackages) { 21160 for (String cid : list) { 21161 // Leave stages untouched for now; installer service owns them 21162 if (PackageInstallerService.isStageName(cid)) continue; 21163 21164 if (DEBUG_SD_INSTALL) 21165 Log.i(TAG, "Processing container " + cid); 21166 String pkgName = getAsecPackageName(cid); 21167 if (pkgName == null) { 21168 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21169 continue; 21170 } 21171 if (DEBUG_SD_INSTALL) 21172 Log.i(TAG, "Looking for pkg : " + pkgName); 21173 21174 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21175 if (ps == null) { 21176 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21177 continue; 21178 } 21179 21180 /* 21181 * Skip packages that are not external if we're unmounting 21182 * external storage. 21183 */ 21184 if (externalStorage && !isMounted && !isExternal(ps)) { 21185 continue; 21186 } 21187 21188 final AsecInstallArgs args = new AsecInstallArgs(cid, 21189 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21190 // The package status is changed only if the code path 21191 // matches between settings and the container id. 21192 if (ps.codePathString != null 21193 && ps.codePathString.startsWith(args.getCodePath())) { 21194 if (DEBUG_SD_INSTALL) { 21195 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21196 + " at code path: " + ps.codePathString); 21197 } 21198 21199 // We do have a valid package installed on sdcard 21200 processCids.put(args, ps.codePathString); 21201 final int uid = ps.appId; 21202 if (uid != -1) { 21203 uidArr = ArrayUtils.appendInt(uidArr, uid); 21204 } 21205 } else { 21206 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21207 + ps.codePathString); 21208 } 21209 } 21210 } 21211 21212 Arrays.sort(uidArr); 21213 } 21214 21215 // Process packages with valid entries. 21216 if (isMounted) { 21217 if (DEBUG_SD_INSTALL) 21218 Log.i(TAG, "Loading packages"); 21219 loadMediaPackages(processCids, uidArr, externalStorage); 21220 startCleaningPackages(); 21221 mInstallerService.onSecureContainersAvailable(); 21222 } else { 21223 if (DEBUG_SD_INSTALL) 21224 Log.i(TAG, "Unloading packages"); 21225 unloadMediaPackages(processCids, uidArr, reportStatus); 21226 } 21227 } 21228 21229 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21230 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21231 final int size = infos.size(); 21232 final String[] packageNames = new String[size]; 21233 final int[] packageUids = new int[size]; 21234 for (int i = 0; i < size; i++) { 21235 final ApplicationInfo info = infos.get(i); 21236 packageNames[i] = info.packageName; 21237 packageUids[i] = info.uid; 21238 } 21239 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21240 finishedReceiver); 21241 } 21242 21243 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21244 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21245 sendResourcesChangedBroadcast(mediaStatus, replacing, 21246 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21247 } 21248 21249 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21250 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21251 int size = pkgList.length; 21252 if (size > 0) { 21253 // Send broadcasts here 21254 Bundle extras = new Bundle(); 21255 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21256 if (uidArr != null) { 21257 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21258 } 21259 if (replacing) { 21260 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21261 } 21262 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21263 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21264 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21265 } 21266 } 21267 21268 /* 21269 * Look at potentially valid container ids from processCids If package 21270 * information doesn't match the one on record or package scanning fails, 21271 * the cid is added to list of removeCids. We currently don't delete stale 21272 * containers. 21273 */ 21274 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21275 boolean externalStorage) { 21276 ArrayList<String> pkgList = new ArrayList<String>(); 21277 Set<AsecInstallArgs> keys = processCids.keySet(); 21278 21279 for (AsecInstallArgs args : keys) { 21280 String codePath = processCids.get(args); 21281 if (DEBUG_SD_INSTALL) 21282 Log.i(TAG, "Loading container : " + args.cid); 21283 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21284 try { 21285 // Make sure there are no container errors first. 21286 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21287 Slog.e(TAG, "Failed to mount cid : " + args.cid 21288 + " when installing from sdcard"); 21289 continue; 21290 } 21291 // Check code path here. 21292 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21293 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21294 + " does not match one in settings " + codePath); 21295 continue; 21296 } 21297 // Parse package 21298 int parseFlags = mDefParseFlags; 21299 if (args.isExternalAsec()) { 21300 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21301 } 21302 if (args.isFwdLocked()) { 21303 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21304 } 21305 21306 synchronized (mInstallLock) { 21307 PackageParser.Package pkg = null; 21308 try { 21309 // Sadly we don't know the package name yet to freeze it 21310 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21311 SCAN_IGNORE_FROZEN, 0, null); 21312 } catch (PackageManagerException e) { 21313 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21314 } 21315 // Scan the package 21316 if (pkg != null) { 21317 /* 21318 * TODO why is the lock being held? doPostInstall is 21319 * called in other places without the lock. This needs 21320 * to be straightened out. 21321 */ 21322 // writer 21323 synchronized (mPackages) { 21324 retCode = PackageManager.INSTALL_SUCCEEDED; 21325 pkgList.add(pkg.packageName); 21326 // Post process args 21327 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21328 pkg.applicationInfo.uid); 21329 } 21330 } else { 21331 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21332 } 21333 } 21334 21335 } finally { 21336 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21337 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21338 } 21339 } 21340 } 21341 // writer 21342 synchronized (mPackages) { 21343 // If the platform SDK has changed since the last time we booted, 21344 // we need to re-grant app permission to catch any new ones that 21345 // appear. This is really a hack, and means that apps can in some 21346 // cases get permissions that the user didn't initially explicitly 21347 // allow... it would be nice to have some better way to handle 21348 // this situation. 21349 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21350 : mSettings.getInternalVersion(); 21351 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21352 : StorageManager.UUID_PRIVATE_INTERNAL; 21353 21354 int updateFlags = UPDATE_PERMISSIONS_ALL; 21355 if (ver.sdkVersion != mSdkVersion) { 21356 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21357 + mSdkVersion + "; regranting permissions for external"); 21358 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21359 } 21360 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21361 21362 // Yay, everything is now upgraded 21363 ver.forceCurrent(); 21364 21365 // can downgrade to reader 21366 // Persist settings 21367 mSettings.writeLPr(); 21368 } 21369 // Send a broadcast to let everyone know we are done processing 21370 if (pkgList.size() > 0) { 21371 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21372 } 21373 } 21374 21375 /* 21376 * Utility method to unload a list of specified containers 21377 */ 21378 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21379 // Just unmount all valid containers. 21380 for (AsecInstallArgs arg : cidArgs) { 21381 synchronized (mInstallLock) { 21382 arg.doPostDeleteLI(false); 21383 } 21384 } 21385 } 21386 21387 /* 21388 * Unload packages mounted on external media. This involves deleting package 21389 * data from internal structures, sending broadcasts about disabled packages, 21390 * gc'ing to free up references, unmounting all secure containers 21391 * corresponding to packages on external media, and posting a 21392 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21393 * that we always have to post this message if status has been requested no 21394 * matter what. 21395 */ 21396 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21397 final boolean reportStatus) { 21398 if (DEBUG_SD_INSTALL) 21399 Log.i(TAG, "unloading media packages"); 21400 ArrayList<String> pkgList = new ArrayList<String>(); 21401 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21402 final Set<AsecInstallArgs> keys = processCids.keySet(); 21403 for (AsecInstallArgs args : keys) { 21404 String pkgName = args.getPackageName(); 21405 if (DEBUG_SD_INSTALL) 21406 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21407 // Delete package internally 21408 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21409 synchronized (mInstallLock) { 21410 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21411 final boolean res; 21412 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21413 "unloadMediaPackages")) { 21414 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21415 null); 21416 } 21417 if (res) { 21418 pkgList.add(pkgName); 21419 } else { 21420 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21421 failedList.add(args); 21422 } 21423 } 21424 } 21425 21426 // reader 21427 synchronized (mPackages) { 21428 // We didn't update the settings after removing each package; 21429 // write them now for all packages. 21430 mSettings.writeLPr(); 21431 } 21432 21433 // We have to absolutely send UPDATED_MEDIA_STATUS only 21434 // after confirming that all the receivers processed the ordered 21435 // broadcast when packages get disabled, force a gc to clean things up. 21436 // and unload all the containers. 21437 if (pkgList.size() > 0) { 21438 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21439 new IIntentReceiver.Stub() { 21440 public void performReceive(Intent intent, int resultCode, String data, 21441 Bundle extras, boolean ordered, boolean sticky, 21442 int sendingUser) throws RemoteException { 21443 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21444 reportStatus ? 1 : 0, 1, keys); 21445 mHandler.sendMessage(msg); 21446 } 21447 }); 21448 } else { 21449 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21450 keys); 21451 mHandler.sendMessage(msg); 21452 } 21453 } 21454 21455 private void loadPrivatePackages(final VolumeInfo vol) { 21456 mHandler.post(new Runnable() { 21457 @Override 21458 public void run() { 21459 loadPrivatePackagesInner(vol); 21460 } 21461 }); 21462 } 21463 21464 private void loadPrivatePackagesInner(VolumeInfo vol) { 21465 final String volumeUuid = vol.fsUuid; 21466 if (TextUtils.isEmpty(volumeUuid)) { 21467 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21468 return; 21469 } 21470 21471 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21472 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21473 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21474 21475 final VersionInfo ver; 21476 final List<PackageSetting> packages; 21477 synchronized (mPackages) { 21478 ver = mSettings.findOrCreateVersion(volumeUuid); 21479 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21480 } 21481 21482 for (PackageSetting ps : packages) { 21483 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21484 synchronized (mInstallLock) { 21485 final PackageParser.Package pkg; 21486 try { 21487 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21488 loaded.add(pkg.applicationInfo); 21489 21490 } catch (PackageManagerException e) { 21491 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21492 } 21493 21494 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21495 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21496 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21497 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21498 } 21499 } 21500 } 21501 21502 // Reconcile app data for all started/unlocked users 21503 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21504 final UserManager um = mContext.getSystemService(UserManager.class); 21505 UserManagerInternal umInternal = getUserManagerInternal(); 21506 for (UserInfo user : um.getUsers()) { 21507 final int flags; 21508 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21509 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21510 } else if (umInternal.isUserRunning(user.id)) { 21511 flags = StorageManager.FLAG_STORAGE_DE; 21512 } else { 21513 continue; 21514 } 21515 21516 try { 21517 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21518 synchronized (mInstallLock) { 21519 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21520 } 21521 } catch (IllegalStateException e) { 21522 // Device was probably ejected, and we'll process that event momentarily 21523 Slog.w(TAG, "Failed to prepare storage: " + e); 21524 } 21525 } 21526 21527 synchronized (mPackages) { 21528 int updateFlags = UPDATE_PERMISSIONS_ALL; 21529 if (ver.sdkVersion != mSdkVersion) { 21530 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21531 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21532 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21533 } 21534 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21535 21536 // Yay, everything is now upgraded 21537 ver.forceCurrent(); 21538 21539 mSettings.writeLPr(); 21540 } 21541 21542 for (PackageFreezer freezer : freezers) { 21543 freezer.close(); 21544 } 21545 21546 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21547 sendResourcesChangedBroadcast(true, false, loaded, null); 21548 } 21549 21550 private void unloadPrivatePackages(final VolumeInfo vol) { 21551 mHandler.post(new Runnable() { 21552 @Override 21553 public void run() { 21554 unloadPrivatePackagesInner(vol); 21555 } 21556 }); 21557 } 21558 21559 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21560 final String volumeUuid = vol.fsUuid; 21561 if (TextUtils.isEmpty(volumeUuid)) { 21562 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21563 return; 21564 } 21565 21566 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21567 synchronized (mInstallLock) { 21568 synchronized (mPackages) { 21569 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21570 for (PackageSetting ps : packages) { 21571 if (ps.pkg == null) continue; 21572 21573 final ApplicationInfo info = ps.pkg.applicationInfo; 21574 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21575 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21576 21577 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21578 "unloadPrivatePackagesInner")) { 21579 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21580 false, null)) { 21581 unloaded.add(info); 21582 } else { 21583 Slog.w(TAG, "Failed to unload " + ps.codePath); 21584 } 21585 } 21586 21587 // Try very hard to release any references to this package 21588 // so we don't risk the system server being killed due to 21589 // open FDs 21590 AttributeCache.instance().removePackage(ps.name); 21591 } 21592 21593 mSettings.writeLPr(); 21594 } 21595 } 21596 21597 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21598 sendResourcesChangedBroadcast(false, false, unloaded, null); 21599 21600 // Try very hard to release any references to this path so we don't risk 21601 // the system server being killed due to open FDs 21602 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21603 21604 for (int i = 0; i < 3; i++) { 21605 System.gc(); 21606 System.runFinalization(); 21607 } 21608 } 21609 21610 private void assertPackageKnown(String volumeUuid, String packageName) 21611 throws PackageManagerException { 21612 synchronized (mPackages) { 21613 // Normalize package name to handle renamed packages 21614 packageName = normalizePackageNameLPr(packageName); 21615 21616 final PackageSetting ps = mSettings.mPackages.get(packageName); 21617 if (ps == null) { 21618 throw new PackageManagerException("Package " + packageName + " is unknown"); 21619 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21620 throw new PackageManagerException( 21621 "Package " + packageName + " found on unknown volume " + volumeUuid 21622 + "; expected volume " + ps.volumeUuid); 21623 } 21624 } 21625 } 21626 21627 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21628 throws PackageManagerException { 21629 synchronized (mPackages) { 21630 // Normalize package name to handle renamed packages 21631 packageName = normalizePackageNameLPr(packageName); 21632 21633 final PackageSetting ps = mSettings.mPackages.get(packageName); 21634 if (ps == null) { 21635 throw new PackageManagerException("Package " + packageName + " is unknown"); 21636 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21637 throw new PackageManagerException( 21638 "Package " + packageName + " found on unknown volume " + volumeUuid 21639 + "; expected volume " + ps.volumeUuid); 21640 } else if (!ps.getInstalled(userId)) { 21641 throw new PackageManagerException( 21642 "Package " + packageName + " not installed for user " + userId); 21643 } 21644 } 21645 } 21646 21647 private List<String> collectAbsoluteCodePaths() { 21648 synchronized (mPackages) { 21649 List<String> codePaths = new ArrayList<>(); 21650 final int packageCount = mSettings.mPackages.size(); 21651 for (int i = 0; i < packageCount; i++) { 21652 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21653 codePaths.add(ps.codePath.getAbsolutePath()); 21654 } 21655 return codePaths; 21656 } 21657 } 21658 21659 /** 21660 * Examine all apps present on given mounted volume, and destroy apps that 21661 * aren't expected, either due to uninstallation or reinstallation on 21662 * another volume. 21663 */ 21664 private void reconcileApps(String volumeUuid) { 21665 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21666 List<File> filesToDelete = null; 21667 21668 final File[] files = FileUtils.listFilesOrEmpty( 21669 Environment.getDataAppDirectory(volumeUuid)); 21670 for (File file : files) { 21671 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21672 && !PackageInstallerService.isStageName(file.getName()); 21673 if (!isPackage) { 21674 // Ignore entries which are not packages 21675 continue; 21676 } 21677 21678 String absolutePath = file.getAbsolutePath(); 21679 21680 boolean pathValid = false; 21681 final int absoluteCodePathCount = absoluteCodePaths.size(); 21682 for (int i = 0; i < absoluteCodePathCount; i++) { 21683 String absoluteCodePath = absoluteCodePaths.get(i); 21684 if (absolutePath.startsWith(absoluteCodePath)) { 21685 pathValid = true; 21686 break; 21687 } 21688 } 21689 21690 if (!pathValid) { 21691 if (filesToDelete == null) { 21692 filesToDelete = new ArrayList<>(); 21693 } 21694 filesToDelete.add(file); 21695 } 21696 } 21697 21698 if (filesToDelete != null) { 21699 final int fileToDeleteCount = filesToDelete.size(); 21700 for (int i = 0; i < fileToDeleteCount; i++) { 21701 File fileToDelete = filesToDelete.get(i); 21702 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21703 synchronized (mInstallLock) { 21704 removeCodePathLI(fileToDelete); 21705 } 21706 } 21707 } 21708 } 21709 21710 /** 21711 * Reconcile all app data for the given user. 21712 * <p> 21713 * Verifies that directories exist and that ownership and labeling is 21714 * correct for all installed apps on all mounted volumes. 21715 */ 21716 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21717 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21718 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21719 final String volumeUuid = vol.getFsUuid(); 21720 synchronized (mInstallLock) { 21721 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21722 } 21723 } 21724 } 21725 21726 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21727 boolean migrateAppData) { 21728 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21729 } 21730 21731 /** 21732 * Reconcile all app data on given mounted volume. 21733 * <p> 21734 * Destroys app data that isn't expected, either due to uninstallation or 21735 * reinstallation on another volume. 21736 * <p> 21737 * Verifies that directories exist and that ownership and labeling is 21738 * correct for all installed apps. 21739 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21740 */ 21741 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21742 boolean migrateAppData, boolean onlyCoreApps) { 21743 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21744 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21745 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21746 21747 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21748 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21749 21750 // First look for stale data that doesn't belong, and check if things 21751 // have changed since we did our last restorecon 21752 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21753 if (StorageManager.isFileEncryptedNativeOrEmulated() 21754 && !StorageManager.isUserKeyUnlocked(userId)) { 21755 throw new RuntimeException( 21756 "Yikes, someone asked us to reconcile CE storage while " + userId 21757 + " was still locked; this would have caused massive data loss!"); 21758 } 21759 21760 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21761 for (File file : files) { 21762 final String packageName = file.getName(); 21763 try { 21764 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21765 } catch (PackageManagerException e) { 21766 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21767 try { 21768 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21769 StorageManager.FLAG_STORAGE_CE, 0); 21770 } catch (InstallerException e2) { 21771 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21772 } 21773 } 21774 } 21775 } 21776 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21777 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21778 for (File file : files) { 21779 final String packageName = file.getName(); 21780 try { 21781 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21782 } catch (PackageManagerException e) { 21783 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21784 try { 21785 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21786 StorageManager.FLAG_STORAGE_DE, 0); 21787 } catch (InstallerException e2) { 21788 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21789 } 21790 } 21791 } 21792 } 21793 21794 // Ensure that data directories are ready to roll for all packages 21795 // installed for this volume and user 21796 final List<PackageSetting> packages; 21797 synchronized (mPackages) { 21798 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21799 } 21800 int preparedCount = 0; 21801 for (PackageSetting ps : packages) { 21802 final String packageName = ps.name; 21803 if (ps.pkg == null) { 21804 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21805 // TODO: might be due to legacy ASEC apps; we should circle back 21806 // and reconcile again once they're scanned 21807 continue; 21808 } 21809 // Skip non-core apps if requested 21810 if (onlyCoreApps && !ps.pkg.coreApp) { 21811 result.add(packageName); 21812 continue; 21813 } 21814 21815 if (ps.getInstalled(userId)) { 21816 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21817 preparedCount++; 21818 } 21819 } 21820 21821 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21822 return result; 21823 } 21824 21825 /** 21826 * Prepare app data for the given app just after it was installed or 21827 * upgraded. This method carefully only touches users that it's installed 21828 * for, and it forces a restorecon to handle any seinfo changes. 21829 * <p> 21830 * Verifies that directories exist and that ownership and labeling is 21831 * correct for all installed apps. If there is an ownership mismatch, it 21832 * will try recovering system apps by wiping data; third-party app data is 21833 * left intact. 21834 * <p> 21835 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21836 */ 21837 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21838 final PackageSetting ps; 21839 synchronized (mPackages) { 21840 ps = mSettings.mPackages.get(pkg.packageName); 21841 mSettings.writeKernelMappingLPr(ps); 21842 } 21843 21844 final UserManager um = mContext.getSystemService(UserManager.class); 21845 UserManagerInternal umInternal = getUserManagerInternal(); 21846 for (UserInfo user : um.getUsers()) { 21847 final int flags; 21848 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21849 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21850 } else if (umInternal.isUserRunning(user.id)) { 21851 flags = StorageManager.FLAG_STORAGE_DE; 21852 } else { 21853 continue; 21854 } 21855 21856 if (ps.getInstalled(user.id)) { 21857 // TODO: when user data is locked, mark that we're still dirty 21858 prepareAppDataLIF(pkg, user.id, flags); 21859 } 21860 } 21861 } 21862 21863 /** 21864 * Prepare app data for the given app. 21865 * <p> 21866 * Verifies that directories exist and that ownership and labeling is 21867 * correct for all installed apps. If there is an ownership mismatch, this 21868 * will try recovering system apps by wiping data; third-party app data is 21869 * left intact. 21870 */ 21871 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21872 if (pkg == null) { 21873 Slog.wtf(TAG, "Package was null!", new Throwable()); 21874 return; 21875 } 21876 prepareAppDataLeafLIF(pkg, userId, flags); 21877 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21878 for (int i = 0; i < childCount; i++) { 21879 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21880 } 21881 } 21882 21883 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21884 boolean maybeMigrateAppData) { 21885 prepareAppDataLIF(pkg, userId, flags); 21886 21887 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21888 // We may have just shuffled around app data directories, so 21889 // prepare them one more time 21890 prepareAppDataLIF(pkg, userId, flags); 21891 } 21892 } 21893 21894 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21895 if (DEBUG_APP_DATA) { 21896 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21897 + Integer.toHexString(flags)); 21898 } 21899 21900 final String volumeUuid = pkg.volumeUuid; 21901 final String packageName = pkg.packageName; 21902 final ApplicationInfo app = pkg.applicationInfo; 21903 final int appId = UserHandle.getAppId(app.uid); 21904 21905 Preconditions.checkNotNull(app.seInfo); 21906 21907 long ceDataInode = -1; 21908 try { 21909 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21910 appId, app.seInfo, app.targetSdkVersion); 21911 } catch (InstallerException e) { 21912 if (app.isSystemApp()) { 21913 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21914 + ", but trying to recover: " + e); 21915 destroyAppDataLeafLIF(pkg, userId, flags); 21916 try { 21917 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21918 appId, app.seInfo, app.targetSdkVersion); 21919 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21920 } catch (InstallerException e2) { 21921 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21922 } 21923 } else { 21924 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21925 } 21926 } 21927 21928 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21929 // TODO: mark this structure as dirty so we persist it! 21930 synchronized (mPackages) { 21931 final PackageSetting ps = mSettings.mPackages.get(packageName); 21932 if (ps != null) { 21933 ps.setCeDataInode(ceDataInode, userId); 21934 } 21935 } 21936 } 21937 21938 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21939 } 21940 21941 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21942 if (pkg == null) { 21943 Slog.wtf(TAG, "Package was null!", new Throwable()); 21944 return; 21945 } 21946 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21947 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21948 for (int i = 0; i < childCount; i++) { 21949 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21950 } 21951 } 21952 21953 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21954 final String volumeUuid = pkg.volumeUuid; 21955 final String packageName = pkg.packageName; 21956 final ApplicationInfo app = pkg.applicationInfo; 21957 21958 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21959 // Create a native library symlink only if we have native libraries 21960 // and if the native libraries are 32 bit libraries. We do not provide 21961 // this symlink for 64 bit libraries. 21962 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21963 final String nativeLibPath = app.nativeLibraryDir; 21964 try { 21965 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21966 nativeLibPath, userId); 21967 } catch (InstallerException e) { 21968 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21969 } 21970 } 21971 } 21972 } 21973 21974 /** 21975 * For system apps on non-FBE devices, this method migrates any existing 21976 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21977 * requested by the app. 21978 */ 21979 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21980 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21981 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21982 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21983 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21984 try { 21985 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21986 storageTarget); 21987 } catch (InstallerException e) { 21988 logCriticalInfo(Log.WARN, 21989 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21990 } 21991 return true; 21992 } else { 21993 return false; 21994 } 21995 } 21996 21997 public PackageFreezer freezePackage(String packageName, String killReason) { 21998 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21999 } 22000 22001 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22002 return new PackageFreezer(packageName, userId, killReason); 22003 } 22004 22005 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22006 String killReason) { 22007 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22008 } 22009 22010 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22011 String killReason) { 22012 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22013 return new PackageFreezer(); 22014 } else { 22015 return freezePackage(packageName, userId, killReason); 22016 } 22017 } 22018 22019 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22020 String killReason) { 22021 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22022 } 22023 22024 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22025 String killReason) { 22026 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22027 return new PackageFreezer(); 22028 } else { 22029 return freezePackage(packageName, userId, killReason); 22030 } 22031 } 22032 22033 /** 22034 * Class that freezes and kills the given package upon creation, and 22035 * unfreezes it upon closing. This is typically used when doing surgery on 22036 * app code/data to prevent the app from running while you're working. 22037 */ 22038 private class PackageFreezer implements AutoCloseable { 22039 private final String mPackageName; 22040 private final PackageFreezer[] mChildren; 22041 22042 private final boolean mWeFroze; 22043 22044 private final AtomicBoolean mClosed = new AtomicBoolean(); 22045 private final CloseGuard mCloseGuard = CloseGuard.get(); 22046 22047 /** 22048 * Create and return a stub freezer that doesn't actually do anything, 22049 * typically used when someone requested 22050 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22051 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22052 */ 22053 public PackageFreezer() { 22054 mPackageName = null; 22055 mChildren = null; 22056 mWeFroze = false; 22057 mCloseGuard.open("close"); 22058 } 22059 22060 public PackageFreezer(String packageName, int userId, String killReason) { 22061 synchronized (mPackages) { 22062 mPackageName = packageName; 22063 mWeFroze = mFrozenPackages.add(mPackageName); 22064 22065 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22066 if (ps != null) { 22067 killApplication(ps.name, ps.appId, userId, killReason); 22068 } 22069 22070 final PackageParser.Package p = mPackages.get(packageName); 22071 if (p != null && p.childPackages != null) { 22072 final int N = p.childPackages.size(); 22073 mChildren = new PackageFreezer[N]; 22074 for (int i = 0; i < N; i++) { 22075 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22076 userId, killReason); 22077 } 22078 } else { 22079 mChildren = null; 22080 } 22081 } 22082 mCloseGuard.open("close"); 22083 } 22084 22085 @Override 22086 protected void finalize() throws Throwable { 22087 try { 22088 mCloseGuard.warnIfOpen(); 22089 close(); 22090 } finally { 22091 super.finalize(); 22092 } 22093 } 22094 22095 @Override 22096 public void close() { 22097 mCloseGuard.close(); 22098 if (mClosed.compareAndSet(false, true)) { 22099 synchronized (mPackages) { 22100 if (mWeFroze) { 22101 mFrozenPackages.remove(mPackageName); 22102 } 22103 22104 if (mChildren != null) { 22105 for (PackageFreezer freezer : mChildren) { 22106 freezer.close(); 22107 } 22108 } 22109 } 22110 } 22111 } 22112 } 22113 22114 /** 22115 * Verify that given package is currently frozen. 22116 */ 22117 private void checkPackageFrozen(String packageName) { 22118 synchronized (mPackages) { 22119 if (!mFrozenPackages.contains(packageName)) { 22120 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22121 } 22122 } 22123 } 22124 22125 @Override 22126 public int movePackage(final String packageName, final String volumeUuid) { 22127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22128 22129 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22130 final int moveId = mNextMoveId.getAndIncrement(); 22131 mHandler.post(new Runnable() { 22132 @Override 22133 public void run() { 22134 try { 22135 movePackageInternal(packageName, volumeUuid, moveId, user); 22136 } catch (PackageManagerException e) { 22137 Slog.w(TAG, "Failed to move " + packageName, e); 22138 mMoveCallbacks.notifyStatusChanged(moveId, 22139 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22140 } 22141 } 22142 }); 22143 return moveId; 22144 } 22145 22146 private void movePackageInternal(final String packageName, final String volumeUuid, 22147 final int moveId, UserHandle user) throws PackageManagerException { 22148 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22149 final PackageManager pm = mContext.getPackageManager(); 22150 22151 final boolean currentAsec; 22152 final String currentVolumeUuid; 22153 final File codeFile; 22154 final String installerPackageName; 22155 final String packageAbiOverride; 22156 final int appId; 22157 final String seinfo; 22158 final String label; 22159 final int targetSdkVersion; 22160 final PackageFreezer freezer; 22161 final int[] installedUserIds; 22162 22163 // reader 22164 synchronized (mPackages) { 22165 final PackageParser.Package pkg = mPackages.get(packageName); 22166 final PackageSetting ps = mSettings.mPackages.get(packageName); 22167 if (pkg == null || ps == null) { 22168 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22169 } 22170 22171 if (pkg.applicationInfo.isSystemApp()) { 22172 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22173 "Cannot move system application"); 22174 } 22175 22176 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22177 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22178 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22179 if (isInternalStorage && !allow3rdPartyOnInternal) { 22180 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22181 "3rd party apps are not allowed on internal storage"); 22182 } 22183 22184 if (pkg.applicationInfo.isExternalAsec()) { 22185 currentAsec = true; 22186 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22187 } else if (pkg.applicationInfo.isForwardLocked()) { 22188 currentAsec = true; 22189 currentVolumeUuid = "forward_locked"; 22190 } else { 22191 currentAsec = false; 22192 currentVolumeUuid = ps.volumeUuid; 22193 22194 final File probe = new File(pkg.codePath); 22195 final File probeOat = new File(probe, "oat"); 22196 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22197 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22198 "Move only supported for modern cluster style installs"); 22199 } 22200 } 22201 22202 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22203 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22204 "Package already moved to " + volumeUuid); 22205 } 22206 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22207 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22208 "Device admin cannot be moved"); 22209 } 22210 22211 if (mFrozenPackages.contains(packageName)) { 22212 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22213 "Failed to move already frozen package"); 22214 } 22215 22216 codeFile = new File(pkg.codePath); 22217 installerPackageName = ps.installerPackageName; 22218 packageAbiOverride = ps.cpuAbiOverrideString; 22219 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22220 seinfo = pkg.applicationInfo.seInfo; 22221 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22222 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22223 freezer = freezePackage(packageName, "movePackageInternal"); 22224 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22225 } 22226 22227 final Bundle extras = new Bundle(); 22228 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22229 extras.putString(Intent.EXTRA_TITLE, label); 22230 mMoveCallbacks.notifyCreated(moveId, extras); 22231 22232 int installFlags; 22233 final boolean moveCompleteApp; 22234 final File measurePath; 22235 22236 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22237 installFlags = INSTALL_INTERNAL; 22238 moveCompleteApp = !currentAsec; 22239 measurePath = Environment.getDataAppDirectory(volumeUuid); 22240 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22241 installFlags = INSTALL_EXTERNAL; 22242 moveCompleteApp = false; 22243 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22244 } else { 22245 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22246 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22247 || !volume.isMountedWritable()) { 22248 freezer.close(); 22249 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22250 "Move location not mounted private volume"); 22251 } 22252 22253 Preconditions.checkState(!currentAsec); 22254 22255 installFlags = INSTALL_INTERNAL; 22256 moveCompleteApp = true; 22257 measurePath = Environment.getDataAppDirectory(volumeUuid); 22258 } 22259 22260 final PackageStats stats = new PackageStats(null, -1); 22261 synchronized (mInstaller) { 22262 for (int userId : installedUserIds) { 22263 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22264 freezer.close(); 22265 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22266 "Failed to measure package size"); 22267 } 22268 } 22269 } 22270 22271 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22272 + stats.dataSize); 22273 22274 final long startFreeBytes = measurePath.getFreeSpace(); 22275 final long sizeBytes; 22276 if (moveCompleteApp) { 22277 sizeBytes = stats.codeSize + stats.dataSize; 22278 } else { 22279 sizeBytes = stats.codeSize; 22280 } 22281 22282 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22283 freezer.close(); 22284 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22285 "Not enough free space to move"); 22286 } 22287 22288 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22289 22290 final CountDownLatch installedLatch = new CountDownLatch(1); 22291 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22292 @Override 22293 public void onUserActionRequired(Intent intent) throws RemoteException { 22294 throw new IllegalStateException(); 22295 } 22296 22297 @Override 22298 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22299 Bundle extras) throws RemoteException { 22300 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22301 + PackageManager.installStatusToString(returnCode, msg)); 22302 22303 installedLatch.countDown(); 22304 freezer.close(); 22305 22306 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22307 switch (status) { 22308 case PackageInstaller.STATUS_SUCCESS: 22309 mMoveCallbacks.notifyStatusChanged(moveId, 22310 PackageManager.MOVE_SUCCEEDED); 22311 break; 22312 case PackageInstaller.STATUS_FAILURE_STORAGE: 22313 mMoveCallbacks.notifyStatusChanged(moveId, 22314 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22315 break; 22316 default: 22317 mMoveCallbacks.notifyStatusChanged(moveId, 22318 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22319 break; 22320 } 22321 } 22322 }; 22323 22324 final MoveInfo move; 22325 if (moveCompleteApp) { 22326 // Kick off a thread to report progress estimates 22327 new Thread() { 22328 @Override 22329 public void run() { 22330 while (true) { 22331 try { 22332 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22333 break; 22334 } 22335 } catch (InterruptedException ignored) { 22336 } 22337 22338 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22339 final int progress = 10 + (int) MathUtils.constrain( 22340 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22341 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22342 } 22343 } 22344 }.start(); 22345 22346 final String dataAppName = codeFile.getName(); 22347 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22348 dataAppName, appId, seinfo, targetSdkVersion); 22349 } else { 22350 move = null; 22351 } 22352 22353 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22354 22355 final Message msg = mHandler.obtainMessage(INIT_COPY); 22356 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22357 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22358 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22359 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22360 PackageManager.INSTALL_REASON_UNKNOWN); 22361 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22362 msg.obj = params; 22363 22364 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22365 System.identityHashCode(msg.obj)); 22366 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22367 System.identityHashCode(msg.obj)); 22368 22369 mHandler.sendMessage(msg); 22370 } 22371 22372 @Override 22373 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22374 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22375 22376 final int realMoveId = mNextMoveId.getAndIncrement(); 22377 final Bundle extras = new Bundle(); 22378 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22379 mMoveCallbacks.notifyCreated(realMoveId, extras); 22380 22381 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22382 @Override 22383 public void onCreated(int moveId, Bundle extras) { 22384 // Ignored 22385 } 22386 22387 @Override 22388 public void onStatusChanged(int moveId, int status, long estMillis) { 22389 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22390 } 22391 }; 22392 22393 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22394 storage.setPrimaryStorageUuid(volumeUuid, callback); 22395 return realMoveId; 22396 } 22397 22398 @Override 22399 public int getMoveStatus(int moveId) { 22400 mContext.enforceCallingOrSelfPermission( 22401 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22402 return mMoveCallbacks.mLastStatus.get(moveId); 22403 } 22404 22405 @Override 22406 public void registerMoveCallback(IPackageMoveObserver callback) { 22407 mContext.enforceCallingOrSelfPermission( 22408 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22409 mMoveCallbacks.register(callback); 22410 } 22411 22412 @Override 22413 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22414 mContext.enforceCallingOrSelfPermission( 22415 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22416 mMoveCallbacks.unregister(callback); 22417 } 22418 22419 @Override 22420 public boolean setInstallLocation(int loc) { 22421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22422 null); 22423 if (getInstallLocation() == loc) { 22424 return true; 22425 } 22426 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22427 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22428 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22429 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22430 return true; 22431 } 22432 return false; 22433 } 22434 22435 @Override 22436 public int getInstallLocation() { 22437 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22438 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22439 PackageHelper.APP_INSTALL_AUTO); 22440 } 22441 22442 /** Called by UserManagerService */ 22443 void cleanUpUser(UserManagerService userManager, int userHandle) { 22444 synchronized (mPackages) { 22445 mDirtyUsers.remove(userHandle); 22446 mUserNeedsBadging.delete(userHandle); 22447 mSettings.removeUserLPw(userHandle); 22448 mPendingBroadcasts.remove(userHandle); 22449 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22450 removeUnusedPackagesLPw(userManager, userHandle); 22451 } 22452 } 22453 22454 /** 22455 * We're removing userHandle and would like to remove any downloaded packages 22456 * that are no longer in use by any other user. 22457 * @param userHandle the user being removed 22458 */ 22459 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22460 final boolean DEBUG_CLEAN_APKS = false; 22461 int [] users = userManager.getUserIds(); 22462 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22463 while (psit.hasNext()) { 22464 PackageSetting ps = psit.next(); 22465 if (ps.pkg == null) { 22466 continue; 22467 } 22468 final String packageName = ps.pkg.packageName; 22469 // Skip over if system app 22470 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22471 continue; 22472 } 22473 if (DEBUG_CLEAN_APKS) { 22474 Slog.i(TAG, "Checking package " + packageName); 22475 } 22476 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22477 if (keep) { 22478 if (DEBUG_CLEAN_APKS) { 22479 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22480 } 22481 } else { 22482 for (int i = 0; i < users.length; i++) { 22483 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22484 keep = true; 22485 if (DEBUG_CLEAN_APKS) { 22486 Slog.i(TAG, " Keeping package " + packageName + " for user " 22487 + users[i]); 22488 } 22489 break; 22490 } 22491 } 22492 } 22493 if (!keep) { 22494 if (DEBUG_CLEAN_APKS) { 22495 Slog.i(TAG, " Removing package " + packageName); 22496 } 22497 mHandler.post(new Runnable() { 22498 public void run() { 22499 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22500 userHandle, 0); 22501 } //end run 22502 }); 22503 } 22504 } 22505 } 22506 22507 /** Called by UserManagerService */ 22508 void createNewUser(int userId, String[] disallowedPackages) { 22509 synchronized (mInstallLock) { 22510 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22511 } 22512 synchronized (mPackages) { 22513 scheduleWritePackageRestrictionsLocked(userId); 22514 scheduleWritePackageListLocked(userId); 22515 applyFactoryDefaultBrowserLPw(userId); 22516 primeDomainVerificationsLPw(userId); 22517 } 22518 } 22519 22520 void onNewUserCreated(final int userId) { 22521 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22522 // If permission review for legacy apps is required, we represent 22523 // dagerous permissions for such apps as always granted runtime 22524 // permissions to keep per user flag state whether review is needed. 22525 // Hence, if a new user is added we have to propagate dangerous 22526 // permission grants for these legacy apps. 22527 if (mPermissionReviewRequired) { 22528 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22529 | UPDATE_PERMISSIONS_REPLACE_ALL); 22530 } 22531 } 22532 22533 @Override 22534 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22535 mContext.enforceCallingOrSelfPermission( 22536 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22537 "Only package verification agents can read the verifier device identity"); 22538 22539 synchronized (mPackages) { 22540 return mSettings.getVerifierDeviceIdentityLPw(); 22541 } 22542 } 22543 22544 @Override 22545 public void setPermissionEnforced(String permission, boolean enforced) { 22546 // TODO: Now that we no longer change GID for storage, this should to away. 22547 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22548 "setPermissionEnforced"); 22549 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22550 synchronized (mPackages) { 22551 if (mSettings.mReadExternalStorageEnforced == null 22552 || mSettings.mReadExternalStorageEnforced != enforced) { 22553 mSettings.mReadExternalStorageEnforced = enforced; 22554 mSettings.writeLPr(); 22555 } 22556 } 22557 // kill any non-foreground processes so we restart them and 22558 // grant/revoke the GID. 22559 final IActivityManager am = ActivityManager.getService(); 22560 if (am != null) { 22561 final long token = Binder.clearCallingIdentity(); 22562 try { 22563 am.killProcessesBelowForeground("setPermissionEnforcement"); 22564 } catch (RemoteException e) { 22565 } finally { 22566 Binder.restoreCallingIdentity(token); 22567 } 22568 } 22569 } else { 22570 throw new IllegalArgumentException("No selective enforcement for " + permission); 22571 } 22572 } 22573 22574 @Override 22575 @Deprecated 22576 public boolean isPermissionEnforced(String permission) { 22577 return true; 22578 } 22579 22580 @Override 22581 public boolean isStorageLow() { 22582 final long token = Binder.clearCallingIdentity(); 22583 try { 22584 final DeviceStorageMonitorInternal 22585 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22586 if (dsm != null) { 22587 return dsm.isMemoryLow(); 22588 } else { 22589 return false; 22590 } 22591 } finally { 22592 Binder.restoreCallingIdentity(token); 22593 } 22594 } 22595 22596 @Override 22597 public IPackageInstaller getPackageInstaller() { 22598 return mInstallerService; 22599 } 22600 22601 private boolean userNeedsBadging(int userId) { 22602 int index = mUserNeedsBadging.indexOfKey(userId); 22603 if (index < 0) { 22604 final UserInfo userInfo; 22605 final long token = Binder.clearCallingIdentity(); 22606 try { 22607 userInfo = sUserManager.getUserInfo(userId); 22608 } finally { 22609 Binder.restoreCallingIdentity(token); 22610 } 22611 final boolean b; 22612 if (userInfo != null && userInfo.isManagedProfile()) { 22613 b = true; 22614 } else { 22615 b = false; 22616 } 22617 mUserNeedsBadging.put(userId, b); 22618 return b; 22619 } 22620 return mUserNeedsBadging.valueAt(index); 22621 } 22622 22623 @Override 22624 public KeySet getKeySetByAlias(String packageName, String alias) { 22625 if (packageName == null || alias == null) { 22626 return null; 22627 } 22628 synchronized(mPackages) { 22629 final PackageParser.Package pkg = mPackages.get(packageName); 22630 if (pkg == null) { 22631 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22632 throw new IllegalArgumentException("Unknown package: " + packageName); 22633 } 22634 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22635 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22636 } 22637 } 22638 22639 @Override 22640 public KeySet getSigningKeySet(String packageName) { 22641 if (packageName == null) { 22642 return null; 22643 } 22644 synchronized(mPackages) { 22645 final PackageParser.Package pkg = mPackages.get(packageName); 22646 if (pkg == null) { 22647 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22648 throw new IllegalArgumentException("Unknown package: " + packageName); 22649 } 22650 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22651 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22652 throw new SecurityException("May not access signing KeySet of other apps."); 22653 } 22654 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22655 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22656 } 22657 } 22658 22659 @Override 22660 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22661 if (packageName == null || ks == null) { 22662 return false; 22663 } 22664 synchronized(mPackages) { 22665 final PackageParser.Package pkg = mPackages.get(packageName); 22666 if (pkg == null) { 22667 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22668 throw new IllegalArgumentException("Unknown package: " + packageName); 22669 } 22670 IBinder ksh = ks.getToken(); 22671 if (ksh instanceof KeySetHandle) { 22672 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22673 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22674 } 22675 return false; 22676 } 22677 } 22678 22679 @Override 22680 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22681 if (packageName == null || ks == null) { 22682 return false; 22683 } 22684 synchronized(mPackages) { 22685 final PackageParser.Package pkg = mPackages.get(packageName); 22686 if (pkg == null) { 22687 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22688 throw new IllegalArgumentException("Unknown package: " + packageName); 22689 } 22690 IBinder ksh = ks.getToken(); 22691 if (ksh instanceof KeySetHandle) { 22692 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22693 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22694 } 22695 return false; 22696 } 22697 } 22698 22699 private void deletePackageIfUnusedLPr(final String packageName) { 22700 PackageSetting ps = mSettings.mPackages.get(packageName); 22701 if (ps == null) { 22702 return; 22703 } 22704 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22705 // TODO Implement atomic delete if package is unused 22706 // It is currently possible that the package will be deleted even if it is installed 22707 // after this method returns. 22708 mHandler.post(new Runnable() { 22709 public void run() { 22710 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22711 0, PackageManager.DELETE_ALL_USERS); 22712 } 22713 }); 22714 } 22715 } 22716 22717 /** 22718 * Check and throw if the given before/after packages would be considered a 22719 * downgrade. 22720 */ 22721 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22722 throws PackageManagerException { 22723 if (after.versionCode < before.mVersionCode) { 22724 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22725 "Update version code " + after.versionCode + " is older than current " 22726 + before.mVersionCode); 22727 } else if (after.versionCode == before.mVersionCode) { 22728 if (after.baseRevisionCode < before.baseRevisionCode) { 22729 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22730 "Update base revision code " + after.baseRevisionCode 22731 + " is older than current " + before.baseRevisionCode); 22732 } 22733 22734 if (!ArrayUtils.isEmpty(after.splitNames)) { 22735 for (int i = 0; i < after.splitNames.length; i++) { 22736 final String splitName = after.splitNames[i]; 22737 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22738 if (j != -1) { 22739 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22740 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22741 "Update split " + splitName + " revision code " 22742 + after.splitRevisionCodes[i] + " is older than current " 22743 + before.splitRevisionCodes[j]); 22744 } 22745 } 22746 } 22747 } 22748 } 22749 } 22750 22751 private static class MoveCallbacks extends Handler { 22752 private static final int MSG_CREATED = 1; 22753 private static final int MSG_STATUS_CHANGED = 2; 22754 22755 private final RemoteCallbackList<IPackageMoveObserver> 22756 mCallbacks = new RemoteCallbackList<>(); 22757 22758 private final SparseIntArray mLastStatus = new SparseIntArray(); 22759 22760 public MoveCallbacks(Looper looper) { 22761 super(looper); 22762 } 22763 22764 public void register(IPackageMoveObserver callback) { 22765 mCallbacks.register(callback); 22766 } 22767 22768 public void unregister(IPackageMoveObserver callback) { 22769 mCallbacks.unregister(callback); 22770 } 22771 22772 @Override 22773 public void handleMessage(Message msg) { 22774 final SomeArgs args = (SomeArgs) msg.obj; 22775 final int n = mCallbacks.beginBroadcast(); 22776 for (int i = 0; i < n; i++) { 22777 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22778 try { 22779 invokeCallback(callback, msg.what, args); 22780 } catch (RemoteException ignored) { 22781 } 22782 } 22783 mCallbacks.finishBroadcast(); 22784 args.recycle(); 22785 } 22786 22787 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22788 throws RemoteException { 22789 switch (what) { 22790 case MSG_CREATED: { 22791 callback.onCreated(args.argi1, (Bundle) args.arg2); 22792 break; 22793 } 22794 case MSG_STATUS_CHANGED: { 22795 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22796 break; 22797 } 22798 } 22799 } 22800 22801 private void notifyCreated(int moveId, Bundle extras) { 22802 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22803 22804 final SomeArgs args = SomeArgs.obtain(); 22805 args.argi1 = moveId; 22806 args.arg2 = extras; 22807 obtainMessage(MSG_CREATED, args).sendToTarget(); 22808 } 22809 22810 private void notifyStatusChanged(int moveId, int status) { 22811 notifyStatusChanged(moveId, status, -1); 22812 } 22813 22814 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22815 Slog.v(TAG, "Move " + moveId + " status " + status); 22816 22817 final SomeArgs args = SomeArgs.obtain(); 22818 args.argi1 = moveId; 22819 args.argi2 = status; 22820 args.arg3 = estMillis; 22821 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22822 22823 synchronized (mLastStatus) { 22824 mLastStatus.put(moveId, status); 22825 } 22826 } 22827 } 22828 22829 private final static class OnPermissionChangeListeners extends Handler { 22830 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22831 22832 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22833 new RemoteCallbackList<>(); 22834 22835 public OnPermissionChangeListeners(Looper looper) { 22836 super(looper); 22837 } 22838 22839 @Override 22840 public void handleMessage(Message msg) { 22841 switch (msg.what) { 22842 case MSG_ON_PERMISSIONS_CHANGED: { 22843 final int uid = msg.arg1; 22844 handleOnPermissionsChanged(uid); 22845 } break; 22846 } 22847 } 22848 22849 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22850 mPermissionListeners.register(listener); 22851 22852 } 22853 22854 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22855 mPermissionListeners.unregister(listener); 22856 } 22857 22858 public void onPermissionsChanged(int uid) { 22859 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22860 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22861 } 22862 } 22863 22864 private void handleOnPermissionsChanged(int uid) { 22865 final int count = mPermissionListeners.beginBroadcast(); 22866 try { 22867 for (int i = 0; i < count; i++) { 22868 IOnPermissionsChangeListener callback = mPermissionListeners 22869 .getBroadcastItem(i); 22870 try { 22871 callback.onPermissionsChanged(uid); 22872 } catch (RemoteException e) { 22873 Log.e(TAG, "Permission listener is dead", e); 22874 } 22875 } 22876 } finally { 22877 mPermissionListeners.finishBroadcast(); 22878 } 22879 } 22880 } 22881 22882 private class PackageManagerInternalImpl extends PackageManagerInternal { 22883 @Override 22884 public void setLocationPackagesProvider(PackagesProvider provider) { 22885 synchronized (mPackages) { 22886 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22887 } 22888 } 22889 22890 @Override 22891 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22892 synchronized (mPackages) { 22893 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22894 } 22895 } 22896 22897 @Override 22898 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22899 synchronized (mPackages) { 22900 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22901 } 22902 } 22903 22904 @Override 22905 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22906 synchronized (mPackages) { 22907 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22908 } 22909 } 22910 22911 @Override 22912 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22913 synchronized (mPackages) { 22914 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22915 } 22916 } 22917 22918 @Override 22919 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22920 synchronized (mPackages) { 22921 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22922 } 22923 } 22924 22925 @Override 22926 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22927 synchronized (mPackages) { 22928 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22929 packageName, userId); 22930 } 22931 } 22932 22933 @Override 22934 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22935 synchronized (mPackages) { 22936 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22937 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22938 packageName, userId); 22939 } 22940 } 22941 22942 @Override 22943 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22944 synchronized (mPackages) { 22945 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22946 packageName, userId); 22947 } 22948 } 22949 22950 @Override 22951 public void setKeepUninstalledPackages(final List<String> packageList) { 22952 Preconditions.checkNotNull(packageList); 22953 List<String> removedFromList = null; 22954 synchronized (mPackages) { 22955 if (mKeepUninstalledPackages != null) { 22956 final int packagesCount = mKeepUninstalledPackages.size(); 22957 for (int i = 0; i < packagesCount; i++) { 22958 String oldPackage = mKeepUninstalledPackages.get(i); 22959 if (packageList != null && packageList.contains(oldPackage)) { 22960 continue; 22961 } 22962 if (removedFromList == null) { 22963 removedFromList = new ArrayList<>(); 22964 } 22965 removedFromList.add(oldPackage); 22966 } 22967 } 22968 mKeepUninstalledPackages = new ArrayList<>(packageList); 22969 if (removedFromList != null) { 22970 final int removedCount = removedFromList.size(); 22971 for (int i = 0; i < removedCount; i++) { 22972 deletePackageIfUnusedLPr(removedFromList.get(i)); 22973 } 22974 } 22975 } 22976 } 22977 22978 @Override 22979 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22980 synchronized (mPackages) { 22981 // If we do not support permission review, done. 22982 if (!mPermissionReviewRequired) { 22983 return false; 22984 } 22985 22986 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22987 if (packageSetting == null) { 22988 return false; 22989 } 22990 22991 // Permission review applies only to apps not supporting the new permission model. 22992 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22993 return false; 22994 } 22995 22996 // Legacy apps have the permission and get user consent on launch. 22997 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22998 return permissionsState.isPermissionReviewRequired(userId); 22999 } 23000 } 23001 23002 @Override 23003 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23004 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23005 } 23006 23007 @Override 23008 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23009 int userId) { 23010 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23011 } 23012 23013 @Override 23014 public void setDeviceAndProfileOwnerPackages( 23015 int deviceOwnerUserId, String deviceOwnerPackage, 23016 SparseArray<String> profileOwnerPackages) { 23017 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23018 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23019 } 23020 23021 @Override 23022 public boolean isPackageDataProtected(int userId, String packageName) { 23023 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23024 } 23025 23026 @Override 23027 public boolean isPackageEphemeral(int userId, String packageName) { 23028 synchronized (mPackages) { 23029 final PackageSetting ps = mSettings.mPackages.get(packageName); 23030 return ps != null ? ps.getInstantApp(userId) : false; 23031 } 23032 } 23033 23034 @Override 23035 public boolean wasPackageEverLaunched(String packageName, int userId) { 23036 synchronized (mPackages) { 23037 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23038 } 23039 } 23040 23041 @Override 23042 public void grantRuntimePermission(String packageName, String name, int userId, 23043 boolean overridePolicy) { 23044 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23045 overridePolicy); 23046 } 23047 23048 @Override 23049 public void revokeRuntimePermission(String packageName, String name, int userId, 23050 boolean overridePolicy) { 23051 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23052 overridePolicy); 23053 } 23054 23055 @Override 23056 public String getNameForUid(int uid) { 23057 return PackageManagerService.this.getNameForUid(uid); 23058 } 23059 23060 @Override 23061 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23062 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23063 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23064 responseObj, origIntent, resolvedType, callingPackage, userId); 23065 } 23066 23067 @Override 23068 public void grantEphemeralAccess(int userId, Intent intent, 23069 int targetAppId, int ephemeralAppId) { 23070 synchronized (mPackages) { 23071 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23072 targetAppId, ephemeralAppId); 23073 } 23074 } 23075 23076 @Override 23077 public boolean isInstantAppInstallerComponent(ComponentName component) { 23078 synchronized (mPackages) { 23079 return component != null && component.equals(mInstantAppInstallerComponent); 23080 } 23081 } 23082 23083 @Override 23084 public void pruneInstantApps() { 23085 synchronized (mPackages) { 23086 mInstantAppRegistry.pruneInstantAppsLPw(); 23087 } 23088 } 23089 23090 @Override 23091 public String getSetupWizardPackageName() { 23092 return mSetupWizardPackage; 23093 } 23094 23095 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23096 if (policy != null) { 23097 mExternalSourcesPolicy = policy; 23098 } 23099 } 23100 23101 @Override 23102 public boolean isPackagePersistent(String packageName) { 23103 synchronized (mPackages) { 23104 PackageParser.Package pkg = mPackages.get(packageName); 23105 return pkg != null 23106 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23107 | ApplicationInfo.FLAG_PERSISTENT)) == 23108 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23109 : false; 23110 } 23111 } 23112 23113 @Override 23114 public List<PackageInfo> getOverlayPackages(int userId) { 23115 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23116 synchronized (mPackages) { 23117 for (PackageParser.Package p : mPackages.values()) { 23118 if (p.mOverlayTarget != null) { 23119 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23120 if (pkg != null) { 23121 overlayPackages.add(pkg); 23122 } 23123 } 23124 } 23125 } 23126 return overlayPackages; 23127 } 23128 23129 @Override 23130 public List<String> getTargetPackageNames(int userId) { 23131 List<String> targetPackages = new ArrayList<>(); 23132 synchronized (mPackages) { 23133 for (PackageParser.Package p : mPackages.values()) { 23134 if (p.mOverlayTarget == null) { 23135 targetPackages.add(p.packageName); 23136 } 23137 } 23138 } 23139 return targetPackages; 23140 } 23141 23142 @Override 23143 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23144 @Nullable List<String> overlayPackageNames) { 23145 synchronized (mPackages) { 23146 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23147 Slog.e(TAG, "failed to find package " + targetPackageName); 23148 return false; 23149 } 23150 23151 ArrayList<String> paths = null; 23152 if (overlayPackageNames != null) { 23153 final int N = overlayPackageNames.size(); 23154 paths = new ArrayList<>(N); 23155 for (int i = 0; i < N; i++) { 23156 final String packageName = overlayPackageNames.get(i); 23157 final PackageParser.Package pkg = mPackages.get(packageName); 23158 if (pkg == null) { 23159 Slog.e(TAG, "failed to find package " + packageName); 23160 return false; 23161 } 23162 paths.add(pkg.baseCodePath); 23163 } 23164 } 23165 23166 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23167 mEnabledOverlayPaths.get(userId); 23168 if (userSpecificOverlays == null) { 23169 userSpecificOverlays = new ArrayMap<>(); 23170 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23171 } 23172 23173 if (paths != null && paths.size() > 0) { 23174 userSpecificOverlays.put(targetPackageName, paths); 23175 } else { 23176 userSpecificOverlays.remove(targetPackageName); 23177 } 23178 return true; 23179 } 23180 } 23181 23182 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23183 int flags, int userId) { 23184 return resolveIntentInternal( 23185 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23186 } 23187 } 23188 23189 @Override 23190 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23191 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23192 synchronized (mPackages) { 23193 final long identity = Binder.clearCallingIdentity(); 23194 try { 23195 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23196 packageNames, userId); 23197 } finally { 23198 Binder.restoreCallingIdentity(identity); 23199 } 23200 } 23201 } 23202 23203 @Override 23204 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23205 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23206 synchronized (mPackages) { 23207 final long identity = Binder.clearCallingIdentity(); 23208 try { 23209 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23210 packageNames, userId); 23211 } finally { 23212 Binder.restoreCallingIdentity(identity); 23213 } 23214 } 23215 } 23216 23217 private static void enforceSystemOrPhoneCaller(String tag) { 23218 int callingUid = Binder.getCallingUid(); 23219 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23220 throw new SecurityException( 23221 "Cannot call " + tag + " from UID " + callingUid); 23222 } 23223 } 23224 23225 boolean isHistoricalPackageUsageAvailable() { 23226 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23227 } 23228 23229 /** 23230 * Return a <b>copy</b> of the collection of packages known to the package manager. 23231 * @return A copy of the values of mPackages. 23232 */ 23233 Collection<PackageParser.Package> getPackages() { 23234 synchronized (mPackages) { 23235 return new ArrayList<>(mPackages.values()); 23236 } 23237 } 23238 23239 /** 23240 * Logs process start information (including base APK hash) to the security log. 23241 * @hide 23242 */ 23243 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23244 String apkFile, int pid) { 23245 if (!SecurityLog.isLoggingEnabled()) { 23246 return; 23247 } 23248 Bundle data = new Bundle(); 23249 data.putLong("startTimestamp", System.currentTimeMillis()); 23250 data.putString("processName", processName); 23251 data.putInt("uid", uid); 23252 data.putString("seinfo", seinfo); 23253 data.putString("apkFile", apkFile); 23254 data.putInt("pid", pid); 23255 Message msg = mProcessLoggingHandler.obtainMessage( 23256 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23257 msg.setData(data); 23258 mProcessLoggingHandler.sendMessage(msg); 23259 } 23260 23261 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23262 return mCompilerStats.getPackageStats(pkgName); 23263 } 23264 23265 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23266 return getOrCreateCompilerPackageStats(pkg.packageName); 23267 } 23268 23269 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23270 return mCompilerStats.getOrCreatePackageStats(pkgName); 23271 } 23272 23273 public void deleteCompilerPackageStats(String pkgName) { 23274 mCompilerStats.deletePackageStats(pkgName); 23275 } 23276 23277 @Override 23278 public int getInstallReason(String packageName, int userId) { 23279 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23280 true /* requireFullPermission */, false /* checkShell */, 23281 "get install reason"); 23282 synchronized (mPackages) { 23283 final PackageSetting ps = mSettings.mPackages.get(packageName); 23284 if (ps != null) { 23285 return ps.getInstallReason(userId); 23286 } 23287 } 23288 return PackageManager.INSTALL_REASON_UNKNOWN; 23289 } 23290 23291 @Override 23292 public boolean canRequestPackageInstalls(String packageName, int userId) { 23293 int callingUid = Binder.getCallingUid(); 23294 int uid = getPackageUid(packageName, 0, userId); 23295 if (callingUid != uid && callingUid != Process.ROOT_UID 23296 && callingUid != Process.SYSTEM_UID) { 23297 throw new SecurityException( 23298 "Caller uid " + callingUid + " does not own package " + packageName); 23299 } 23300 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23301 if (info == null) { 23302 return false; 23303 } 23304 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23305 throw new UnsupportedOperationException( 23306 "Operation only supported on apps targeting Android O or higher"); 23307 } 23308 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23309 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23310 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23311 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23312 } 23313 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23314 return false; 23315 } 23316 if (mExternalSourcesPolicy != null) { 23317 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23318 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23319 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23320 } 23321 } 23322 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23323 } 23324 23325 @Override 23326 public ComponentName getInstantAppResolverSettingsComponent() { 23327 return mInstantAppResolverSettingsComponent; 23328 } 23329} 23330