PackageManagerService.java revision 90978b4159dd1394c0643ae8171d24668fbc27a4
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_SHARED_APK = 5; 541 public static final int REASON_FORCED_DEXOPT = 6; 542 543 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 544 545 /** All dangerous permission names in the same order as the events in MetricsEvent */ 546 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 547 Manifest.permission.READ_CALENDAR, 548 Manifest.permission.WRITE_CALENDAR, 549 Manifest.permission.CAMERA, 550 Manifest.permission.READ_CONTACTS, 551 Manifest.permission.WRITE_CONTACTS, 552 Manifest.permission.GET_ACCOUNTS, 553 Manifest.permission.ACCESS_FINE_LOCATION, 554 Manifest.permission.ACCESS_COARSE_LOCATION, 555 Manifest.permission.RECORD_AUDIO, 556 Manifest.permission.READ_PHONE_STATE, 557 Manifest.permission.CALL_PHONE, 558 Manifest.permission.READ_CALL_LOG, 559 Manifest.permission.WRITE_CALL_LOG, 560 Manifest.permission.ADD_VOICEMAIL, 561 Manifest.permission.USE_SIP, 562 Manifest.permission.PROCESS_OUTGOING_CALLS, 563 Manifest.permission.READ_CELL_BROADCASTS, 564 Manifest.permission.BODY_SENSORS, 565 Manifest.permission.SEND_SMS, 566 Manifest.permission.RECEIVE_SMS, 567 Manifest.permission.READ_SMS, 568 Manifest.permission.RECEIVE_WAP_PUSH, 569 Manifest.permission.RECEIVE_MMS, 570 Manifest.permission.READ_EXTERNAL_STORAGE, 571 Manifest.permission.WRITE_EXTERNAL_STORAGE, 572 Manifest.permission.READ_PHONE_NUMBER, 573 Manifest.permission.ANSWER_PHONE_CALLS); 574 575 576 /** 577 * Version number for the package parser cache. Increment this whenever the format or 578 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 579 */ 580 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 581 582 /** 583 * Whether the package parser cache is enabled. 584 */ 585 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 586 587 final ServiceThread mHandlerThread; 588 589 final PackageHandler mHandler; 590 591 private final ProcessLoggingHandler mProcessLoggingHandler; 592 593 /** 594 * Messages for {@link #mHandler} that need to wait for system ready before 595 * being dispatched. 596 */ 597 private ArrayList<Message> mPostSystemReadyMessages; 598 599 final int mSdkVersion = Build.VERSION.SDK_INT; 600 601 final Context mContext; 602 final boolean mFactoryTest; 603 final boolean mOnlyCore; 604 final DisplayMetrics mMetrics; 605 final int mDefParseFlags; 606 final String[] mSeparateProcesses; 607 final boolean mIsUpgrade; 608 final boolean mIsPreNUpgrade; 609 final boolean mIsPreNMR1Upgrade; 610 611 @GuardedBy("mPackages") 612 private boolean mDexOptDialogShown; 613 614 /** The location for ASEC container files on internal storage. */ 615 final String mAsecInternalPath; 616 617 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 618 // LOCK HELD. Can be called with mInstallLock held. 619 @GuardedBy("mInstallLock") 620 final Installer mInstaller; 621 622 /** Directory where installed third-party apps stored */ 623 final File mAppInstallDir; 624 625 /** 626 * Directory to which applications installed internally have their 627 * 32 bit native libraries copied. 628 */ 629 private File mAppLib32InstallDir; 630 631 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 632 // apps. 633 final File mDrmAppPrivateInstallDir; 634 635 // ---------------------------------------------------------------- 636 637 // Lock for state used when installing and doing other long running 638 // operations. Methods that must be called with this lock held have 639 // the suffix "LI". 640 final Object mInstallLock = new Object(); 641 642 // ---------------------------------------------------------------- 643 644 // Keys are String (package name), values are Package. This also serves 645 // as the lock for the global state. Methods that must be called with 646 // this lock held have the prefix "LP". 647 @GuardedBy("mPackages") 648 final ArrayMap<String, PackageParser.Package> mPackages = 649 new ArrayMap<String, PackageParser.Package>(); 650 651 final ArrayMap<String, Set<String>> mKnownCodebase = 652 new ArrayMap<String, Set<String>>(); 653 654 // List of APK paths to load for each user and package. This data is never 655 // persisted by the package manager. Instead, the overlay manager will 656 // ensure the data is up-to-date in runtime. 657 @GuardedBy("mPackages") 658 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 659 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 660 661 /** 662 * Tracks new system packages [received in an OTA] that we expect to 663 * find updated user-installed versions. Keys are package name, values 664 * are package location. 665 */ 666 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 667 /** 668 * Tracks high priority intent filters for protected actions. During boot, certain 669 * filter actions are protected and should never be allowed to have a high priority 670 * intent filter for them. However, there is one, and only one exception -- the 671 * setup wizard. It must be able to define a high priority intent filter for these 672 * actions to ensure there are no escapes from the wizard. We need to delay processing 673 * of these during boot as we need to look at all of the system packages in order 674 * to know which component is the setup wizard. 675 */ 676 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 677 /** 678 * Whether or not processing protected filters should be deferred. 679 */ 680 private boolean mDeferProtectedFilters = true; 681 682 /** 683 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 684 */ 685 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 686 /** 687 * Whether or not system app permissions should be promoted from install to runtime. 688 */ 689 boolean mPromoteSystemApps; 690 691 @GuardedBy("mPackages") 692 final Settings mSettings; 693 694 /** 695 * Set of package names that are currently "frozen", which means active 696 * surgery is being done on the code/data for that package. The platform 697 * will refuse to launch frozen packages to avoid race conditions. 698 * 699 * @see PackageFreezer 700 */ 701 @GuardedBy("mPackages") 702 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 703 704 final ProtectedPackages mProtectedPackages; 705 706 boolean mFirstBoot; 707 708 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 709 710 // System configuration read by SystemConfig. 711 final int[] mGlobalGids; 712 final SparseArray<ArraySet<String>> mSystemPermissions; 713 @GuardedBy("mAvailableFeatures") 714 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 715 716 // If mac_permissions.xml was found for seinfo labeling. 717 boolean mFoundPolicyFile; 718 719 private final InstantAppRegistry mInstantAppRegistry; 720 721 @GuardedBy("mPackages") 722 int mChangedPackagesSequenceNumber; 723 /** 724 * List of changed [installed, removed or updated] packages. 725 * mapping from user id -> sequence number -> package name 726 */ 727 @GuardedBy("mPackages") 728 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 729 /** 730 * The sequence number of the last change to a package. 731 * mapping from user id -> package name -> sequence number 732 */ 733 @GuardedBy("mPackages") 734 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 735 736 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 737 @Override public boolean hasFeature(String feature) { 738 return PackageManagerService.this.hasSystemFeature(feature, 0); 739 } 740 }; 741 742 public static final class SharedLibraryEntry { 743 public final String path; 744 public final String apk; 745 public final SharedLibraryInfo info; 746 747 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 748 String declaringPackageName, int declaringPackageVersionCode) { 749 path = _path; 750 apk = _apk; 751 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 752 declaringPackageName, declaringPackageVersionCode), null); 753 } 754 } 755 756 // Currently known shared libraries. 757 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 758 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 759 new ArrayMap<>(); 760 761 // All available activities, for your resolving pleasure. 762 final ActivityIntentResolver mActivities = 763 new ActivityIntentResolver(); 764 765 // All available receivers, for your resolving pleasure. 766 final ActivityIntentResolver mReceivers = 767 new ActivityIntentResolver(); 768 769 // All available services, for your resolving pleasure. 770 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 771 772 // All available providers, for your resolving pleasure. 773 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 774 775 // Mapping from provider base names (first directory in content URI codePath) 776 // to the provider information. 777 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 778 new ArrayMap<String, PackageParser.Provider>(); 779 780 // Mapping from instrumentation class names to info about them. 781 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 782 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 783 784 // Mapping from permission names to info about them. 785 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 786 new ArrayMap<String, PackageParser.PermissionGroup>(); 787 788 // Packages whose data we have transfered into another package, thus 789 // should no longer exist. 790 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 791 792 // Broadcast actions that are only available to the system. 793 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 794 795 /** List of packages waiting for verification. */ 796 final SparseArray<PackageVerificationState> mPendingVerification 797 = new SparseArray<PackageVerificationState>(); 798 799 /** Set of packages associated with each app op permission. */ 800 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 801 802 final PackageInstallerService mInstallerService; 803 804 private final PackageDexOptimizer mPackageDexOptimizer; 805 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 806 // is used by other apps). 807 private final DexManager mDexManager; 808 809 private AtomicInteger mNextMoveId = new AtomicInteger(); 810 private final MoveCallbacks mMoveCallbacks; 811 812 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 813 814 // Cache of users who need badging. 815 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 816 817 /** Token for keys in mPendingVerification. */ 818 private int mPendingVerificationToken = 0; 819 820 volatile boolean mSystemReady; 821 volatile boolean mSafeMode; 822 volatile boolean mHasSystemUidErrors; 823 824 ApplicationInfo mAndroidApplication; 825 final ActivityInfo mResolveActivity = new ActivityInfo(); 826 final ResolveInfo mResolveInfo = new ResolveInfo(); 827 ComponentName mResolveComponentName; 828 PackageParser.Package mPlatformPackage; 829 ComponentName mCustomResolverComponentName; 830 831 boolean mResolverReplaced = false; 832 833 private final @Nullable ComponentName mIntentFilterVerifierComponent; 834 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 835 836 private int mIntentFilterVerificationToken = 0; 837 838 /** The service connection to the ephemeral resolver */ 839 final EphemeralResolverConnection mInstantAppResolverConnection; 840 841 /** Component used to install ephemeral applications */ 842 ComponentName mInstantAppInstallerComponent; 843 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 844 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 845 846 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 847 = new SparseArray<IntentFilterVerificationState>(); 848 849 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 850 851 // List of packages names to keep cached, even if they are uninstalled for all users 852 private List<String> mKeepUninstalledPackages; 853 854 private UserManagerInternal mUserManagerInternal; 855 856 private DeviceIdleController.LocalService mDeviceIdleController; 857 858 private File mCacheDir; 859 860 private ArraySet<String> mPrivappPermissionsViolations; 861 862 private Future<?> mPrepareAppDataFuture; 863 864 private static class IFVerificationParams { 865 PackageParser.Package pkg; 866 boolean replacing; 867 int userId; 868 int verifierUid; 869 870 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 871 int _userId, int _verifierUid) { 872 pkg = _pkg; 873 replacing = _replacing; 874 userId = _userId; 875 replacing = _replacing; 876 verifierUid = _verifierUid; 877 } 878 } 879 880 private interface IntentFilterVerifier<T extends IntentFilter> { 881 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 882 T filter, String packageName); 883 void startVerifications(int userId); 884 void receiveVerificationResponse(int verificationId); 885 } 886 887 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 888 private Context mContext; 889 private ComponentName mIntentFilterVerifierComponent; 890 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 891 892 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 893 mContext = context; 894 mIntentFilterVerifierComponent = verifierComponent; 895 } 896 897 private String getDefaultScheme() { 898 return IntentFilter.SCHEME_HTTPS; 899 } 900 901 @Override 902 public void startVerifications(int userId) { 903 // Launch verifications requests 904 int count = mCurrentIntentFilterVerifications.size(); 905 for (int n=0; n<count; n++) { 906 int verificationId = mCurrentIntentFilterVerifications.get(n); 907 final IntentFilterVerificationState ivs = 908 mIntentFilterVerificationStates.get(verificationId); 909 910 String packageName = ivs.getPackageName(); 911 912 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 913 final int filterCount = filters.size(); 914 ArraySet<String> domainsSet = new ArraySet<>(); 915 for (int m=0; m<filterCount; m++) { 916 PackageParser.ActivityIntentInfo filter = filters.get(m); 917 domainsSet.addAll(filter.getHostsList()); 918 } 919 synchronized (mPackages) { 920 if (mSettings.createIntentFilterVerificationIfNeededLPw( 921 packageName, domainsSet) != null) { 922 scheduleWriteSettingsLocked(); 923 } 924 } 925 sendVerificationRequest(userId, verificationId, ivs); 926 } 927 mCurrentIntentFilterVerifications.clear(); 928 } 929 930 private void sendVerificationRequest(int userId, int verificationId, 931 IntentFilterVerificationState ivs) { 932 933 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 934 verificationIntent.putExtra( 935 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 936 verificationId); 937 verificationIntent.putExtra( 938 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 939 getDefaultScheme()); 940 verificationIntent.putExtra( 941 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 942 ivs.getHostsString()); 943 verificationIntent.putExtra( 944 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 945 ivs.getPackageName()); 946 verificationIntent.setComponent(mIntentFilterVerifierComponent); 947 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 948 949 UserHandle user = new UserHandle(userId); 950 mContext.sendBroadcastAsUser(verificationIntent, user); 951 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 952 "Sending IntentFilter verification broadcast"); 953 } 954 955 public void receiveVerificationResponse(int verificationId) { 956 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 957 958 final boolean verified = ivs.isVerified(); 959 960 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 961 final int count = filters.size(); 962 if (DEBUG_DOMAIN_VERIFICATION) { 963 Slog.i(TAG, "Received verification response " + verificationId 964 + " for " + count + " filters, verified=" + verified); 965 } 966 for (int n=0; n<count; n++) { 967 PackageParser.ActivityIntentInfo filter = filters.get(n); 968 filter.setVerified(verified); 969 970 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 971 + " verified with result:" + verified + " and hosts:" 972 + ivs.getHostsString()); 973 } 974 975 mIntentFilterVerificationStates.remove(verificationId); 976 977 final String packageName = ivs.getPackageName(); 978 IntentFilterVerificationInfo ivi = null; 979 980 synchronized (mPackages) { 981 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 982 } 983 if (ivi == null) { 984 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 985 + verificationId + " packageName:" + packageName); 986 return; 987 } 988 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 989 "Updating IntentFilterVerificationInfo for package " + packageName 990 +" verificationId:" + verificationId); 991 992 synchronized (mPackages) { 993 if (verified) { 994 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 995 } else { 996 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 997 } 998 scheduleWriteSettingsLocked(); 999 1000 final int userId = ivs.getUserId(); 1001 if (userId != UserHandle.USER_ALL) { 1002 final int userStatus = 1003 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1004 1005 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1006 boolean needUpdate = false; 1007 1008 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1009 // already been set by the User thru the Disambiguation dialog 1010 switch (userStatus) { 1011 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1012 if (verified) { 1013 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1014 } else { 1015 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1016 } 1017 needUpdate = true; 1018 break; 1019 1020 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1021 if (verified) { 1022 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1023 needUpdate = true; 1024 } 1025 break; 1026 1027 default: 1028 // Nothing to do 1029 } 1030 1031 if (needUpdate) { 1032 mSettings.updateIntentFilterVerificationStatusLPw( 1033 packageName, updatedStatus, userId); 1034 scheduleWritePackageRestrictionsLocked(userId); 1035 } 1036 } 1037 } 1038 } 1039 1040 @Override 1041 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1042 ActivityIntentInfo filter, String packageName) { 1043 if (!hasValidDomains(filter)) { 1044 return false; 1045 } 1046 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1047 if (ivs == null) { 1048 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1049 packageName); 1050 } 1051 if (DEBUG_DOMAIN_VERIFICATION) { 1052 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1053 } 1054 ivs.addFilter(filter); 1055 return true; 1056 } 1057 1058 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1059 int userId, int verificationId, String packageName) { 1060 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1061 verifierUid, userId, packageName); 1062 ivs.setPendingState(); 1063 synchronized (mPackages) { 1064 mIntentFilterVerificationStates.append(verificationId, ivs); 1065 mCurrentIntentFilterVerifications.add(verificationId); 1066 } 1067 return ivs; 1068 } 1069 } 1070 1071 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1072 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1073 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1074 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1075 } 1076 1077 // Set of pending broadcasts for aggregating enable/disable of components. 1078 static class PendingPackageBroadcasts { 1079 // for each user id, a map of <package name -> components within that package> 1080 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1081 1082 public PendingPackageBroadcasts() { 1083 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1084 } 1085 1086 public ArrayList<String> get(int userId, String packageName) { 1087 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1088 return packages.get(packageName); 1089 } 1090 1091 public void put(int userId, String packageName, ArrayList<String> components) { 1092 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1093 packages.put(packageName, components); 1094 } 1095 1096 public void remove(int userId, String packageName) { 1097 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1098 if (packages != null) { 1099 packages.remove(packageName); 1100 } 1101 } 1102 1103 public void remove(int userId) { 1104 mUidMap.remove(userId); 1105 } 1106 1107 public int userIdCount() { 1108 return mUidMap.size(); 1109 } 1110 1111 public int userIdAt(int n) { 1112 return mUidMap.keyAt(n); 1113 } 1114 1115 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1116 return mUidMap.get(userId); 1117 } 1118 1119 public int size() { 1120 // total number of pending broadcast entries across all userIds 1121 int num = 0; 1122 for (int i = 0; i< mUidMap.size(); i++) { 1123 num += mUidMap.valueAt(i).size(); 1124 } 1125 return num; 1126 } 1127 1128 public void clear() { 1129 mUidMap.clear(); 1130 } 1131 1132 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1133 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1134 if (map == null) { 1135 map = new ArrayMap<String, ArrayList<String>>(); 1136 mUidMap.put(userId, map); 1137 } 1138 return map; 1139 } 1140 } 1141 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1142 1143 // Service Connection to remote media container service to copy 1144 // package uri's from external media onto secure containers 1145 // or internal storage. 1146 private IMediaContainerService mContainerService = null; 1147 1148 static final int SEND_PENDING_BROADCAST = 1; 1149 static final int MCS_BOUND = 3; 1150 static final int END_COPY = 4; 1151 static final int INIT_COPY = 5; 1152 static final int MCS_UNBIND = 6; 1153 static final int START_CLEANING_PACKAGE = 7; 1154 static final int FIND_INSTALL_LOC = 8; 1155 static final int POST_INSTALL = 9; 1156 static final int MCS_RECONNECT = 10; 1157 static final int MCS_GIVE_UP = 11; 1158 static final int UPDATED_MEDIA_STATUS = 12; 1159 static final int WRITE_SETTINGS = 13; 1160 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1161 static final int PACKAGE_VERIFIED = 15; 1162 static final int CHECK_PENDING_VERIFICATION = 16; 1163 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1164 static final int INTENT_FILTER_VERIFIED = 18; 1165 static final int WRITE_PACKAGE_LIST = 19; 1166 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1167 1168 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1169 1170 // Delay time in millisecs 1171 static final int BROADCAST_DELAY = 10 * 1000; 1172 1173 static UserManagerService sUserManager; 1174 1175 // Stores a list of users whose package restrictions file needs to be updated 1176 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1177 1178 final private DefaultContainerConnection mDefContainerConn = 1179 new DefaultContainerConnection(); 1180 class DefaultContainerConnection implements ServiceConnection { 1181 public void onServiceConnected(ComponentName name, IBinder service) { 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1183 final IMediaContainerService imcs = IMediaContainerService.Stub 1184 .asInterface(Binder.allowBlocking(service)); 1185 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1186 } 1187 1188 public void onServiceDisconnected(ComponentName name) { 1189 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1190 } 1191 } 1192 1193 // Recordkeeping of restore-after-install operations that are currently in flight 1194 // between the Package Manager and the Backup Manager 1195 static class PostInstallData { 1196 public InstallArgs args; 1197 public PackageInstalledInfo res; 1198 1199 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1200 args = _a; 1201 res = _r; 1202 } 1203 } 1204 1205 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1206 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1207 1208 // XML tags for backup/restore of various bits of state 1209 private static final String TAG_PREFERRED_BACKUP = "pa"; 1210 private static final String TAG_DEFAULT_APPS = "da"; 1211 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1212 1213 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1214 private static final String TAG_ALL_GRANTS = "rt-grants"; 1215 private static final String TAG_GRANT = "grant"; 1216 private static final String ATTR_PACKAGE_NAME = "pkg"; 1217 1218 private static final String TAG_PERMISSION = "perm"; 1219 private static final String ATTR_PERMISSION_NAME = "name"; 1220 private static final String ATTR_IS_GRANTED = "g"; 1221 private static final String ATTR_USER_SET = "set"; 1222 private static final String ATTR_USER_FIXED = "fixed"; 1223 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1224 1225 // System/policy permission grants are not backed up 1226 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1227 FLAG_PERMISSION_POLICY_FIXED 1228 | FLAG_PERMISSION_SYSTEM_FIXED 1229 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1230 1231 // And we back up these user-adjusted states 1232 private static final int USER_RUNTIME_GRANT_MASK = 1233 FLAG_PERMISSION_USER_SET 1234 | FLAG_PERMISSION_USER_FIXED 1235 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1236 1237 final @Nullable String mRequiredVerifierPackage; 1238 final @NonNull String mRequiredInstallerPackage; 1239 final @NonNull String mRequiredUninstallerPackage; 1240 final @Nullable String mSetupWizardPackage; 1241 final @Nullable String mStorageManagerPackage; 1242 final @NonNull String mServicesSystemSharedLibraryPackageName; 1243 final @NonNull String mSharedSystemSharedLibraryPackageName; 1244 1245 final boolean mPermissionReviewRequired; 1246 1247 private final PackageUsage mPackageUsage = new PackageUsage(); 1248 private final CompilerStats mCompilerStats = new CompilerStats(); 1249 1250 class PackageHandler extends Handler { 1251 private boolean mBound = false; 1252 final ArrayList<HandlerParams> mPendingInstalls = 1253 new ArrayList<HandlerParams>(); 1254 1255 private boolean connectToService() { 1256 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1257 " DefaultContainerService"); 1258 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1260 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1261 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1263 mBound = true; 1264 return true; 1265 } 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1267 return false; 1268 } 1269 1270 private void disconnectService() { 1271 mContainerService = null; 1272 mBound = false; 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1274 mContext.unbindService(mDefContainerConn); 1275 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1276 } 1277 1278 PackageHandler(Looper looper) { 1279 super(looper); 1280 } 1281 1282 public void handleMessage(Message msg) { 1283 try { 1284 doHandleMessage(msg); 1285 } finally { 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1287 } 1288 } 1289 1290 void doHandleMessage(Message msg) { 1291 switch (msg.what) { 1292 case INIT_COPY: { 1293 HandlerParams params = (HandlerParams) msg.obj; 1294 int idx = mPendingInstalls.size(); 1295 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1296 // If a bind was already initiated we dont really 1297 // need to do anything. The pending install 1298 // will be processed later on. 1299 if (!mBound) { 1300 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1301 System.identityHashCode(mHandler)); 1302 // If this is the only one pending we might 1303 // have to bind to the service again. 1304 if (!connectToService()) { 1305 Slog.e(TAG, "Failed to bind to media container service"); 1306 params.serviceError(); 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1308 System.identityHashCode(mHandler)); 1309 if (params.traceMethod != null) { 1310 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1311 params.traceCookie); 1312 } 1313 return; 1314 } else { 1315 // Once we bind to the service, the first 1316 // pending request will be processed. 1317 mPendingInstalls.add(idx, params); 1318 } 1319 } else { 1320 mPendingInstalls.add(idx, params); 1321 // Already bound to the service. Just make 1322 // sure we trigger off processing the first request. 1323 if (idx == 0) { 1324 mHandler.sendEmptyMessage(MCS_BOUND); 1325 } 1326 } 1327 break; 1328 } 1329 case MCS_BOUND: { 1330 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1331 if (msg.obj != null) { 1332 mContainerService = (IMediaContainerService) msg.obj; 1333 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1334 System.identityHashCode(mHandler)); 1335 } 1336 if (mContainerService == null) { 1337 if (!mBound) { 1338 // Something seriously wrong since we are not bound and we are not 1339 // waiting for connection. Bail out. 1340 Slog.e(TAG, "Cannot bind to media container service"); 1341 for (HandlerParams params : mPendingInstalls) { 1342 // Indicate service bind error 1343 params.serviceError(); 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1345 System.identityHashCode(params)); 1346 if (params.traceMethod != null) { 1347 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1348 params.traceMethod, params.traceCookie); 1349 } 1350 return; 1351 } 1352 mPendingInstalls.clear(); 1353 } else { 1354 Slog.w(TAG, "Waiting to connect to media container service"); 1355 } 1356 } else if (mPendingInstalls.size() > 0) { 1357 HandlerParams params = mPendingInstalls.get(0); 1358 if (params != null) { 1359 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1360 System.identityHashCode(params)); 1361 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1362 if (params.startCopy()) { 1363 // We are done... look for more work or to 1364 // go idle. 1365 if (DEBUG_SD_INSTALL) Log.i(TAG, 1366 "Checking for more work or unbind..."); 1367 // Delete pending install 1368 if (mPendingInstalls.size() > 0) { 1369 mPendingInstalls.remove(0); 1370 } 1371 if (mPendingInstalls.size() == 0) { 1372 if (mBound) { 1373 if (DEBUG_SD_INSTALL) Log.i(TAG, 1374 "Posting delayed MCS_UNBIND"); 1375 removeMessages(MCS_UNBIND); 1376 Message ubmsg = obtainMessage(MCS_UNBIND); 1377 // Unbind after a little delay, to avoid 1378 // continual thrashing. 1379 sendMessageDelayed(ubmsg, 10000); 1380 } 1381 } else { 1382 // There are more pending requests in queue. 1383 // Just post MCS_BOUND message to trigger processing 1384 // of next pending install. 1385 if (DEBUG_SD_INSTALL) Log.i(TAG, 1386 "Posting MCS_BOUND for next work"); 1387 mHandler.sendEmptyMessage(MCS_BOUND); 1388 } 1389 } 1390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1391 } 1392 } else { 1393 // Should never happen ideally. 1394 Slog.w(TAG, "Empty queue"); 1395 } 1396 break; 1397 } 1398 case MCS_RECONNECT: { 1399 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1400 if (mPendingInstalls.size() > 0) { 1401 if (mBound) { 1402 disconnectService(); 1403 } 1404 if (!connectToService()) { 1405 Slog.e(TAG, "Failed to bind to media container service"); 1406 for (HandlerParams params : mPendingInstalls) { 1407 // Indicate service bind error 1408 params.serviceError(); 1409 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1410 System.identityHashCode(params)); 1411 } 1412 mPendingInstalls.clear(); 1413 } 1414 } 1415 break; 1416 } 1417 case MCS_UNBIND: { 1418 // If there is no actual work left, then time to unbind. 1419 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1420 1421 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1422 if (mBound) { 1423 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1424 1425 disconnectService(); 1426 } 1427 } else if (mPendingInstalls.size() > 0) { 1428 // There are more pending requests in queue. 1429 // Just post MCS_BOUND message to trigger processing 1430 // of next pending install. 1431 mHandler.sendEmptyMessage(MCS_BOUND); 1432 } 1433 1434 break; 1435 } 1436 case MCS_GIVE_UP: { 1437 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1438 HandlerParams params = mPendingInstalls.remove(0); 1439 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1440 System.identityHashCode(params)); 1441 break; 1442 } 1443 case SEND_PENDING_BROADCAST: { 1444 String packages[]; 1445 ArrayList<String> components[]; 1446 int size = 0; 1447 int uids[]; 1448 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1449 synchronized (mPackages) { 1450 if (mPendingBroadcasts == null) { 1451 return; 1452 } 1453 size = mPendingBroadcasts.size(); 1454 if (size <= 0) { 1455 // Nothing to be done. Just return 1456 return; 1457 } 1458 packages = new String[size]; 1459 components = new ArrayList[size]; 1460 uids = new int[size]; 1461 int i = 0; // filling out the above arrays 1462 1463 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1464 int packageUserId = mPendingBroadcasts.userIdAt(n); 1465 Iterator<Map.Entry<String, ArrayList<String>>> it 1466 = mPendingBroadcasts.packagesForUserId(packageUserId) 1467 .entrySet().iterator(); 1468 while (it.hasNext() && i < size) { 1469 Map.Entry<String, ArrayList<String>> ent = it.next(); 1470 packages[i] = ent.getKey(); 1471 components[i] = ent.getValue(); 1472 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1473 uids[i] = (ps != null) 1474 ? UserHandle.getUid(packageUserId, ps.appId) 1475 : -1; 1476 i++; 1477 } 1478 } 1479 size = i; 1480 mPendingBroadcasts.clear(); 1481 } 1482 // Send broadcasts 1483 for (int i = 0; i < size; i++) { 1484 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1485 } 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1487 break; 1488 } 1489 case START_CLEANING_PACKAGE: { 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1491 final String packageName = (String)msg.obj; 1492 final int userId = msg.arg1; 1493 final boolean andCode = msg.arg2 != 0; 1494 synchronized (mPackages) { 1495 if (userId == UserHandle.USER_ALL) { 1496 int[] users = sUserManager.getUserIds(); 1497 for (int user : users) { 1498 mSettings.addPackageToCleanLPw( 1499 new PackageCleanItem(user, packageName, andCode)); 1500 } 1501 } else { 1502 mSettings.addPackageToCleanLPw( 1503 new PackageCleanItem(userId, packageName, andCode)); 1504 } 1505 } 1506 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1507 startCleaningPackages(); 1508 } break; 1509 case POST_INSTALL: { 1510 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1511 1512 PostInstallData data = mRunningInstalls.get(msg.arg1); 1513 final boolean didRestore = (msg.arg2 != 0); 1514 mRunningInstalls.delete(msg.arg1); 1515 1516 if (data != null) { 1517 InstallArgs args = data.args; 1518 PackageInstalledInfo parentRes = data.res; 1519 1520 final boolean grantPermissions = (args.installFlags 1521 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1522 final boolean killApp = (args.installFlags 1523 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1524 final String[] grantedPermissions = args.installGrantPermissions; 1525 1526 // Handle the parent package 1527 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1528 grantedPermissions, didRestore, args.installerPackageName, 1529 args.observer); 1530 1531 // Handle the child packages 1532 final int childCount = (parentRes.addedChildPackages != null) 1533 ? parentRes.addedChildPackages.size() : 0; 1534 for (int i = 0; i < childCount; i++) { 1535 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1536 handlePackagePostInstall(childRes, grantPermissions, killApp, 1537 grantedPermissions, false, args.installerPackageName, 1538 args.observer); 1539 } 1540 1541 // Log tracing if needed 1542 if (args.traceMethod != null) { 1543 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1544 args.traceCookie); 1545 } 1546 } else { 1547 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1548 } 1549 1550 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1551 } break; 1552 case UPDATED_MEDIA_STATUS: { 1553 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1554 boolean reportStatus = msg.arg1 == 1; 1555 boolean doGc = msg.arg2 == 1; 1556 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1557 if (doGc) { 1558 // Force a gc to clear up stale containers. 1559 Runtime.getRuntime().gc(); 1560 } 1561 if (msg.obj != null) { 1562 @SuppressWarnings("unchecked") 1563 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1565 // Unload containers 1566 unloadAllContainers(args); 1567 } 1568 if (reportStatus) { 1569 try { 1570 if (DEBUG_SD_INSTALL) Log.i(TAG, 1571 "Invoking StorageManagerService call back"); 1572 PackageHelper.getStorageManager().finishMediaUpdate(); 1573 } catch (RemoteException e) { 1574 Log.e(TAG, "StorageManagerService not running?"); 1575 } 1576 } 1577 } break; 1578 case WRITE_SETTINGS: { 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1580 synchronized (mPackages) { 1581 removeMessages(WRITE_SETTINGS); 1582 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1583 mSettings.writeLPr(); 1584 mDirtyUsers.clear(); 1585 } 1586 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1587 } break; 1588 case WRITE_PACKAGE_RESTRICTIONS: { 1589 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1590 synchronized (mPackages) { 1591 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1592 for (int userId : mDirtyUsers) { 1593 mSettings.writePackageRestrictionsLPr(userId); 1594 } 1595 mDirtyUsers.clear(); 1596 } 1597 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1598 } break; 1599 case WRITE_PACKAGE_LIST: { 1600 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1601 synchronized (mPackages) { 1602 removeMessages(WRITE_PACKAGE_LIST); 1603 mSettings.writePackageListLPr(msg.arg1); 1604 } 1605 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1606 } break; 1607 case CHECK_PENDING_VERIFICATION: { 1608 final int verificationId = msg.arg1; 1609 final PackageVerificationState state = mPendingVerification.get(verificationId); 1610 1611 if ((state != null) && !state.timeoutExtended()) { 1612 final InstallArgs args = state.getInstallArgs(); 1613 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1614 1615 Slog.i(TAG, "Verification timed out for " + originUri); 1616 mPendingVerification.remove(verificationId); 1617 1618 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1619 1620 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1621 Slog.i(TAG, "Continuing with installation of " + originUri); 1622 state.setVerifierResponse(Binder.getCallingUid(), 1623 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1624 broadcastPackageVerified(verificationId, originUri, 1625 PackageManager.VERIFICATION_ALLOW, 1626 state.getInstallArgs().getUser()); 1627 try { 1628 ret = args.copyApk(mContainerService, true); 1629 } catch (RemoteException e) { 1630 Slog.e(TAG, "Could not contact the ContainerService"); 1631 } 1632 } else { 1633 broadcastPackageVerified(verificationId, originUri, 1634 PackageManager.VERIFICATION_REJECT, 1635 state.getInstallArgs().getUser()); 1636 } 1637 1638 Trace.asyncTraceEnd( 1639 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1640 1641 processPendingInstall(args, ret); 1642 mHandler.sendEmptyMessage(MCS_UNBIND); 1643 } 1644 break; 1645 } 1646 case PACKAGE_VERIFIED: { 1647 final int verificationId = msg.arg1; 1648 1649 final PackageVerificationState state = mPendingVerification.get(verificationId); 1650 if (state == null) { 1651 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1652 break; 1653 } 1654 1655 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1656 1657 state.setVerifierResponse(response.callerUid, response.code); 1658 1659 if (state.isVerificationComplete()) { 1660 mPendingVerification.remove(verificationId); 1661 1662 final InstallArgs args = state.getInstallArgs(); 1663 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1664 1665 int ret; 1666 if (state.isInstallAllowed()) { 1667 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1668 broadcastPackageVerified(verificationId, originUri, 1669 response.code, state.getInstallArgs().getUser()); 1670 try { 1671 ret = args.copyApk(mContainerService, true); 1672 } catch (RemoteException e) { 1673 Slog.e(TAG, "Could not contact the ContainerService"); 1674 } 1675 } else { 1676 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1677 } 1678 1679 Trace.asyncTraceEnd( 1680 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1681 1682 processPendingInstall(args, ret); 1683 mHandler.sendEmptyMessage(MCS_UNBIND); 1684 } 1685 1686 break; 1687 } 1688 case START_INTENT_FILTER_VERIFICATIONS: { 1689 IFVerificationParams params = (IFVerificationParams) msg.obj; 1690 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1691 params.replacing, params.pkg); 1692 break; 1693 } 1694 case INTENT_FILTER_VERIFIED: { 1695 final int verificationId = msg.arg1; 1696 1697 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1698 verificationId); 1699 if (state == null) { 1700 Slog.w(TAG, "Invalid IntentFilter verification token " 1701 + verificationId + " received"); 1702 break; 1703 } 1704 1705 final int userId = state.getUserId(); 1706 1707 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1708 "Processing IntentFilter verification with token:" 1709 + verificationId + " and userId:" + userId); 1710 1711 final IntentFilterVerificationResponse response = 1712 (IntentFilterVerificationResponse) msg.obj; 1713 1714 state.setVerifierResponse(response.callerUid, response.code); 1715 1716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1717 "IntentFilter verification with token:" + verificationId 1718 + " and userId:" + userId 1719 + " is settings verifier response with response code:" 1720 + response.code); 1721 1722 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1724 + response.getFailedDomainsString()); 1725 } 1726 1727 if (state.isVerificationComplete()) { 1728 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1729 } else { 1730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1731 "IntentFilter verification with token:" + verificationId 1732 + " was not said to be complete"); 1733 } 1734 1735 break; 1736 } 1737 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1738 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1739 mInstantAppResolverConnection, 1740 (InstantAppRequest) msg.obj, 1741 mInstantAppInstallerActivity, 1742 mHandler); 1743 } 1744 } 1745 } 1746 } 1747 1748 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1749 boolean killApp, String[] grantedPermissions, 1750 boolean launchedForRestore, String installerPackage, 1751 IPackageInstallObserver2 installObserver) { 1752 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1753 // Send the removed broadcasts 1754 if (res.removedInfo != null) { 1755 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1756 } 1757 1758 // Now that we successfully installed the package, grant runtime 1759 // permissions if requested before broadcasting the install. Also 1760 // for legacy apps in permission review mode we clear the permission 1761 // review flag which is used to emulate runtime permissions for 1762 // legacy apps. 1763 if (grantPermissions) { 1764 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1765 } 1766 1767 final boolean update = res.removedInfo != null 1768 && res.removedInfo.removedPackage != null; 1769 1770 // If this is the first time we have child packages for a disabled privileged 1771 // app that had no children, we grant requested runtime permissions to the new 1772 // children if the parent on the system image had them already granted. 1773 if (res.pkg.parentPackage != null) { 1774 synchronized (mPackages) { 1775 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1776 } 1777 } 1778 1779 synchronized (mPackages) { 1780 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1781 } 1782 1783 final String packageName = res.pkg.applicationInfo.packageName; 1784 1785 // Determine the set of users who are adding this package for 1786 // the first time vs. those who are seeing an update. 1787 int[] firstUsers = EMPTY_INT_ARRAY; 1788 int[] updateUsers = EMPTY_INT_ARRAY; 1789 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1790 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1791 for (int newUser : res.newUsers) { 1792 if (ps.getInstantApp(newUser)) { 1793 continue; 1794 } 1795 if (allNewUsers) { 1796 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1797 continue; 1798 } 1799 boolean isNew = true; 1800 for (int origUser : res.origUsers) { 1801 if (origUser == newUser) { 1802 isNew = false; 1803 break; 1804 } 1805 } 1806 if (isNew) { 1807 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1808 } else { 1809 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1810 } 1811 } 1812 1813 // Send installed broadcasts if the package is not a static shared lib. 1814 if (res.pkg.staticSharedLibName == null) { 1815 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1816 1817 // Send added for users that see the package for the first time 1818 // sendPackageAddedForNewUsers also deals with system apps 1819 int appId = UserHandle.getAppId(res.uid); 1820 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1821 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1822 1823 // Send added for users that don't see the package for the first time 1824 Bundle extras = new Bundle(1); 1825 extras.putInt(Intent.EXTRA_UID, res.uid); 1826 if (update) { 1827 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1828 } 1829 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1830 extras, 0 /*flags*/, null /*targetPackage*/, 1831 null /*finishedReceiver*/, updateUsers); 1832 1833 // Send replaced for users that don't see the package for the first time 1834 if (update) { 1835 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1836 packageName, extras, 0 /*flags*/, 1837 null /*targetPackage*/, null /*finishedReceiver*/, 1838 updateUsers); 1839 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1840 null /*package*/, null /*extras*/, 0 /*flags*/, 1841 packageName /*targetPackage*/, 1842 null /*finishedReceiver*/, updateUsers); 1843 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1844 // First-install and we did a restore, so we're responsible for the 1845 // first-launch broadcast. 1846 if (DEBUG_BACKUP) { 1847 Slog.i(TAG, "Post-restore of " + packageName 1848 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1849 } 1850 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1851 } 1852 1853 // Send broadcast package appeared if forward locked/external for all users 1854 // treat asec-hosted packages like removable media on upgrade 1855 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1856 if (DEBUG_INSTALL) { 1857 Slog.i(TAG, "upgrading pkg " + res.pkg 1858 + " is ASEC-hosted -> AVAILABLE"); 1859 } 1860 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1861 ArrayList<String> pkgList = new ArrayList<>(1); 1862 pkgList.add(packageName); 1863 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1864 } 1865 } 1866 1867 // Work that needs to happen on first install within each user 1868 if (firstUsers != null && firstUsers.length > 0) { 1869 synchronized (mPackages) { 1870 for (int userId : firstUsers) { 1871 // If this app is a browser and it's newly-installed for some 1872 // users, clear any default-browser state in those users. The 1873 // app's nature doesn't depend on the user, so we can just check 1874 // its browser nature in any user and generalize. 1875 if (packageIsBrowser(packageName, userId)) { 1876 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1877 } 1878 1879 // We may also need to apply pending (restored) runtime 1880 // permission grants within these users. 1881 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1882 } 1883 } 1884 } 1885 1886 // Log current value of "unknown sources" setting 1887 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1888 getUnknownSourcesSettings()); 1889 1890 // Force a gc to clear up things 1891 Runtime.getRuntime().gc(); 1892 1893 // Remove the replaced package's older resources safely now 1894 // We delete after a gc for applications on sdcard. 1895 if (res.removedInfo != null && res.removedInfo.args != null) { 1896 synchronized (mInstallLock) { 1897 res.removedInfo.args.doPostDeleteLI(true); 1898 } 1899 } 1900 1901 // Notify DexManager that the package was installed for new users. 1902 // The updated users should already be indexed and the package code paths 1903 // should not change. 1904 // Don't notify the manager for ephemeral apps as they are not expected to 1905 // survive long enough to benefit of background optimizations. 1906 for (int userId : firstUsers) { 1907 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1908 mDexManager.notifyPackageInstalled(info, userId); 1909 } 1910 } 1911 1912 // If someone is watching installs - notify them 1913 if (installObserver != null) { 1914 try { 1915 Bundle extras = extrasForInstallResult(res); 1916 installObserver.onPackageInstalled(res.name, res.returnCode, 1917 res.returnMsg, extras); 1918 } catch (RemoteException e) { 1919 Slog.i(TAG, "Observer no longer exists."); 1920 } 1921 } 1922 } 1923 1924 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1925 PackageParser.Package pkg) { 1926 if (pkg.parentPackage == null) { 1927 return; 1928 } 1929 if (pkg.requestedPermissions == null) { 1930 return; 1931 } 1932 final PackageSetting disabledSysParentPs = mSettings 1933 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1934 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1935 || !disabledSysParentPs.isPrivileged() 1936 || (disabledSysParentPs.childPackageNames != null 1937 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1938 return; 1939 } 1940 final int[] allUserIds = sUserManager.getUserIds(); 1941 final int permCount = pkg.requestedPermissions.size(); 1942 for (int i = 0; i < permCount; i++) { 1943 String permission = pkg.requestedPermissions.get(i); 1944 BasePermission bp = mSettings.mPermissions.get(permission); 1945 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1946 continue; 1947 } 1948 for (int userId : allUserIds) { 1949 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1950 permission, userId)) { 1951 grantRuntimePermission(pkg.packageName, permission, userId); 1952 } 1953 } 1954 } 1955 } 1956 1957 private StorageEventListener mStorageListener = new StorageEventListener() { 1958 @Override 1959 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1960 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1961 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1962 final String volumeUuid = vol.getFsUuid(); 1963 1964 // Clean up any users or apps that were removed or recreated 1965 // while this volume was missing 1966 sUserManager.reconcileUsers(volumeUuid); 1967 reconcileApps(volumeUuid); 1968 1969 // Clean up any install sessions that expired or were 1970 // cancelled while this volume was missing 1971 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1972 1973 loadPrivatePackages(vol); 1974 1975 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1976 unloadPrivatePackages(vol); 1977 } 1978 } 1979 1980 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1981 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1982 updateExternalMediaStatus(true, false); 1983 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1984 updateExternalMediaStatus(false, false); 1985 } 1986 } 1987 } 1988 1989 @Override 1990 public void onVolumeForgotten(String fsUuid) { 1991 if (TextUtils.isEmpty(fsUuid)) { 1992 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1993 return; 1994 } 1995 1996 // Remove any apps installed on the forgotten volume 1997 synchronized (mPackages) { 1998 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1999 for (PackageSetting ps : packages) { 2000 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2001 deletePackageVersioned(new VersionedPackage(ps.name, 2002 PackageManager.VERSION_CODE_HIGHEST), 2003 new LegacyPackageDeleteObserver(null).getBinder(), 2004 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2005 // Try very hard to release any references to this package 2006 // so we don't risk the system server being killed due to 2007 // open FDs 2008 AttributeCache.instance().removePackage(ps.name); 2009 } 2010 2011 mSettings.onVolumeForgotten(fsUuid); 2012 mSettings.writeLPr(); 2013 } 2014 } 2015 }; 2016 2017 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2018 String[] grantedPermissions) { 2019 for (int userId : userIds) { 2020 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2021 } 2022 } 2023 2024 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2025 String[] grantedPermissions) { 2026 SettingBase sb = (SettingBase) pkg.mExtras; 2027 if (sb == null) { 2028 return; 2029 } 2030 2031 PermissionsState permissionsState = sb.getPermissionsState(); 2032 2033 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2034 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2035 2036 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2037 >= Build.VERSION_CODES.M; 2038 2039 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2040 2041 for (String permission : pkg.requestedPermissions) { 2042 final BasePermission bp; 2043 synchronized (mPackages) { 2044 bp = mSettings.mPermissions.get(permission); 2045 } 2046 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2047 && (!instantApp || bp.isInstant()) 2048 && (grantedPermissions == null 2049 || ArrayUtils.contains(grantedPermissions, permission))) { 2050 final int flags = permissionsState.getPermissionFlags(permission, userId); 2051 if (supportsRuntimePermissions) { 2052 // Installer cannot change immutable permissions. 2053 if ((flags & immutableFlags) == 0) { 2054 grantRuntimePermission(pkg.packageName, permission, userId); 2055 } 2056 } else if (mPermissionReviewRequired) { 2057 // In permission review mode we clear the review flag when we 2058 // are asked to install the app with all permissions granted. 2059 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2060 updatePermissionFlags(permission, pkg.packageName, 2061 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2062 } 2063 } 2064 } 2065 } 2066 } 2067 2068 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2069 Bundle extras = null; 2070 switch (res.returnCode) { 2071 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2072 extras = new Bundle(); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2074 res.origPermission); 2075 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2076 res.origPackage); 2077 break; 2078 } 2079 case PackageManager.INSTALL_SUCCEEDED: { 2080 extras = new Bundle(); 2081 extras.putBoolean(Intent.EXTRA_REPLACING, 2082 res.removedInfo != null && res.removedInfo.removedPackage != null); 2083 break; 2084 } 2085 } 2086 return extras; 2087 } 2088 2089 void scheduleWriteSettingsLocked() { 2090 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2091 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2092 } 2093 } 2094 2095 void scheduleWritePackageListLocked(int userId) { 2096 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2097 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2098 msg.arg1 = userId; 2099 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2100 } 2101 } 2102 2103 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2104 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2105 scheduleWritePackageRestrictionsLocked(userId); 2106 } 2107 2108 void scheduleWritePackageRestrictionsLocked(int userId) { 2109 final int[] userIds = (userId == UserHandle.USER_ALL) 2110 ? sUserManager.getUserIds() : new int[]{userId}; 2111 for (int nextUserId : userIds) { 2112 if (!sUserManager.exists(nextUserId)) return; 2113 mDirtyUsers.add(nextUserId); 2114 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2115 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2116 } 2117 } 2118 } 2119 2120 public static PackageManagerService main(Context context, Installer installer, 2121 boolean factoryTest, boolean onlyCore) { 2122 // Self-check for initial settings. 2123 PackageManagerServiceCompilerMapping.checkProperties(); 2124 2125 PackageManagerService m = new PackageManagerService(context, installer, 2126 factoryTest, onlyCore); 2127 m.enableSystemUserPackages(); 2128 ServiceManager.addService("package", m); 2129 return m; 2130 } 2131 2132 private void enableSystemUserPackages() { 2133 if (!UserManager.isSplitSystemUser()) { 2134 return; 2135 } 2136 // For system user, enable apps based on the following conditions: 2137 // - app is whitelisted or belong to one of these groups: 2138 // -- system app which has no launcher icons 2139 // -- system app which has INTERACT_ACROSS_USERS permission 2140 // -- system IME app 2141 // - app is not in the blacklist 2142 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2143 Set<String> enableApps = new ArraySet<>(); 2144 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2145 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2146 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2147 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2148 enableApps.addAll(wlApps); 2149 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2150 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2151 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2152 enableApps.removeAll(blApps); 2153 Log.i(TAG, "Applications installed for system user: " + enableApps); 2154 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2155 UserHandle.SYSTEM); 2156 final int allAppsSize = allAps.size(); 2157 synchronized (mPackages) { 2158 for (int i = 0; i < allAppsSize; i++) { 2159 String pName = allAps.get(i); 2160 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2161 // Should not happen, but we shouldn't be failing if it does 2162 if (pkgSetting == null) { 2163 continue; 2164 } 2165 boolean install = enableApps.contains(pName); 2166 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2167 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2168 + " for system user"); 2169 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2170 } 2171 } 2172 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2173 } 2174 } 2175 2176 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2177 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2178 Context.DISPLAY_SERVICE); 2179 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2180 } 2181 2182 /** 2183 * Requests that files preopted on a secondary system partition be copied to the data partition 2184 * if possible. Note that the actual copying of the files is accomplished by init for security 2185 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2186 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2187 */ 2188 private static void requestCopyPreoptedFiles() { 2189 final int WAIT_TIME_MS = 100; 2190 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2191 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2192 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2193 // We will wait for up to 100 seconds. 2194 final long timeStart = SystemClock.uptimeMillis(); 2195 final long timeEnd = timeStart + 100 * 1000; 2196 long timeNow = timeStart; 2197 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2198 try { 2199 Thread.sleep(WAIT_TIME_MS); 2200 } catch (InterruptedException e) { 2201 // Do nothing 2202 } 2203 timeNow = SystemClock.uptimeMillis(); 2204 if (timeNow > timeEnd) { 2205 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2206 Slog.wtf(TAG, "cppreopt did not finish!"); 2207 break; 2208 } 2209 } 2210 2211 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2212 } 2213 } 2214 2215 public PackageManagerService(Context context, Installer installer, 2216 boolean factoryTest, boolean onlyCore) { 2217 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2218 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2219 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2220 SystemClock.uptimeMillis()); 2221 2222 if (mSdkVersion <= 0) { 2223 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2224 } 2225 2226 mContext = context; 2227 2228 mPermissionReviewRequired = context.getResources().getBoolean( 2229 R.bool.config_permissionReviewRequired); 2230 2231 mFactoryTest = factoryTest; 2232 mOnlyCore = onlyCore; 2233 mMetrics = new DisplayMetrics(); 2234 mSettings = new Settings(mPackages); 2235 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2242 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2243 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2244 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2245 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2246 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2247 2248 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2249 if (separateProcesses != null && separateProcesses.length() > 0) { 2250 if ("*".equals(separateProcesses)) { 2251 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2252 mSeparateProcesses = null; 2253 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2254 } else { 2255 mDefParseFlags = 0; 2256 mSeparateProcesses = separateProcesses.split(","); 2257 Slog.w(TAG, "Running with debug.separate_processes: " 2258 + separateProcesses); 2259 } 2260 } else { 2261 mDefParseFlags = 0; 2262 mSeparateProcesses = null; 2263 } 2264 2265 mInstaller = installer; 2266 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2267 "*dexopt*"); 2268 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2269 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2270 2271 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2272 FgThread.get().getLooper()); 2273 2274 getDefaultDisplayMetrics(context, mMetrics); 2275 2276 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2277 SystemConfig systemConfig = SystemConfig.getInstance(); 2278 mGlobalGids = systemConfig.getGlobalGids(); 2279 mSystemPermissions = systemConfig.getSystemPermissions(); 2280 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2282 2283 mProtectedPackages = new ProtectedPackages(mContext); 2284 2285 synchronized (mInstallLock) { 2286 // writer 2287 synchronized (mPackages) { 2288 mHandlerThread = new ServiceThread(TAG, 2289 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2290 mHandlerThread.start(); 2291 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2292 mProcessLoggingHandler = new ProcessLoggingHandler(); 2293 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2294 2295 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2296 mInstantAppRegistry = new InstantAppRegistry(this); 2297 2298 File dataDir = Environment.getDataDirectory(); 2299 mAppInstallDir = new File(dataDir, "app"); 2300 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2301 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2302 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2303 sUserManager = new UserManagerService(context, this, 2304 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2305 2306 // Propagate permission configuration in to package manager. 2307 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2308 = systemConfig.getPermissions(); 2309 for (int i=0; i<permConfig.size(); i++) { 2310 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2311 BasePermission bp = mSettings.mPermissions.get(perm.name); 2312 if (bp == null) { 2313 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2314 mSettings.mPermissions.put(perm.name, bp); 2315 } 2316 if (perm.gids != null) { 2317 bp.setGids(perm.gids, perm.perUser); 2318 } 2319 } 2320 2321 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2322 final int builtInLibCount = libConfig.size(); 2323 for (int i = 0; i < builtInLibCount; i++) { 2324 String name = libConfig.keyAt(i); 2325 String path = libConfig.valueAt(i); 2326 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2327 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2328 } 2329 2330 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2331 2332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2333 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2335 2336 // Clean up orphaned packages for which the code path doesn't exist 2337 // and they are an update to a system app - caused by bug/32321269 2338 final int packageSettingCount = mSettings.mPackages.size(); 2339 for (int i = packageSettingCount - 1; i >= 0; i--) { 2340 PackageSetting ps = mSettings.mPackages.valueAt(i); 2341 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2342 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2343 mSettings.mPackages.removeAt(i); 2344 mSettings.enableSystemPackageLPw(ps.name); 2345 } 2346 } 2347 2348 if (mFirstBoot) { 2349 requestCopyPreoptedFiles(); 2350 } 2351 2352 String customResolverActivity = Resources.getSystem().getString( 2353 R.string.config_customResolverActivity); 2354 if (TextUtils.isEmpty(customResolverActivity)) { 2355 customResolverActivity = null; 2356 } else { 2357 mCustomResolverComponentName = ComponentName.unflattenFromString( 2358 customResolverActivity); 2359 } 2360 2361 long startTime = SystemClock.uptimeMillis(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2364 startTime); 2365 2366 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2367 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2368 2369 if (bootClassPath == null) { 2370 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2371 } 2372 2373 if (systemServerClassPath == null) { 2374 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2375 } 2376 2377 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2378 final String[] dexCodeInstructionSets = 2379 getDexCodeInstructionSets( 2380 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2381 2382 /** 2383 * Ensure all external libraries have had dexopt run on them. 2384 */ 2385 if (mSharedLibraries.size() > 0) { 2386 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2387 // NOTE: For now, we're compiling these system "shared libraries" 2388 // (and framework jars) into all available architectures. It's possible 2389 // to compile them only when we come across an app that uses them (there's 2390 // already logic for that in scanPackageLI) but that adds some complexity. 2391 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2392 final int libCount = mSharedLibraries.size(); 2393 for (int i = 0; i < libCount; i++) { 2394 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2395 final int versionCount = versionedLib.size(); 2396 for (int j = 0; j < versionCount; j++) { 2397 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2398 final String libPath = libEntry.path != null 2399 ? libEntry.path : libEntry.apk; 2400 if (libPath == null) { 2401 continue; 2402 } 2403 try { 2404 // Shared libraries do not have profiles so we perform a full 2405 // AOT compilation (if needed). 2406 int dexoptNeeded = DexFile.getDexOptNeeded( 2407 libPath, dexCodeInstructionSet, 2408 getCompilerFilterForReason(REASON_SHARED_APK), 2409 false /* newProfile */); 2410 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2411 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2412 dexCodeInstructionSet, dexoptNeeded, null, 2413 DEXOPT_PUBLIC, 2414 getCompilerFilterForReason(REASON_SHARED_APK), 2415 StorageManager.UUID_PRIVATE_INTERNAL, 2416 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2417 } 2418 } catch (FileNotFoundException e) { 2419 Slog.w(TAG, "Library not found: " + libPath); 2420 } catch (IOException | InstallerException e) { 2421 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2422 + e.getMessage()); 2423 } 2424 } 2425 } 2426 } 2427 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2428 } 2429 2430 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2431 2432 final VersionInfo ver = mSettings.getInternalVersion(); 2433 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2434 2435 // when upgrading from pre-M, promote system app permissions from install to runtime 2436 mPromoteSystemApps = 2437 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2438 2439 // When upgrading from pre-N, we need to handle package extraction like first boot, 2440 // as there is no profiling data available. 2441 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2442 2443 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2444 2445 // save off the names of pre-existing system packages prior to scanning; we don't 2446 // want to automatically grant runtime permissions for new system apps 2447 if (mPromoteSystemApps) { 2448 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2449 while (pkgSettingIter.hasNext()) { 2450 PackageSetting ps = pkgSettingIter.next(); 2451 if (isSystemApp(ps)) { 2452 mExistingSystemPackages.add(ps.name); 2453 } 2454 } 2455 } 2456 2457 mCacheDir = preparePackageParserCache(mIsUpgrade); 2458 2459 // Set flag to monitor and not change apk file paths when 2460 // scanning install directories. 2461 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2462 2463 if (mIsUpgrade || mFirstBoot) { 2464 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2465 } 2466 2467 // Collect vendor overlay packages. (Do this before scanning any apps.) 2468 // For security and version matching reason, only consider 2469 // overlay packages if they reside in the right directory. 2470 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2471 | PackageParser.PARSE_IS_SYSTEM 2472 | PackageParser.PARSE_IS_SYSTEM_DIR 2473 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2474 2475 // Find base frameworks (resource packages without code). 2476 scanDirTracedLI(frameworkDir, mDefParseFlags 2477 | PackageParser.PARSE_IS_SYSTEM 2478 | PackageParser.PARSE_IS_SYSTEM_DIR 2479 | PackageParser.PARSE_IS_PRIVILEGED, 2480 scanFlags | SCAN_NO_DEX, 0); 2481 2482 // Collected privileged system packages. 2483 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2484 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2485 | PackageParser.PARSE_IS_SYSTEM 2486 | PackageParser.PARSE_IS_SYSTEM_DIR 2487 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2488 2489 // Collect ordinary system packages. 2490 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2491 scanDirTracedLI(systemAppDir, mDefParseFlags 2492 | PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2494 2495 // Collect all vendor packages. 2496 File vendorAppDir = new File("/vendor/app"); 2497 try { 2498 vendorAppDir = vendorAppDir.getCanonicalFile(); 2499 } catch (IOException e) { 2500 // failed to look up canonical path, continue with original one 2501 } 2502 scanDirTracedLI(vendorAppDir, mDefParseFlags 2503 | PackageParser.PARSE_IS_SYSTEM 2504 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2505 2506 // Collect all OEM packages. 2507 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2508 scanDirTracedLI(oemAppDir, mDefParseFlags 2509 | PackageParser.PARSE_IS_SYSTEM 2510 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2511 2512 // Prune any system packages that no longer exist. 2513 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2514 if (!mOnlyCore) { 2515 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2516 while (psit.hasNext()) { 2517 PackageSetting ps = psit.next(); 2518 2519 /* 2520 * If this is not a system app, it can't be a 2521 * disable system app. 2522 */ 2523 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2524 continue; 2525 } 2526 2527 /* 2528 * If the package is scanned, it's not erased. 2529 */ 2530 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2531 if (scannedPkg != null) { 2532 /* 2533 * If the system app is both scanned and in the 2534 * disabled packages list, then it must have been 2535 * added via OTA. Remove it from the currently 2536 * scanned package so the previously user-installed 2537 * application can be scanned. 2538 */ 2539 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2540 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2541 + ps.name + "; removing system app. Last known codePath=" 2542 + ps.codePathString + ", installStatus=" + ps.installStatus 2543 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2544 + scannedPkg.mVersionCode); 2545 removePackageLI(scannedPkg, true); 2546 mExpectingBetter.put(ps.name, ps.codePath); 2547 } 2548 2549 continue; 2550 } 2551 2552 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2553 psit.remove(); 2554 logCriticalInfo(Log.WARN, "System package " + ps.name 2555 + " no longer exists; it's data will be wiped"); 2556 // Actual deletion of code and data will be handled by later 2557 // reconciliation step 2558 } else { 2559 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2560 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2561 possiblyDeletedUpdatedSystemApps.add(ps.name); 2562 } 2563 } 2564 } 2565 } 2566 2567 //look for any incomplete package installations 2568 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2569 for (int i = 0; i < deletePkgsList.size(); i++) { 2570 // Actual deletion of code and data will be handled by later 2571 // reconciliation step 2572 final String packageName = deletePkgsList.get(i).name; 2573 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2574 synchronized (mPackages) { 2575 mSettings.removePackageLPw(packageName); 2576 } 2577 } 2578 2579 //delete tmp files 2580 deleteTempPackageFiles(); 2581 2582 // Remove any shared userIDs that have no associated packages 2583 mSettings.pruneSharedUsersLPw(); 2584 2585 if (!mOnlyCore) { 2586 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2587 SystemClock.uptimeMillis()); 2588 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2589 2590 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2591 | PackageParser.PARSE_FORWARD_LOCK, 2592 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2593 2594 /** 2595 * Remove disable package settings for any updated system 2596 * apps that were removed via an OTA. If they're not a 2597 * previously-updated app, remove them completely. 2598 * Otherwise, just revoke their system-level permissions. 2599 */ 2600 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2601 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2602 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2603 2604 String msg; 2605 if (deletedPkg == null) { 2606 msg = "Updated system package " + deletedAppName 2607 + " no longer exists; it's data will be wiped"; 2608 // Actual deletion of code and data will be handled by later 2609 // reconciliation step 2610 } else { 2611 msg = "Updated system app + " + deletedAppName 2612 + " no longer present; removing system privileges for " 2613 + deletedAppName; 2614 2615 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2616 2617 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2618 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2619 } 2620 logCriticalInfo(Log.WARN, msg); 2621 } 2622 2623 /** 2624 * Make sure all system apps that we expected to appear on 2625 * the userdata partition actually showed up. If they never 2626 * appeared, crawl back and revive the system version. 2627 */ 2628 for (int i = 0; i < mExpectingBetter.size(); i++) { 2629 final String packageName = mExpectingBetter.keyAt(i); 2630 if (!mPackages.containsKey(packageName)) { 2631 final File scanFile = mExpectingBetter.valueAt(i); 2632 2633 logCriticalInfo(Log.WARN, "Expected better " + packageName 2634 + " but never showed up; reverting to system"); 2635 2636 int reparseFlags = mDefParseFlags; 2637 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2638 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2639 | PackageParser.PARSE_IS_SYSTEM_DIR 2640 | PackageParser.PARSE_IS_PRIVILEGED; 2641 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2642 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2643 | PackageParser.PARSE_IS_SYSTEM_DIR; 2644 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR; 2647 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2648 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2649 | PackageParser.PARSE_IS_SYSTEM_DIR; 2650 } else { 2651 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2652 continue; 2653 } 2654 2655 mSettings.enableSystemPackageLPw(packageName); 2656 2657 try { 2658 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2659 } catch (PackageManagerException e) { 2660 Slog.e(TAG, "Failed to parse original system package: " 2661 + e.getMessage()); 2662 } 2663 } 2664 } 2665 } 2666 mExpectingBetter.clear(); 2667 2668 // Resolve the storage manager. 2669 mStorageManagerPackage = getStorageManagerPackageName(); 2670 2671 // Resolve protected action filters. Only the setup wizard is allowed to 2672 // have a high priority filter for these actions. 2673 mSetupWizardPackage = getSetupWizardPackageName(); 2674 if (mProtectedFilters.size() > 0) { 2675 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2676 Slog.i(TAG, "No setup wizard;" 2677 + " All protected intents capped to priority 0"); 2678 } 2679 for (ActivityIntentInfo filter : mProtectedFilters) { 2680 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2681 if (DEBUG_FILTERS) { 2682 Slog.i(TAG, "Found setup wizard;" 2683 + " allow priority " + filter.getPriority() + ";" 2684 + " package: " + filter.activity.info.packageName 2685 + " activity: " + filter.activity.className 2686 + " priority: " + filter.getPriority()); 2687 } 2688 // skip setup wizard; allow it to keep the high priority filter 2689 continue; 2690 } 2691 Slog.w(TAG, "Protected action; cap priority to 0;" 2692 + " package: " + filter.activity.info.packageName 2693 + " activity: " + filter.activity.className 2694 + " origPrio: " + filter.getPriority()); 2695 filter.setPriority(0); 2696 } 2697 } 2698 mDeferProtectedFilters = false; 2699 mProtectedFilters.clear(); 2700 2701 // Now that we know all of the shared libraries, update all clients to have 2702 // the correct library paths. 2703 updateAllSharedLibrariesLPw(null); 2704 2705 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2706 // NOTE: We ignore potential failures here during a system scan (like 2707 // the rest of the commands above) because there's precious little we 2708 // can do about it. A settings error is reported, though. 2709 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2710 } 2711 2712 // Now that we know all the packages we are keeping, 2713 // read and update their last usage times. 2714 mPackageUsage.read(mPackages); 2715 mCompilerStats.read(); 2716 2717 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2718 SystemClock.uptimeMillis()); 2719 Slog.i(TAG, "Time to scan packages: " 2720 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2721 + " seconds"); 2722 2723 // If the platform SDK has changed since the last time we booted, 2724 // we need to re-grant app permission to catch any new ones that 2725 // appear. This is really a hack, and means that apps can in some 2726 // cases get permissions that the user didn't initially explicitly 2727 // allow... it would be nice to have some better way to handle 2728 // this situation. 2729 int updateFlags = UPDATE_PERMISSIONS_ALL; 2730 if (ver.sdkVersion != mSdkVersion) { 2731 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2732 + mSdkVersion + "; regranting permissions for internal storage"); 2733 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2734 } 2735 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2736 ver.sdkVersion = mSdkVersion; 2737 2738 // If this is the first boot or an update from pre-M, and it is a normal 2739 // boot, then we need to initialize the default preferred apps across 2740 // all defined users. 2741 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2742 for (UserInfo user : sUserManager.getUsers(true)) { 2743 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2744 applyFactoryDefaultBrowserLPw(user.id); 2745 primeDomainVerificationsLPw(user.id); 2746 } 2747 } 2748 2749 // Prepare storage for system user really early during boot, 2750 // since core system apps like SettingsProvider and SystemUI 2751 // can't wait for user to start 2752 final int storageFlags; 2753 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2754 storageFlags = StorageManager.FLAG_STORAGE_DE; 2755 } else { 2756 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2757 } 2758 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2759 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2760 true /* onlyCoreApps */); 2761 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2762 if (deferPackages == null || deferPackages.isEmpty()) { 2763 return; 2764 } 2765 int count = 0; 2766 for (String pkgName : deferPackages) { 2767 PackageParser.Package pkg = null; 2768 synchronized (mPackages) { 2769 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2770 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2771 pkg = ps.pkg; 2772 } 2773 } 2774 if (pkg != null) { 2775 synchronized (mInstallLock) { 2776 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2777 true /* maybeMigrateAppData */); 2778 } 2779 count++; 2780 } 2781 } 2782 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2783 }, "prepareAppData"); 2784 2785 // If this is first boot after an OTA, and a normal boot, then 2786 // we need to clear code cache directories. 2787 // Note that we do *not* clear the application profiles. These remain valid 2788 // across OTAs and are used to drive profile verification (post OTA) and 2789 // profile compilation (without waiting to collect a fresh set of profiles). 2790 if (mIsUpgrade && !onlyCore) { 2791 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2792 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2793 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2794 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2795 // No apps are running this early, so no need to freeze 2796 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2797 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2798 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2799 } 2800 } 2801 ver.fingerprint = Build.FINGERPRINT; 2802 } 2803 2804 checkDefaultBrowser(); 2805 2806 // clear only after permissions and other defaults have been updated 2807 mExistingSystemPackages.clear(); 2808 mPromoteSystemApps = false; 2809 2810 // All the changes are done during package scanning. 2811 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2812 2813 // can downgrade to reader 2814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2815 mSettings.writeLPr(); 2816 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2817 2818 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2819 SystemClock.uptimeMillis()); 2820 2821 if (!mOnlyCore) { 2822 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2823 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2824 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2825 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2826 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2827 mIntentFilterVerifierComponent); 2828 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2829 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2830 SharedLibraryInfo.VERSION_UNDEFINED); 2831 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2832 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2833 SharedLibraryInfo.VERSION_UNDEFINED); 2834 } else { 2835 mRequiredVerifierPackage = null; 2836 mRequiredInstallerPackage = null; 2837 mRequiredUninstallerPackage = null; 2838 mIntentFilterVerifierComponent = null; 2839 mIntentFilterVerifier = null; 2840 mServicesSystemSharedLibraryPackageName = null; 2841 mSharedSystemSharedLibraryPackageName = null; 2842 } 2843 2844 mInstallerService = new PackageInstallerService(context, this); 2845 2846 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2847 if (ephemeralResolverComponent != null) { 2848 if (DEBUG_EPHEMERAL) { 2849 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2850 } 2851 mInstantAppResolverConnection = 2852 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2853 } else { 2854 mInstantAppResolverConnection = null; 2855 } 2856 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2857 if (mInstantAppInstallerComponent != null) { 2858 if (DEBUG_EPHEMERAL) { 2859 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2860 } 2861 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2862 } 2863 2864 // Read and update the usage of dex files. 2865 // Do this at the end of PM init so that all the packages have their 2866 // data directory reconciled. 2867 // At this point we know the code paths of the packages, so we can validate 2868 // the disk file and build the internal cache. 2869 // The usage file is expected to be small so loading and verifying it 2870 // should take a fairly small time compare to the other activities (e.g. package 2871 // scanning). 2872 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2873 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2874 for (int userId : currentUserIds) { 2875 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2876 } 2877 mDexManager.load(userPackages); 2878 } // synchronized (mPackages) 2879 } // synchronized (mInstallLock) 2880 2881 // Now after opening every single application zip, make sure they 2882 // are all flushed. Not really needed, but keeps things nice and 2883 // tidy. 2884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2885 Runtime.getRuntime().gc(); 2886 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2887 2888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2889 FallbackCategoryProvider.loadFallbacks(); 2890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2891 2892 // The initial scanning above does many calls into installd while 2893 // holding the mPackages lock, but we're mostly interested in yelling 2894 // once we have a booted system. 2895 mInstaller.setWarnIfHeld(mPackages); 2896 2897 // Expose private service for system components to use. 2898 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2900 } 2901 2902 private static File preparePackageParserCache(boolean isUpgrade) { 2903 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2904 return null; 2905 } 2906 2907 // Disable package parsing on eng builds to allow for faster incremental development. 2908 if ("eng".equals(Build.TYPE)) { 2909 return null; 2910 } 2911 2912 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2913 Slog.i(TAG, "Disabling package parser cache due to system property."); 2914 return null; 2915 } 2916 2917 // The base directory for the package parser cache lives under /data/system/. 2918 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2919 "package_cache"); 2920 if (cacheBaseDir == null) { 2921 return null; 2922 } 2923 2924 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2925 // This also serves to "GC" unused entries when the package cache version changes (which 2926 // can only happen during upgrades). 2927 if (isUpgrade) { 2928 FileUtils.deleteContents(cacheBaseDir); 2929 } 2930 2931 2932 // Return the versioned package cache directory. This is something like 2933 // "/data/system/package_cache/1" 2934 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2935 2936 // The following is a workaround to aid development on non-numbered userdebug 2937 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2938 // the system partition is newer. 2939 // 2940 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2941 // that starts with "eng." to signify that this is an engineering build and not 2942 // destined for release. 2943 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2944 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2945 2946 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2947 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2948 // in general and should not be used for production changes. In this specific case, 2949 // we know that they will work. 2950 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2951 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2952 FileUtils.deleteContents(cacheBaseDir); 2953 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2954 } 2955 } 2956 2957 return cacheDir; 2958 } 2959 2960 @Override 2961 public boolean isFirstBoot() { 2962 return mFirstBoot; 2963 } 2964 2965 @Override 2966 public boolean isOnlyCoreApps() { 2967 return mOnlyCore; 2968 } 2969 2970 @Override 2971 public boolean isUpgrade() { 2972 return mIsUpgrade; 2973 } 2974 2975 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2976 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2977 2978 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2979 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2980 UserHandle.USER_SYSTEM); 2981 if (matches.size() == 1) { 2982 return matches.get(0).getComponentInfo().packageName; 2983 } else if (matches.size() == 0) { 2984 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2985 return null; 2986 } 2987 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2988 } 2989 2990 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2991 synchronized (mPackages) { 2992 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2993 if (libraryEntry == null) { 2994 throw new IllegalStateException("Missing required shared library:" + name); 2995 } 2996 return libraryEntry.apk; 2997 } 2998 } 2999 3000 private @NonNull String getRequiredInstallerLPr() { 3001 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3002 intent.addCategory(Intent.CATEGORY_DEFAULT); 3003 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3004 3005 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3006 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3007 UserHandle.USER_SYSTEM); 3008 if (matches.size() == 1) { 3009 ResolveInfo resolveInfo = matches.get(0); 3010 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3011 throw new RuntimeException("The installer must be a privileged app"); 3012 } 3013 return matches.get(0).getComponentInfo().packageName; 3014 } else { 3015 throw new RuntimeException("There must be exactly one installer; found " + matches); 3016 } 3017 } 3018 3019 private @NonNull String getRequiredUninstallerLPr() { 3020 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3021 intent.addCategory(Intent.CATEGORY_DEFAULT); 3022 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3023 3024 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3025 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3026 UserHandle.USER_SYSTEM); 3027 if (resolveInfo == null || 3028 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3029 throw new RuntimeException("There must be exactly one uninstaller; found " 3030 + resolveInfo); 3031 } 3032 return resolveInfo.getComponentInfo().packageName; 3033 } 3034 3035 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3036 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3037 3038 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3039 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3040 UserHandle.USER_SYSTEM); 3041 ResolveInfo best = null; 3042 final int N = matches.size(); 3043 for (int i = 0; i < N; i++) { 3044 final ResolveInfo cur = matches.get(i); 3045 final String packageName = cur.getComponentInfo().packageName; 3046 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3047 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3048 continue; 3049 } 3050 3051 if (best == null || cur.priority > best.priority) { 3052 best = cur; 3053 } 3054 } 3055 3056 if (best != null) { 3057 return best.getComponentInfo().getComponentName(); 3058 } else { 3059 throw new RuntimeException("There must be at least one intent filter verifier"); 3060 } 3061 } 3062 3063 private @Nullable ComponentName getEphemeralResolverLPr() { 3064 final String[] packageArray = 3065 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3066 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3067 if (DEBUG_EPHEMERAL) { 3068 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3069 } 3070 return null; 3071 } 3072 3073 final int resolveFlags = 3074 MATCH_DIRECT_BOOT_AWARE 3075 | MATCH_DIRECT_BOOT_UNAWARE 3076 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3077 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3078 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3079 resolveFlags, UserHandle.USER_SYSTEM); 3080 3081 final int N = resolvers.size(); 3082 if (N == 0) { 3083 if (DEBUG_EPHEMERAL) { 3084 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3085 } 3086 return null; 3087 } 3088 3089 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3090 for (int i = 0; i < N; i++) { 3091 final ResolveInfo info = resolvers.get(i); 3092 3093 if (info.serviceInfo == null) { 3094 continue; 3095 } 3096 3097 final String packageName = info.serviceInfo.packageName; 3098 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3099 if (DEBUG_EPHEMERAL) { 3100 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3101 + " pkg: " + packageName + ", info:" + info); 3102 } 3103 continue; 3104 } 3105 3106 if (DEBUG_EPHEMERAL) { 3107 Slog.v(TAG, "Ephemeral resolver found;" 3108 + " pkg: " + packageName + ", info:" + info); 3109 } 3110 return new ComponentName(packageName, info.serviceInfo.name); 3111 } 3112 if (DEBUG_EPHEMERAL) { 3113 Slog.v(TAG, "Ephemeral resolver NOT found"); 3114 } 3115 return null; 3116 } 3117 3118 private @Nullable ComponentName getEphemeralInstallerLPr() { 3119 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3120 intent.addCategory(Intent.CATEGORY_DEFAULT); 3121 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3122 3123 final int resolveFlags = 3124 MATCH_DIRECT_BOOT_AWARE 3125 | MATCH_DIRECT_BOOT_UNAWARE 3126 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3127 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3128 resolveFlags, UserHandle.USER_SYSTEM); 3129 Iterator<ResolveInfo> iter = matches.iterator(); 3130 while (iter.hasNext()) { 3131 final ResolveInfo rInfo = iter.next(); 3132 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3133 if (ps != null) { 3134 final PermissionsState permissionsState = ps.getPermissionsState(); 3135 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3136 continue; 3137 } 3138 } 3139 iter.remove(); 3140 } 3141 if (matches.size() == 0) { 3142 return null; 3143 } else if (matches.size() == 1) { 3144 return matches.get(0).getComponentInfo().getComponentName(); 3145 } else { 3146 throw new RuntimeException( 3147 "There must be at most one ephemeral installer; found " + matches); 3148 } 3149 } 3150 3151 private void primeDomainVerificationsLPw(int userId) { 3152 if (DEBUG_DOMAIN_VERIFICATION) { 3153 Slog.d(TAG, "Priming domain verifications in user " + userId); 3154 } 3155 3156 SystemConfig systemConfig = SystemConfig.getInstance(); 3157 ArraySet<String> packages = systemConfig.getLinkedApps(); 3158 3159 for (String packageName : packages) { 3160 PackageParser.Package pkg = mPackages.get(packageName); 3161 if (pkg != null) { 3162 if (!pkg.isSystemApp()) { 3163 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3164 continue; 3165 } 3166 3167 ArraySet<String> domains = null; 3168 for (PackageParser.Activity a : pkg.activities) { 3169 for (ActivityIntentInfo filter : a.intents) { 3170 if (hasValidDomains(filter)) { 3171 if (domains == null) { 3172 domains = new ArraySet<String>(); 3173 } 3174 domains.addAll(filter.getHostsList()); 3175 } 3176 } 3177 } 3178 3179 if (domains != null && domains.size() > 0) { 3180 if (DEBUG_DOMAIN_VERIFICATION) { 3181 Slog.v(TAG, " + " + packageName); 3182 } 3183 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3184 // state w.r.t. the formal app-linkage "no verification attempted" state; 3185 // and then 'always' in the per-user state actually used for intent resolution. 3186 final IntentFilterVerificationInfo ivi; 3187 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3188 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3189 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3190 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3191 } else { 3192 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3193 + "' does not handle web links"); 3194 } 3195 } else { 3196 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3197 } 3198 } 3199 3200 scheduleWritePackageRestrictionsLocked(userId); 3201 scheduleWriteSettingsLocked(); 3202 } 3203 3204 private void applyFactoryDefaultBrowserLPw(int userId) { 3205 // The default browser app's package name is stored in a string resource, 3206 // with a product-specific overlay used for vendor customization. 3207 String browserPkg = mContext.getResources().getString( 3208 com.android.internal.R.string.default_browser); 3209 if (!TextUtils.isEmpty(browserPkg)) { 3210 // non-empty string => required to be a known package 3211 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3212 if (ps == null) { 3213 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3214 browserPkg = null; 3215 } else { 3216 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3217 } 3218 } 3219 3220 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3221 // default. If there's more than one, just leave everything alone. 3222 if (browserPkg == null) { 3223 calculateDefaultBrowserLPw(userId); 3224 } 3225 } 3226 3227 private void calculateDefaultBrowserLPw(int userId) { 3228 List<String> allBrowsers = resolveAllBrowserApps(userId); 3229 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3230 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3231 } 3232 3233 private List<String> resolveAllBrowserApps(int userId) { 3234 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3235 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3236 PackageManager.MATCH_ALL, userId); 3237 3238 final int count = list.size(); 3239 List<String> result = new ArrayList<String>(count); 3240 for (int i=0; i<count; i++) { 3241 ResolveInfo info = list.get(i); 3242 if (info.activityInfo == null 3243 || !info.handleAllWebDataURI 3244 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3245 || result.contains(info.activityInfo.packageName)) { 3246 continue; 3247 } 3248 result.add(info.activityInfo.packageName); 3249 } 3250 3251 return result; 3252 } 3253 3254 private boolean packageIsBrowser(String packageName, int userId) { 3255 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3256 PackageManager.MATCH_ALL, userId); 3257 final int N = list.size(); 3258 for (int i = 0; i < N; i++) { 3259 ResolveInfo info = list.get(i); 3260 if (packageName.equals(info.activityInfo.packageName)) { 3261 return true; 3262 } 3263 } 3264 return false; 3265 } 3266 3267 private void checkDefaultBrowser() { 3268 final int myUserId = UserHandle.myUserId(); 3269 final String packageName = getDefaultBrowserPackageName(myUserId); 3270 if (packageName != null) { 3271 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3272 if (info == null) { 3273 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3274 synchronized (mPackages) { 3275 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3276 } 3277 } 3278 } 3279 } 3280 3281 @Override 3282 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3283 throws RemoteException { 3284 try { 3285 return super.onTransact(code, data, reply, flags); 3286 } catch (RuntimeException e) { 3287 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3288 Slog.wtf(TAG, "Package Manager Crash", e); 3289 } 3290 throw e; 3291 } 3292 } 3293 3294 static int[] appendInts(int[] cur, int[] add) { 3295 if (add == null) return cur; 3296 if (cur == null) return add; 3297 final int N = add.length; 3298 for (int i=0; i<N; i++) { 3299 cur = appendInt(cur, add[i]); 3300 } 3301 return cur; 3302 } 3303 3304 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3305 if (!sUserManager.exists(userId)) return null; 3306 if (ps == null) { 3307 return null; 3308 } 3309 final PackageParser.Package p = ps.pkg; 3310 if (p == null) { 3311 return null; 3312 } 3313 // Filter out ephemeral app metadata: 3314 // * The system/shell/root can see metadata for any app 3315 // * An installed app can see metadata for 1) other installed apps 3316 // and 2) ephemeral apps that have explicitly interacted with it 3317 // * Ephemeral apps can only see their own data and exposed installed apps 3318 // * Holding a signature permission allows seeing instant apps 3319 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3320 if (callingAppId != Process.SYSTEM_UID 3321 && callingAppId != Process.SHELL_UID 3322 && callingAppId != Process.ROOT_UID 3323 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3324 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3325 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3326 if (instantAppPackageName != null) { 3327 // ephemeral apps can only get information on themselves or 3328 // installed apps that are exposed. 3329 if (!instantAppPackageName.equals(p.packageName) 3330 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3331 return null; 3332 } 3333 } else { 3334 if (ps.getInstantApp(userId)) { 3335 // only get access to the ephemeral app if we've been granted access 3336 if (!mInstantAppRegistry.isInstantAccessGranted( 3337 userId, callingAppId, ps.appId)) { 3338 return null; 3339 } 3340 } 3341 } 3342 } 3343 3344 final PermissionsState permissionsState = ps.getPermissionsState(); 3345 3346 // Compute GIDs only if requested 3347 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3348 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3349 // Compute granted permissions only if package has requested permissions 3350 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3351 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3352 final PackageUserState state = ps.readUserState(userId); 3353 3354 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3355 && ps.isSystem()) { 3356 flags |= MATCH_ANY_USER; 3357 } 3358 3359 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3360 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3361 3362 if (packageInfo == null) { 3363 return null; 3364 } 3365 3366 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3367 3368 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3369 resolveExternalPackageNameLPr(p); 3370 3371 return packageInfo; 3372 } 3373 3374 @Override 3375 public void checkPackageStartable(String packageName, int userId) { 3376 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3377 3378 synchronized (mPackages) { 3379 final PackageSetting ps = mSettings.mPackages.get(packageName); 3380 if (ps == null) { 3381 throw new SecurityException("Package " + packageName + " was not found!"); 3382 } 3383 3384 if (!ps.getInstalled(userId)) { 3385 throw new SecurityException( 3386 "Package " + packageName + " was not installed for user " + userId + "!"); 3387 } 3388 3389 if (mSafeMode && !ps.isSystem()) { 3390 throw new SecurityException("Package " + packageName + " not a system app!"); 3391 } 3392 3393 if (mFrozenPackages.contains(packageName)) { 3394 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3395 } 3396 3397 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3398 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3399 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3400 } 3401 } 3402 } 3403 3404 @Override 3405 public boolean isPackageAvailable(String packageName, int userId) { 3406 if (!sUserManager.exists(userId)) return false; 3407 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3408 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3409 synchronized (mPackages) { 3410 PackageParser.Package p = mPackages.get(packageName); 3411 if (p != null) { 3412 final PackageSetting ps = (PackageSetting) p.mExtras; 3413 if (ps != null) { 3414 final PackageUserState state = ps.readUserState(userId); 3415 if (state != null) { 3416 return PackageParser.isAvailable(state); 3417 } 3418 } 3419 } 3420 } 3421 return false; 3422 } 3423 3424 @Override 3425 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3426 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3427 flags, userId); 3428 } 3429 3430 @Override 3431 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3432 int flags, int userId) { 3433 return getPackageInfoInternal(versionedPackage.getPackageName(), 3434 // TODO: We will change version code to long, so in the new API it is long 3435 (int) versionedPackage.getVersionCode(), flags, userId); 3436 } 3437 3438 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3439 int flags, int userId) { 3440 if (!sUserManager.exists(userId)) return null; 3441 flags = updateFlagsForPackage(flags, userId, packageName); 3442 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3443 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3444 3445 // reader 3446 synchronized (mPackages) { 3447 // Normalize package name to handle renamed packages and static libs 3448 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3449 3450 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3451 if (matchFactoryOnly) { 3452 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3453 if (ps != null) { 3454 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3455 return null; 3456 } 3457 return generatePackageInfo(ps, flags, userId); 3458 } 3459 } 3460 3461 PackageParser.Package p = mPackages.get(packageName); 3462 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3463 return null; 3464 } 3465 if (DEBUG_PACKAGE_INFO) 3466 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3467 if (p != null) { 3468 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3469 Binder.getCallingUid(), userId)) { 3470 return null; 3471 } 3472 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3473 } 3474 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3475 final PackageSetting ps = mSettings.mPackages.get(packageName); 3476 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3477 return null; 3478 } 3479 return generatePackageInfo(ps, flags, userId); 3480 } 3481 } 3482 return null; 3483 } 3484 3485 3486 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3487 // System/shell/root get to see all static libs 3488 final int appId = UserHandle.getAppId(uid); 3489 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3490 || appId == Process.ROOT_UID) { 3491 return false; 3492 } 3493 3494 // No package means no static lib as it is always on internal storage 3495 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3496 return false; 3497 } 3498 3499 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3500 ps.pkg.staticSharedLibVersion); 3501 if (libEntry == null) { 3502 return false; 3503 } 3504 3505 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3506 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3507 if (uidPackageNames == null) { 3508 return true; 3509 } 3510 3511 for (String uidPackageName : uidPackageNames) { 3512 if (ps.name.equals(uidPackageName)) { 3513 return false; 3514 } 3515 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3516 if (uidPs != null) { 3517 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3518 libEntry.info.getName()); 3519 if (index < 0) { 3520 continue; 3521 } 3522 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3523 return false; 3524 } 3525 } 3526 } 3527 return true; 3528 } 3529 3530 @Override 3531 public String[] currentToCanonicalPackageNames(String[] names) { 3532 String[] out = new String[names.length]; 3533 // reader 3534 synchronized (mPackages) { 3535 for (int i=names.length-1; i>=0; i--) { 3536 PackageSetting ps = mSettings.mPackages.get(names[i]); 3537 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3538 } 3539 } 3540 return out; 3541 } 3542 3543 @Override 3544 public String[] canonicalToCurrentPackageNames(String[] names) { 3545 String[] out = new String[names.length]; 3546 // reader 3547 synchronized (mPackages) { 3548 for (int i=names.length-1; i>=0; i--) { 3549 String cur = mSettings.getRenamedPackageLPr(names[i]); 3550 out[i] = cur != null ? cur : names[i]; 3551 } 3552 } 3553 return out; 3554 } 3555 3556 @Override 3557 public int getPackageUid(String packageName, int flags, int userId) { 3558 if (!sUserManager.exists(userId)) return -1; 3559 flags = updateFlagsForPackage(flags, userId, packageName); 3560 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3561 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3562 3563 // reader 3564 synchronized (mPackages) { 3565 final PackageParser.Package p = mPackages.get(packageName); 3566 if (p != null && p.isMatch(flags)) { 3567 return UserHandle.getUid(userId, p.applicationInfo.uid); 3568 } 3569 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3570 final PackageSetting ps = mSettings.mPackages.get(packageName); 3571 if (ps != null && ps.isMatch(flags)) { 3572 return UserHandle.getUid(userId, ps.appId); 3573 } 3574 } 3575 } 3576 3577 return -1; 3578 } 3579 3580 @Override 3581 public int[] getPackageGids(String packageName, int flags, int userId) { 3582 if (!sUserManager.exists(userId)) return null; 3583 flags = updateFlagsForPackage(flags, userId, packageName); 3584 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3585 false /* requireFullPermission */, false /* checkShell */, 3586 "getPackageGids"); 3587 3588 // reader 3589 synchronized (mPackages) { 3590 final PackageParser.Package p = mPackages.get(packageName); 3591 if (p != null && p.isMatch(flags)) { 3592 PackageSetting ps = (PackageSetting) p.mExtras; 3593 // TODO: Shouldn't this be checking for package installed state for userId and 3594 // return null? 3595 return ps.getPermissionsState().computeGids(userId); 3596 } 3597 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3598 final PackageSetting ps = mSettings.mPackages.get(packageName); 3599 if (ps != null && ps.isMatch(flags)) { 3600 return ps.getPermissionsState().computeGids(userId); 3601 } 3602 } 3603 } 3604 3605 return null; 3606 } 3607 3608 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3609 if (bp.perm != null) { 3610 return PackageParser.generatePermissionInfo(bp.perm, flags); 3611 } 3612 PermissionInfo pi = new PermissionInfo(); 3613 pi.name = bp.name; 3614 pi.packageName = bp.sourcePackage; 3615 pi.nonLocalizedLabel = bp.name; 3616 pi.protectionLevel = bp.protectionLevel; 3617 return pi; 3618 } 3619 3620 @Override 3621 public PermissionInfo getPermissionInfo(String name, int flags) { 3622 // reader 3623 synchronized (mPackages) { 3624 final BasePermission p = mSettings.mPermissions.get(name); 3625 if (p != null) { 3626 return generatePermissionInfo(p, flags); 3627 } 3628 return null; 3629 } 3630 } 3631 3632 @Override 3633 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3634 int flags) { 3635 // reader 3636 synchronized (mPackages) { 3637 if (group != null && !mPermissionGroups.containsKey(group)) { 3638 // This is thrown as NameNotFoundException 3639 return null; 3640 } 3641 3642 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3643 for (BasePermission p : mSettings.mPermissions.values()) { 3644 if (group == null) { 3645 if (p.perm == null || p.perm.info.group == null) { 3646 out.add(generatePermissionInfo(p, flags)); 3647 } 3648 } else { 3649 if (p.perm != null && group.equals(p.perm.info.group)) { 3650 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3651 } 3652 } 3653 } 3654 return new ParceledListSlice<>(out); 3655 } 3656 } 3657 3658 @Override 3659 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3660 // reader 3661 synchronized (mPackages) { 3662 return PackageParser.generatePermissionGroupInfo( 3663 mPermissionGroups.get(name), flags); 3664 } 3665 } 3666 3667 @Override 3668 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3669 // reader 3670 synchronized (mPackages) { 3671 final int N = mPermissionGroups.size(); 3672 ArrayList<PermissionGroupInfo> out 3673 = new ArrayList<PermissionGroupInfo>(N); 3674 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3675 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3676 } 3677 return new ParceledListSlice<>(out); 3678 } 3679 } 3680 3681 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3682 int uid, int userId) { 3683 if (!sUserManager.exists(userId)) return null; 3684 PackageSetting ps = mSettings.mPackages.get(packageName); 3685 if (ps != null) { 3686 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3687 return null; 3688 } 3689 if (ps.pkg == null) { 3690 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3691 if (pInfo != null) { 3692 return pInfo.applicationInfo; 3693 } 3694 return null; 3695 } 3696 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3697 ps.readUserState(userId), userId); 3698 if (ai != null) { 3699 rebaseEnabledOverlays(ai, userId); 3700 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3701 } 3702 return ai; 3703 } 3704 return null; 3705 } 3706 3707 @Override 3708 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3709 if (!sUserManager.exists(userId)) return null; 3710 flags = updateFlagsForApplication(flags, userId, packageName); 3711 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3712 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3713 3714 // writer 3715 synchronized (mPackages) { 3716 // Normalize package name to handle renamed packages and static libs 3717 packageName = resolveInternalPackageNameLPr(packageName, 3718 PackageManager.VERSION_CODE_HIGHEST); 3719 3720 PackageParser.Package p = mPackages.get(packageName); 3721 if (DEBUG_PACKAGE_INFO) Log.v( 3722 TAG, "getApplicationInfo " + packageName 3723 + ": " + p); 3724 if (p != null) { 3725 PackageSetting ps = mSettings.mPackages.get(packageName); 3726 if (ps == null) return null; 3727 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3728 return null; 3729 } 3730 // Note: isEnabledLP() does not apply here - always return info 3731 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3732 p, flags, ps.readUserState(userId), userId); 3733 if (ai != null) { 3734 rebaseEnabledOverlays(ai, userId); 3735 ai.packageName = resolveExternalPackageNameLPr(p); 3736 } 3737 return ai; 3738 } 3739 if ("android".equals(packageName)||"system".equals(packageName)) { 3740 return mAndroidApplication; 3741 } 3742 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3743 // Already generates the external package name 3744 return generateApplicationInfoFromSettingsLPw(packageName, 3745 Binder.getCallingUid(), flags, userId); 3746 } 3747 } 3748 return null; 3749 } 3750 3751 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3752 List<String> paths = new ArrayList<>(); 3753 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3754 mEnabledOverlayPaths.get(userId); 3755 if (userSpecificOverlays != null) { 3756 if (!"android".equals(ai.packageName)) { 3757 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3758 if (frameworkOverlays != null) { 3759 paths.addAll(frameworkOverlays); 3760 } 3761 } 3762 3763 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3764 if (appOverlays != null) { 3765 paths.addAll(appOverlays); 3766 } 3767 } 3768 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3769 } 3770 3771 private String normalizePackageNameLPr(String packageName) { 3772 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3773 return normalizedPackageName != null ? normalizedPackageName : packageName; 3774 } 3775 3776 @Override 3777 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3778 final IPackageDataObserver observer) { 3779 mContext.enforceCallingOrSelfPermission( 3780 android.Manifest.permission.CLEAR_APP_CACHE, null); 3781 mHandler.post(() -> { 3782 boolean success = false; 3783 try { 3784 freeStorage(volumeUuid, freeStorageSize, 0); 3785 success = true; 3786 } catch (IOException e) { 3787 Slog.w(TAG, e); 3788 } 3789 if (observer != null) { 3790 try { 3791 observer.onRemoveCompleted(null, success); 3792 } catch (RemoteException e) { 3793 Slog.w(TAG, e); 3794 } 3795 } 3796 }); 3797 } 3798 3799 @Override 3800 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3801 final IntentSender pi) { 3802 mContext.enforceCallingOrSelfPermission( 3803 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3804 mHandler.post(() -> { 3805 boolean success = false; 3806 try { 3807 freeStorage(volumeUuid, freeStorageSize, 0); 3808 success = true; 3809 } catch (IOException e) { 3810 Slog.w(TAG, e); 3811 } 3812 if (pi != null) { 3813 try { 3814 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3815 } catch (SendIntentException e) { 3816 Slog.w(TAG, e); 3817 } 3818 } 3819 }); 3820 } 3821 3822 /** 3823 * Blocking call to clear various types of cached data across the system 3824 * until the requested bytes are available. 3825 */ 3826 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3827 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3828 final File file = storage.findPathForUuid(volumeUuid); 3829 3830 if (ENABLE_FREE_CACHE_V2) { 3831 final boolean aggressive = (storageFlags 3832 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3833 3834 // 1. Pre-flight to determine if we have any chance to succeed 3835 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3836 3837 // 3. Consider parsed APK data (aggressive only) 3838 if (aggressive) { 3839 FileUtils.deleteContents(mCacheDir); 3840 } 3841 if (file.getUsableSpace() >= bytes) return; 3842 3843 // 4. Consider cached app data (above quotas) 3844 try { 3845 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3846 } catch (InstallerException ignored) { 3847 } 3848 if (file.getUsableSpace() >= bytes) return; 3849 3850 // 5. Consider shared libraries with refcount=0 and age>2h 3851 // 6. Consider dexopt output (aggressive only) 3852 // 7. Consider ephemeral apps not used in last week 3853 3854 // 8. Consider cached app data (below quotas) 3855 try { 3856 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3857 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3858 } catch (InstallerException ignored) { 3859 } 3860 if (file.getUsableSpace() >= bytes) return; 3861 3862 // 9. Consider DropBox entries 3863 // 10. Consider ephemeral cookies 3864 3865 } else { 3866 try { 3867 mInstaller.freeCache(volumeUuid, bytes, 0); 3868 } catch (InstallerException ignored) { 3869 } 3870 if (file.getUsableSpace() >= bytes) return; 3871 } 3872 3873 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3874 } 3875 3876 /** 3877 * Update given flags based on encryption status of current user. 3878 */ 3879 private int updateFlags(int flags, int userId) { 3880 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3881 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3882 // Caller expressed an explicit opinion about what encryption 3883 // aware/unaware components they want to see, so fall through and 3884 // give them what they want 3885 } else { 3886 // Caller expressed no opinion, so match based on user state 3887 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3888 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3889 } else { 3890 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3891 } 3892 } 3893 return flags; 3894 } 3895 3896 private UserManagerInternal getUserManagerInternal() { 3897 if (mUserManagerInternal == null) { 3898 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3899 } 3900 return mUserManagerInternal; 3901 } 3902 3903 private DeviceIdleController.LocalService getDeviceIdleController() { 3904 if (mDeviceIdleController == null) { 3905 mDeviceIdleController = 3906 LocalServices.getService(DeviceIdleController.LocalService.class); 3907 } 3908 return mDeviceIdleController; 3909 } 3910 3911 /** 3912 * Update given flags when being used to request {@link PackageInfo}. 3913 */ 3914 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3915 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3916 boolean triaged = true; 3917 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3918 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3919 // Caller is asking for component details, so they'd better be 3920 // asking for specific encryption matching behavior, or be triaged 3921 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3922 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3923 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3924 triaged = false; 3925 } 3926 } 3927 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3928 | PackageManager.MATCH_SYSTEM_ONLY 3929 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3930 triaged = false; 3931 } 3932 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3933 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3934 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3935 + Debug.getCallers(5)); 3936 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3937 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3938 // If the caller wants all packages and has a restricted profile associated with it, 3939 // then match all users. This is to make sure that launchers that need to access work 3940 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3941 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3942 flags |= PackageManager.MATCH_ANY_USER; 3943 } 3944 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3945 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3946 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3947 } 3948 return updateFlags(flags, userId); 3949 } 3950 3951 /** 3952 * Update given flags when being used to request {@link ApplicationInfo}. 3953 */ 3954 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3955 return updateFlagsForPackage(flags, userId, cookie); 3956 } 3957 3958 /** 3959 * Update given flags when being used to request {@link ComponentInfo}. 3960 */ 3961 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3962 if (cookie instanceof Intent) { 3963 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3964 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3965 } 3966 } 3967 3968 boolean triaged = true; 3969 // Caller is asking for component details, so they'd better be 3970 // asking for specific encryption matching behavior, or be triaged 3971 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3972 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3973 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3974 triaged = false; 3975 } 3976 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3977 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3978 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3979 } 3980 3981 return updateFlags(flags, userId); 3982 } 3983 3984 /** 3985 * Update given intent when being used to request {@link ResolveInfo}. 3986 */ 3987 private Intent updateIntentForResolve(Intent intent) { 3988 if (intent.getSelector() != null) { 3989 intent = intent.getSelector(); 3990 } 3991 if (DEBUG_PREFERRED) { 3992 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3993 } 3994 return intent; 3995 } 3996 3997 /** 3998 * Update given flags when being used to request {@link ResolveInfo}. 3999 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4000 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4001 * flag set. However, this flag is only honoured in three circumstances: 4002 * <ul> 4003 * <li>when called from a system process</li> 4004 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4005 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4006 * action and a {@code android.intent.category.BROWSABLE} category</li> 4007 * </ul> 4008 */ 4009 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4010 // Safe mode means we shouldn't match any third-party components 4011 if (mSafeMode) { 4012 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4013 } 4014 final int callingUid = Binder.getCallingUid(); 4015 if (getInstantAppPackageName(callingUid) != null) { 4016 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4017 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4018 flags |= PackageManager.MATCH_INSTANT; 4019 } else { 4020 // Otherwise, prevent leaking ephemeral components 4021 final boolean isSpecialProcess = 4022 callingUid == Process.SYSTEM_UID 4023 || callingUid == Process.SHELL_UID 4024 || callingUid == 0; 4025 final boolean allowMatchInstant = 4026 (includeInstantApp 4027 && Intent.ACTION_VIEW.equals(intent.getAction()) 4028 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4029 && hasWebURI(intent)) 4030 || isSpecialProcess 4031 || mContext.checkCallingOrSelfPermission( 4032 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4033 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4034 if (!allowMatchInstant) { 4035 flags &= ~PackageManager.MATCH_INSTANT; 4036 } 4037 } 4038 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4039 } 4040 4041 @Override 4042 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4043 if (!sUserManager.exists(userId)) return null; 4044 flags = updateFlagsForComponent(flags, userId, component); 4045 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4046 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4047 synchronized (mPackages) { 4048 PackageParser.Activity a = mActivities.mActivities.get(component); 4049 4050 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4051 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4052 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4053 if (ps == null) return null; 4054 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4055 userId); 4056 } 4057 if (mResolveComponentName.equals(component)) { 4058 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4059 new PackageUserState(), userId); 4060 } 4061 } 4062 return null; 4063 } 4064 4065 @Override 4066 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4067 String resolvedType) { 4068 synchronized (mPackages) { 4069 if (component.equals(mResolveComponentName)) { 4070 // The resolver supports EVERYTHING! 4071 return true; 4072 } 4073 PackageParser.Activity a = mActivities.mActivities.get(component); 4074 if (a == null) { 4075 return false; 4076 } 4077 for (int i=0; i<a.intents.size(); i++) { 4078 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4079 intent.getData(), intent.getCategories(), TAG) >= 0) { 4080 return true; 4081 } 4082 } 4083 return false; 4084 } 4085 } 4086 4087 @Override 4088 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4089 if (!sUserManager.exists(userId)) return null; 4090 flags = updateFlagsForComponent(flags, userId, component); 4091 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4092 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4093 synchronized (mPackages) { 4094 PackageParser.Activity a = mReceivers.mActivities.get(component); 4095 if (DEBUG_PACKAGE_INFO) Log.v( 4096 TAG, "getReceiverInfo " + component + ": " + a); 4097 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4098 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4099 if (ps == null) return null; 4100 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4101 ps.readUserState(userId), userId); 4102 if (ri != null) { 4103 rebaseEnabledOverlays(ri.applicationInfo, userId); 4104 } 4105 return ri; 4106 } 4107 } 4108 return null; 4109 } 4110 4111 @Override 4112 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4113 if (!sUserManager.exists(userId)) return null; 4114 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4115 4116 flags = updateFlagsForPackage(flags, userId, null); 4117 4118 final boolean canSeeStaticLibraries = 4119 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4120 == PERMISSION_GRANTED 4121 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4122 == PERMISSION_GRANTED 4123 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4124 == PERMISSION_GRANTED 4125 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4126 == PERMISSION_GRANTED; 4127 4128 synchronized (mPackages) { 4129 List<SharedLibraryInfo> result = null; 4130 4131 final int libCount = mSharedLibraries.size(); 4132 for (int i = 0; i < libCount; i++) { 4133 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4134 if (versionedLib == null) { 4135 continue; 4136 } 4137 4138 final int versionCount = versionedLib.size(); 4139 for (int j = 0; j < versionCount; j++) { 4140 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4141 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4142 break; 4143 } 4144 final long identity = Binder.clearCallingIdentity(); 4145 try { 4146 // TODO: We will change version code to long, so in the new API it is long 4147 PackageInfo packageInfo = getPackageInfoVersioned( 4148 libInfo.getDeclaringPackage(), flags, userId); 4149 if (packageInfo == null) { 4150 continue; 4151 } 4152 } finally { 4153 Binder.restoreCallingIdentity(identity); 4154 } 4155 4156 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4157 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4158 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4159 4160 if (result == null) { 4161 result = new ArrayList<>(); 4162 } 4163 result.add(resLibInfo); 4164 } 4165 } 4166 4167 return result != null ? new ParceledListSlice<>(result) : null; 4168 } 4169 } 4170 4171 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4172 SharedLibraryInfo libInfo, int flags, int userId) { 4173 List<VersionedPackage> versionedPackages = null; 4174 final int packageCount = mSettings.mPackages.size(); 4175 for (int i = 0; i < packageCount; i++) { 4176 PackageSetting ps = mSettings.mPackages.valueAt(i); 4177 4178 if (ps == null) { 4179 continue; 4180 } 4181 4182 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4183 continue; 4184 } 4185 4186 final String libName = libInfo.getName(); 4187 if (libInfo.isStatic()) { 4188 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4189 if (libIdx < 0) { 4190 continue; 4191 } 4192 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4193 continue; 4194 } 4195 if (versionedPackages == null) { 4196 versionedPackages = new ArrayList<>(); 4197 } 4198 // If the dependent is a static shared lib, use the public package name 4199 String dependentPackageName = ps.name; 4200 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4201 dependentPackageName = ps.pkg.manifestPackageName; 4202 } 4203 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4204 } else if (ps.pkg != null) { 4205 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4206 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4207 if (versionedPackages == null) { 4208 versionedPackages = new ArrayList<>(); 4209 } 4210 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4211 } 4212 } 4213 } 4214 4215 return versionedPackages; 4216 } 4217 4218 @Override 4219 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4220 if (!sUserManager.exists(userId)) return null; 4221 flags = updateFlagsForComponent(flags, userId, component); 4222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4223 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4224 synchronized (mPackages) { 4225 PackageParser.Service s = mServices.mServices.get(component); 4226 if (DEBUG_PACKAGE_INFO) Log.v( 4227 TAG, "getServiceInfo " + component + ": " + s); 4228 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4229 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4230 if (ps == null) return null; 4231 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4232 ps.readUserState(userId), userId); 4233 if (si != null) { 4234 rebaseEnabledOverlays(si.applicationInfo, userId); 4235 } 4236 return si; 4237 } 4238 } 4239 return null; 4240 } 4241 4242 @Override 4243 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4244 if (!sUserManager.exists(userId)) return null; 4245 flags = updateFlagsForComponent(flags, userId, component); 4246 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4247 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4248 synchronized (mPackages) { 4249 PackageParser.Provider p = mProviders.mProviders.get(component); 4250 if (DEBUG_PACKAGE_INFO) Log.v( 4251 TAG, "getProviderInfo " + component + ": " + p); 4252 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4253 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4254 if (ps == null) return null; 4255 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4256 ps.readUserState(userId), userId); 4257 if (pi != null) { 4258 rebaseEnabledOverlays(pi.applicationInfo, userId); 4259 } 4260 return pi; 4261 } 4262 } 4263 return null; 4264 } 4265 4266 @Override 4267 public String[] getSystemSharedLibraryNames() { 4268 synchronized (mPackages) { 4269 Set<String> libs = null; 4270 final int libCount = mSharedLibraries.size(); 4271 for (int i = 0; i < libCount; i++) { 4272 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4273 if (versionedLib == null) { 4274 continue; 4275 } 4276 final int versionCount = versionedLib.size(); 4277 for (int j = 0; j < versionCount; j++) { 4278 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4279 if (!libEntry.info.isStatic()) { 4280 if (libs == null) { 4281 libs = new ArraySet<>(); 4282 } 4283 libs.add(libEntry.info.getName()); 4284 break; 4285 } 4286 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4287 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4288 UserHandle.getUserId(Binder.getCallingUid()))) { 4289 if (libs == null) { 4290 libs = new ArraySet<>(); 4291 } 4292 libs.add(libEntry.info.getName()); 4293 break; 4294 } 4295 } 4296 } 4297 4298 if (libs != null) { 4299 String[] libsArray = new String[libs.size()]; 4300 libs.toArray(libsArray); 4301 return libsArray; 4302 } 4303 4304 return null; 4305 } 4306 } 4307 4308 @Override 4309 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4310 synchronized (mPackages) { 4311 return mServicesSystemSharedLibraryPackageName; 4312 } 4313 } 4314 4315 @Override 4316 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4317 synchronized (mPackages) { 4318 return mSharedSystemSharedLibraryPackageName; 4319 } 4320 } 4321 4322 private void updateSequenceNumberLP(String packageName, int[] userList) { 4323 for (int i = userList.length - 1; i >= 0; --i) { 4324 final int userId = userList[i]; 4325 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4326 if (changedPackages == null) { 4327 changedPackages = new SparseArray<>(); 4328 mChangedPackages.put(userId, changedPackages); 4329 } 4330 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4331 if (sequenceNumbers == null) { 4332 sequenceNumbers = new HashMap<>(); 4333 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4334 } 4335 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4336 if (sequenceNumber != null) { 4337 changedPackages.remove(sequenceNumber); 4338 } 4339 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4340 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4341 } 4342 mChangedPackagesSequenceNumber++; 4343 } 4344 4345 @Override 4346 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4347 synchronized (mPackages) { 4348 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4349 return null; 4350 } 4351 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4352 if (changedPackages == null) { 4353 return null; 4354 } 4355 final List<String> packageNames = 4356 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4357 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4358 final String packageName = changedPackages.get(i); 4359 if (packageName != null) { 4360 packageNames.add(packageName); 4361 } 4362 } 4363 return packageNames.isEmpty() 4364 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4365 } 4366 } 4367 4368 @Override 4369 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4370 ArrayList<FeatureInfo> res; 4371 synchronized (mAvailableFeatures) { 4372 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4373 res.addAll(mAvailableFeatures.values()); 4374 } 4375 final FeatureInfo fi = new FeatureInfo(); 4376 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4377 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4378 res.add(fi); 4379 4380 return new ParceledListSlice<>(res); 4381 } 4382 4383 @Override 4384 public boolean hasSystemFeature(String name, int version) { 4385 synchronized (mAvailableFeatures) { 4386 final FeatureInfo feat = mAvailableFeatures.get(name); 4387 if (feat == null) { 4388 return false; 4389 } else { 4390 return feat.version >= version; 4391 } 4392 } 4393 } 4394 4395 @Override 4396 public int checkPermission(String permName, String pkgName, int userId) { 4397 if (!sUserManager.exists(userId)) { 4398 return PackageManager.PERMISSION_DENIED; 4399 } 4400 4401 synchronized (mPackages) { 4402 final PackageParser.Package p = mPackages.get(pkgName); 4403 if (p != null && p.mExtras != null) { 4404 final PackageSetting ps = (PackageSetting) p.mExtras; 4405 final PermissionsState permissionsState = ps.getPermissionsState(); 4406 if (permissionsState.hasPermission(permName, userId)) { 4407 return PackageManager.PERMISSION_GRANTED; 4408 } 4409 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4410 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4411 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4412 return PackageManager.PERMISSION_GRANTED; 4413 } 4414 } 4415 } 4416 4417 return PackageManager.PERMISSION_DENIED; 4418 } 4419 4420 @Override 4421 public int checkUidPermission(String permName, int uid) { 4422 final int userId = UserHandle.getUserId(uid); 4423 4424 if (!sUserManager.exists(userId)) { 4425 return PackageManager.PERMISSION_DENIED; 4426 } 4427 4428 synchronized (mPackages) { 4429 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4430 if (obj != null) { 4431 final SettingBase ps = (SettingBase) obj; 4432 final PermissionsState permissionsState = ps.getPermissionsState(); 4433 if (permissionsState.hasPermission(permName, userId)) { 4434 return PackageManager.PERMISSION_GRANTED; 4435 } 4436 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4437 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4438 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4439 return PackageManager.PERMISSION_GRANTED; 4440 } 4441 } else { 4442 ArraySet<String> perms = mSystemPermissions.get(uid); 4443 if (perms != null) { 4444 if (perms.contains(permName)) { 4445 return PackageManager.PERMISSION_GRANTED; 4446 } 4447 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4448 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4449 return PackageManager.PERMISSION_GRANTED; 4450 } 4451 } 4452 } 4453 } 4454 4455 return PackageManager.PERMISSION_DENIED; 4456 } 4457 4458 @Override 4459 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4460 if (UserHandle.getCallingUserId() != userId) { 4461 mContext.enforceCallingPermission( 4462 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4463 "isPermissionRevokedByPolicy for user " + userId); 4464 } 4465 4466 if (checkPermission(permission, packageName, userId) 4467 == PackageManager.PERMISSION_GRANTED) { 4468 return false; 4469 } 4470 4471 final long identity = Binder.clearCallingIdentity(); 4472 try { 4473 final int flags = getPermissionFlags(permission, packageName, userId); 4474 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4475 } finally { 4476 Binder.restoreCallingIdentity(identity); 4477 } 4478 } 4479 4480 @Override 4481 public String getPermissionControllerPackageName() { 4482 synchronized (mPackages) { 4483 return mRequiredInstallerPackage; 4484 } 4485 } 4486 4487 /** 4488 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4489 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4490 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4491 * @param message the message to log on security exception 4492 */ 4493 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4494 boolean checkShell, String message) { 4495 if (userId < 0) { 4496 throw new IllegalArgumentException("Invalid userId " + userId); 4497 } 4498 if (checkShell) { 4499 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4500 } 4501 if (userId == UserHandle.getUserId(callingUid)) return; 4502 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4503 if (requireFullPermission) { 4504 mContext.enforceCallingOrSelfPermission( 4505 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4506 } else { 4507 try { 4508 mContext.enforceCallingOrSelfPermission( 4509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4510 } catch (SecurityException se) { 4511 mContext.enforceCallingOrSelfPermission( 4512 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4513 } 4514 } 4515 } 4516 } 4517 4518 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4519 if (callingUid == Process.SHELL_UID) { 4520 if (userHandle >= 0 4521 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4522 throw new SecurityException("Shell does not have permission to access user " 4523 + userHandle); 4524 } else if (userHandle < 0) { 4525 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4526 + Debug.getCallers(3)); 4527 } 4528 } 4529 } 4530 4531 private BasePermission findPermissionTreeLP(String permName) { 4532 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4533 if (permName.startsWith(bp.name) && 4534 permName.length() > bp.name.length() && 4535 permName.charAt(bp.name.length()) == '.') { 4536 return bp; 4537 } 4538 } 4539 return null; 4540 } 4541 4542 private BasePermission checkPermissionTreeLP(String permName) { 4543 if (permName != null) { 4544 BasePermission bp = findPermissionTreeLP(permName); 4545 if (bp != null) { 4546 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4547 return bp; 4548 } 4549 throw new SecurityException("Calling uid " 4550 + Binder.getCallingUid() 4551 + " is not allowed to add to permission tree " 4552 + bp.name + " owned by uid " + bp.uid); 4553 } 4554 } 4555 throw new SecurityException("No permission tree found for " + permName); 4556 } 4557 4558 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4559 if (s1 == null) { 4560 return s2 == null; 4561 } 4562 if (s2 == null) { 4563 return false; 4564 } 4565 if (s1.getClass() != s2.getClass()) { 4566 return false; 4567 } 4568 return s1.equals(s2); 4569 } 4570 4571 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4572 if (pi1.icon != pi2.icon) return false; 4573 if (pi1.logo != pi2.logo) return false; 4574 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4575 if (!compareStrings(pi1.name, pi2.name)) return false; 4576 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4577 // We'll take care of setting this one. 4578 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4579 // These are not currently stored in settings. 4580 //if (!compareStrings(pi1.group, pi2.group)) return false; 4581 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4582 //if (pi1.labelRes != pi2.labelRes) return false; 4583 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4584 return true; 4585 } 4586 4587 int permissionInfoFootprint(PermissionInfo info) { 4588 int size = info.name.length(); 4589 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4590 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4591 return size; 4592 } 4593 4594 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4595 int size = 0; 4596 for (BasePermission perm : mSettings.mPermissions.values()) { 4597 if (perm.uid == tree.uid) { 4598 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4599 } 4600 } 4601 return size; 4602 } 4603 4604 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4605 // We calculate the max size of permissions defined by this uid and throw 4606 // if that plus the size of 'info' would exceed our stated maximum. 4607 if (tree.uid != Process.SYSTEM_UID) { 4608 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4609 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4610 throw new SecurityException("Permission tree size cap exceeded"); 4611 } 4612 } 4613 } 4614 4615 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4616 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4617 throw new SecurityException("Label must be specified in permission"); 4618 } 4619 BasePermission tree = checkPermissionTreeLP(info.name); 4620 BasePermission bp = mSettings.mPermissions.get(info.name); 4621 boolean added = bp == null; 4622 boolean changed = true; 4623 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4624 if (added) { 4625 enforcePermissionCapLocked(info, tree); 4626 bp = new BasePermission(info.name, tree.sourcePackage, 4627 BasePermission.TYPE_DYNAMIC); 4628 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4629 throw new SecurityException( 4630 "Not allowed to modify non-dynamic permission " 4631 + info.name); 4632 } else { 4633 if (bp.protectionLevel == fixedLevel 4634 && bp.perm.owner.equals(tree.perm.owner) 4635 && bp.uid == tree.uid 4636 && comparePermissionInfos(bp.perm.info, info)) { 4637 changed = false; 4638 } 4639 } 4640 bp.protectionLevel = fixedLevel; 4641 info = new PermissionInfo(info); 4642 info.protectionLevel = fixedLevel; 4643 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4644 bp.perm.info.packageName = tree.perm.info.packageName; 4645 bp.uid = tree.uid; 4646 if (added) { 4647 mSettings.mPermissions.put(info.name, bp); 4648 } 4649 if (changed) { 4650 if (!async) { 4651 mSettings.writeLPr(); 4652 } else { 4653 scheduleWriteSettingsLocked(); 4654 } 4655 } 4656 return added; 4657 } 4658 4659 @Override 4660 public boolean addPermission(PermissionInfo info) { 4661 synchronized (mPackages) { 4662 return addPermissionLocked(info, false); 4663 } 4664 } 4665 4666 @Override 4667 public boolean addPermissionAsync(PermissionInfo info) { 4668 synchronized (mPackages) { 4669 return addPermissionLocked(info, true); 4670 } 4671 } 4672 4673 @Override 4674 public void removePermission(String name) { 4675 synchronized (mPackages) { 4676 checkPermissionTreeLP(name); 4677 BasePermission bp = mSettings.mPermissions.get(name); 4678 if (bp != null) { 4679 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4680 throw new SecurityException( 4681 "Not allowed to modify non-dynamic permission " 4682 + name); 4683 } 4684 mSettings.mPermissions.remove(name); 4685 mSettings.writeLPr(); 4686 } 4687 } 4688 } 4689 4690 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4691 BasePermission bp) { 4692 int index = pkg.requestedPermissions.indexOf(bp.name); 4693 if (index == -1) { 4694 throw new SecurityException("Package " + pkg.packageName 4695 + " has not requested permission " + bp.name); 4696 } 4697 if (!bp.isRuntime() && !bp.isDevelopment()) { 4698 throw new SecurityException("Permission " + bp.name 4699 + " is not a changeable permission type"); 4700 } 4701 } 4702 4703 @Override 4704 public void grantRuntimePermission(String packageName, String name, final int userId) { 4705 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4706 } 4707 4708 private void grantRuntimePermission(String packageName, String name, final int userId, 4709 boolean overridePolicy) { 4710 if (!sUserManager.exists(userId)) { 4711 Log.e(TAG, "No such user:" + userId); 4712 return; 4713 } 4714 4715 mContext.enforceCallingOrSelfPermission( 4716 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4717 "grantRuntimePermission"); 4718 4719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4720 true /* requireFullPermission */, true /* checkShell */, 4721 "grantRuntimePermission"); 4722 4723 final int uid; 4724 final SettingBase sb; 4725 4726 synchronized (mPackages) { 4727 final PackageParser.Package pkg = mPackages.get(packageName); 4728 if (pkg == null) { 4729 throw new IllegalArgumentException("Unknown package: " + packageName); 4730 } 4731 4732 final BasePermission bp = mSettings.mPermissions.get(name); 4733 if (bp == null) { 4734 throw new IllegalArgumentException("Unknown permission: " + name); 4735 } 4736 4737 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4738 4739 // If a permission review is required for legacy apps we represent 4740 // their permissions as always granted runtime ones since we need 4741 // to keep the review required permission flag per user while an 4742 // install permission's state is shared across all users. 4743 if (mPermissionReviewRequired 4744 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4745 && bp.isRuntime()) { 4746 return; 4747 } 4748 4749 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4750 sb = (SettingBase) pkg.mExtras; 4751 if (sb == null) { 4752 throw new IllegalArgumentException("Unknown package: " + packageName); 4753 } 4754 4755 final PermissionsState permissionsState = sb.getPermissionsState(); 4756 4757 final int flags = permissionsState.getPermissionFlags(name, userId); 4758 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4759 throw new SecurityException("Cannot grant system fixed permission " 4760 + name + " for package " + packageName); 4761 } 4762 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4763 throw new SecurityException("Cannot grant policy fixed permission " 4764 + name + " for package " + packageName); 4765 } 4766 4767 if (bp.isDevelopment()) { 4768 // Development permissions must be handled specially, since they are not 4769 // normal runtime permissions. For now they apply to all users. 4770 if (permissionsState.grantInstallPermission(bp) != 4771 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4772 scheduleWriteSettingsLocked(); 4773 } 4774 return; 4775 } 4776 4777 final PackageSetting ps = mSettings.mPackages.get(packageName); 4778 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4779 throw new SecurityException("Cannot grant non-ephemeral permission" 4780 + name + " for package " + packageName); 4781 } 4782 4783 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4784 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4785 return; 4786 } 4787 4788 final int result = permissionsState.grantRuntimePermission(bp, userId); 4789 switch (result) { 4790 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4791 return; 4792 } 4793 4794 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4795 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4796 mHandler.post(new Runnable() { 4797 @Override 4798 public void run() { 4799 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4800 } 4801 }); 4802 } 4803 break; 4804 } 4805 4806 if (bp.isRuntime()) { 4807 logPermissionGranted(mContext, name, packageName); 4808 } 4809 4810 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4811 4812 // Not critical if that is lost - app has to request again. 4813 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4814 } 4815 4816 // Only need to do this if user is initialized. Otherwise it's a new user 4817 // and there are no processes running as the user yet and there's no need 4818 // to make an expensive call to remount processes for the changed permissions. 4819 if (READ_EXTERNAL_STORAGE.equals(name) 4820 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4821 final long token = Binder.clearCallingIdentity(); 4822 try { 4823 if (sUserManager.isInitialized(userId)) { 4824 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4825 StorageManagerInternal.class); 4826 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4827 } 4828 } finally { 4829 Binder.restoreCallingIdentity(token); 4830 } 4831 } 4832 } 4833 4834 @Override 4835 public void revokeRuntimePermission(String packageName, String name, int userId) { 4836 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4837 } 4838 4839 private void revokeRuntimePermission(String packageName, String name, int userId, 4840 boolean overridePolicy) { 4841 if (!sUserManager.exists(userId)) { 4842 Log.e(TAG, "No such user:" + userId); 4843 return; 4844 } 4845 4846 mContext.enforceCallingOrSelfPermission( 4847 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4848 "revokeRuntimePermission"); 4849 4850 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4851 true /* requireFullPermission */, true /* checkShell */, 4852 "revokeRuntimePermission"); 4853 4854 final int appId; 4855 4856 synchronized (mPackages) { 4857 final PackageParser.Package pkg = mPackages.get(packageName); 4858 if (pkg == null) { 4859 throw new IllegalArgumentException("Unknown package: " + packageName); 4860 } 4861 4862 final BasePermission bp = mSettings.mPermissions.get(name); 4863 if (bp == null) { 4864 throw new IllegalArgumentException("Unknown permission: " + name); 4865 } 4866 4867 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4868 4869 // If a permission review is required for legacy apps we represent 4870 // their permissions as always granted runtime ones since we need 4871 // to keep the review required permission flag per user while an 4872 // install permission's state is shared across all users. 4873 if (mPermissionReviewRequired 4874 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4875 && bp.isRuntime()) { 4876 return; 4877 } 4878 4879 SettingBase sb = (SettingBase) pkg.mExtras; 4880 if (sb == null) { 4881 throw new IllegalArgumentException("Unknown package: " + packageName); 4882 } 4883 4884 final PermissionsState permissionsState = sb.getPermissionsState(); 4885 4886 final int flags = permissionsState.getPermissionFlags(name, userId); 4887 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4888 throw new SecurityException("Cannot revoke system fixed permission " 4889 + name + " for package " + packageName); 4890 } 4891 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4892 throw new SecurityException("Cannot revoke policy fixed permission " 4893 + name + " for package " + packageName); 4894 } 4895 4896 if (bp.isDevelopment()) { 4897 // Development permissions must be handled specially, since they are not 4898 // normal runtime permissions. For now they apply to all users. 4899 if (permissionsState.revokeInstallPermission(bp) != 4900 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4901 scheduleWriteSettingsLocked(); 4902 } 4903 return; 4904 } 4905 4906 if (permissionsState.revokeRuntimePermission(bp, userId) == 4907 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4908 return; 4909 } 4910 4911 if (bp.isRuntime()) { 4912 logPermissionRevoked(mContext, name, packageName); 4913 } 4914 4915 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4916 4917 // Critical, after this call app should never have the permission. 4918 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4919 4920 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4921 } 4922 4923 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4924 } 4925 4926 /** 4927 * Get the first event id for the permission. 4928 * 4929 * <p>There are four events for each permission: <ul> 4930 * <li>Request permission: first id + 0</li> 4931 * <li>Grant permission: first id + 1</li> 4932 * <li>Request for permission denied: first id + 2</li> 4933 * <li>Revoke permission: first id + 3</li> 4934 * </ul></p> 4935 * 4936 * @param name name of the permission 4937 * 4938 * @return The first event id for the permission 4939 */ 4940 private static int getBaseEventId(@NonNull String name) { 4941 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4942 4943 if (eventIdIndex == -1) { 4944 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4945 || "user".equals(Build.TYPE)) { 4946 Log.i(TAG, "Unknown permission " + name); 4947 4948 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4949 } else { 4950 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4951 // 4952 // Also update 4953 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4954 // - metrics_constants.proto 4955 throw new IllegalStateException("Unknown permission " + name); 4956 } 4957 } 4958 4959 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4960 } 4961 4962 /** 4963 * Log that a permission was revoked. 4964 * 4965 * @param context Context of the caller 4966 * @param name name of the permission 4967 * @param packageName package permission if for 4968 */ 4969 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4970 @NonNull String packageName) { 4971 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4972 } 4973 4974 /** 4975 * Log that a permission request was granted. 4976 * 4977 * @param context Context of the caller 4978 * @param name name of the permission 4979 * @param packageName package permission if for 4980 */ 4981 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4982 @NonNull String packageName) { 4983 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4984 } 4985 4986 @Override 4987 public void resetRuntimePermissions() { 4988 mContext.enforceCallingOrSelfPermission( 4989 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4990 "revokeRuntimePermission"); 4991 4992 int callingUid = Binder.getCallingUid(); 4993 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4994 mContext.enforceCallingOrSelfPermission( 4995 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4996 "resetRuntimePermissions"); 4997 } 4998 4999 synchronized (mPackages) { 5000 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5001 for (int userId : UserManagerService.getInstance().getUserIds()) { 5002 final int packageCount = mPackages.size(); 5003 for (int i = 0; i < packageCount; i++) { 5004 PackageParser.Package pkg = mPackages.valueAt(i); 5005 if (!(pkg.mExtras instanceof PackageSetting)) { 5006 continue; 5007 } 5008 PackageSetting ps = (PackageSetting) pkg.mExtras; 5009 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5010 } 5011 } 5012 } 5013 } 5014 5015 @Override 5016 public int getPermissionFlags(String name, String packageName, int userId) { 5017 if (!sUserManager.exists(userId)) { 5018 return 0; 5019 } 5020 5021 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5022 5023 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5024 true /* requireFullPermission */, false /* checkShell */, 5025 "getPermissionFlags"); 5026 5027 synchronized (mPackages) { 5028 final PackageParser.Package pkg = mPackages.get(packageName); 5029 if (pkg == null) { 5030 return 0; 5031 } 5032 5033 final BasePermission bp = mSettings.mPermissions.get(name); 5034 if (bp == null) { 5035 return 0; 5036 } 5037 5038 SettingBase sb = (SettingBase) pkg.mExtras; 5039 if (sb == null) { 5040 return 0; 5041 } 5042 5043 PermissionsState permissionsState = sb.getPermissionsState(); 5044 return permissionsState.getPermissionFlags(name, userId); 5045 } 5046 } 5047 5048 @Override 5049 public void updatePermissionFlags(String name, String packageName, int flagMask, 5050 int flagValues, int userId) { 5051 if (!sUserManager.exists(userId)) { 5052 return; 5053 } 5054 5055 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5056 5057 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5058 true /* requireFullPermission */, true /* checkShell */, 5059 "updatePermissionFlags"); 5060 5061 // Only the system can change these flags and nothing else. 5062 if (getCallingUid() != Process.SYSTEM_UID) { 5063 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5064 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5065 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5066 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5067 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5068 } 5069 5070 synchronized (mPackages) { 5071 final PackageParser.Package pkg = mPackages.get(packageName); 5072 if (pkg == null) { 5073 throw new IllegalArgumentException("Unknown package: " + packageName); 5074 } 5075 5076 final BasePermission bp = mSettings.mPermissions.get(name); 5077 if (bp == null) { 5078 throw new IllegalArgumentException("Unknown permission: " + name); 5079 } 5080 5081 SettingBase sb = (SettingBase) pkg.mExtras; 5082 if (sb == null) { 5083 throw new IllegalArgumentException("Unknown package: " + packageName); 5084 } 5085 5086 PermissionsState permissionsState = sb.getPermissionsState(); 5087 5088 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5089 5090 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5091 // Install and runtime permissions are stored in different places, 5092 // so figure out what permission changed and persist the change. 5093 if (permissionsState.getInstallPermissionState(name) != null) { 5094 scheduleWriteSettingsLocked(); 5095 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5096 || hadState) { 5097 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5098 } 5099 } 5100 } 5101 } 5102 5103 /** 5104 * Update the permission flags for all packages and runtime permissions of a user in order 5105 * to allow device or profile owner to remove POLICY_FIXED. 5106 */ 5107 @Override 5108 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5109 if (!sUserManager.exists(userId)) { 5110 return; 5111 } 5112 5113 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5114 5115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5116 true /* requireFullPermission */, true /* checkShell */, 5117 "updatePermissionFlagsForAllApps"); 5118 5119 // Only the system can change system fixed flags. 5120 if (getCallingUid() != Process.SYSTEM_UID) { 5121 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5122 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5123 } 5124 5125 synchronized (mPackages) { 5126 boolean changed = false; 5127 final int packageCount = mPackages.size(); 5128 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5129 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5130 SettingBase sb = (SettingBase) pkg.mExtras; 5131 if (sb == null) { 5132 continue; 5133 } 5134 PermissionsState permissionsState = sb.getPermissionsState(); 5135 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5136 userId, flagMask, flagValues); 5137 } 5138 if (changed) { 5139 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5140 } 5141 } 5142 } 5143 5144 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5145 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5146 != PackageManager.PERMISSION_GRANTED 5147 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5148 != PackageManager.PERMISSION_GRANTED) { 5149 throw new SecurityException(message + " requires " 5150 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5151 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5152 } 5153 } 5154 5155 @Override 5156 public boolean shouldShowRequestPermissionRationale(String permissionName, 5157 String packageName, int userId) { 5158 if (UserHandle.getCallingUserId() != userId) { 5159 mContext.enforceCallingPermission( 5160 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5161 "canShowRequestPermissionRationale for user " + userId); 5162 } 5163 5164 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5165 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5166 return false; 5167 } 5168 5169 if (checkPermission(permissionName, packageName, userId) 5170 == PackageManager.PERMISSION_GRANTED) { 5171 return false; 5172 } 5173 5174 final int flags; 5175 5176 final long identity = Binder.clearCallingIdentity(); 5177 try { 5178 flags = getPermissionFlags(permissionName, 5179 packageName, userId); 5180 } finally { 5181 Binder.restoreCallingIdentity(identity); 5182 } 5183 5184 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5185 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5186 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5187 5188 if ((flags & fixedFlags) != 0) { 5189 return false; 5190 } 5191 5192 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5193 } 5194 5195 @Override 5196 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5197 mContext.enforceCallingOrSelfPermission( 5198 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5199 "addOnPermissionsChangeListener"); 5200 5201 synchronized (mPackages) { 5202 mOnPermissionChangeListeners.addListenerLocked(listener); 5203 } 5204 } 5205 5206 @Override 5207 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5208 synchronized (mPackages) { 5209 mOnPermissionChangeListeners.removeListenerLocked(listener); 5210 } 5211 } 5212 5213 @Override 5214 public boolean isProtectedBroadcast(String actionName) { 5215 synchronized (mPackages) { 5216 if (mProtectedBroadcasts.contains(actionName)) { 5217 return true; 5218 } else if (actionName != null) { 5219 // TODO: remove these terrible hacks 5220 if (actionName.startsWith("android.net.netmon.lingerExpired") 5221 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5222 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5223 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5224 return true; 5225 } 5226 } 5227 } 5228 return false; 5229 } 5230 5231 @Override 5232 public int checkSignatures(String pkg1, String pkg2) { 5233 synchronized (mPackages) { 5234 final PackageParser.Package p1 = mPackages.get(pkg1); 5235 final PackageParser.Package p2 = mPackages.get(pkg2); 5236 if (p1 == null || p1.mExtras == null 5237 || p2 == null || p2.mExtras == null) { 5238 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5239 } 5240 return compareSignatures(p1.mSignatures, p2.mSignatures); 5241 } 5242 } 5243 5244 @Override 5245 public int checkUidSignatures(int uid1, int uid2) { 5246 // Map to base uids. 5247 uid1 = UserHandle.getAppId(uid1); 5248 uid2 = UserHandle.getAppId(uid2); 5249 // reader 5250 synchronized (mPackages) { 5251 Signature[] s1; 5252 Signature[] s2; 5253 Object obj = mSettings.getUserIdLPr(uid1); 5254 if (obj != null) { 5255 if (obj instanceof SharedUserSetting) { 5256 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5257 } else if (obj instanceof PackageSetting) { 5258 s1 = ((PackageSetting)obj).signatures.mSignatures; 5259 } else { 5260 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5261 } 5262 } else { 5263 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5264 } 5265 obj = mSettings.getUserIdLPr(uid2); 5266 if (obj != null) { 5267 if (obj instanceof SharedUserSetting) { 5268 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5269 } else if (obj instanceof PackageSetting) { 5270 s2 = ((PackageSetting)obj).signatures.mSignatures; 5271 } else { 5272 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5273 } 5274 } else { 5275 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5276 } 5277 return compareSignatures(s1, s2); 5278 } 5279 } 5280 5281 /** 5282 * This method should typically only be used when granting or revoking 5283 * permissions, since the app may immediately restart after this call. 5284 * <p> 5285 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5286 * guard your work against the app being relaunched. 5287 */ 5288 private void killUid(int appId, int userId, String reason) { 5289 final long identity = Binder.clearCallingIdentity(); 5290 try { 5291 IActivityManager am = ActivityManager.getService(); 5292 if (am != null) { 5293 try { 5294 am.killUid(appId, userId, reason); 5295 } catch (RemoteException e) { 5296 /* ignore - same process */ 5297 } 5298 } 5299 } finally { 5300 Binder.restoreCallingIdentity(identity); 5301 } 5302 } 5303 5304 /** 5305 * Compares two sets of signatures. Returns: 5306 * <br /> 5307 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5308 * <br /> 5309 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5310 * <br /> 5311 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5312 * <br /> 5313 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5314 * <br /> 5315 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5316 */ 5317 static int compareSignatures(Signature[] s1, Signature[] s2) { 5318 if (s1 == null) { 5319 return s2 == null 5320 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5321 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5322 } 5323 5324 if (s2 == null) { 5325 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5326 } 5327 5328 if (s1.length != s2.length) { 5329 return PackageManager.SIGNATURE_NO_MATCH; 5330 } 5331 5332 // Since both signature sets are of size 1, we can compare without HashSets. 5333 if (s1.length == 1) { 5334 return s1[0].equals(s2[0]) ? 5335 PackageManager.SIGNATURE_MATCH : 5336 PackageManager.SIGNATURE_NO_MATCH; 5337 } 5338 5339 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5340 for (Signature sig : s1) { 5341 set1.add(sig); 5342 } 5343 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5344 for (Signature sig : s2) { 5345 set2.add(sig); 5346 } 5347 // Make sure s2 contains all signatures in s1. 5348 if (set1.equals(set2)) { 5349 return PackageManager.SIGNATURE_MATCH; 5350 } 5351 return PackageManager.SIGNATURE_NO_MATCH; 5352 } 5353 5354 /** 5355 * If the database version for this type of package (internal storage or 5356 * external storage) is less than the version where package signatures 5357 * were updated, return true. 5358 */ 5359 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5360 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5361 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5362 } 5363 5364 /** 5365 * Used for backward compatibility to make sure any packages with 5366 * certificate chains get upgraded to the new style. {@code existingSigs} 5367 * will be in the old format (since they were stored on disk from before the 5368 * system upgrade) and {@code scannedSigs} will be in the newer format. 5369 */ 5370 private int compareSignaturesCompat(PackageSignatures existingSigs, 5371 PackageParser.Package scannedPkg) { 5372 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5373 return PackageManager.SIGNATURE_NO_MATCH; 5374 } 5375 5376 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5377 for (Signature sig : existingSigs.mSignatures) { 5378 existingSet.add(sig); 5379 } 5380 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5381 for (Signature sig : scannedPkg.mSignatures) { 5382 try { 5383 Signature[] chainSignatures = sig.getChainSignatures(); 5384 for (Signature chainSig : chainSignatures) { 5385 scannedCompatSet.add(chainSig); 5386 } 5387 } catch (CertificateEncodingException e) { 5388 scannedCompatSet.add(sig); 5389 } 5390 } 5391 /* 5392 * Make sure the expanded scanned set contains all signatures in the 5393 * existing one. 5394 */ 5395 if (scannedCompatSet.equals(existingSet)) { 5396 // Migrate the old signatures to the new scheme. 5397 existingSigs.assignSignatures(scannedPkg.mSignatures); 5398 // The new KeySets will be re-added later in the scanning process. 5399 synchronized (mPackages) { 5400 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5401 } 5402 return PackageManager.SIGNATURE_MATCH; 5403 } 5404 return PackageManager.SIGNATURE_NO_MATCH; 5405 } 5406 5407 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5408 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5409 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5410 } 5411 5412 private int compareSignaturesRecover(PackageSignatures existingSigs, 5413 PackageParser.Package scannedPkg) { 5414 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5415 return PackageManager.SIGNATURE_NO_MATCH; 5416 } 5417 5418 String msg = null; 5419 try { 5420 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5421 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5422 + scannedPkg.packageName); 5423 return PackageManager.SIGNATURE_MATCH; 5424 } 5425 } catch (CertificateException e) { 5426 msg = e.getMessage(); 5427 } 5428 5429 logCriticalInfo(Log.INFO, 5430 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5431 return PackageManager.SIGNATURE_NO_MATCH; 5432 } 5433 5434 @Override 5435 public List<String> getAllPackages() { 5436 synchronized (mPackages) { 5437 return new ArrayList<String>(mPackages.keySet()); 5438 } 5439 } 5440 5441 @Override 5442 public String[] getPackagesForUid(int uid) { 5443 final int userId = UserHandle.getUserId(uid); 5444 uid = UserHandle.getAppId(uid); 5445 // reader 5446 synchronized (mPackages) { 5447 Object obj = mSettings.getUserIdLPr(uid); 5448 if (obj instanceof SharedUserSetting) { 5449 final SharedUserSetting sus = (SharedUserSetting) obj; 5450 final int N = sus.packages.size(); 5451 String[] res = new String[N]; 5452 final Iterator<PackageSetting> it = sus.packages.iterator(); 5453 int i = 0; 5454 while (it.hasNext()) { 5455 PackageSetting ps = it.next(); 5456 if (ps.getInstalled(userId)) { 5457 res[i++] = ps.name; 5458 } else { 5459 res = ArrayUtils.removeElement(String.class, res, res[i]); 5460 } 5461 } 5462 return res; 5463 } else if (obj instanceof PackageSetting) { 5464 final PackageSetting ps = (PackageSetting) obj; 5465 if (ps.getInstalled(userId)) { 5466 return new String[]{ps.name}; 5467 } 5468 } 5469 } 5470 return null; 5471 } 5472 5473 @Override 5474 public String getNameForUid(int uid) { 5475 // reader 5476 synchronized (mPackages) { 5477 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5478 if (obj instanceof SharedUserSetting) { 5479 final SharedUserSetting sus = (SharedUserSetting) obj; 5480 return sus.name + ":" + sus.userId; 5481 } else if (obj instanceof PackageSetting) { 5482 final PackageSetting ps = (PackageSetting) obj; 5483 return ps.name; 5484 } 5485 } 5486 return null; 5487 } 5488 5489 @Override 5490 public int getUidForSharedUser(String sharedUserName) { 5491 if(sharedUserName == null) { 5492 return -1; 5493 } 5494 // reader 5495 synchronized (mPackages) { 5496 SharedUserSetting suid; 5497 try { 5498 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5499 if (suid != null) { 5500 return suid.userId; 5501 } 5502 } catch (PackageManagerException ignore) { 5503 // can't happen, but, still need to catch it 5504 } 5505 return -1; 5506 } 5507 } 5508 5509 @Override 5510 public int getFlagsForUid(int uid) { 5511 synchronized (mPackages) { 5512 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5513 if (obj instanceof SharedUserSetting) { 5514 final SharedUserSetting sus = (SharedUserSetting) obj; 5515 return sus.pkgFlags; 5516 } else if (obj instanceof PackageSetting) { 5517 final PackageSetting ps = (PackageSetting) obj; 5518 return ps.pkgFlags; 5519 } 5520 } 5521 return 0; 5522 } 5523 5524 @Override 5525 public int getPrivateFlagsForUid(int uid) { 5526 synchronized (mPackages) { 5527 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5528 if (obj instanceof SharedUserSetting) { 5529 final SharedUserSetting sus = (SharedUserSetting) obj; 5530 return sus.pkgPrivateFlags; 5531 } else if (obj instanceof PackageSetting) { 5532 final PackageSetting ps = (PackageSetting) obj; 5533 return ps.pkgPrivateFlags; 5534 } 5535 } 5536 return 0; 5537 } 5538 5539 @Override 5540 public boolean isUidPrivileged(int uid) { 5541 uid = UserHandle.getAppId(uid); 5542 // reader 5543 synchronized (mPackages) { 5544 Object obj = mSettings.getUserIdLPr(uid); 5545 if (obj instanceof SharedUserSetting) { 5546 final SharedUserSetting sus = (SharedUserSetting) obj; 5547 final Iterator<PackageSetting> it = sus.packages.iterator(); 5548 while (it.hasNext()) { 5549 if (it.next().isPrivileged()) { 5550 return true; 5551 } 5552 } 5553 } else if (obj instanceof PackageSetting) { 5554 final PackageSetting ps = (PackageSetting) obj; 5555 return ps.isPrivileged(); 5556 } 5557 } 5558 return false; 5559 } 5560 5561 @Override 5562 public String[] getAppOpPermissionPackages(String permissionName) { 5563 synchronized (mPackages) { 5564 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5565 if (pkgs == null) { 5566 return null; 5567 } 5568 return pkgs.toArray(new String[pkgs.size()]); 5569 } 5570 } 5571 5572 @Override 5573 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5574 int flags, int userId) { 5575 return resolveIntentInternal( 5576 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5577 } 5578 5579 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5580 int flags, int userId, boolean includeInstantApp) { 5581 try { 5582 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5583 5584 if (!sUserManager.exists(userId)) return null; 5585 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5586 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5587 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5588 5589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5590 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5591 flags, userId, includeInstantApp); 5592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5593 5594 final ResolveInfo bestChoice = 5595 chooseBestActivity(intent, resolvedType, flags, query, userId); 5596 return bestChoice; 5597 } finally { 5598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5599 } 5600 } 5601 5602 @Override 5603 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5604 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5605 throw new SecurityException( 5606 "findPersistentPreferredActivity can only be run by the system"); 5607 } 5608 if (!sUserManager.exists(userId)) { 5609 return null; 5610 } 5611 intent = updateIntentForResolve(intent); 5612 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5613 final int flags = updateFlagsForResolve(0, userId, intent, false); 5614 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5615 userId); 5616 synchronized (mPackages) { 5617 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5618 userId); 5619 } 5620 } 5621 5622 @Override 5623 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5624 IntentFilter filter, int match, ComponentName activity) { 5625 final int userId = UserHandle.getCallingUserId(); 5626 if (DEBUG_PREFERRED) { 5627 Log.v(TAG, "setLastChosenActivity intent=" + intent 5628 + " resolvedType=" + resolvedType 5629 + " flags=" + flags 5630 + " filter=" + filter 5631 + " match=" + match 5632 + " activity=" + activity); 5633 filter.dump(new PrintStreamPrinter(System.out), " "); 5634 } 5635 intent.setComponent(null); 5636 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5637 userId); 5638 // Find any earlier preferred or last chosen entries and nuke them 5639 findPreferredActivity(intent, resolvedType, 5640 flags, query, 0, false, true, false, userId); 5641 // Add the new activity as the last chosen for this filter 5642 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5643 "Setting last chosen"); 5644 } 5645 5646 @Override 5647 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5648 final int userId = UserHandle.getCallingUserId(); 5649 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5650 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5651 userId); 5652 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5653 false, false, false, userId); 5654 } 5655 5656 /** 5657 * Returns whether or not instant apps have been disabled remotely. 5658 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5659 * held. Otherwise we run the risk of deadlock. 5660 */ 5661 private boolean isEphemeralDisabled() { 5662 // ephemeral apps have been disabled across the board 5663 if (DISABLE_EPHEMERAL_APPS) { 5664 return true; 5665 } 5666 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5667 if (!mSystemReady) { 5668 return true; 5669 } 5670 // we can't get a content resolver until the system is ready; these checks must happen last 5671 final ContentResolver resolver = mContext.getContentResolver(); 5672 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5673 return true; 5674 } 5675 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5676 } 5677 5678 private boolean isEphemeralAllowed( 5679 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5680 boolean skipPackageCheck) { 5681 final int callingUser = UserHandle.getCallingUserId(); 5682 if (callingUser != UserHandle.USER_SYSTEM) { 5683 return false; 5684 } 5685 if (mInstantAppResolverConnection == null) { 5686 return false; 5687 } 5688 if (mInstantAppInstallerComponent == null) { 5689 return false; 5690 } 5691 if (intent.getComponent() != null) { 5692 return false; 5693 } 5694 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5695 return false; 5696 } 5697 if (!skipPackageCheck && intent.getPackage() != null) { 5698 return false; 5699 } 5700 final boolean isWebUri = hasWebURI(intent); 5701 if (!isWebUri || intent.getData().getHost() == null) { 5702 return false; 5703 } 5704 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5705 // Or if there's already an ephemeral app installed that handles the action 5706 synchronized (mPackages) { 5707 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5708 for (int n = 0; n < count; n++) { 5709 ResolveInfo info = resolvedActivities.get(n); 5710 String packageName = info.activityInfo.packageName; 5711 PackageSetting ps = mSettings.mPackages.get(packageName); 5712 if (ps != null) { 5713 // Try to get the status from User settings first 5714 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5715 int status = (int) (packedStatus >> 32); 5716 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5717 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5718 if (DEBUG_EPHEMERAL) { 5719 Slog.v(TAG, "DENY ephemeral apps;" 5720 + " pkg: " + packageName + ", status: " + status); 5721 } 5722 return false; 5723 } 5724 if (ps.getInstantApp(userId)) { 5725 return false; 5726 } 5727 } 5728 } 5729 } 5730 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5731 return true; 5732 } 5733 5734 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5735 Intent origIntent, String resolvedType, String callingPackage, 5736 int userId) { 5737 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5738 new InstantAppRequest(responseObj, origIntent, resolvedType, 5739 callingPackage, userId)); 5740 mHandler.sendMessage(msg); 5741 } 5742 5743 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5744 int flags, List<ResolveInfo> query, int userId) { 5745 if (query != null) { 5746 final int N = query.size(); 5747 if (N == 1) { 5748 return query.get(0); 5749 } else if (N > 1) { 5750 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5751 // If there is more than one activity with the same priority, 5752 // then let the user decide between them. 5753 ResolveInfo r0 = query.get(0); 5754 ResolveInfo r1 = query.get(1); 5755 if (DEBUG_INTENT_MATCHING || debug) { 5756 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5757 + r1.activityInfo.name + "=" + r1.priority); 5758 } 5759 // If the first activity has a higher priority, or a different 5760 // default, then it is always desirable to pick it. 5761 if (r0.priority != r1.priority 5762 || r0.preferredOrder != r1.preferredOrder 5763 || r0.isDefault != r1.isDefault) { 5764 return query.get(0); 5765 } 5766 // If we have saved a preference for a preferred activity for 5767 // this Intent, use that. 5768 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5769 flags, query, r0.priority, true, false, debug, userId); 5770 if (ri != null) { 5771 return ri; 5772 } 5773 // If we have an ephemeral app, use it 5774 for (int i = 0; i < N; i++) { 5775 ri = query.get(i); 5776 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5777 return ri; 5778 } 5779 } 5780 ri = new ResolveInfo(mResolveInfo); 5781 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5782 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5783 // If all of the options come from the same package, show the application's 5784 // label and icon instead of the generic resolver's. 5785 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5786 // and then throw away the ResolveInfo itself, meaning that the caller loses 5787 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5788 // a fallback for this case; we only set the target package's resources on 5789 // the ResolveInfo, not the ActivityInfo. 5790 final String intentPackage = intent.getPackage(); 5791 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5792 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5793 ri.resolvePackageName = intentPackage; 5794 if (userNeedsBadging(userId)) { 5795 ri.noResourceId = true; 5796 } else { 5797 ri.icon = appi.icon; 5798 } 5799 ri.iconResourceId = appi.icon; 5800 ri.labelRes = appi.labelRes; 5801 } 5802 ri.activityInfo.applicationInfo = new ApplicationInfo( 5803 ri.activityInfo.applicationInfo); 5804 if (userId != 0) { 5805 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5806 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5807 } 5808 // Make sure that the resolver is displayable in car mode 5809 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5810 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5811 return ri; 5812 } 5813 } 5814 return null; 5815 } 5816 5817 /** 5818 * Return true if the given list is not empty and all of its contents have 5819 * an activityInfo with the given package name. 5820 */ 5821 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5822 if (ArrayUtils.isEmpty(list)) { 5823 return false; 5824 } 5825 for (int i = 0, N = list.size(); i < N; i++) { 5826 final ResolveInfo ri = list.get(i); 5827 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5828 if (ai == null || !packageName.equals(ai.packageName)) { 5829 return false; 5830 } 5831 } 5832 return true; 5833 } 5834 5835 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5836 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5837 final int N = query.size(); 5838 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5839 .get(userId); 5840 // Get the list of persistent preferred activities that handle the intent 5841 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5842 List<PersistentPreferredActivity> pprefs = ppir != null 5843 ? ppir.queryIntent(intent, resolvedType, 5844 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5845 userId) 5846 : null; 5847 if (pprefs != null && pprefs.size() > 0) { 5848 final int M = pprefs.size(); 5849 for (int i=0; i<M; i++) { 5850 final PersistentPreferredActivity ppa = pprefs.get(i); 5851 if (DEBUG_PREFERRED || debug) { 5852 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5853 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5854 + "\n component=" + ppa.mComponent); 5855 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5856 } 5857 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5858 flags | MATCH_DISABLED_COMPONENTS, userId); 5859 if (DEBUG_PREFERRED || debug) { 5860 Slog.v(TAG, "Found persistent preferred activity:"); 5861 if (ai != null) { 5862 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5863 } else { 5864 Slog.v(TAG, " null"); 5865 } 5866 } 5867 if (ai == null) { 5868 // This previously registered persistent preferred activity 5869 // component is no longer known. Ignore it and do NOT remove it. 5870 continue; 5871 } 5872 for (int j=0; j<N; j++) { 5873 final ResolveInfo ri = query.get(j); 5874 if (!ri.activityInfo.applicationInfo.packageName 5875 .equals(ai.applicationInfo.packageName)) { 5876 continue; 5877 } 5878 if (!ri.activityInfo.name.equals(ai.name)) { 5879 continue; 5880 } 5881 // Found a persistent preference that can handle the intent. 5882 if (DEBUG_PREFERRED || debug) { 5883 Slog.v(TAG, "Returning persistent preferred activity: " + 5884 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5885 } 5886 return ri; 5887 } 5888 } 5889 } 5890 return null; 5891 } 5892 5893 // TODO: handle preferred activities missing while user has amnesia 5894 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5895 List<ResolveInfo> query, int priority, boolean always, 5896 boolean removeMatches, boolean debug, int userId) { 5897 if (!sUserManager.exists(userId)) return null; 5898 flags = updateFlagsForResolve(flags, userId, intent, false); 5899 intent = updateIntentForResolve(intent); 5900 // writer 5901 synchronized (mPackages) { 5902 // Try to find a matching persistent preferred activity. 5903 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5904 debug, userId); 5905 5906 // If a persistent preferred activity matched, use it. 5907 if (pri != null) { 5908 return pri; 5909 } 5910 5911 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5912 // Get the list of preferred activities that handle the intent 5913 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5914 List<PreferredActivity> prefs = pir != null 5915 ? pir.queryIntent(intent, resolvedType, 5916 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5917 userId) 5918 : null; 5919 if (prefs != null && prefs.size() > 0) { 5920 boolean changed = false; 5921 try { 5922 // First figure out how good the original match set is. 5923 // We will only allow preferred activities that came 5924 // from the same match quality. 5925 int match = 0; 5926 5927 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5928 5929 final int N = query.size(); 5930 for (int j=0; j<N; j++) { 5931 final ResolveInfo ri = query.get(j); 5932 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5933 + ": 0x" + Integer.toHexString(match)); 5934 if (ri.match > match) { 5935 match = ri.match; 5936 } 5937 } 5938 5939 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5940 + Integer.toHexString(match)); 5941 5942 match &= IntentFilter.MATCH_CATEGORY_MASK; 5943 final int M = prefs.size(); 5944 for (int i=0; i<M; i++) { 5945 final PreferredActivity pa = prefs.get(i); 5946 if (DEBUG_PREFERRED || debug) { 5947 Slog.v(TAG, "Checking PreferredActivity ds=" 5948 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5949 + "\n component=" + pa.mPref.mComponent); 5950 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5951 } 5952 if (pa.mPref.mMatch != match) { 5953 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5954 + Integer.toHexString(pa.mPref.mMatch)); 5955 continue; 5956 } 5957 // If it's not an "always" type preferred activity and that's what we're 5958 // looking for, skip it. 5959 if (always && !pa.mPref.mAlways) { 5960 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5961 continue; 5962 } 5963 final ActivityInfo ai = getActivityInfo( 5964 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5965 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5966 userId); 5967 if (DEBUG_PREFERRED || debug) { 5968 Slog.v(TAG, "Found preferred activity:"); 5969 if (ai != null) { 5970 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5971 } else { 5972 Slog.v(TAG, " null"); 5973 } 5974 } 5975 if (ai == null) { 5976 // This previously registered preferred activity 5977 // component is no longer known. Most likely an update 5978 // to the app was installed and in the new version this 5979 // component no longer exists. Clean it up by removing 5980 // it from the preferred activities list, and skip it. 5981 Slog.w(TAG, "Removing dangling preferred activity: " 5982 + pa.mPref.mComponent); 5983 pir.removeFilter(pa); 5984 changed = true; 5985 continue; 5986 } 5987 for (int j=0; j<N; j++) { 5988 final ResolveInfo ri = query.get(j); 5989 if (!ri.activityInfo.applicationInfo.packageName 5990 .equals(ai.applicationInfo.packageName)) { 5991 continue; 5992 } 5993 if (!ri.activityInfo.name.equals(ai.name)) { 5994 continue; 5995 } 5996 5997 if (removeMatches) { 5998 pir.removeFilter(pa); 5999 changed = true; 6000 if (DEBUG_PREFERRED) { 6001 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6002 } 6003 break; 6004 } 6005 6006 // Okay we found a previously set preferred or last chosen app. 6007 // If the result set is different from when this 6008 // was created, we need to clear it and re-ask the 6009 // user their preference, if we're looking for an "always" type entry. 6010 if (always && !pa.mPref.sameSet(query)) { 6011 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6012 + intent + " type " + resolvedType); 6013 if (DEBUG_PREFERRED) { 6014 Slog.v(TAG, "Removing preferred activity since set changed " 6015 + pa.mPref.mComponent); 6016 } 6017 pir.removeFilter(pa); 6018 // Re-add the filter as a "last chosen" entry (!always) 6019 PreferredActivity lastChosen = new PreferredActivity( 6020 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6021 pir.addFilter(lastChosen); 6022 changed = true; 6023 return null; 6024 } 6025 6026 // Yay! Either the set matched or we're looking for the last chosen 6027 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6028 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6029 return ri; 6030 } 6031 } 6032 } finally { 6033 if (changed) { 6034 if (DEBUG_PREFERRED) { 6035 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6036 } 6037 scheduleWritePackageRestrictionsLocked(userId); 6038 } 6039 } 6040 } 6041 } 6042 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6043 return null; 6044 } 6045 6046 /* 6047 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6048 */ 6049 @Override 6050 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6051 int targetUserId) { 6052 mContext.enforceCallingOrSelfPermission( 6053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6054 List<CrossProfileIntentFilter> matches = 6055 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6056 if (matches != null) { 6057 int size = matches.size(); 6058 for (int i = 0; i < size; i++) { 6059 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6060 } 6061 } 6062 if (hasWebURI(intent)) { 6063 // cross-profile app linking works only towards the parent. 6064 final UserInfo parent = getProfileParent(sourceUserId); 6065 synchronized(mPackages) { 6066 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6067 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6068 intent, resolvedType, flags, sourceUserId, parent.id); 6069 return xpDomainInfo != null; 6070 } 6071 } 6072 return false; 6073 } 6074 6075 private UserInfo getProfileParent(int userId) { 6076 final long identity = Binder.clearCallingIdentity(); 6077 try { 6078 return sUserManager.getProfileParent(userId); 6079 } finally { 6080 Binder.restoreCallingIdentity(identity); 6081 } 6082 } 6083 6084 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6085 String resolvedType, int userId) { 6086 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6087 if (resolver != null) { 6088 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6089 } 6090 return null; 6091 } 6092 6093 @Override 6094 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6095 String resolvedType, int flags, int userId) { 6096 try { 6097 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6098 6099 return new ParceledListSlice<>( 6100 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6101 } finally { 6102 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6103 } 6104 } 6105 6106 /** 6107 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6108 * instant, returns {@code null}. 6109 */ 6110 private String getInstantAppPackageName(int callingUid) { 6111 final int appId = UserHandle.getAppId(callingUid); 6112 synchronized (mPackages) { 6113 final Object obj = mSettings.getUserIdLPr(appId); 6114 if (obj instanceof PackageSetting) { 6115 final PackageSetting ps = (PackageSetting) obj; 6116 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6117 return isInstantApp ? ps.pkg.packageName : null; 6118 } 6119 } 6120 return null; 6121 } 6122 6123 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6124 String resolvedType, int flags, int userId) { 6125 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6126 } 6127 6128 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6129 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6130 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6131 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6132 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6133 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6134 false /* requireFullPermission */, false /* checkShell */, 6135 "query intent activities"); 6136 ComponentName comp = intent.getComponent(); 6137 if (comp == null) { 6138 if (intent.getSelector() != null) { 6139 intent = intent.getSelector(); 6140 comp = intent.getComponent(); 6141 } 6142 } 6143 6144 if (comp != null) { 6145 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6146 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6147 if (ai != null) { 6148 // When specifying an explicit component, we prevent the activity from being 6149 // used when either 1) the calling package is normal and the activity is within 6150 // an ephemeral application or 2) the calling package is ephemeral and the 6151 // activity is not visible to ephemeral applications. 6152 final boolean matchInstantApp = 6153 (flags & PackageManager.MATCH_INSTANT) != 0; 6154 final boolean matchVisibleToInstantAppOnly = 6155 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6156 final boolean isCallerInstantApp = 6157 instantAppPkgName != null; 6158 final boolean isTargetSameInstantApp = 6159 comp.getPackageName().equals(instantAppPkgName); 6160 final boolean isTargetInstantApp = 6161 (ai.applicationInfo.privateFlags 6162 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6163 final boolean isTargetHiddenFromInstantApp = 6164 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6165 final boolean blockResolution = 6166 !isTargetSameInstantApp 6167 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6168 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6169 && isTargetHiddenFromInstantApp)); 6170 if (!blockResolution) { 6171 final ResolveInfo ri = new ResolveInfo(); 6172 ri.activityInfo = ai; 6173 list.add(ri); 6174 } 6175 } 6176 return applyPostResolutionFilter(list, instantAppPkgName); 6177 } 6178 6179 // reader 6180 boolean sortResult = false; 6181 boolean addEphemeral = false; 6182 List<ResolveInfo> result; 6183 final String pkgName = intent.getPackage(); 6184 final boolean ephemeralDisabled = isEphemeralDisabled(); 6185 synchronized (mPackages) { 6186 if (pkgName == null) { 6187 List<CrossProfileIntentFilter> matchingFilters = 6188 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6189 // Check for results that need to skip the current profile. 6190 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6191 resolvedType, flags, userId); 6192 if (xpResolveInfo != null) { 6193 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6194 xpResult.add(xpResolveInfo); 6195 return applyPostResolutionFilter( 6196 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6197 } 6198 6199 // Check for results in the current profile. 6200 result = filterIfNotSystemUser(mActivities.queryIntent( 6201 intent, resolvedType, flags, userId), userId); 6202 addEphemeral = !ephemeralDisabled 6203 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6204 6205 // Check for cross profile results. 6206 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6207 xpResolveInfo = queryCrossProfileIntents( 6208 matchingFilters, intent, resolvedType, flags, userId, 6209 hasNonNegativePriorityResult); 6210 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6211 boolean isVisibleToUser = filterIfNotSystemUser( 6212 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6213 if (isVisibleToUser) { 6214 result.add(xpResolveInfo); 6215 sortResult = true; 6216 } 6217 } 6218 if (hasWebURI(intent)) { 6219 CrossProfileDomainInfo xpDomainInfo = null; 6220 final UserInfo parent = getProfileParent(userId); 6221 if (parent != null) { 6222 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6223 flags, userId, parent.id); 6224 } 6225 if (xpDomainInfo != null) { 6226 if (xpResolveInfo != null) { 6227 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6228 // in the result. 6229 result.remove(xpResolveInfo); 6230 } 6231 if (result.size() == 0 && !addEphemeral) { 6232 // No result in current profile, but found candidate in parent user. 6233 // And we are not going to add emphemeral app, so we can return the 6234 // result straight away. 6235 result.add(xpDomainInfo.resolveInfo); 6236 return applyPostResolutionFilter(result, instantAppPkgName); 6237 } 6238 } else if (result.size() <= 1 && !addEphemeral) { 6239 // No result in parent user and <= 1 result in current profile, and we 6240 // are not going to add emphemeral app, so we can return the result without 6241 // further processing. 6242 return applyPostResolutionFilter(result, instantAppPkgName); 6243 } 6244 // We have more than one candidate (combining results from current and parent 6245 // profile), so we need filtering and sorting. 6246 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6247 intent, flags, result, xpDomainInfo, userId); 6248 sortResult = true; 6249 } 6250 } else { 6251 final PackageParser.Package pkg = mPackages.get(pkgName); 6252 if (pkg != null) { 6253 result = applyPostResolutionFilter(filterIfNotSystemUser( 6254 mActivities.queryIntentForPackage( 6255 intent, resolvedType, flags, pkg.activities, userId), 6256 userId), instantAppPkgName); 6257 } else { 6258 // the caller wants to resolve for a particular package; however, there 6259 // were no installed results, so, try to find an ephemeral result 6260 addEphemeral = !ephemeralDisabled 6261 && isEphemeralAllowed( 6262 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6263 result = new ArrayList<ResolveInfo>(); 6264 } 6265 } 6266 } 6267 if (addEphemeral) { 6268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6269 final InstantAppRequest requestObject = new InstantAppRequest( 6270 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6271 null /*callingPackage*/, userId); 6272 final AuxiliaryResolveInfo auxiliaryResponse = 6273 InstantAppResolver.doInstantAppResolutionPhaseOne( 6274 mContext, mInstantAppResolverConnection, requestObject); 6275 if (auxiliaryResponse != null) { 6276 if (DEBUG_EPHEMERAL) { 6277 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6278 } 6279 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6280 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6281 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6282 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6283 // make sure this resolver is the default 6284 ephemeralInstaller.isDefault = true; 6285 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6286 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6287 // add a non-generic filter 6288 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6289 ephemeralInstaller.filter.addDataPath( 6290 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6291 ephemeralInstaller.instantAppAvailable = true; 6292 result.add(ephemeralInstaller); 6293 } 6294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6295 } 6296 if (sortResult) { 6297 Collections.sort(result, mResolvePrioritySorter); 6298 } 6299 return applyPostResolutionFilter(result, instantAppPkgName); 6300 } 6301 6302 private static class CrossProfileDomainInfo { 6303 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6304 ResolveInfo resolveInfo; 6305 /* Best domain verification status of the activities found in the other profile */ 6306 int bestDomainVerificationStatus; 6307 } 6308 6309 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6310 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6311 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6312 sourceUserId)) { 6313 return null; 6314 } 6315 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6316 resolvedType, flags, parentUserId); 6317 6318 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6319 return null; 6320 } 6321 CrossProfileDomainInfo result = null; 6322 int size = resultTargetUser.size(); 6323 for (int i = 0; i < size; i++) { 6324 ResolveInfo riTargetUser = resultTargetUser.get(i); 6325 // Intent filter verification is only for filters that specify a host. So don't return 6326 // those that handle all web uris. 6327 if (riTargetUser.handleAllWebDataURI) { 6328 continue; 6329 } 6330 String packageName = riTargetUser.activityInfo.packageName; 6331 PackageSetting ps = mSettings.mPackages.get(packageName); 6332 if (ps == null) { 6333 continue; 6334 } 6335 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6336 int status = (int)(verificationState >> 32); 6337 if (result == null) { 6338 result = new CrossProfileDomainInfo(); 6339 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6340 sourceUserId, parentUserId); 6341 result.bestDomainVerificationStatus = status; 6342 } else { 6343 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6344 result.bestDomainVerificationStatus); 6345 } 6346 } 6347 // Don't consider matches with status NEVER across profiles. 6348 if (result != null && result.bestDomainVerificationStatus 6349 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6350 return null; 6351 } 6352 return result; 6353 } 6354 6355 /** 6356 * Verification statuses are ordered from the worse to the best, except for 6357 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6358 */ 6359 private int bestDomainVerificationStatus(int status1, int status2) { 6360 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6361 return status2; 6362 } 6363 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6364 return status1; 6365 } 6366 return (int) MathUtils.max(status1, status2); 6367 } 6368 6369 private boolean isUserEnabled(int userId) { 6370 long callingId = Binder.clearCallingIdentity(); 6371 try { 6372 UserInfo userInfo = sUserManager.getUserInfo(userId); 6373 return userInfo != null && userInfo.isEnabled(); 6374 } finally { 6375 Binder.restoreCallingIdentity(callingId); 6376 } 6377 } 6378 6379 /** 6380 * Filter out activities with systemUserOnly flag set, when current user is not System. 6381 * 6382 * @return filtered list 6383 */ 6384 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6385 if (userId == UserHandle.USER_SYSTEM) { 6386 return resolveInfos; 6387 } 6388 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6389 ResolveInfo info = resolveInfos.get(i); 6390 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6391 resolveInfos.remove(i); 6392 } 6393 } 6394 return resolveInfos; 6395 } 6396 6397 /** 6398 * Filters out ephemeral activities. 6399 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6400 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6401 * 6402 * @param resolveInfos The pre-filtered list of resolved activities 6403 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6404 * is performed. 6405 * @return A filtered list of resolved activities. 6406 */ 6407 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6408 String ephemeralPkgName) { 6409 // TODO: When adding on-demand split support for non-instant apps, remove this check 6410 // and always apply post filtering 6411 if (ephemeralPkgName == null) { 6412 return resolveInfos; 6413 } 6414 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6415 final ResolveInfo info = resolveInfos.get(i); 6416 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6417 // allow activities that are defined in the provided package 6418 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6419 if (info.activityInfo.splitName != null 6420 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6421 info.activityInfo.splitName)) { 6422 // requested activity is defined in a split that hasn't been installed yet. 6423 // add the installer to the resolve list 6424 if (DEBUG_EPHEMERAL) { 6425 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6426 } 6427 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6428 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6429 info.activityInfo.packageName, info.activityInfo.splitName, 6430 info.activityInfo.applicationInfo.versionCode); 6431 // make sure this resolver is the default 6432 installerInfo.isDefault = true; 6433 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6434 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6435 // add a non-generic filter 6436 installerInfo.filter = new IntentFilter(); 6437 // load resources from the correct package 6438 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6439 resolveInfos.set(i, installerInfo); 6440 } 6441 continue; 6442 } 6443 // allow activities that have been explicitly exposed to ephemeral apps 6444 if (!isEphemeralApp 6445 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6446 continue; 6447 } 6448 resolveInfos.remove(i); 6449 } 6450 return resolveInfos; 6451 } 6452 6453 /** 6454 * @param resolveInfos list of resolve infos in descending priority order 6455 * @return if the list contains a resolve info with non-negative priority 6456 */ 6457 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6458 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6459 } 6460 6461 private static boolean hasWebURI(Intent intent) { 6462 if (intent.getData() == null) { 6463 return false; 6464 } 6465 final String scheme = intent.getScheme(); 6466 if (TextUtils.isEmpty(scheme)) { 6467 return false; 6468 } 6469 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6470 } 6471 6472 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6473 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6474 int userId) { 6475 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6476 6477 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6478 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6479 candidates.size()); 6480 } 6481 6482 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6483 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6484 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6485 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6486 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6487 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6488 6489 synchronized (mPackages) { 6490 final int count = candidates.size(); 6491 // First, try to use linked apps. Partition the candidates into four lists: 6492 // one for the final results, one for the "do not use ever", one for "undefined status" 6493 // and finally one for "browser app type". 6494 for (int n=0; n<count; n++) { 6495 ResolveInfo info = candidates.get(n); 6496 String packageName = info.activityInfo.packageName; 6497 PackageSetting ps = mSettings.mPackages.get(packageName); 6498 if (ps != null) { 6499 // Add to the special match all list (Browser use case) 6500 if (info.handleAllWebDataURI) { 6501 matchAllList.add(info); 6502 continue; 6503 } 6504 // Try to get the status from User settings first 6505 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6506 int status = (int)(packedStatus >> 32); 6507 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6508 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6509 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6510 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6511 + " : linkgen=" + linkGeneration); 6512 } 6513 // Use link-enabled generation as preferredOrder, i.e. 6514 // prefer newly-enabled over earlier-enabled. 6515 info.preferredOrder = linkGeneration; 6516 alwaysList.add(info); 6517 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6518 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6519 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6520 } 6521 neverList.add(info); 6522 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6523 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6524 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6525 } 6526 alwaysAskList.add(info); 6527 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6528 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6529 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6530 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6531 } 6532 undefinedList.add(info); 6533 } 6534 } 6535 } 6536 6537 // We'll want to include browser possibilities in a few cases 6538 boolean includeBrowser = false; 6539 6540 // First try to add the "always" resolution(s) for the current user, if any 6541 if (alwaysList.size() > 0) { 6542 result.addAll(alwaysList); 6543 } else { 6544 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6545 result.addAll(undefinedList); 6546 // Maybe add one for the other profile. 6547 if (xpDomainInfo != null && ( 6548 xpDomainInfo.bestDomainVerificationStatus 6549 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6550 result.add(xpDomainInfo.resolveInfo); 6551 } 6552 includeBrowser = true; 6553 } 6554 6555 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6556 // If there were 'always' entries their preferred order has been set, so we also 6557 // back that off to make the alternatives equivalent 6558 if (alwaysAskList.size() > 0) { 6559 for (ResolveInfo i : result) { 6560 i.preferredOrder = 0; 6561 } 6562 result.addAll(alwaysAskList); 6563 includeBrowser = true; 6564 } 6565 6566 if (includeBrowser) { 6567 // Also add browsers (all of them or only the default one) 6568 if (DEBUG_DOMAIN_VERIFICATION) { 6569 Slog.v(TAG, " ...including browsers in candidate set"); 6570 } 6571 if ((matchFlags & MATCH_ALL) != 0) { 6572 result.addAll(matchAllList); 6573 } else { 6574 // Browser/generic handling case. If there's a default browser, go straight 6575 // to that (but only if there is no other higher-priority match). 6576 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6577 int maxMatchPrio = 0; 6578 ResolveInfo defaultBrowserMatch = null; 6579 final int numCandidates = matchAllList.size(); 6580 for (int n = 0; n < numCandidates; n++) { 6581 ResolveInfo info = matchAllList.get(n); 6582 // track the highest overall match priority... 6583 if (info.priority > maxMatchPrio) { 6584 maxMatchPrio = info.priority; 6585 } 6586 // ...and the highest-priority default browser match 6587 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6588 if (defaultBrowserMatch == null 6589 || (defaultBrowserMatch.priority < info.priority)) { 6590 if (debug) { 6591 Slog.v(TAG, "Considering default browser match " + info); 6592 } 6593 defaultBrowserMatch = info; 6594 } 6595 } 6596 } 6597 if (defaultBrowserMatch != null 6598 && defaultBrowserMatch.priority >= maxMatchPrio 6599 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6600 { 6601 if (debug) { 6602 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6603 } 6604 result.add(defaultBrowserMatch); 6605 } else { 6606 result.addAll(matchAllList); 6607 } 6608 } 6609 6610 // If there is nothing selected, add all candidates and remove the ones that the user 6611 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6612 if (result.size() == 0) { 6613 result.addAll(candidates); 6614 result.removeAll(neverList); 6615 } 6616 } 6617 } 6618 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6619 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6620 result.size()); 6621 for (ResolveInfo info : result) { 6622 Slog.v(TAG, " + " + info.activityInfo); 6623 } 6624 } 6625 return result; 6626 } 6627 6628 // Returns a packed value as a long: 6629 // 6630 // high 'int'-sized word: link status: undefined/ask/never/always. 6631 // low 'int'-sized word: relative priority among 'always' results. 6632 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6633 long result = ps.getDomainVerificationStatusForUser(userId); 6634 // if none available, get the master status 6635 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6636 if (ps.getIntentFilterVerificationInfo() != null) { 6637 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6638 } 6639 } 6640 return result; 6641 } 6642 6643 private ResolveInfo querySkipCurrentProfileIntents( 6644 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6645 int flags, int sourceUserId) { 6646 if (matchingFilters != null) { 6647 int size = matchingFilters.size(); 6648 for (int i = 0; i < size; i ++) { 6649 CrossProfileIntentFilter filter = matchingFilters.get(i); 6650 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6651 // Checking if there are activities in the target user that can handle the 6652 // intent. 6653 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6654 resolvedType, flags, sourceUserId); 6655 if (resolveInfo != null) { 6656 return resolveInfo; 6657 } 6658 } 6659 } 6660 } 6661 return null; 6662 } 6663 6664 // Return matching ResolveInfo in target user if any. 6665 private ResolveInfo queryCrossProfileIntents( 6666 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6667 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6668 if (matchingFilters != null) { 6669 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6670 // match the same intent. For performance reasons, it is better not to 6671 // run queryIntent twice for the same userId 6672 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6673 int size = matchingFilters.size(); 6674 for (int i = 0; i < size; i++) { 6675 CrossProfileIntentFilter filter = matchingFilters.get(i); 6676 int targetUserId = filter.getTargetUserId(); 6677 boolean skipCurrentProfile = 6678 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6679 boolean skipCurrentProfileIfNoMatchFound = 6680 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6681 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6682 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6683 // Checking if there are activities in the target user that can handle the 6684 // intent. 6685 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6686 resolvedType, flags, sourceUserId); 6687 if (resolveInfo != null) return resolveInfo; 6688 alreadyTriedUserIds.put(targetUserId, true); 6689 } 6690 } 6691 } 6692 return null; 6693 } 6694 6695 /** 6696 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6697 * will forward the intent to the filter's target user. 6698 * Otherwise, returns null. 6699 */ 6700 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6701 String resolvedType, int flags, int sourceUserId) { 6702 int targetUserId = filter.getTargetUserId(); 6703 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6704 resolvedType, flags, targetUserId); 6705 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6706 // If all the matches in the target profile are suspended, return null. 6707 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6708 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6709 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6710 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6711 targetUserId); 6712 } 6713 } 6714 } 6715 return null; 6716 } 6717 6718 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6719 int sourceUserId, int targetUserId) { 6720 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6721 long ident = Binder.clearCallingIdentity(); 6722 boolean targetIsProfile; 6723 try { 6724 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6725 } finally { 6726 Binder.restoreCallingIdentity(ident); 6727 } 6728 String className; 6729 if (targetIsProfile) { 6730 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6731 } else { 6732 className = FORWARD_INTENT_TO_PARENT; 6733 } 6734 ComponentName forwardingActivityComponentName = new ComponentName( 6735 mAndroidApplication.packageName, className); 6736 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6737 sourceUserId); 6738 if (!targetIsProfile) { 6739 forwardingActivityInfo.showUserIcon = targetUserId; 6740 forwardingResolveInfo.noResourceId = true; 6741 } 6742 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6743 forwardingResolveInfo.priority = 0; 6744 forwardingResolveInfo.preferredOrder = 0; 6745 forwardingResolveInfo.match = 0; 6746 forwardingResolveInfo.isDefault = true; 6747 forwardingResolveInfo.filter = filter; 6748 forwardingResolveInfo.targetUserId = targetUserId; 6749 return forwardingResolveInfo; 6750 } 6751 6752 @Override 6753 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6754 Intent[] specifics, String[] specificTypes, Intent intent, 6755 String resolvedType, int flags, int userId) { 6756 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6757 specificTypes, intent, resolvedType, flags, userId)); 6758 } 6759 6760 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6761 Intent[] specifics, String[] specificTypes, Intent intent, 6762 String resolvedType, int flags, int userId) { 6763 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6764 flags = updateFlagsForResolve(flags, userId, intent, false); 6765 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6766 false /* requireFullPermission */, false /* checkShell */, 6767 "query intent activity options"); 6768 final String resultsAction = intent.getAction(); 6769 6770 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6771 | PackageManager.GET_RESOLVED_FILTER, userId); 6772 6773 if (DEBUG_INTENT_MATCHING) { 6774 Log.v(TAG, "Query " + intent + ": " + results); 6775 } 6776 6777 int specificsPos = 0; 6778 int N; 6779 6780 // todo: note that the algorithm used here is O(N^2). This 6781 // isn't a problem in our current environment, but if we start running 6782 // into situations where we have more than 5 or 10 matches then this 6783 // should probably be changed to something smarter... 6784 6785 // First we go through and resolve each of the specific items 6786 // that were supplied, taking care of removing any corresponding 6787 // duplicate items in the generic resolve list. 6788 if (specifics != null) { 6789 for (int i=0; i<specifics.length; i++) { 6790 final Intent sintent = specifics[i]; 6791 if (sintent == null) { 6792 continue; 6793 } 6794 6795 if (DEBUG_INTENT_MATCHING) { 6796 Log.v(TAG, "Specific #" + i + ": " + sintent); 6797 } 6798 6799 String action = sintent.getAction(); 6800 if (resultsAction != null && resultsAction.equals(action)) { 6801 // If this action was explicitly requested, then don't 6802 // remove things that have it. 6803 action = null; 6804 } 6805 6806 ResolveInfo ri = null; 6807 ActivityInfo ai = null; 6808 6809 ComponentName comp = sintent.getComponent(); 6810 if (comp == null) { 6811 ri = resolveIntent( 6812 sintent, 6813 specificTypes != null ? specificTypes[i] : null, 6814 flags, userId); 6815 if (ri == null) { 6816 continue; 6817 } 6818 if (ri == mResolveInfo) { 6819 // ACK! Must do something better with this. 6820 } 6821 ai = ri.activityInfo; 6822 comp = new ComponentName(ai.applicationInfo.packageName, 6823 ai.name); 6824 } else { 6825 ai = getActivityInfo(comp, flags, userId); 6826 if (ai == null) { 6827 continue; 6828 } 6829 } 6830 6831 // Look for any generic query activities that are duplicates 6832 // of this specific one, and remove them from the results. 6833 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6834 N = results.size(); 6835 int j; 6836 for (j=specificsPos; j<N; j++) { 6837 ResolveInfo sri = results.get(j); 6838 if ((sri.activityInfo.name.equals(comp.getClassName()) 6839 && sri.activityInfo.applicationInfo.packageName.equals( 6840 comp.getPackageName())) 6841 || (action != null && sri.filter.matchAction(action))) { 6842 results.remove(j); 6843 if (DEBUG_INTENT_MATCHING) Log.v( 6844 TAG, "Removing duplicate item from " + j 6845 + " due to specific " + specificsPos); 6846 if (ri == null) { 6847 ri = sri; 6848 } 6849 j--; 6850 N--; 6851 } 6852 } 6853 6854 // Add this specific item to its proper place. 6855 if (ri == null) { 6856 ri = new ResolveInfo(); 6857 ri.activityInfo = ai; 6858 } 6859 results.add(specificsPos, ri); 6860 ri.specificIndex = i; 6861 specificsPos++; 6862 } 6863 } 6864 6865 // Now we go through the remaining generic results and remove any 6866 // duplicate actions that are found here. 6867 N = results.size(); 6868 for (int i=specificsPos; i<N-1; i++) { 6869 final ResolveInfo rii = results.get(i); 6870 if (rii.filter == null) { 6871 continue; 6872 } 6873 6874 // Iterate over all of the actions of this result's intent 6875 // filter... typically this should be just one. 6876 final Iterator<String> it = rii.filter.actionsIterator(); 6877 if (it == null) { 6878 continue; 6879 } 6880 while (it.hasNext()) { 6881 final String action = it.next(); 6882 if (resultsAction != null && resultsAction.equals(action)) { 6883 // If this action was explicitly requested, then don't 6884 // remove things that have it. 6885 continue; 6886 } 6887 for (int j=i+1; j<N; j++) { 6888 final ResolveInfo rij = results.get(j); 6889 if (rij.filter != null && rij.filter.hasAction(action)) { 6890 results.remove(j); 6891 if (DEBUG_INTENT_MATCHING) Log.v( 6892 TAG, "Removing duplicate item from " + j 6893 + " due to action " + action + " at " + i); 6894 j--; 6895 N--; 6896 } 6897 } 6898 } 6899 6900 // If the caller didn't request filter information, drop it now 6901 // so we don't have to marshall/unmarshall it. 6902 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6903 rii.filter = null; 6904 } 6905 } 6906 6907 // Filter out the caller activity if so requested. 6908 if (caller != null) { 6909 N = results.size(); 6910 for (int i=0; i<N; i++) { 6911 ActivityInfo ainfo = results.get(i).activityInfo; 6912 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6913 && caller.getClassName().equals(ainfo.name)) { 6914 results.remove(i); 6915 break; 6916 } 6917 } 6918 } 6919 6920 // If the caller didn't request filter information, 6921 // drop them now so we don't have to 6922 // marshall/unmarshall it. 6923 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6924 N = results.size(); 6925 for (int i=0; i<N; i++) { 6926 results.get(i).filter = null; 6927 } 6928 } 6929 6930 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6931 return results; 6932 } 6933 6934 @Override 6935 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6936 String resolvedType, int flags, int userId) { 6937 return new ParceledListSlice<>( 6938 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6939 } 6940 6941 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6942 String resolvedType, int flags, int userId) { 6943 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6944 flags = updateFlagsForResolve(flags, userId, intent, false); 6945 ComponentName comp = intent.getComponent(); 6946 if (comp == null) { 6947 if (intent.getSelector() != null) { 6948 intent = intent.getSelector(); 6949 comp = intent.getComponent(); 6950 } 6951 } 6952 if (comp != null) { 6953 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6954 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6955 if (ai != null) { 6956 ResolveInfo ri = new ResolveInfo(); 6957 ri.activityInfo = ai; 6958 list.add(ri); 6959 } 6960 return list; 6961 } 6962 6963 // reader 6964 synchronized (mPackages) { 6965 String pkgName = intent.getPackage(); 6966 if (pkgName == null) { 6967 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6968 } 6969 final PackageParser.Package pkg = mPackages.get(pkgName); 6970 if (pkg != null) { 6971 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6972 userId); 6973 } 6974 return Collections.emptyList(); 6975 } 6976 } 6977 6978 @Override 6979 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6980 if (!sUserManager.exists(userId)) return null; 6981 flags = updateFlagsForResolve(flags, userId, intent, false); 6982 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6983 if (query != null) { 6984 if (query.size() >= 1) { 6985 // If there is more than one service with the same priority, 6986 // just arbitrarily pick the first one. 6987 return query.get(0); 6988 } 6989 } 6990 return null; 6991 } 6992 6993 @Override 6994 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6995 String resolvedType, int flags, int userId) { 6996 return new ParceledListSlice<>( 6997 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6998 } 6999 7000 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7001 String resolvedType, int flags, int userId) { 7002 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7003 flags = updateFlagsForResolve(flags, userId, intent, false); 7004 ComponentName comp = intent.getComponent(); 7005 if (comp == null) { 7006 if (intent.getSelector() != null) { 7007 intent = intent.getSelector(); 7008 comp = intent.getComponent(); 7009 } 7010 } 7011 if (comp != null) { 7012 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7013 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7014 if (si != null) { 7015 final ResolveInfo ri = new ResolveInfo(); 7016 ri.serviceInfo = si; 7017 list.add(ri); 7018 } 7019 return list; 7020 } 7021 7022 // reader 7023 synchronized (mPackages) { 7024 String pkgName = intent.getPackage(); 7025 if (pkgName == null) { 7026 return mServices.queryIntent(intent, resolvedType, flags, userId); 7027 } 7028 final PackageParser.Package pkg = mPackages.get(pkgName); 7029 if (pkg != null) { 7030 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7031 userId); 7032 } 7033 return Collections.emptyList(); 7034 } 7035 } 7036 7037 @Override 7038 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7039 String resolvedType, int flags, int userId) { 7040 return new ParceledListSlice<>( 7041 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7042 } 7043 7044 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7045 Intent intent, String resolvedType, int flags, int userId) { 7046 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7047 flags = updateFlagsForResolve(flags, userId, intent, false); 7048 ComponentName comp = intent.getComponent(); 7049 if (comp == null) { 7050 if (intent.getSelector() != null) { 7051 intent = intent.getSelector(); 7052 comp = intent.getComponent(); 7053 } 7054 } 7055 if (comp != null) { 7056 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7057 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7058 if (pi != null) { 7059 final ResolveInfo ri = new ResolveInfo(); 7060 ri.providerInfo = pi; 7061 list.add(ri); 7062 } 7063 return list; 7064 } 7065 7066 // reader 7067 synchronized (mPackages) { 7068 String pkgName = intent.getPackage(); 7069 if (pkgName == null) { 7070 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7071 } 7072 final PackageParser.Package pkg = mPackages.get(pkgName); 7073 if (pkg != null) { 7074 return mProviders.queryIntentForPackage( 7075 intent, resolvedType, flags, pkg.providers, userId); 7076 } 7077 return Collections.emptyList(); 7078 } 7079 } 7080 7081 @Override 7082 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7083 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7084 flags = updateFlagsForPackage(flags, userId, null); 7085 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7086 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7087 true /* requireFullPermission */, false /* checkShell */, 7088 "get installed packages"); 7089 7090 // writer 7091 synchronized (mPackages) { 7092 ArrayList<PackageInfo> list; 7093 if (listUninstalled) { 7094 list = new ArrayList<>(mSettings.mPackages.size()); 7095 for (PackageSetting ps : mSettings.mPackages.values()) { 7096 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7097 continue; 7098 } 7099 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7100 if (pi != null) { 7101 list.add(pi); 7102 } 7103 } 7104 } else { 7105 list = new ArrayList<>(mPackages.size()); 7106 for (PackageParser.Package p : mPackages.values()) { 7107 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7108 Binder.getCallingUid(), userId)) { 7109 continue; 7110 } 7111 final PackageInfo pi = generatePackageInfo((PackageSetting) 7112 p.mExtras, flags, userId); 7113 if (pi != null) { 7114 list.add(pi); 7115 } 7116 } 7117 } 7118 7119 return new ParceledListSlice<>(list); 7120 } 7121 } 7122 7123 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7124 String[] permissions, boolean[] tmp, int flags, int userId) { 7125 int numMatch = 0; 7126 final PermissionsState permissionsState = ps.getPermissionsState(); 7127 for (int i=0; i<permissions.length; i++) { 7128 final String permission = permissions[i]; 7129 if (permissionsState.hasPermission(permission, userId)) { 7130 tmp[i] = true; 7131 numMatch++; 7132 } else { 7133 tmp[i] = false; 7134 } 7135 } 7136 if (numMatch == 0) { 7137 return; 7138 } 7139 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7140 7141 // The above might return null in cases of uninstalled apps or install-state 7142 // skew across users/profiles. 7143 if (pi != null) { 7144 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7145 if (numMatch == permissions.length) { 7146 pi.requestedPermissions = permissions; 7147 } else { 7148 pi.requestedPermissions = new String[numMatch]; 7149 numMatch = 0; 7150 for (int i=0; i<permissions.length; i++) { 7151 if (tmp[i]) { 7152 pi.requestedPermissions[numMatch] = permissions[i]; 7153 numMatch++; 7154 } 7155 } 7156 } 7157 } 7158 list.add(pi); 7159 } 7160 } 7161 7162 @Override 7163 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7164 String[] permissions, int flags, int userId) { 7165 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7166 flags = updateFlagsForPackage(flags, userId, permissions); 7167 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7168 true /* requireFullPermission */, false /* checkShell */, 7169 "get packages holding permissions"); 7170 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7171 7172 // writer 7173 synchronized (mPackages) { 7174 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7175 boolean[] tmpBools = new boolean[permissions.length]; 7176 if (listUninstalled) { 7177 for (PackageSetting ps : mSettings.mPackages.values()) { 7178 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7179 userId); 7180 } 7181 } else { 7182 for (PackageParser.Package pkg : mPackages.values()) { 7183 PackageSetting ps = (PackageSetting)pkg.mExtras; 7184 if (ps != null) { 7185 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7186 userId); 7187 } 7188 } 7189 } 7190 7191 return new ParceledListSlice<PackageInfo>(list); 7192 } 7193 } 7194 7195 @Override 7196 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7197 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7198 flags = updateFlagsForApplication(flags, userId, null); 7199 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7200 7201 // writer 7202 synchronized (mPackages) { 7203 ArrayList<ApplicationInfo> list; 7204 if (listUninstalled) { 7205 list = new ArrayList<>(mSettings.mPackages.size()); 7206 for (PackageSetting ps : mSettings.mPackages.values()) { 7207 ApplicationInfo ai; 7208 int effectiveFlags = flags; 7209 if (ps.isSystem()) { 7210 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7211 } 7212 if (ps.pkg != null) { 7213 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7214 continue; 7215 } 7216 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7217 ps.readUserState(userId), userId); 7218 if (ai != null) { 7219 rebaseEnabledOverlays(ai, userId); 7220 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7221 } 7222 } else { 7223 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7224 // and already converts to externally visible package name 7225 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7226 Binder.getCallingUid(), effectiveFlags, userId); 7227 } 7228 if (ai != null) { 7229 list.add(ai); 7230 } 7231 } 7232 } else { 7233 list = new ArrayList<>(mPackages.size()); 7234 for (PackageParser.Package p : mPackages.values()) { 7235 if (p.mExtras != null) { 7236 PackageSetting ps = (PackageSetting) p.mExtras; 7237 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7238 continue; 7239 } 7240 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7241 ps.readUserState(userId), userId); 7242 if (ai != null) { 7243 rebaseEnabledOverlays(ai, userId); 7244 ai.packageName = resolveExternalPackageNameLPr(p); 7245 list.add(ai); 7246 } 7247 } 7248 } 7249 } 7250 7251 return new ParceledListSlice<>(list); 7252 } 7253 } 7254 7255 @Override 7256 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7257 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7258 return null; 7259 } 7260 7261 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7262 "getEphemeralApplications"); 7263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7264 true /* requireFullPermission */, false /* checkShell */, 7265 "getEphemeralApplications"); 7266 synchronized (mPackages) { 7267 List<InstantAppInfo> instantApps = mInstantAppRegistry 7268 .getInstantAppsLPr(userId); 7269 if (instantApps != null) { 7270 return new ParceledListSlice<>(instantApps); 7271 } 7272 } 7273 return null; 7274 } 7275 7276 @Override 7277 public boolean isInstantApp(String packageName, int userId) { 7278 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7279 true /* requireFullPermission */, false /* checkShell */, 7280 "isInstantApp"); 7281 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7282 return false; 7283 } 7284 7285 synchronized (mPackages) { 7286 final PackageSetting ps = mSettings.mPackages.get(packageName); 7287 final boolean returnAllowed = 7288 ps != null 7289 && (isCallerSameApp(packageName) 7290 || mContext.checkCallingOrSelfPermission( 7291 android.Manifest.permission.ACCESS_INSTANT_APPS) 7292 == PERMISSION_GRANTED 7293 || mInstantAppRegistry.isInstantAccessGranted( 7294 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7295 if (returnAllowed) { 7296 return ps.getInstantApp(userId); 7297 } 7298 } 7299 return false; 7300 } 7301 7302 @Override 7303 public byte[] getInstantAppCookie(String packageName, int userId) { 7304 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7305 return null; 7306 } 7307 7308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7309 true /* requireFullPermission */, false /* checkShell */, 7310 "getInstantAppCookie"); 7311 if (!isCallerSameApp(packageName)) { 7312 return null; 7313 } 7314 synchronized (mPackages) { 7315 return mInstantAppRegistry.getInstantAppCookieLPw( 7316 packageName, userId); 7317 } 7318 } 7319 7320 @Override 7321 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7322 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7323 return true; 7324 } 7325 7326 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7327 true /* requireFullPermission */, true /* checkShell */, 7328 "setInstantAppCookie"); 7329 if (!isCallerSameApp(packageName)) { 7330 return false; 7331 } 7332 synchronized (mPackages) { 7333 return mInstantAppRegistry.setInstantAppCookieLPw( 7334 packageName, cookie, userId); 7335 } 7336 } 7337 7338 @Override 7339 public Bitmap getInstantAppIcon(String packageName, int userId) { 7340 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7341 return null; 7342 } 7343 7344 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7345 "getInstantAppIcon"); 7346 7347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7348 true /* requireFullPermission */, false /* checkShell */, 7349 "getInstantAppIcon"); 7350 7351 synchronized (mPackages) { 7352 return mInstantAppRegistry.getInstantAppIconLPw( 7353 packageName, userId); 7354 } 7355 } 7356 7357 private boolean isCallerSameApp(String packageName) { 7358 PackageParser.Package pkg = mPackages.get(packageName); 7359 return pkg != null 7360 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7361 } 7362 7363 @Override 7364 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7365 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7366 } 7367 7368 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7369 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7370 7371 // reader 7372 synchronized (mPackages) { 7373 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7374 final int userId = UserHandle.getCallingUserId(); 7375 while (i.hasNext()) { 7376 final PackageParser.Package p = i.next(); 7377 if (p.applicationInfo == null) continue; 7378 7379 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7380 && !p.applicationInfo.isDirectBootAware(); 7381 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7382 && p.applicationInfo.isDirectBootAware(); 7383 7384 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7385 && (!mSafeMode || isSystemApp(p)) 7386 && (matchesUnaware || matchesAware)) { 7387 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7388 if (ps != null) { 7389 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7390 ps.readUserState(userId), userId); 7391 if (ai != null) { 7392 rebaseEnabledOverlays(ai, userId); 7393 finalList.add(ai); 7394 } 7395 } 7396 } 7397 } 7398 } 7399 7400 return finalList; 7401 } 7402 7403 @Override 7404 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7405 if (!sUserManager.exists(userId)) return null; 7406 flags = updateFlagsForComponent(flags, userId, name); 7407 // reader 7408 synchronized (mPackages) { 7409 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7410 PackageSetting ps = provider != null 7411 ? mSettings.mPackages.get(provider.owner.packageName) 7412 : null; 7413 return ps != null 7414 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7415 ? PackageParser.generateProviderInfo(provider, flags, 7416 ps.readUserState(userId), userId) 7417 : null; 7418 } 7419 } 7420 7421 /** 7422 * @deprecated 7423 */ 7424 @Deprecated 7425 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7426 // reader 7427 synchronized (mPackages) { 7428 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7429 .entrySet().iterator(); 7430 final int userId = UserHandle.getCallingUserId(); 7431 while (i.hasNext()) { 7432 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7433 PackageParser.Provider p = entry.getValue(); 7434 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7435 7436 if (ps != null && p.syncable 7437 && (!mSafeMode || (p.info.applicationInfo.flags 7438 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7439 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7440 ps.readUserState(userId), userId); 7441 if (info != null) { 7442 outNames.add(entry.getKey()); 7443 outInfo.add(info); 7444 } 7445 } 7446 } 7447 } 7448 } 7449 7450 @Override 7451 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7452 int uid, int flags, String metaDataKey) { 7453 final int userId = processName != null ? UserHandle.getUserId(uid) 7454 : UserHandle.getCallingUserId(); 7455 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7456 flags = updateFlagsForComponent(flags, userId, processName); 7457 7458 ArrayList<ProviderInfo> finalList = null; 7459 // reader 7460 synchronized (mPackages) { 7461 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7462 while (i.hasNext()) { 7463 final PackageParser.Provider p = i.next(); 7464 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7465 if (ps != null && p.info.authority != null 7466 && (processName == null 7467 || (p.info.processName.equals(processName) 7468 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7469 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7470 7471 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7472 // parameter. 7473 if (metaDataKey != null 7474 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7475 continue; 7476 } 7477 7478 if (finalList == null) { 7479 finalList = new ArrayList<ProviderInfo>(3); 7480 } 7481 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7482 ps.readUserState(userId), userId); 7483 if (info != null) { 7484 finalList.add(info); 7485 } 7486 } 7487 } 7488 } 7489 7490 if (finalList != null) { 7491 Collections.sort(finalList, mProviderInitOrderSorter); 7492 return new ParceledListSlice<ProviderInfo>(finalList); 7493 } 7494 7495 return ParceledListSlice.emptyList(); 7496 } 7497 7498 @Override 7499 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7500 // reader 7501 synchronized (mPackages) { 7502 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7503 return PackageParser.generateInstrumentationInfo(i, flags); 7504 } 7505 } 7506 7507 @Override 7508 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7509 String targetPackage, int flags) { 7510 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7511 } 7512 7513 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7514 int flags) { 7515 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7516 7517 // reader 7518 synchronized (mPackages) { 7519 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7520 while (i.hasNext()) { 7521 final PackageParser.Instrumentation p = i.next(); 7522 if (targetPackage == null 7523 || targetPackage.equals(p.info.targetPackage)) { 7524 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7525 flags); 7526 if (ii != null) { 7527 finalList.add(ii); 7528 } 7529 } 7530 } 7531 } 7532 7533 return finalList; 7534 } 7535 7536 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7537 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7538 try { 7539 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7540 } finally { 7541 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7542 } 7543 } 7544 7545 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7546 final File[] files = dir.listFiles(); 7547 if (ArrayUtils.isEmpty(files)) { 7548 Log.d(TAG, "No files in app dir " + dir); 7549 return; 7550 } 7551 7552 if (DEBUG_PACKAGE_SCANNING) { 7553 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7554 + " flags=0x" + Integer.toHexString(parseFlags)); 7555 } 7556 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7557 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7558 7559 // Submit files for parsing in parallel 7560 int fileCount = 0; 7561 for (File file : files) { 7562 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7563 && !PackageInstallerService.isStageName(file.getName()); 7564 if (!isPackage) { 7565 // Ignore entries which are not packages 7566 continue; 7567 } 7568 parallelPackageParser.submit(file, parseFlags); 7569 fileCount++; 7570 } 7571 7572 // Process results one by one 7573 for (; fileCount > 0; fileCount--) { 7574 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7575 Throwable throwable = parseResult.throwable; 7576 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7577 7578 if (throwable == null) { 7579 // Static shared libraries have synthetic package names 7580 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7581 renameStaticSharedLibraryPackage(parseResult.pkg); 7582 } 7583 try { 7584 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7585 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7586 currentTime, null); 7587 } 7588 } catch (PackageManagerException e) { 7589 errorCode = e.error; 7590 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7591 } 7592 } else if (throwable instanceof PackageParser.PackageParserException) { 7593 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7594 throwable; 7595 errorCode = e.error; 7596 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7597 } else { 7598 throw new IllegalStateException("Unexpected exception occurred while parsing " 7599 + parseResult.scanFile, throwable); 7600 } 7601 7602 // Delete invalid userdata apps 7603 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7604 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7605 logCriticalInfo(Log.WARN, 7606 "Deleting invalid package at " + parseResult.scanFile); 7607 removeCodePathLI(parseResult.scanFile); 7608 } 7609 } 7610 parallelPackageParser.close(); 7611 } 7612 7613 private static File getSettingsProblemFile() { 7614 File dataDir = Environment.getDataDirectory(); 7615 File systemDir = new File(dataDir, "system"); 7616 File fname = new File(systemDir, "uiderrors.txt"); 7617 return fname; 7618 } 7619 7620 static void reportSettingsProblem(int priority, String msg) { 7621 logCriticalInfo(priority, msg); 7622 } 7623 7624 public static void logCriticalInfo(int priority, String msg) { 7625 Slog.println(priority, TAG, msg); 7626 EventLogTags.writePmCriticalInfo(msg); 7627 try { 7628 File fname = getSettingsProblemFile(); 7629 FileOutputStream out = new FileOutputStream(fname, true); 7630 PrintWriter pw = new FastPrintWriter(out); 7631 SimpleDateFormat formatter = new SimpleDateFormat(); 7632 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7633 pw.println(dateString + ": " + msg); 7634 pw.close(); 7635 FileUtils.setPermissions( 7636 fname.toString(), 7637 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7638 -1, -1); 7639 } catch (java.io.IOException e) { 7640 } 7641 } 7642 7643 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7644 if (srcFile.isDirectory()) { 7645 final File baseFile = new File(pkg.baseCodePath); 7646 long maxModifiedTime = baseFile.lastModified(); 7647 if (pkg.splitCodePaths != null) { 7648 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7649 final File splitFile = new File(pkg.splitCodePaths[i]); 7650 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7651 } 7652 } 7653 return maxModifiedTime; 7654 } 7655 return srcFile.lastModified(); 7656 } 7657 7658 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7659 final int policyFlags) throws PackageManagerException { 7660 // When upgrading from pre-N MR1, verify the package time stamp using the package 7661 // directory and not the APK file. 7662 final long lastModifiedTime = mIsPreNMR1Upgrade 7663 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7664 if (ps != null 7665 && ps.codePath.equals(srcFile) 7666 && ps.timeStamp == lastModifiedTime 7667 && !isCompatSignatureUpdateNeeded(pkg) 7668 && !isRecoverSignatureUpdateNeeded(pkg)) { 7669 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7670 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7671 ArraySet<PublicKey> signingKs; 7672 synchronized (mPackages) { 7673 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7674 } 7675 if (ps.signatures.mSignatures != null 7676 && ps.signatures.mSignatures.length != 0 7677 && signingKs != null) { 7678 // Optimization: reuse the existing cached certificates 7679 // if the package appears to be unchanged. 7680 pkg.mSignatures = ps.signatures.mSignatures; 7681 pkg.mSigningKeys = signingKs; 7682 return; 7683 } 7684 7685 Slog.w(TAG, "PackageSetting for " + ps.name 7686 + " is missing signatures. Collecting certs again to recover them."); 7687 } else { 7688 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7689 } 7690 7691 try { 7692 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7693 PackageParser.collectCertificates(pkg, policyFlags); 7694 } catch (PackageParserException e) { 7695 throw PackageManagerException.from(e); 7696 } finally { 7697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7698 } 7699 } 7700 7701 /** 7702 * Traces a package scan. 7703 * @see #scanPackageLI(File, int, int, long, UserHandle) 7704 */ 7705 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7706 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7708 try { 7709 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7710 } finally { 7711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7712 } 7713 } 7714 7715 /** 7716 * Scans a package and returns the newly parsed package. 7717 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7718 */ 7719 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7720 long currentTime, UserHandle user) throws PackageManagerException { 7721 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7722 PackageParser pp = new PackageParser(); 7723 pp.setSeparateProcesses(mSeparateProcesses); 7724 pp.setOnlyCoreApps(mOnlyCore); 7725 pp.setDisplayMetrics(mMetrics); 7726 pp.setCallback(mPackageParserCallback); 7727 7728 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7729 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7730 } 7731 7732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7733 final PackageParser.Package pkg; 7734 try { 7735 pkg = pp.parsePackage(scanFile, parseFlags); 7736 } catch (PackageParserException e) { 7737 throw PackageManagerException.from(e); 7738 } finally { 7739 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7740 } 7741 7742 // Static shared libraries have synthetic package names 7743 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7744 renameStaticSharedLibraryPackage(pkg); 7745 } 7746 7747 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7748 } 7749 7750 /** 7751 * Scans a package and returns the newly parsed package. 7752 * @throws PackageManagerException on a parse error. 7753 */ 7754 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7755 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7756 throws PackageManagerException { 7757 // If the package has children and this is the first dive in the function 7758 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7759 // packages (parent and children) would be successfully scanned before the 7760 // actual scan since scanning mutates internal state and we want to atomically 7761 // install the package and its children. 7762 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7763 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7764 scanFlags |= SCAN_CHECK_ONLY; 7765 } 7766 } else { 7767 scanFlags &= ~SCAN_CHECK_ONLY; 7768 } 7769 7770 // Scan the parent 7771 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7772 scanFlags, currentTime, user); 7773 7774 // Scan the children 7775 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7776 for (int i = 0; i < childCount; i++) { 7777 PackageParser.Package childPackage = pkg.childPackages.get(i); 7778 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7779 currentTime, user); 7780 } 7781 7782 7783 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7784 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7785 } 7786 7787 return scannedPkg; 7788 } 7789 7790 /** 7791 * Scans a package and returns the newly parsed package. 7792 * @throws PackageManagerException on a parse error. 7793 */ 7794 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7795 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7796 throws PackageManagerException { 7797 PackageSetting ps = null; 7798 PackageSetting updatedPkg; 7799 // reader 7800 synchronized (mPackages) { 7801 // Look to see if we already know about this package. 7802 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7803 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7804 // This package has been renamed to its original name. Let's 7805 // use that. 7806 ps = mSettings.getPackageLPr(oldName); 7807 } 7808 // If there was no original package, see one for the real package name. 7809 if (ps == null) { 7810 ps = mSettings.getPackageLPr(pkg.packageName); 7811 } 7812 // Check to see if this package could be hiding/updating a system 7813 // package. Must look for it either under the original or real 7814 // package name depending on our state. 7815 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7816 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7817 7818 // If this is a package we don't know about on the system partition, we 7819 // may need to remove disabled child packages on the system partition 7820 // or may need to not add child packages if the parent apk is updated 7821 // on the data partition and no longer defines this child package. 7822 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7823 // If this is a parent package for an updated system app and this system 7824 // app got an OTA update which no longer defines some of the child packages 7825 // we have to prune them from the disabled system packages. 7826 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7827 if (disabledPs != null) { 7828 final int scannedChildCount = (pkg.childPackages != null) 7829 ? pkg.childPackages.size() : 0; 7830 final int disabledChildCount = disabledPs.childPackageNames != null 7831 ? disabledPs.childPackageNames.size() : 0; 7832 for (int i = 0; i < disabledChildCount; i++) { 7833 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7834 boolean disabledPackageAvailable = false; 7835 for (int j = 0; j < scannedChildCount; j++) { 7836 PackageParser.Package childPkg = pkg.childPackages.get(j); 7837 if (childPkg.packageName.equals(disabledChildPackageName)) { 7838 disabledPackageAvailable = true; 7839 break; 7840 } 7841 } 7842 if (!disabledPackageAvailable) { 7843 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7844 } 7845 } 7846 } 7847 } 7848 } 7849 7850 boolean updatedPkgBetter = false; 7851 // First check if this is a system package that may involve an update 7852 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7853 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7854 // it needs to drop FLAG_PRIVILEGED. 7855 if (locationIsPrivileged(scanFile)) { 7856 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7857 } else { 7858 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7859 } 7860 7861 if (ps != null && !ps.codePath.equals(scanFile)) { 7862 // The path has changed from what was last scanned... check the 7863 // version of the new path against what we have stored to determine 7864 // what to do. 7865 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7866 if (pkg.mVersionCode <= ps.versionCode) { 7867 // The system package has been updated and the code path does not match 7868 // Ignore entry. Skip it. 7869 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7870 + " ignored: updated version " + ps.versionCode 7871 + " better than this " + pkg.mVersionCode); 7872 if (!updatedPkg.codePath.equals(scanFile)) { 7873 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7874 + ps.name + " changing from " + updatedPkg.codePathString 7875 + " to " + scanFile); 7876 updatedPkg.codePath = scanFile; 7877 updatedPkg.codePathString = scanFile.toString(); 7878 updatedPkg.resourcePath = scanFile; 7879 updatedPkg.resourcePathString = scanFile.toString(); 7880 } 7881 updatedPkg.pkg = pkg; 7882 updatedPkg.versionCode = pkg.mVersionCode; 7883 7884 // Update the disabled system child packages to point to the package too. 7885 final int childCount = updatedPkg.childPackageNames != null 7886 ? updatedPkg.childPackageNames.size() : 0; 7887 for (int i = 0; i < childCount; i++) { 7888 String childPackageName = updatedPkg.childPackageNames.get(i); 7889 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7890 childPackageName); 7891 if (updatedChildPkg != null) { 7892 updatedChildPkg.pkg = pkg; 7893 updatedChildPkg.versionCode = pkg.mVersionCode; 7894 } 7895 } 7896 7897 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7898 + scanFile + " ignored: updated version " + ps.versionCode 7899 + " better than this " + pkg.mVersionCode); 7900 } else { 7901 // The current app on the system partition is better than 7902 // what we have updated to on the data partition; switch 7903 // back to the system partition version. 7904 // At this point, its safely assumed that package installation for 7905 // apps in system partition will go through. If not there won't be a working 7906 // version of the app 7907 // writer 7908 synchronized (mPackages) { 7909 // Just remove the loaded entries from package lists. 7910 mPackages.remove(ps.name); 7911 } 7912 7913 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7914 + " reverting from " + ps.codePathString 7915 + ": new version " + pkg.mVersionCode 7916 + " better than installed " + ps.versionCode); 7917 7918 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7919 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7920 synchronized (mInstallLock) { 7921 args.cleanUpResourcesLI(); 7922 } 7923 synchronized (mPackages) { 7924 mSettings.enableSystemPackageLPw(ps.name); 7925 } 7926 updatedPkgBetter = true; 7927 } 7928 } 7929 } 7930 7931 if (updatedPkg != null) { 7932 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7933 // initially 7934 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7935 7936 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7937 // flag set initially 7938 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7939 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7940 } 7941 } 7942 7943 // Verify certificates against what was last scanned 7944 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7945 7946 /* 7947 * A new system app appeared, but we already had a non-system one of the 7948 * same name installed earlier. 7949 */ 7950 boolean shouldHideSystemApp = false; 7951 if (updatedPkg == null && ps != null 7952 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7953 /* 7954 * Check to make sure the signatures match first. If they don't, 7955 * wipe the installed application and its data. 7956 */ 7957 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7958 != PackageManager.SIGNATURE_MATCH) { 7959 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7960 + " signatures don't match existing userdata copy; removing"); 7961 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7962 "scanPackageInternalLI")) { 7963 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7964 } 7965 ps = null; 7966 } else { 7967 /* 7968 * If the newly-added system app is an older version than the 7969 * already installed version, hide it. It will be scanned later 7970 * and re-added like an update. 7971 */ 7972 if (pkg.mVersionCode <= ps.versionCode) { 7973 shouldHideSystemApp = true; 7974 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7975 + " but new version " + pkg.mVersionCode + " better than installed " 7976 + ps.versionCode + "; hiding system"); 7977 } else { 7978 /* 7979 * The newly found system app is a newer version that the 7980 * one previously installed. Simply remove the 7981 * already-installed application and replace it with our own 7982 * while keeping the application data. 7983 */ 7984 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7985 + " reverting from " + ps.codePathString + ": new version " 7986 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7987 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7988 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7989 synchronized (mInstallLock) { 7990 args.cleanUpResourcesLI(); 7991 } 7992 } 7993 } 7994 } 7995 7996 // The apk is forward locked (not public) if its code and resources 7997 // are kept in different files. (except for app in either system or 7998 // vendor path). 7999 // TODO grab this value from PackageSettings 8000 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8001 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8002 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8003 } 8004 } 8005 8006 // TODO: extend to support forward-locked splits 8007 String resourcePath = null; 8008 String baseResourcePath = null; 8009 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8010 if (ps != null && ps.resourcePathString != null) { 8011 resourcePath = ps.resourcePathString; 8012 baseResourcePath = ps.resourcePathString; 8013 } else { 8014 // Should not happen at all. Just log an error. 8015 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8016 } 8017 } else { 8018 resourcePath = pkg.codePath; 8019 baseResourcePath = pkg.baseCodePath; 8020 } 8021 8022 // Set application objects path explicitly. 8023 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8024 pkg.setApplicationInfoCodePath(pkg.codePath); 8025 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8026 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8027 pkg.setApplicationInfoResourcePath(resourcePath); 8028 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8029 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8030 8031 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8032 if (ps != null && ps.getInstantApp(userId)) { 8033 scanFlags |= SCAN_AS_INSTANT_APP; 8034 } 8035 8036 // Note that we invoke the following method only if we are about to unpack an application 8037 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8038 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8039 8040 /* 8041 * If the system app should be overridden by a previously installed 8042 * data, hide the system app now and let the /data/app scan pick it up 8043 * again. 8044 */ 8045 if (shouldHideSystemApp) { 8046 synchronized (mPackages) { 8047 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8048 } 8049 } 8050 8051 return scannedPkg; 8052 } 8053 8054 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8055 // Derive the new package synthetic package name 8056 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8057 + pkg.staticSharedLibVersion); 8058 } 8059 8060 private static String fixProcessName(String defProcessName, 8061 String processName) { 8062 if (processName == null) { 8063 return defProcessName; 8064 } 8065 return processName; 8066 } 8067 8068 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8069 throws PackageManagerException { 8070 if (pkgSetting.signatures.mSignatures != null) { 8071 // Already existing package. Make sure signatures match 8072 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8073 == PackageManager.SIGNATURE_MATCH; 8074 if (!match) { 8075 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8076 == PackageManager.SIGNATURE_MATCH; 8077 } 8078 if (!match) { 8079 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8080 == PackageManager.SIGNATURE_MATCH; 8081 } 8082 if (!match) { 8083 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8084 + pkg.packageName + " signatures do not match the " 8085 + "previously installed version; ignoring!"); 8086 } 8087 } 8088 8089 // Check for shared user signatures 8090 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8091 // Already existing package. Make sure signatures match 8092 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8093 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8094 if (!match) { 8095 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8096 == PackageManager.SIGNATURE_MATCH; 8097 } 8098 if (!match) { 8099 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8100 == PackageManager.SIGNATURE_MATCH; 8101 } 8102 if (!match) { 8103 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8104 "Package " + pkg.packageName 8105 + " has no signatures that match those in shared user " 8106 + pkgSetting.sharedUser.name + "; ignoring!"); 8107 } 8108 } 8109 } 8110 8111 /** 8112 * Enforces that only the system UID or root's UID can call a method exposed 8113 * via Binder. 8114 * 8115 * @param message used as message if SecurityException is thrown 8116 * @throws SecurityException if the caller is not system or root 8117 */ 8118 private static final void enforceSystemOrRoot(String message) { 8119 final int uid = Binder.getCallingUid(); 8120 if (uid != Process.SYSTEM_UID && uid != 0) { 8121 throw new SecurityException(message); 8122 } 8123 } 8124 8125 @Override 8126 public void performFstrimIfNeeded() { 8127 enforceSystemOrRoot("Only the system can request fstrim"); 8128 8129 // Before everything else, see whether we need to fstrim. 8130 try { 8131 IStorageManager sm = PackageHelper.getStorageManager(); 8132 if (sm != null) { 8133 boolean doTrim = false; 8134 final long interval = android.provider.Settings.Global.getLong( 8135 mContext.getContentResolver(), 8136 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8137 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8138 if (interval > 0) { 8139 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8140 if (timeSinceLast > interval) { 8141 doTrim = true; 8142 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8143 + "; running immediately"); 8144 } 8145 } 8146 if (doTrim) { 8147 final boolean dexOptDialogShown; 8148 synchronized (mPackages) { 8149 dexOptDialogShown = mDexOptDialogShown; 8150 } 8151 if (!isFirstBoot() && dexOptDialogShown) { 8152 try { 8153 ActivityManager.getService().showBootMessage( 8154 mContext.getResources().getString( 8155 R.string.android_upgrading_fstrim), true); 8156 } catch (RemoteException e) { 8157 } 8158 } 8159 sm.runMaintenance(); 8160 } 8161 } else { 8162 Slog.e(TAG, "storageManager service unavailable!"); 8163 } 8164 } catch (RemoteException e) { 8165 // Can't happen; StorageManagerService is local 8166 } 8167 } 8168 8169 @Override 8170 public void updatePackagesIfNeeded() { 8171 enforceSystemOrRoot("Only the system can request package update"); 8172 8173 // We need to re-extract after an OTA. 8174 boolean causeUpgrade = isUpgrade(); 8175 8176 // First boot or factory reset. 8177 // Note: we also handle devices that are upgrading to N right now as if it is their 8178 // first boot, as they do not have profile data. 8179 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8180 8181 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8182 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8183 8184 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8185 return; 8186 } 8187 8188 List<PackageParser.Package> pkgs; 8189 synchronized (mPackages) { 8190 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8191 } 8192 8193 final long startTime = System.nanoTime(); 8194 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8195 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8196 8197 final int elapsedTimeSeconds = 8198 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8199 8200 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8201 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8202 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8203 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8204 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8205 } 8206 8207 /** 8208 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8209 * containing statistics about the invocation. The array consists of three elements, 8210 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8211 * and {@code numberOfPackagesFailed}. 8212 */ 8213 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8214 String compilerFilter) { 8215 8216 int numberOfPackagesVisited = 0; 8217 int numberOfPackagesOptimized = 0; 8218 int numberOfPackagesSkipped = 0; 8219 int numberOfPackagesFailed = 0; 8220 final int numberOfPackagesToDexopt = pkgs.size(); 8221 8222 for (PackageParser.Package pkg : pkgs) { 8223 numberOfPackagesVisited++; 8224 8225 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8226 if (DEBUG_DEXOPT) { 8227 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8228 } 8229 numberOfPackagesSkipped++; 8230 continue; 8231 } 8232 8233 if (DEBUG_DEXOPT) { 8234 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8235 numberOfPackagesToDexopt + ": " + pkg.packageName); 8236 } 8237 8238 if (showDialog) { 8239 try { 8240 ActivityManager.getService().showBootMessage( 8241 mContext.getResources().getString(R.string.android_upgrading_apk, 8242 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8243 } catch (RemoteException e) { 8244 } 8245 synchronized (mPackages) { 8246 mDexOptDialogShown = true; 8247 } 8248 } 8249 8250 // If the OTA updates a system app which was previously preopted to a non-preopted state 8251 // the app might end up being verified at runtime. That's because by default the apps 8252 // are verify-profile but for preopted apps there's no profile. 8253 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8254 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8255 // filter (by default interpret-only). 8256 // Note that at this stage unused apps are already filtered. 8257 if (isSystemApp(pkg) && 8258 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8259 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8260 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8261 } 8262 8263 // checkProfiles is false to avoid merging profiles during boot which 8264 // might interfere with background compilation (b/28612421). 8265 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8266 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8267 // trade-off worth doing to save boot time work. 8268 int dexOptStatus = performDexOptTraced(pkg.packageName, 8269 false /* checkProfiles */, 8270 compilerFilter, 8271 false /* force */); 8272 switch (dexOptStatus) { 8273 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8274 numberOfPackagesOptimized++; 8275 break; 8276 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8277 numberOfPackagesSkipped++; 8278 break; 8279 case PackageDexOptimizer.DEX_OPT_FAILED: 8280 numberOfPackagesFailed++; 8281 break; 8282 default: 8283 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8284 break; 8285 } 8286 } 8287 8288 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8289 numberOfPackagesFailed }; 8290 } 8291 8292 @Override 8293 public void notifyPackageUse(String packageName, int reason) { 8294 synchronized (mPackages) { 8295 PackageParser.Package p = mPackages.get(packageName); 8296 if (p == null) { 8297 return; 8298 } 8299 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8300 } 8301 } 8302 8303 @Override 8304 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8305 int userId = UserHandle.getCallingUserId(); 8306 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8307 if (ai == null) { 8308 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8309 + loadingPackageName + ", user=" + userId); 8310 return; 8311 } 8312 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8313 } 8314 8315 // TODO: this is not used nor needed. Delete it. 8316 @Override 8317 public boolean performDexOptIfNeeded(String packageName) { 8318 int dexOptStatus = performDexOptTraced(packageName, 8319 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8320 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8321 } 8322 8323 @Override 8324 public boolean performDexOpt(String packageName, 8325 boolean checkProfiles, int compileReason, boolean force) { 8326 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8327 getCompilerFilterForReason(compileReason), force); 8328 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8329 } 8330 8331 @Override 8332 public boolean performDexOptMode(String packageName, 8333 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8334 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8335 targetCompilerFilter, force); 8336 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8337 } 8338 8339 private int performDexOptTraced(String packageName, 8340 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8341 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8342 try { 8343 return performDexOptInternal(packageName, checkProfiles, 8344 targetCompilerFilter, force); 8345 } finally { 8346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8347 } 8348 } 8349 8350 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8351 // if the package can now be considered up to date for the given filter. 8352 private int performDexOptInternal(String packageName, 8353 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8354 PackageParser.Package p; 8355 synchronized (mPackages) { 8356 p = mPackages.get(packageName); 8357 if (p == null) { 8358 // Package could not be found. Report failure. 8359 return PackageDexOptimizer.DEX_OPT_FAILED; 8360 } 8361 mPackageUsage.maybeWriteAsync(mPackages); 8362 mCompilerStats.maybeWriteAsync(); 8363 } 8364 long callingId = Binder.clearCallingIdentity(); 8365 try { 8366 synchronized (mInstallLock) { 8367 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8368 targetCompilerFilter, force); 8369 } 8370 } finally { 8371 Binder.restoreCallingIdentity(callingId); 8372 } 8373 } 8374 8375 public ArraySet<String> getOptimizablePackages() { 8376 ArraySet<String> pkgs = new ArraySet<String>(); 8377 synchronized (mPackages) { 8378 for (PackageParser.Package p : mPackages.values()) { 8379 if (PackageDexOptimizer.canOptimizePackage(p)) { 8380 pkgs.add(p.packageName); 8381 } 8382 } 8383 } 8384 return pkgs; 8385 } 8386 8387 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8388 boolean checkProfiles, String targetCompilerFilter, 8389 boolean force) { 8390 // Select the dex optimizer based on the force parameter. 8391 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8392 // allocate an object here. 8393 PackageDexOptimizer pdo = force 8394 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8395 : mPackageDexOptimizer; 8396 8397 // Dexopt all dependencies first. Note: we ignore the return value and march on 8398 // on errors. 8399 // Note that we are going to call performDexOpt on those libraries as many times as 8400 // they are referenced in packages. When we do a batch of performDexOpt (for example 8401 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8402 // and the first package that uses the library will dexopt it. The 8403 // others will see that the compiled code for the library is up to date. 8404 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8405 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8406 if (!deps.isEmpty()) { 8407 for (PackageParser.Package depPackage : deps) { 8408 // TODO: Analyze and investigate if we (should) profile libraries. 8409 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8410 false /* checkProfiles */, 8411 targetCompilerFilter, 8412 getOrCreateCompilerPackageStats(depPackage), 8413 true /* isUsedByOtherApps */); 8414 } 8415 } 8416 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8417 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8418 mDexManager.isUsedByOtherApps(p.packageName)); 8419 } 8420 8421 // Performs dexopt on the used secondary dex files belonging to the given package. 8422 // Returns true if all dex files were process successfully (which could mean either dexopt or 8423 // skip). Returns false if any of the files caused errors. 8424 @Override 8425 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8426 boolean force) { 8427 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8428 } 8429 8430 public boolean performDexOptSecondary(String packageName, int compileReason, 8431 boolean force) { 8432 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8433 } 8434 8435 /** 8436 * Reconcile the information we have about the secondary dex files belonging to 8437 * {@code packagName} and the actual dex files. For all dex files that were 8438 * deleted, update the internal records and delete the generated oat files. 8439 */ 8440 @Override 8441 public void reconcileSecondaryDexFiles(String packageName) { 8442 mDexManager.reconcileSecondaryDexFiles(packageName); 8443 } 8444 8445 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8446 // a reference there. 8447 /*package*/ DexManager getDexManager() { 8448 return mDexManager; 8449 } 8450 8451 /** 8452 * Execute the background dexopt job immediately. 8453 */ 8454 @Override 8455 public boolean runBackgroundDexoptJob() { 8456 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8457 } 8458 8459 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8460 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8461 || p.usesStaticLibraries != null) { 8462 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8463 Set<String> collectedNames = new HashSet<>(); 8464 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8465 8466 retValue.remove(p); 8467 8468 return retValue; 8469 } else { 8470 return Collections.emptyList(); 8471 } 8472 } 8473 8474 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8475 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8476 if (!collectedNames.contains(p.packageName)) { 8477 collectedNames.add(p.packageName); 8478 collected.add(p); 8479 8480 if (p.usesLibraries != null) { 8481 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8482 null, collected, collectedNames); 8483 } 8484 if (p.usesOptionalLibraries != null) { 8485 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8486 null, collected, collectedNames); 8487 } 8488 if (p.usesStaticLibraries != null) { 8489 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8490 p.usesStaticLibrariesVersions, collected, collectedNames); 8491 } 8492 } 8493 } 8494 8495 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8496 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8497 final int libNameCount = libs.size(); 8498 for (int i = 0; i < libNameCount; i++) { 8499 String libName = libs.get(i); 8500 int version = (versions != null && versions.length == libNameCount) 8501 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8502 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8503 if (libPkg != null) { 8504 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8505 } 8506 } 8507 } 8508 8509 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8510 synchronized (mPackages) { 8511 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8512 if (libEntry != null) { 8513 return mPackages.get(libEntry.apk); 8514 } 8515 return null; 8516 } 8517 } 8518 8519 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8520 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8521 if (versionedLib == null) { 8522 return null; 8523 } 8524 return versionedLib.get(version); 8525 } 8526 8527 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8528 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8529 pkg.staticSharedLibName); 8530 if (versionedLib == null) { 8531 return null; 8532 } 8533 int previousLibVersion = -1; 8534 final int versionCount = versionedLib.size(); 8535 for (int i = 0; i < versionCount; i++) { 8536 final int libVersion = versionedLib.keyAt(i); 8537 if (libVersion < pkg.staticSharedLibVersion) { 8538 previousLibVersion = Math.max(previousLibVersion, libVersion); 8539 } 8540 } 8541 if (previousLibVersion >= 0) { 8542 return versionedLib.get(previousLibVersion); 8543 } 8544 return null; 8545 } 8546 8547 public void shutdown() { 8548 mPackageUsage.writeNow(mPackages); 8549 mCompilerStats.writeNow(); 8550 } 8551 8552 @Override 8553 public void dumpProfiles(String packageName) { 8554 PackageParser.Package pkg; 8555 synchronized (mPackages) { 8556 pkg = mPackages.get(packageName); 8557 if (pkg == null) { 8558 throw new IllegalArgumentException("Unknown package: " + packageName); 8559 } 8560 } 8561 /* Only the shell, root, or the app user should be able to dump profiles. */ 8562 int callingUid = Binder.getCallingUid(); 8563 if (callingUid != Process.SHELL_UID && 8564 callingUid != Process.ROOT_UID && 8565 callingUid != pkg.applicationInfo.uid) { 8566 throw new SecurityException("dumpProfiles"); 8567 } 8568 8569 synchronized (mInstallLock) { 8570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8571 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8572 try { 8573 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8574 String codePaths = TextUtils.join(";", allCodePaths); 8575 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8576 } catch (InstallerException e) { 8577 Slog.w(TAG, "Failed to dump profiles", e); 8578 } 8579 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8580 } 8581 } 8582 8583 @Override 8584 public void forceDexOpt(String packageName) { 8585 enforceSystemOrRoot("forceDexOpt"); 8586 8587 PackageParser.Package pkg; 8588 synchronized (mPackages) { 8589 pkg = mPackages.get(packageName); 8590 if (pkg == null) { 8591 throw new IllegalArgumentException("Unknown package: " + packageName); 8592 } 8593 } 8594 8595 synchronized (mInstallLock) { 8596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8597 8598 // Whoever is calling forceDexOpt wants a fully compiled package. 8599 // Don't use profiles since that may cause compilation to be skipped. 8600 final int res = performDexOptInternalWithDependenciesLI(pkg, 8601 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8602 true /* force */); 8603 8604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8605 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8606 throw new IllegalStateException("Failed to dexopt: " + res); 8607 } 8608 } 8609 } 8610 8611 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8612 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8613 Slog.w(TAG, "Unable to update from " + oldPkg.name 8614 + " to " + newPkg.packageName 8615 + ": old package not in system partition"); 8616 return false; 8617 } else if (mPackages.get(oldPkg.name) != null) { 8618 Slog.w(TAG, "Unable to update from " + oldPkg.name 8619 + " to " + newPkg.packageName 8620 + ": old package still exists"); 8621 return false; 8622 } 8623 return true; 8624 } 8625 8626 void removeCodePathLI(File codePath) { 8627 if (codePath.isDirectory()) { 8628 try { 8629 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8630 } catch (InstallerException e) { 8631 Slog.w(TAG, "Failed to remove code path", e); 8632 } 8633 } else { 8634 codePath.delete(); 8635 } 8636 } 8637 8638 private int[] resolveUserIds(int userId) { 8639 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8640 } 8641 8642 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8643 if (pkg == null) { 8644 Slog.wtf(TAG, "Package was null!", new Throwable()); 8645 return; 8646 } 8647 clearAppDataLeafLIF(pkg, userId, flags); 8648 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8649 for (int i = 0; i < childCount; i++) { 8650 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8651 } 8652 } 8653 8654 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8655 final PackageSetting ps; 8656 synchronized (mPackages) { 8657 ps = mSettings.mPackages.get(pkg.packageName); 8658 } 8659 for (int realUserId : resolveUserIds(userId)) { 8660 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8661 try { 8662 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8663 ceDataInode); 8664 } catch (InstallerException e) { 8665 Slog.w(TAG, String.valueOf(e)); 8666 } 8667 } 8668 } 8669 8670 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8671 if (pkg == null) { 8672 Slog.wtf(TAG, "Package was null!", new Throwable()); 8673 return; 8674 } 8675 destroyAppDataLeafLIF(pkg, userId, flags); 8676 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8677 for (int i = 0; i < childCount; i++) { 8678 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8679 } 8680 } 8681 8682 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8683 final PackageSetting ps; 8684 synchronized (mPackages) { 8685 ps = mSettings.mPackages.get(pkg.packageName); 8686 } 8687 for (int realUserId : resolveUserIds(userId)) { 8688 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8689 try { 8690 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8691 ceDataInode); 8692 } catch (InstallerException e) { 8693 Slog.w(TAG, String.valueOf(e)); 8694 } 8695 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8696 } 8697 } 8698 8699 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8700 if (pkg == null) { 8701 Slog.wtf(TAG, "Package was null!", new Throwable()); 8702 return; 8703 } 8704 destroyAppProfilesLeafLIF(pkg); 8705 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8706 for (int i = 0; i < childCount; i++) { 8707 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8708 } 8709 } 8710 8711 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8712 try { 8713 mInstaller.destroyAppProfiles(pkg.packageName); 8714 } catch (InstallerException e) { 8715 Slog.w(TAG, String.valueOf(e)); 8716 } 8717 } 8718 8719 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8720 if (pkg == null) { 8721 Slog.wtf(TAG, "Package was null!", new Throwable()); 8722 return; 8723 } 8724 clearAppProfilesLeafLIF(pkg); 8725 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8726 for (int i = 0; i < childCount; i++) { 8727 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8728 } 8729 } 8730 8731 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8732 try { 8733 mInstaller.clearAppProfiles(pkg.packageName); 8734 } catch (InstallerException e) { 8735 Slog.w(TAG, String.valueOf(e)); 8736 } 8737 } 8738 8739 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8740 long lastUpdateTime) { 8741 // Set parent install/update time 8742 PackageSetting ps = (PackageSetting) pkg.mExtras; 8743 if (ps != null) { 8744 ps.firstInstallTime = firstInstallTime; 8745 ps.lastUpdateTime = lastUpdateTime; 8746 } 8747 // Set children install/update time 8748 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8749 for (int i = 0; i < childCount; i++) { 8750 PackageParser.Package childPkg = pkg.childPackages.get(i); 8751 ps = (PackageSetting) childPkg.mExtras; 8752 if (ps != null) { 8753 ps.firstInstallTime = firstInstallTime; 8754 ps.lastUpdateTime = lastUpdateTime; 8755 } 8756 } 8757 } 8758 8759 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8760 PackageParser.Package changingLib) { 8761 if (file.path != null) { 8762 usesLibraryFiles.add(file.path); 8763 return; 8764 } 8765 PackageParser.Package p = mPackages.get(file.apk); 8766 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8767 // If we are doing this while in the middle of updating a library apk, 8768 // then we need to make sure to use that new apk for determining the 8769 // dependencies here. (We haven't yet finished committing the new apk 8770 // to the package manager state.) 8771 if (p == null || p.packageName.equals(changingLib.packageName)) { 8772 p = changingLib; 8773 } 8774 } 8775 if (p != null) { 8776 usesLibraryFiles.addAll(p.getAllCodePaths()); 8777 } 8778 } 8779 8780 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8781 PackageParser.Package changingLib) throws PackageManagerException { 8782 if (pkg == null) { 8783 return; 8784 } 8785 ArraySet<String> usesLibraryFiles = null; 8786 if (pkg.usesLibraries != null) { 8787 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8788 null, null, pkg.packageName, changingLib, true, null); 8789 } 8790 if (pkg.usesStaticLibraries != null) { 8791 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8792 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8793 pkg.packageName, changingLib, true, usesLibraryFiles); 8794 } 8795 if (pkg.usesOptionalLibraries != null) { 8796 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8797 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8798 } 8799 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8800 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8801 } else { 8802 pkg.usesLibraryFiles = null; 8803 } 8804 } 8805 8806 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8807 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8808 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8809 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8810 throws PackageManagerException { 8811 final int libCount = requestedLibraries.size(); 8812 for (int i = 0; i < libCount; i++) { 8813 final String libName = requestedLibraries.get(i); 8814 final int libVersion = requiredVersions != null ? requiredVersions[i] 8815 : SharedLibraryInfo.VERSION_UNDEFINED; 8816 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8817 if (libEntry == null) { 8818 if (required) { 8819 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8820 "Package " + packageName + " requires unavailable shared library " 8821 + libName + "; failing!"); 8822 } else { 8823 Slog.w(TAG, "Package " + packageName 8824 + " desires unavailable shared library " 8825 + libName + "; ignoring!"); 8826 } 8827 } else { 8828 if (requiredVersions != null && requiredCertDigests != null) { 8829 if (libEntry.info.getVersion() != requiredVersions[i]) { 8830 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8831 "Package " + packageName + " requires unavailable static shared" 8832 + " library " + libName + " version " 8833 + libEntry.info.getVersion() + "; failing!"); 8834 } 8835 8836 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8837 if (libPkg == null) { 8838 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8839 "Package " + packageName + " requires unavailable static shared" 8840 + " library; failing!"); 8841 } 8842 8843 String expectedCertDigest = requiredCertDigests[i]; 8844 String libCertDigest = PackageUtils.computeCertSha256Digest( 8845 libPkg.mSignatures[0]); 8846 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8847 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8848 "Package " + packageName + " requires differently signed" + 8849 " static shared library; failing!"); 8850 } 8851 } 8852 8853 if (outUsedLibraries == null) { 8854 outUsedLibraries = new ArraySet<>(); 8855 } 8856 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8857 } 8858 } 8859 return outUsedLibraries; 8860 } 8861 8862 private static boolean hasString(List<String> list, List<String> which) { 8863 if (list == null) { 8864 return false; 8865 } 8866 for (int i=list.size()-1; i>=0; i--) { 8867 for (int j=which.size()-1; j>=0; j--) { 8868 if (which.get(j).equals(list.get(i))) { 8869 return true; 8870 } 8871 } 8872 } 8873 return false; 8874 } 8875 8876 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8877 PackageParser.Package changingPkg) { 8878 ArrayList<PackageParser.Package> res = null; 8879 for (PackageParser.Package pkg : mPackages.values()) { 8880 if (changingPkg != null 8881 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8882 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8883 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8884 changingPkg.staticSharedLibName)) { 8885 return null; 8886 } 8887 if (res == null) { 8888 res = new ArrayList<>(); 8889 } 8890 res.add(pkg); 8891 try { 8892 updateSharedLibrariesLPr(pkg, changingPkg); 8893 } catch (PackageManagerException e) { 8894 // If a system app update or an app and a required lib missing we 8895 // delete the package and for updated system apps keep the data as 8896 // it is better for the user to reinstall than to be in an limbo 8897 // state. Also libs disappearing under an app should never happen 8898 // - just in case. 8899 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8900 final int flags = pkg.isUpdatedSystemApp() 8901 ? PackageManager.DELETE_KEEP_DATA : 0; 8902 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8903 flags , null, true, null); 8904 } 8905 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8906 } 8907 } 8908 return res; 8909 } 8910 8911 /** 8912 * Derive the value of the {@code cpuAbiOverride} based on the provided 8913 * value and an optional stored value from the package settings. 8914 */ 8915 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8916 String cpuAbiOverride = null; 8917 8918 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8919 cpuAbiOverride = null; 8920 } else if (abiOverride != null) { 8921 cpuAbiOverride = abiOverride; 8922 } else if (settings != null) { 8923 cpuAbiOverride = settings.cpuAbiOverrideString; 8924 } 8925 8926 return cpuAbiOverride; 8927 } 8928 8929 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8930 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8931 throws PackageManagerException { 8932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8933 // If the package has children and this is the first dive in the function 8934 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8935 // whether all packages (parent and children) would be successfully scanned 8936 // before the actual scan since scanning mutates internal state and we want 8937 // to atomically install the package and its children. 8938 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8939 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8940 scanFlags |= SCAN_CHECK_ONLY; 8941 } 8942 } else { 8943 scanFlags &= ~SCAN_CHECK_ONLY; 8944 } 8945 8946 final PackageParser.Package scannedPkg; 8947 try { 8948 // Scan the parent 8949 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8950 // Scan the children 8951 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8952 for (int i = 0; i < childCount; i++) { 8953 PackageParser.Package childPkg = pkg.childPackages.get(i); 8954 scanPackageLI(childPkg, policyFlags, 8955 scanFlags, currentTime, user); 8956 } 8957 } finally { 8958 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8959 } 8960 8961 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8962 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8963 } 8964 8965 return scannedPkg; 8966 } 8967 8968 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8969 int scanFlags, long currentTime, @Nullable UserHandle user) 8970 throws PackageManagerException { 8971 boolean success = false; 8972 try { 8973 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8974 currentTime, user); 8975 success = true; 8976 return res; 8977 } finally { 8978 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8979 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8980 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8981 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8982 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8983 } 8984 } 8985 } 8986 8987 /** 8988 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8989 */ 8990 private static boolean apkHasCode(String fileName) { 8991 StrictJarFile jarFile = null; 8992 try { 8993 jarFile = new StrictJarFile(fileName, 8994 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8995 return jarFile.findEntry("classes.dex") != null; 8996 } catch (IOException ignore) { 8997 } finally { 8998 try { 8999 if (jarFile != null) { 9000 jarFile.close(); 9001 } 9002 } catch (IOException ignore) {} 9003 } 9004 return false; 9005 } 9006 9007 /** 9008 * Enforces code policy for the package. This ensures that if an APK has 9009 * declared hasCode="true" in its manifest that the APK actually contains 9010 * code. 9011 * 9012 * @throws PackageManagerException If bytecode could not be found when it should exist 9013 */ 9014 private static void assertCodePolicy(PackageParser.Package pkg) 9015 throws PackageManagerException { 9016 final boolean shouldHaveCode = 9017 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9018 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9019 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9020 "Package " + pkg.baseCodePath + " code is missing"); 9021 } 9022 9023 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9024 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9025 final boolean splitShouldHaveCode = 9026 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9027 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9028 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9029 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9030 } 9031 } 9032 } 9033 } 9034 9035 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9036 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9037 throws PackageManagerException { 9038 if (DEBUG_PACKAGE_SCANNING) { 9039 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9040 Log.d(TAG, "Scanning package " + pkg.packageName); 9041 } 9042 9043 applyPolicy(pkg, policyFlags); 9044 9045 assertPackageIsValid(pkg, policyFlags, scanFlags); 9046 9047 // Initialize package source and resource directories 9048 final File scanFile = new File(pkg.codePath); 9049 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9050 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9051 9052 SharedUserSetting suid = null; 9053 PackageSetting pkgSetting = null; 9054 9055 // Getting the package setting may have a side-effect, so if we 9056 // are only checking if scan would succeed, stash a copy of the 9057 // old setting to restore at the end. 9058 PackageSetting nonMutatedPs = null; 9059 9060 // We keep references to the derived CPU Abis from settings in oder to reuse 9061 // them in the case where we're not upgrading or booting for the first time. 9062 String primaryCpuAbiFromSettings = null; 9063 String secondaryCpuAbiFromSettings = null; 9064 9065 // writer 9066 synchronized (mPackages) { 9067 if (pkg.mSharedUserId != null) { 9068 // SIDE EFFECTS; may potentially allocate a new shared user 9069 suid = mSettings.getSharedUserLPw( 9070 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9071 if (DEBUG_PACKAGE_SCANNING) { 9072 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9073 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9074 + "): packages=" + suid.packages); 9075 } 9076 } 9077 9078 // Check if we are renaming from an original package name. 9079 PackageSetting origPackage = null; 9080 String realName = null; 9081 if (pkg.mOriginalPackages != null) { 9082 // This package may need to be renamed to a previously 9083 // installed name. Let's check on that... 9084 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9085 if (pkg.mOriginalPackages.contains(renamed)) { 9086 // This package had originally been installed as the 9087 // original name, and we have already taken care of 9088 // transitioning to the new one. Just update the new 9089 // one to continue using the old name. 9090 realName = pkg.mRealPackage; 9091 if (!pkg.packageName.equals(renamed)) { 9092 // Callers into this function may have already taken 9093 // care of renaming the package; only do it here if 9094 // it is not already done. 9095 pkg.setPackageName(renamed); 9096 } 9097 } else { 9098 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9099 if ((origPackage = mSettings.getPackageLPr( 9100 pkg.mOriginalPackages.get(i))) != null) { 9101 // We do have the package already installed under its 9102 // original name... should we use it? 9103 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9104 // New package is not compatible with original. 9105 origPackage = null; 9106 continue; 9107 } else if (origPackage.sharedUser != null) { 9108 // Make sure uid is compatible between packages. 9109 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9110 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9111 + " to " + pkg.packageName + ": old uid " 9112 + origPackage.sharedUser.name 9113 + " differs from " + pkg.mSharedUserId); 9114 origPackage = null; 9115 continue; 9116 } 9117 // TODO: Add case when shared user id is added [b/28144775] 9118 } else { 9119 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9120 + pkg.packageName + " to old name " + origPackage.name); 9121 } 9122 break; 9123 } 9124 } 9125 } 9126 } 9127 9128 if (mTransferedPackages.contains(pkg.packageName)) { 9129 Slog.w(TAG, "Package " + pkg.packageName 9130 + " was transferred to another, but its .apk remains"); 9131 } 9132 9133 // See comments in nonMutatedPs declaration 9134 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9135 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9136 if (foundPs != null) { 9137 nonMutatedPs = new PackageSetting(foundPs); 9138 } 9139 } 9140 9141 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9142 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9143 if (foundPs != null) { 9144 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9145 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9146 } 9147 } 9148 9149 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9150 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9151 PackageManagerService.reportSettingsProblem(Log.WARN, 9152 "Package " + pkg.packageName + " shared user changed from " 9153 + (pkgSetting.sharedUser != null 9154 ? pkgSetting.sharedUser.name : "<nothing>") 9155 + " to " 9156 + (suid != null ? suid.name : "<nothing>") 9157 + "; replacing with new"); 9158 pkgSetting = null; 9159 } 9160 final PackageSetting oldPkgSetting = 9161 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9162 final PackageSetting disabledPkgSetting = 9163 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9164 9165 String[] usesStaticLibraries = null; 9166 if (pkg.usesStaticLibraries != null) { 9167 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9168 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9169 } 9170 9171 if (pkgSetting == null) { 9172 final String parentPackageName = (pkg.parentPackage != null) 9173 ? pkg.parentPackage.packageName : null; 9174 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9175 // REMOVE SharedUserSetting from method; update in a separate call 9176 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9177 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9178 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9179 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9180 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9181 true /*allowInstall*/, instantApp, parentPackageName, 9182 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9183 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9184 // SIDE EFFECTS; updates system state; move elsewhere 9185 if (origPackage != null) { 9186 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9187 } 9188 mSettings.addUserToSettingLPw(pkgSetting); 9189 } else { 9190 // REMOVE SharedUserSetting from method; update in a separate call. 9191 // 9192 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9193 // secondaryCpuAbi are not known at this point so we always update them 9194 // to null here, only to reset them at a later point. 9195 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9196 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9197 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9198 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9199 UserManagerService.getInstance(), usesStaticLibraries, 9200 pkg.usesStaticLibrariesVersions); 9201 } 9202 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9203 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9204 9205 // SIDE EFFECTS; modifies system state; move elsewhere 9206 if (pkgSetting.origPackage != null) { 9207 // If we are first transitioning from an original package, 9208 // fix up the new package's name now. We need to do this after 9209 // looking up the package under its new name, so getPackageLP 9210 // can take care of fiddling things correctly. 9211 pkg.setPackageName(origPackage.name); 9212 9213 // File a report about this. 9214 String msg = "New package " + pkgSetting.realName 9215 + " renamed to replace old package " + pkgSetting.name; 9216 reportSettingsProblem(Log.WARN, msg); 9217 9218 // Make a note of it. 9219 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9220 mTransferedPackages.add(origPackage.name); 9221 } 9222 9223 // No longer need to retain this. 9224 pkgSetting.origPackage = null; 9225 } 9226 9227 // SIDE EFFECTS; modifies system state; move elsewhere 9228 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9229 // Make a note of it. 9230 mTransferedPackages.add(pkg.packageName); 9231 } 9232 9233 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9234 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9235 } 9236 9237 if ((scanFlags & SCAN_BOOTING) == 0 9238 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9239 // Check all shared libraries and map to their actual file path. 9240 // We only do this here for apps not on a system dir, because those 9241 // are the only ones that can fail an install due to this. We 9242 // will take care of the system apps by updating all of their 9243 // library paths after the scan is done. Also during the initial 9244 // scan don't update any libs as we do this wholesale after all 9245 // apps are scanned to avoid dependency based scanning. 9246 updateSharedLibrariesLPr(pkg, null); 9247 } 9248 9249 if (mFoundPolicyFile) { 9250 SELinuxMMAC.assignSeInfoValue(pkg); 9251 } 9252 pkg.applicationInfo.uid = pkgSetting.appId; 9253 pkg.mExtras = pkgSetting; 9254 9255 9256 // Static shared libs have same package with different versions where 9257 // we internally use a synthetic package name to allow multiple versions 9258 // of the same package, therefore we need to compare signatures against 9259 // the package setting for the latest library version. 9260 PackageSetting signatureCheckPs = pkgSetting; 9261 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9262 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9263 if (libraryEntry != null) { 9264 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9265 } 9266 } 9267 9268 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9269 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9270 // We just determined the app is signed correctly, so bring 9271 // over the latest parsed certs. 9272 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9273 } else { 9274 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9275 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9276 "Package " + pkg.packageName + " upgrade keys do not match the " 9277 + "previously installed version"); 9278 } else { 9279 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9280 String msg = "System package " + pkg.packageName 9281 + " signature changed; retaining data."; 9282 reportSettingsProblem(Log.WARN, msg); 9283 } 9284 } 9285 } else { 9286 try { 9287 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9288 verifySignaturesLP(signatureCheckPs, pkg); 9289 // We just determined the app is signed correctly, so bring 9290 // over the latest parsed certs. 9291 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9292 } catch (PackageManagerException e) { 9293 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9294 throw e; 9295 } 9296 // The signature has changed, but this package is in the system 9297 // image... let's recover! 9298 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9299 // However... if this package is part of a shared user, but it 9300 // doesn't match the signature of the shared user, let's fail. 9301 // What this means is that you can't change the signatures 9302 // associated with an overall shared user, which doesn't seem all 9303 // that unreasonable. 9304 if (signatureCheckPs.sharedUser != null) { 9305 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9306 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9307 throw new PackageManagerException( 9308 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9309 "Signature mismatch for shared user: " 9310 + pkgSetting.sharedUser); 9311 } 9312 } 9313 // File a report about this. 9314 String msg = "System package " + pkg.packageName 9315 + " signature changed; retaining data."; 9316 reportSettingsProblem(Log.WARN, msg); 9317 } 9318 } 9319 9320 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9321 // This package wants to adopt ownership of permissions from 9322 // another package. 9323 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9324 final String origName = pkg.mAdoptPermissions.get(i); 9325 final PackageSetting orig = mSettings.getPackageLPr(origName); 9326 if (orig != null) { 9327 if (verifyPackageUpdateLPr(orig, pkg)) { 9328 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9329 + pkg.packageName); 9330 // SIDE EFFECTS; updates permissions system state; move elsewhere 9331 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9332 } 9333 } 9334 } 9335 } 9336 } 9337 9338 pkg.applicationInfo.processName = fixProcessName( 9339 pkg.applicationInfo.packageName, 9340 pkg.applicationInfo.processName); 9341 9342 if (pkg != mPlatformPackage) { 9343 // Get all of our default paths setup 9344 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9345 } 9346 9347 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9348 9349 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9350 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9351 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9352 derivePackageAbi( 9353 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9354 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9355 9356 // Some system apps still use directory structure for native libraries 9357 // in which case we might end up not detecting abi solely based on apk 9358 // structure. Try to detect abi based on directory structure. 9359 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9360 pkg.applicationInfo.primaryCpuAbi == null) { 9361 setBundledAppAbisAndRoots(pkg, pkgSetting); 9362 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9363 } 9364 } else { 9365 // This is not a first boot or an upgrade, don't bother deriving the 9366 // ABI during the scan. Instead, trust the value that was stored in the 9367 // package setting. 9368 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9369 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9370 9371 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9372 9373 if (DEBUG_ABI_SELECTION) { 9374 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9375 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9376 pkg.applicationInfo.secondaryCpuAbi); 9377 } 9378 } 9379 } else { 9380 if ((scanFlags & SCAN_MOVE) != 0) { 9381 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9382 // but we already have this packages package info in the PackageSetting. We just 9383 // use that and derive the native library path based on the new codepath. 9384 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9385 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9386 } 9387 9388 // Set native library paths again. For moves, the path will be updated based on the 9389 // ABIs we've determined above. For non-moves, the path will be updated based on the 9390 // ABIs we determined during compilation, but the path will depend on the final 9391 // package path (after the rename away from the stage path). 9392 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9393 } 9394 9395 // This is a special case for the "system" package, where the ABI is 9396 // dictated by the zygote configuration (and init.rc). We should keep track 9397 // of this ABI so that we can deal with "normal" applications that run under 9398 // the same UID correctly. 9399 if (mPlatformPackage == pkg) { 9400 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9401 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9402 } 9403 9404 // If there's a mismatch between the abi-override in the package setting 9405 // and the abiOverride specified for the install. Warn about this because we 9406 // would've already compiled the app without taking the package setting into 9407 // account. 9408 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9409 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9410 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9411 " for package " + pkg.packageName); 9412 } 9413 } 9414 9415 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9416 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9417 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9418 9419 // Copy the derived override back to the parsed package, so that we can 9420 // update the package settings accordingly. 9421 pkg.cpuAbiOverride = cpuAbiOverride; 9422 9423 if (DEBUG_ABI_SELECTION) { 9424 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9425 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9426 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9427 } 9428 9429 // Push the derived path down into PackageSettings so we know what to 9430 // clean up at uninstall time. 9431 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9432 9433 if (DEBUG_ABI_SELECTION) { 9434 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9435 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9436 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9437 } 9438 9439 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9440 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9441 // We don't do this here during boot because we can do it all 9442 // at once after scanning all existing packages. 9443 // 9444 // We also do this *before* we perform dexopt on this package, so that 9445 // we can avoid redundant dexopts, and also to make sure we've got the 9446 // code and package path correct. 9447 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9448 } 9449 9450 if (mFactoryTest && pkg.requestedPermissions.contains( 9451 android.Manifest.permission.FACTORY_TEST)) { 9452 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9453 } 9454 9455 if (isSystemApp(pkg)) { 9456 pkgSetting.isOrphaned = true; 9457 } 9458 9459 // Take care of first install / last update times. 9460 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9461 if (currentTime != 0) { 9462 if (pkgSetting.firstInstallTime == 0) { 9463 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9464 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9465 pkgSetting.lastUpdateTime = currentTime; 9466 } 9467 } else if (pkgSetting.firstInstallTime == 0) { 9468 // We need *something*. Take time time stamp of the file. 9469 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9470 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9471 if (scanFileTime != pkgSetting.timeStamp) { 9472 // A package on the system image has changed; consider this 9473 // to be an update. 9474 pkgSetting.lastUpdateTime = scanFileTime; 9475 } 9476 } 9477 pkgSetting.setTimeStamp(scanFileTime); 9478 9479 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9480 if (nonMutatedPs != null) { 9481 synchronized (mPackages) { 9482 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9483 } 9484 } 9485 } else { 9486 final int userId = user == null ? 0 : user.getIdentifier(); 9487 // Modify state for the given package setting 9488 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9489 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9490 if (pkgSetting.getInstantApp(userId)) { 9491 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9492 } 9493 } 9494 return pkg; 9495 } 9496 9497 /** 9498 * Applies policy to the parsed package based upon the given policy flags. 9499 * Ensures the package is in a good state. 9500 * <p> 9501 * Implementation detail: This method must NOT have any side effect. It would 9502 * ideally be static, but, it requires locks to read system state. 9503 */ 9504 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9505 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9506 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9507 if (pkg.applicationInfo.isDirectBootAware()) { 9508 // we're direct boot aware; set for all components 9509 for (PackageParser.Service s : pkg.services) { 9510 s.info.encryptionAware = s.info.directBootAware = true; 9511 } 9512 for (PackageParser.Provider p : pkg.providers) { 9513 p.info.encryptionAware = p.info.directBootAware = true; 9514 } 9515 for (PackageParser.Activity a : pkg.activities) { 9516 a.info.encryptionAware = a.info.directBootAware = true; 9517 } 9518 for (PackageParser.Activity r : pkg.receivers) { 9519 r.info.encryptionAware = r.info.directBootAware = true; 9520 } 9521 } 9522 } else { 9523 // Only allow system apps to be flagged as core apps. 9524 pkg.coreApp = false; 9525 // clear flags not applicable to regular apps 9526 pkg.applicationInfo.privateFlags &= 9527 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9528 pkg.applicationInfo.privateFlags &= 9529 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9530 } 9531 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9532 9533 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9534 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9535 } 9536 9537 if (!isSystemApp(pkg)) { 9538 // Only system apps can use these features. 9539 pkg.mOriginalPackages = null; 9540 pkg.mRealPackage = null; 9541 pkg.mAdoptPermissions = null; 9542 } 9543 } 9544 9545 /** 9546 * Asserts the parsed package is valid according to the given policy. If the 9547 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9548 * <p> 9549 * Implementation detail: This method must NOT have any side effects. It would 9550 * ideally be static, but, it requires locks to read system state. 9551 * 9552 * @throws PackageManagerException If the package fails any of the validation checks 9553 */ 9554 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9555 throws PackageManagerException { 9556 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9557 assertCodePolicy(pkg); 9558 } 9559 9560 if (pkg.applicationInfo.getCodePath() == null || 9561 pkg.applicationInfo.getResourcePath() == null) { 9562 // Bail out. The resource and code paths haven't been set. 9563 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9564 "Code and resource paths haven't been set correctly"); 9565 } 9566 9567 // Make sure we're not adding any bogus keyset info 9568 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9569 ksms.assertScannedPackageValid(pkg); 9570 9571 synchronized (mPackages) { 9572 // The special "android" package can only be defined once 9573 if (pkg.packageName.equals("android")) { 9574 if (mAndroidApplication != null) { 9575 Slog.w(TAG, "*************************************************"); 9576 Slog.w(TAG, "Core android package being redefined. Skipping."); 9577 Slog.w(TAG, " codePath=" + pkg.codePath); 9578 Slog.w(TAG, "*************************************************"); 9579 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9580 "Core android package being redefined. Skipping."); 9581 } 9582 } 9583 9584 // A package name must be unique; don't allow duplicates 9585 if (mPackages.containsKey(pkg.packageName)) { 9586 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9587 "Application package " + pkg.packageName 9588 + " already installed. Skipping duplicate."); 9589 } 9590 9591 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9592 // Static libs have a synthetic package name containing the version 9593 // but we still want the base name to be unique. 9594 if (mPackages.containsKey(pkg.manifestPackageName)) { 9595 throw new PackageManagerException( 9596 "Duplicate static shared lib provider package"); 9597 } 9598 9599 // Static shared libraries should have at least O target SDK 9600 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9601 throw new PackageManagerException( 9602 "Packages declaring static-shared libs must target O SDK or higher"); 9603 } 9604 9605 // Package declaring static a shared lib cannot be instant apps 9606 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9607 throw new PackageManagerException( 9608 "Packages declaring static-shared libs cannot be instant apps"); 9609 } 9610 9611 // Package declaring static a shared lib cannot be renamed since the package 9612 // name is synthetic and apps can't code around package manager internals. 9613 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9614 throw new PackageManagerException( 9615 "Packages declaring static-shared libs cannot be renamed"); 9616 } 9617 9618 // Package declaring static a shared lib cannot declare child packages 9619 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9620 throw new PackageManagerException( 9621 "Packages declaring static-shared libs cannot have child packages"); 9622 } 9623 9624 // Package declaring static a shared lib cannot declare dynamic libs 9625 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9626 throw new PackageManagerException( 9627 "Packages declaring static-shared libs cannot declare dynamic libs"); 9628 } 9629 9630 // Package declaring static a shared lib cannot declare shared users 9631 if (pkg.mSharedUserId != null) { 9632 throw new PackageManagerException( 9633 "Packages declaring static-shared libs cannot declare shared users"); 9634 } 9635 9636 // Static shared libs cannot declare activities 9637 if (!pkg.activities.isEmpty()) { 9638 throw new PackageManagerException( 9639 "Static shared libs cannot declare activities"); 9640 } 9641 9642 // Static shared libs cannot declare services 9643 if (!pkg.services.isEmpty()) { 9644 throw new PackageManagerException( 9645 "Static shared libs cannot declare services"); 9646 } 9647 9648 // Static shared libs cannot declare providers 9649 if (!pkg.providers.isEmpty()) { 9650 throw new PackageManagerException( 9651 "Static shared libs cannot declare content providers"); 9652 } 9653 9654 // Static shared libs cannot declare receivers 9655 if (!pkg.receivers.isEmpty()) { 9656 throw new PackageManagerException( 9657 "Static shared libs cannot declare broadcast receivers"); 9658 } 9659 9660 // Static shared libs cannot declare permission groups 9661 if (!pkg.permissionGroups.isEmpty()) { 9662 throw new PackageManagerException( 9663 "Static shared libs cannot declare permission groups"); 9664 } 9665 9666 // Static shared libs cannot declare permissions 9667 if (!pkg.permissions.isEmpty()) { 9668 throw new PackageManagerException( 9669 "Static shared libs cannot declare permissions"); 9670 } 9671 9672 // Static shared libs cannot declare protected broadcasts 9673 if (pkg.protectedBroadcasts != null) { 9674 throw new PackageManagerException( 9675 "Static shared libs cannot declare protected broadcasts"); 9676 } 9677 9678 // Static shared libs cannot be overlay targets 9679 if (pkg.mOverlayTarget != null) { 9680 throw new PackageManagerException( 9681 "Static shared libs cannot be overlay targets"); 9682 } 9683 9684 // The version codes must be ordered as lib versions 9685 int minVersionCode = Integer.MIN_VALUE; 9686 int maxVersionCode = Integer.MAX_VALUE; 9687 9688 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9689 pkg.staticSharedLibName); 9690 if (versionedLib != null) { 9691 final int versionCount = versionedLib.size(); 9692 for (int i = 0; i < versionCount; i++) { 9693 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9694 // TODO: We will change version code to long, so in the new API it is long 9695 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9696 .getVersionCode(); 9697 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9698 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9699 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9700 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9701 } else { 9702 minVersionCode = maxVersionCode = libVersionCode; 9703 break; 9704 } 9705 } 9706 } 9707 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9708 throw new PackageManagerException("Static shared" 9709 + " lib version codes must be ordered as lib versions"); 9710 } 9711 } 9712 9713 // Only privileged apps and updated privileged apps can add child packages. 9714 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9715 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9716 throw new PackageManagerException("Only privileged apps can add child " 9717 + "packages. Ignoring package " + pkg.packageName); 9718 } 9719 final int childCount = pkg.childPackages.size(); 9720 for (int i = 0; i < childCount; i++) { 9721 PackageParser.Package childPkg = pkg.childPackages.get(i); 9722 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9723 childPkg.packageName)) { 9724 throw new PackageManagerException("Can't override child of " 9725 + "another disabled app. Ignoring package " + pkg.packageName); 9726 } 9727 } 9728 } 9729 9730 // If we're only installing presumed-existing packages, require that the 9731 // scanned APK is both already known and at the path previously established 9732 // for it. Previously unknown packages we pick up normally, but if we have an 9733 // a priori expectation about this package's install presence, enforce it. 9734 // With a singular exception for new system packages. When an OTA contains 9735 // a new system package, we allow the codepath to change from a system location 9736 // to the user-installed location. If we don't allow this change, any newer, 9737 // user-installed version of the application will be ignored. 9738 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9739 if (mExpectingBetter.containsKey(pkg.packageName)) { 9740 logCriticalInfo(Log.WARN, 9741 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9742 } else { 9743 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9744 if (known != null) { 9745 if (DEBUG_PACKAGE_SCANNING) { 9746 Log.d(TAG, "Examining " + pkg.codePath 9747 + " and requiring known paths " + known.codePathString 9748 + " & " + known.resourcePathString); 9749 } 9750 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9751 || !pkg.applicationInfo.getResourcePath().equals( 9752 known.resourcePathString)) { 9753 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9754 "Application package " + pkg.packageName 9755 + " found at " + pkg.applicationInfo.getCodePath() 9756 + " but expected at " + known.codePathString 9757 + "; ignoring."); 9758 } 9759 } 9760 } 9761 } 9762 9763 // Verify that this new package doesn't have any content providers 9764 // that conflict with existing packages. Only do this if the 9765 // package isn't already installed, since we don't want to break 9766 // things that are installed. 9767 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9768 final int N = pkg.providers.size(); 9769 int i; 9770 for (i=0; i<N; i++) { 9771 PackageParser.Provider p = pkg.providers.get(i); 9772 if (p.info.authority != null) { 9773 String names[] = p.info.authority.split(";"); 9774 for (int j = 0; j < names.length; j++) { 9775 if (mProvidersByAuthority.containsKey(names[j])) { 9776 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9777 final String otherPackageName = 9778 ((other != null && other.getComponentName() != null) ? 9779 other.getComponentName().getPackageName() : "?"); 9780 throw new PackageManagerException( 9781 INSTALL_FAILED_CONFLICTING_PROVIDER, 9782 "Can't install because provider name " + names[j] 9783 + " (in package " + pkg.applicationInfo.packageName 9784 + ") is already used by " + otherPackageName); 9785 } 9786 } 9787 } 9788 } 9789 } 9790 } 9791 } 9792 9793 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9794 int type, String declaringPackageName, int declaringVersionCode) { 9795 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9796 if (versionedLib == null) { 9797 versionedLib = new SparseArray<>(); 9798 mSharedLibraries.put(name, versionedLib); 9799 if (type == SharedLibraryInfo.TYPE_STATIC) { 9800 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9801 } 9802 } else if (versionedLib.indexOfKey(version) >= 0) { 9803 return false; 9804 } 9805 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9806 version, type, declaringPackageName, declaringVersionCode); 9807 versionedLib.put(version, libEntry); 9808 return true; 9809 } 9810 9811 private boolean removeSharedLibraryLPw(String name, int version) { 9812 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9813 if (versionedLib == null) { 9814 return false; 9815 } 9816 final int libIdx = versionedLib.indexOfKey(version); 9817 if (libIdx < 0) { 9818 return false; 9819 } 9820 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9821 versionedLib.remove(version); 9822 if (versionedLib.size() <= 0) { 9823 mSharedLibraries.remove(name); 9824 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9825 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9826 .getPackageName()); 9827 } 9828 } 9829 return true; 9830 } 9831 9832 /** 9833 * Adds a scanned package to the system. When this method is finished, the package will 9834 * be available for query, resolution, etc... 9835 */ 9836 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9837 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9838 final String pkgName = pkg.packageName; 9839 if (mCustomResolverComponentName != null && 9840 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9841 setUpCustomResolverActivity(pkg); 9842 } 9843 9844 if (pkg.packageName.equals("android")) { 9845 synchronized (mPackages) { 9846 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9847 // Set up information for our fall-back user intent resolution activity. 9848 mPlatformPackage = pkg; 9849 pkg.mVersionCode = mSdkVersion; 9850 mAndroidApplication = pkg.applicationInfo; 9851 if (!mResolverReplaced) { 9852 mResolveActivity.applicationInfo = mAndroidApplication; 9853 mResolveActivity.name = ResolverActivity.class.getName(); 9854 mResolveActivity.packageName = mAndroidApplication.packageName; 9855 mResolveActivity.processName = "system:ui"; 9856 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9857 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9858 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9859 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9860 mResolveActivity.exported = true; 9861 mResolveActivity.enabled = true; 9862 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9863 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9864 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9865 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9866 | ActivityInfo.CONFIG_ORIENTATION 9867 | ActivityInfo.CONFIG_KEYBOARD 9868 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9869 mResolveInfo.activityInfo = mResolveActivity; 9870 mResolveInfo.priority = 0; 9871 mResolveInfo.preferredOrder = 0; 9872 mResolveInfo.match = 0; 9873 mResolveComponentName = new ComponentName( 9874 mAndroidApplication.packageName, mResolveActivity.name); 9875 } 9876 } 9877 } 9878 } 9879 9880 ArrayList<PackageParser.Package> clientLibPkgs = null; 9881 // writer 9882 synchronized (mPackages) { 9883 boolean hasStaticSharedLibs = false; 9884 9885 // Any app can add new static shared libraries 9886 if (pkg.staticSharedLibName != null) { 9887 // Static shared libs don't allow renaming as they have synthetic package 9888 // names to allow install of multiple versions, so use name from manifest. 9889 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9890 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9891 pkg.manifestPackageName, pkg.mVersionCode)) { 9892 hasStaticSharedLibs = true; 9893 } else { 9894 Slog.w(TAG, "Package " + pkg.packageName + " library " 9895 + pkg.staticSharedLibName + " already exists; skipping"); 9896 } 9897 // Static shared libs cannot be updated once installed since they 9898 // use synthetic package name which includes the version code, so 9899 // not need to update other packages's shared lib dependencies. 9900 } 9901 9902 if (!hasStaticSharedLibs 9903 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9904 // Only system apps can add new dynamic shared libraries. 9905 if (pkg.libraryNames != null) { 9906 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9907 String name = pkg.libraryNames.get(i); 9908 boolean allowed = false; 9909 if (pkg.isUpdatedSystemApp()) { 9910 // New library entries can only be added through the 9911 // system image. This is important to get rid of a lot 9912 // of nasty edge cases: for example if we allowed a non- 9913 // system update of the app to add a library, then uninstalling 9914 // the update would make the library go away, and assumptions 9915 // we made such as through app install filtering would now 9916 // have allowed apps on the device which aren't compatible 9917 // with it. Better to just have the restriction here, be 9918 // conservative, and create many fewer cases that can negatively 9919 // impact the user experience. 9920 final PackageSetting sysPs = mSettings 9921 .getDisabledSystemPkgLPr(pkg.packageName); 9922 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9923 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9924 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9925 allowed = true; 9926 break; 9927 } 9928 } 9929 } 9930 } else { 9931 allowed = true; 9932 } 9933 if (allowed) { 9934 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9935 SharedLibraryInfo.VERSION_UNDEFINED, 9936 SharedLibraryInfo.TYPE_DYNAMIC, 9937 pkg.packageName, pkg.mVersionCode)) { 9938 Slog.w(TAG, "Package " + pkg.packageName + " library " 9939 + name + " already exists; skipping"); 9940 } 9941 } else { 9942 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9943 + name + " that is not declared on system image; skipping"); 9944 } 9945 } 9946 9947 if ((scanFlags & SCAN_BOOTING) == 0) { 9948 // If we are not booting, we need to update any applications 9949 // that are clients of our shared library. If we are booting, 9950 // this will all be done once the scan is complete. 9951 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9952 } 9953 } 9954 } 9955 } 9956 9957 if ((scanFlags & SCAN_BOOTING) != 0) { 9958 // No apps can run during boot scan, so they don't need to be frozen 9959 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9960 // Caller asked to not kill app, so it's probably not frozen 9961 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9962 // Caller asked us to ignore frozen check for some reason; they 9963 // probably didn't know the package name 9964 } else { 9965 // We're doing major surgery on this package, so it better be frozen 9966 // right now to keep it from launching 9967 checkPackageFrozen(pkgName); 9968 } 9969 9970 // Also need to kill any apps that are dependent on the library. 9971 if (clientLibPkgs != null) { 9972 for (int i=0; i<clientLibPkgs.size(); i++) { 9973 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9974 killApplication(clientPkg.applicationInfo.packageName, 9975 clientPkg.applicationInfo.uid, "update lib"); 9976 } 9977 } 9978 9979 // writer 9980 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9981 9982 synchronized (mPackages) { 9983 // We don't expect installation to fail beyond this point 9984 9985 // Add the new setting to mSettings 9986 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9987 // Add the new setting to mPackages 9988 mPackages.put(pkg.applicationInfo.packageName, pkg); 9989 // Make sure we don't accidentally delete its data. 9990 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9991 while (iter.hasNext()) { 9992 PackageCleanItem item = iter.next(); 9993 if (pkgName.equals(item.packageName)) { 9994 iter.remove(); 9995 } 9996 } 9997 9998 // Add the package's KeySets to the global KeySetManagerService 9999 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10000 ksms.addScannedPackageLPw(pkg); 10001 10002 int N = pkg.providers.size(); 10003 StringBuilder r = null; 10004 int i; 10005 for (i=0; i<N; i++) { 10006 PackageParser.Provider p = pkg.providers.get(i); 10007 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10008 p.info.processName); 10009 mProviders.addProvider(p); 10010 p.syncable = p.info.isSyncable; 10011 if (p.info.authority != null) { 10012 String names[] = p.info.authority.split(";"); 10013 p.info.authority = null; 10014 for (int j = 0; j < names.length; j++) { 10015 if (j == 1 && p.syncable) { 10016 // We only want the first authority for a provider to possibly be 10017 // syncable, so if we already added this provider using a different 10018 // authority clear the syncable flag. We copy the provider before 10019 // changing it because the mProviders object contains a reference 10020 // to a provider that we don't want to change. 10021 // Only do this for the second authority since the resulting provider 10022 // object can be the same for all future authorities for this provider. 10023 p = new PackageParser.Provider(p); 10024 p.syncable = false; 10025 } 10026 if (!mProvidersByAuthority.containsKey(names[j])) { 10027 mProvidersByAuthority.put(names[j], p); 10028 if (p.info.authority == null) { 10029 p.info.authority = names[j]; 10030 } else { 10031 p.info.authority = p.info.authority + ";" + names[j]; 10032 } 10033 if (DEBUG_PACKAGE_SCANNING) { 10034 if (chatty) 10035 Log.d(TAG, "Registered content provider: " + names[j] 10036 + ", className = " + p.info.name + ", isSyncable = " 10037 + p.info.isSyncable); 10038 } 10039 } else { 10040 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10041 Slog.w(TAG, "Skipping provider name " + names[j] + 10042 " (in package " + pkg.applicationInfo.packageName + 10043 "): name already used by " 10044 + ((other != null && other.getComponentName() != null) 10045 ? other.getComponentName().getPackageName() : "?")); 10046 } 10047 } 10048 } 10049 if (chatty) { 10050 if (r == null) { 10051 r = new StringBuilder(256); 10052 } else { 10053 r.append(' '); 10054 } 10055 r.append(p.info.name); 10056 } 10057 } 10058 if (r != null) { 10059 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10060 } 10061 10062 N = pkg.services.size(); 10063 r = null; 10064 for (i=0; i<N; i++) { 10065 PackageParser.Service s = pkg.services.get(i); 10066 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10067 s.info.processName); 10068 mServices.addService(s); 10069 if (chatty) { 10070 if (r == null) { 10071 r = new StringBuilder(256); 10072 } else { 10073 r.append(' '); 10074 } 10075 r.append(s.info.name); 10076 } 10077 } 10078 if (r != null) { 10079 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10080 } 10081 10082 N = pkg.receivers.size(); 10083 r = null; 10084 for (i=0; i<N; i++) { 10085 PackageParser.Activity a = pkg.receivers.get(i); 10086 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10087 a.info.processName); 10088 mReceivers.addActivity(a, "receiver"); 10089 if (chatty) { 10090 if (r == null) { 10091 r = new StringBuilder(256); 10092 } else { 10093 r.append(' '); 10094 } 10095 r.append(a.info.name); 10096 } 10097 } 10098 if (r != null) { 10099 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10100 } 10101 10102 N = pkg.activities.size(); 10103 r = null; 10104 for (i=0; i<N; i++) { 10105 PackageParser.Activity a = pkg.activities.get(i); 10106 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10107 a.info.processName); 10108 mActivities.addActivity(a, "activity"); 10109 if (chatty) { 10110 if (r == null) { 10111 r = new StringBuilder(256); 10112 } else { 10113 r.append(' '); 10114 } 10115 r.append(a.info.name); 10116 } 10117 } 10118 if (r != null) { 10119 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10120 } 10121 10122 N = pkg.permissionGroups.size(); 10123 r = null; 10124 for (i=0; i<N; i++) { 10125 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10126 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10127 final String curPackageName = cur == null ? null : cur.info.packageName; 10128 // Dont allow ephemeral apps to define new permission groups. 10129 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10130 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10131 + pg.info.packageName 10132 + " ignored: instant apps cannot define new permission groups."); 10133 continue; 10134 } 10135 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10136 if (cur == null || isPackageUpdate) { 10137 mPermissionGroups.put(pg.info.name, pg); 10138 if (chatty) { 10139 if (r == null) { 10140 r = new StringBuilder(256); 10141 } else { 10142 r.append(' '); 10143 } 10144 if (isPackageUpdate) { 10145 r.append("UPD:"); 10146 } 10147 r.append(pg.info.name); 10148 } 10149 } else { 10150 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10151 + pg.info.packageName + " ignored: original from " 10152 + cur.info.packageName); 10153 if (chatty) { 10154 if (r == null) { 10155 r = new StringBuilder(256); 10156 } else { 10157 r.append(' '); 10158 } 10159 r.append("DUP:"); 10160 r.append(pg.info.name); 10161 } 10162 } 10163 } 10164 if (r != null) { 10165 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10166 } 10167 10168 N = pkg.permissions.size(); 10169 r = null; 10170 for (i=0; i<N; i++) { 10171 PackageParser.Permission p = pkg.permissions.get(i); 10172 10173 // Dont allow ephemeral apps to define new permissions. 10174 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10175 Slog.w(TAG, "Permission " + p.info.name + " from package " 10176 + p.info.packageName 10177 + " ignored: instant apps cannot define new permissions."); 10178 continue; 10179 } 10180 10181 // Assume by default that we did not install this permission into the system. 10182 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10183 10184 // Now that permission groups have a special meaning, we ignore permission 10185 // groups for legacy apps to prevent unexpected behavior. In particular, 10186 // permissions for one app being granted to someone just becase they happen 10187 // to be in a group defined by another app (before this had no implications). 10188 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10189 p.group = mPermissionGroups.get(p.info.group); 10190 // Warn for a permission in an unknown group. 10191 if (p.info.group != null && p.group == null) { 10192 Slog.w(TAG, "Permission " + p.info.name + " from package " 10193 + p.info.packageName + " in an unknown group " + p.info.group); 10194 } 10195 } 10196 10197 ArrayMap<String, BasePermission> permissionMap = 10198 p.tree ? mSettings.mPermissionTrees 10199 : mSettings.mPermissions; 10200 BasePermission bp = permissionMap.get(p.info.name); 10201 10202 // Allow system apps to redefine non-system permissions 10203 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10204 final boolean currentOwnerIsSystem = (bp.perm != null 10205 && isSystemApp(bp.perm.owner)); 10206 if (isSystemApp(p.owner)) { 10207 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10208 // It's a built-in permission and no owner, take ownership now 10209 bp.packageSetting = pkgSetting; 10210 bp.perm = p; 10211 bp.uid = pkg.applicationInfo.uid; 10212 bp.sourcePackage = p.info.packageName; 10213 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10214 } else if (!currentOwnerIsSystem) { 10215 String msg = "New decl " + p.owner + " of permission " 10216 + p.info.name + " is system; overriding " + bp.sourcePackage; 10217 reportSettingsProblem(Log.WARN, msg); 10218 bp = null; 10219 } 10220 } 10221 } 10222 10223 if (bp == null) { 10224 bp = new BasePermission(p.info.name, p.info.packageName, 10225 BasePermission.TYPE_NORMAL); 10226 permissionMap.put(p.info.name, bp); 10227 } 10228 10229 if (bp.perm == null) { 10230 if (bp.sourcePackage == null 10231 || bp.sourcePackage.equals(p.info.packageName)) { 10232 BasePermission tree = findPermissionTreeLP(p.info.name); 10233 if (tree == null 10234 || tree.sourcePackage.equals(p.info.packageName)) { 10235 bp.packageSetting = pkgSetting; 10236 bp.perm = p; 10237 bp.uid = pkg.applicationInfo.uid; 10238 bp.sourcePackage = p.info.packageName; 10239 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10240 if (chatty) { 10241 if (r == null) { 10242 r = new StringBuilder(256); 10243 } else { 10244 r.append(' '); 10245 } 10246 r.append(p.info.name); 10247 } 10248 } else { 10249 Slog.w(TAG, "Permission " + p.info.name + " from package " 10250 + p.info.packageName + " ignored: base tree " 10251 + tree.name + " is from package " 10252 + tree.sourcePackage); 10253 } 10254 } else { 10255 Slog.w(TAG, "Permission " + p.info.name + " from package " 10256 + p.info.packageName + " ignored: original from " 10257 + bp.sourcePackage); 10258 } 10259 } else if (chatty) { 10260 if (r == null) { 10261 r = new StringBuilder(256); 10262 } else { 10263 r.append(' '); 10264 } 10265 r.append("DUP:"); 10266 r.append(p.info.name); 10267 } 10268 if (bp.perm == p) { 10269 bp.protectionLevel = p.info.protectionLevel; 10270 } 10271 } 10272 10273 if (r != null) { 10274 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10275 } 10276 10277 N = pkg.instrumentation.size(); 10278 r = null; 10279 for (i=0; i<N; i++) { 10280 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10281 a.info.packageName = pkg.applicationInfo.packageName; 10282 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10283 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10284 a.info.splitNames = pkg.splitNames; 10285 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10286 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10287 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10288 a.info.dataDir = pkg.applicationInfo.dataDir; 10289 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10290 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10291 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10292 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10293 mInstrumentation.put(a.getComponentName(), a); 10294 if (chatty) { 10295 if (r == null) { 10296 r = new StringBuilder(256); 10297 } else { 10298 r.append(' '); 10299 } 10300 r.append(a.info.name); 10301 } 10302 } 10303 if (r != null) { 10304 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10305 } 10306 10307 if (pkg.protectedBroadcasts != null) { 10308 N = pkg.protectedBroadcasts.size(); 10309 for (i=0; i<N; i++) { 10310 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10311 } 10312 } 10313 } 10314 10315 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10316 } 10317 10318 /** 10319 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10320 * is derived purely on the basis of the contents of {@code scanFile} and 10321 * {@code cpuAbiOverride}. 10322 * 10323 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10324 */ 10325 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10326 String cpuAbiOverride, boolean extractLibs, 10327 File appLib32InstallDir) 10328 throws PackageManagerException { 10329 // Give ourselves some initial paths; we'll come back for another 10330 // pass once we've determined ABI below. 10331 setNativeLibraryPaths(pkg, appLib32InstallDir); 10332 10333 // We would never need to extract libs for forward-locked and external packages, 10334 // since the container service will do it for us. We shouldn't attempt to 10335 // extract libs from system app when it was not updated. 10336 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10337 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10338 extractLibs = false; 10339 } 10340 10341 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10342 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10343 10344 NativeLibraryHelper.Handle handle = null; 10345 try { 10346 handle = NativeLibraryHelper.Handle.create(pkg); 10347 // TODO(multiArch): This can be null for apps that didn't go through the 10348 // usual installation process. We can calculate it again, like we 10349 // do during install time. 10350 // 10351 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10352 // unnecessary. 10353 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10354 10355 // Null out the abis so that they can be recalculated. 10356 pkg.applicationInfo.primaryCpuAbi = null; 10357 pkg.applicationInfo.secondaryCpuAbi = null; 10358 if (isMultiArch(pkg.applicationInfo)) { 10359 // Warn if we've set an abiOverride for multi-lib packages.. 10360 // By definition, we need to copy both 32 and 64 bit libraries for 10361 // such packages. 10362 if (pkg.cpuAbiOverride != null 10363 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10364 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10365 } 10366 10367 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10368 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10369 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10370 if (extractLibs) { 10371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10372 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10373 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10374 useIsaSpecificSubdirs); 10375 } else { 10376 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10377 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10378 } 10379 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10380 } 10381 10382 maybeThrowExceptionForMultiArchCopy( 10383 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10384 10385 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10386 if (extractLibs) { 10387 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10388 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10389 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10390 useIsaSpecificSubdirs); 10391 } else { 10392 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10393 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10394 } 10395 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10396 } 10397 10398 maybeThrowExceptionForMultiArchCopy( 10399 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10400 10401 if (abi64 >= 0) { 10402 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10403 } 10404 10405 if (abi32 >= 0) { 10406 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10407 if (abi64 >= 0) { 10408 if (pkg.use32bitAbi) { 10409 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10410 pkg.applicationInfo.primaryCpuAbi = abi; 10411 } else { 10412 pkg.applicationInfo.secondaryCpuAbi = abi; 10413 } 10414 } else { 10415 pkg.applicationInfo.primaryCpuAbi = abi; 10416 } 10417 } 10418 10419 } else { 10420 String[] abiList = (cpuAbiOverride != null) ? 10421 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10422 10423 // Enable gross and lame hacks for apps that are built with old 10424 // SDK tools. We must scan their APKs for renderscript bitcode and 10425 // not launch them if it's present. Don't bother checking on devices 10426 // that don't have 64 bit support. 10427 boolean needsRenderScriptOverride = false; 10428 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10429 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10430 abiList = Build.SUPPORTED_32_BIT_ABIS; 10431 needsRenderScriptOverride = true; 10432 } 10433 10434 final int copyRet; 10435 if (extractLibs) { 10436 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10437 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10438 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10439 } else { 10440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10441 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10442 } 10443 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10444 10445 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10446 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10447 "Error unpackaging native libs for app, errorCode=" + copyRet); 10448 } 10449 10450 if (copyRet >= 0) { 10451 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10452 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10453 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10454 } else if (needsRenderScriptOverride) { 10455 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10456 } 10457 } 10458 } catch (IOException ioe) { 10459 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10460 } finally { 10461 IoUtils.closeQuietly(handle); 10462 } 10463 10464 // Now that we've calculated the ABIs and determined if it's an internal app, 10465 // we will go ahead and populate the nativeLibraryPath. 10466 setNativeLibraryPaths(pkg, appLib32InstallDir); 10467 } 10468 10469 /** 10470 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10471 * i.e, so that all packages can be run inside a single process if required. 10472 * 10473 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10474 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10475 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10476 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10477 * updating a package that belongs to a shared user. 10478 * 10479 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10480 * adds unnecessary complexity. 10481 */ 10482 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10483 PackageParser.Package scannedPackage) { 10484 String requiredInstructionSet = null; 10485 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10486 requiredInstructionSet = VMRuntime.getInstructionSet( 10487 scannedPackage.applicationInfo.primaryCpuAbi); 10488 } 10489 10490 PackageSetting requirer = null; 10491 for (PackageSetting ps : packagesForUser) { 10492 // If packagesForUser contains scannedPackage, we skip it. This will happen 10493 // when scannedPackage is an update of an existing package. Without this check, 10494 // we will never be able to change the ABI of any package belonging to a shared 10495 // user, even if it's compatible with other packages. 10496 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10497 if (ps.primaryCpuAbiString == null) { 10498 continue; 10499 } 10500 10501 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10502 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10503 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10504 // this but there's not much we can do. 10505 String errorMessage = "Instruction set mismatch, " 10506 + ((requirer == null) ? "[caller]" : requirer) 10507 + " requires " + requiredInstructionSet + " whereas " + ps 10508 + " requires " + instructionSet; 10509 Slog.w(TAG, errorMessage); 10510 } 10511 10512 if (requiredInstructionSet == null) { 10513 requiredInstructionSet = instructionSet; 10514 requirer = ps; 10515 } 10516 } 10517 } 10518 10519 if (requiredInstructionSet != null) { 10520 String adjustedAbi; 10521 if (requirer != null) { 10522 // requirer != null implies that either scannedPackage was null or that scannedPackage 10523 // did not require an ABI, in which case we have to adjust scannedPackage to match 10524 // the ABI of the set (which is the same as requirer's ABI) 10525 adjustedAbi = requirer.primaryCpuAbiString; 10526 if (scannedPackage != null) { 10527 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10528 } 10529 } else { 10530 // requirer == null implies that we're updating all ABIs in the set to 10531 // match scannedPackage. 10532 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10533 } 10534 10535 for (PackageSetting ps : packagesForUser) { 10536 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10537 if (ps.primaryCpuAbiString != null) { 10538 continue; 10539 } 10540 10541 ps.primaryCpuAbiString = adjustedAbi; 10542 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10543 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10544 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10545 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10546 + " (requirer=" 10547 + (requirer != null ? requirer.pkg : "null") 10548 + ", scannedPackage=" 10549 + (scannedPackage != null ? scannedPackage : "null") 10550 + ")"); 10551 try { 10552 mInstaller.rmdex(ps.codePathString, 10553 getDexCodeInstructionSet(getPreferredInstructionSet())); 10554 } catch (InstallerException ignored) { 10555 } 10556 } 10557 } 10558 } 10559 } 10560 } 10561 10562 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10563 synchronized (mPackages) { 10564 mResolverReplaced = true; 10565 // Set up information for custom user intent resolution activity. 10566 mResolveActivity.applicationInfo = pkg.applicationInfo; 10567 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10568 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10569 mResolveActivity.processName = pkg.applicationInfo.packageName; 10570 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10571 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10572 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10573 mResolveActivity.theme = 0; 10574 mResolveActivity.exported = true; 10575 mResolveActivity.enabled = true; 10576 mResolveInfo.activityInfo = mResolveActivity; 10577 mResolveInfo.priority = 0; 10578 mResolveInfo.preferredOrder = 0; 10579 mResolveInfo.match = 0; 10580 mResolveComponentName = mCustomResolverComponentName; 10581 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10582 mResolveComponentName); 10583 } 10584 } 10585 10586 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10587 if (installerComponent == null) { 10588 if (DEBUG_EPHEMERAL) { 10589 Slog.d(TAG, "Clear ephemeral installer activity"); 10590 } 10591 mInstantAppInstallerActivity.applicationInfo = null; 10592 return; 10593 } 10594 10595 if (DEBUG_EPHEMERAL) { 10596 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10597 } 10598 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10599 // Set up information for ephemeral installer activity 10600 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10601 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10602 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10603 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10604 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10605 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10606 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10607 mInstantAppInstallerActivity.theme = 0; 10608 mInstantAppInstallerActivity.exported = true; 10609 mInstantAppInstallerActivity.enabled = true; 10610 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10611 mInstantAppInstallerInfo.priority = 0; 10612 mInstantAppInstallerInfo.preferredOrder = 1; 10613 mInstantAppInstallerInfo.isDefault = true; 10614 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10615 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10616 } 10617 10618 private static String calculateBundledApkRoot(final String codePathString) { 10619 final File codePath = new File(codePathString); 10620 final File codeRoot; 10621 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10622 codeRoot = Environment.getRootDirectory(); 10623 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10624 codeRoot = Environment.getOemDirectory(); 10625 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10626 codeRoot = Environment.getVendorDirectory(); 10627 } else { 10628 // Unrecognized code path; take its top real segment as the apk root: 10629 // e.g. /something/app/blah.apk => /something 10630 try { 10631 File f = codePath.getCanonicalFile(); 10632 File parent = f.getParentFile(); // non-null because codePath is a file 10633 File tmp; 10634 while ((tmp = parent.getParentFile()) != null) { 10635 f = parent; 10636 parent = tmp; 10637 } 10638 codeRoot = f; 10639 Slog.w(TAG, "Unrecognized code path " 10640 + codePath + " - using " + codeRoot); 10641 } catch (IOException e) { 10642 // Can't canonicalize the code path -- shenanigans? 10643 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10644 return Environment.getRootDirectory().getPath(); 10645 } 10646 } 10647 return codeRoot.getPath(); 10648 } 10649 10650 /** 10651 * Derive and set the location of native libraries for the given package, 10652 * which varies depending on where and how the package was installed. 10653 */ 10654 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10655 final ApplicationInfo info = pkg.applicationInfo; 10656 final String codePath = pkg.codePath; 10657 final File codeFile = new File(codePath); 10658 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10659 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10660 10661 info.nativeLibraryRootDir = null; 10662 info.nativeLibraryRootRequiresIsa = false; 10663 info.nativeLibraryDir = null; 10664 info.secondaryNativeLibraryDir = null; 10665 10666 if (isApkFile(codeFile)) { 10667 // Monolithic install 10668 if (bundledApp) { 10669 // If "/system/lib64/apkname" exists, assume that is the per-package 10670 // native library directory to use; otherwise use "/system/lib/apkname". 10671 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10672 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10673 getPrimaryInstructionSet(info)); 10674 10675 // This is a bundled system app so choose the path based on the ABI. 10676 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10677 // is just the default path. 10678 final String apkName = deriveCodePathName(codePath); 10679 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10680 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10681 apkName).getAbsolutePath(); 10682 10683 if (info.secondaryCpuAbi != null) { 10684 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10685 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10686 secondaryLibDir, apkName).getAbsolutePath(); 10687 } 10688 } else if (asecApp) { 10689 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10690 .getAbsolutePath(); 10691 } else { 10692 final String apkName = deriveCodePathName(codePath); 10693 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10694 .getAbsolutePath(); 10695 } 10696 10697 info.nativeLibraryRootRequiresIsa = false; 10698 info.nativeLibraryDir = info.nativeLibraryRootDir; 10699 } else { 10700 // Cluster install 10701 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10702 info.nativeLibraryRootRequiresIsa = true; 10703 10704 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10705 getPrimaryInstructionSet(info)).getAbsolutePath(); 10706 10707 if (info.secondaryCpuAbi != null) { 10708 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10709 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10710 } 10711 } 10712 } 10713 10714 /** 10715 * Calculate the abis and roots for a bundled app. These can uniquely 10716 * be determined from the contents of the system partition, i.e whether 10717 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10718 * of this information, and instead assume that the system was built 10719 * sensibly. 10720 */ 10721 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10722 PackageSetting pkgSetting) { 10723 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10724 10725 // If "/system/lib64/apkname" exists, assume that is the per-package 10726 // native library directory to use; otherwise use "/system/lib/apkname". 10727 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10728 setBundledAppAbi(pkg, apkRoot, apkName); 10729 // pkgSetting might be null during rescan following uninstall of updates 10730 // to a bundled app, so accommodate that possibility. The settings in 10731 // that case will be established later from the parsed package. 10732 // 10733 // If the settings aren't null, sync them up with what we've just derived. 10734 // note that apkRoot isn't stored in the package settings. 10735 if (pkgSetting != null) { 10736 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10737 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10738 } 10739 } 10740 10741 /** 10742 * Deduces the ABI of a bundled app and sets the relevant fields on the 10743 * parsed pkg object. 10744 * 10745 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10746 * under which system libraries are installed. 10747 * @param apkName the name of the installed package. 10748 */ 10749 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10750 final File codeFile = new File(pkg.codePath); 10751 10752 final boolean has64BitLibs; 10753 final boolean has32BitLibs; 10754 if (isApkFile(codeFile)) { 10755 // Monolithic install 10756 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10757 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10758 } else { 10759 // Cluster install 10760 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10761 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10762 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10763 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10764 has64BitLibs = (new File(rootDir, isa)).exists(); 10765 } else { 10766 has64BitLibs = false; 10767 } 10768 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10769 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10770 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10771 has32BitLibs = (new File(rootDir, isa)).exists(); 10772 } else { 10773 has32BitLibs = false; 10774 } 10775 } 10776 10777 if (has64BitLibs && !has32BitLibs) { 10778 // The package has 64 bit libs, but not 32 bit libs. Its primary 10779 // ABI should be 64 bit. We can safely assume here that the bundled 10780 // native libraries correspond to the most preferred ABI in the list. 10781 10782 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10783 pkg.applicationInfo.secondaryCpuAbi = null; 10784 } else if (has32BitLibs && !has64BitLibs) { 10785 // The package has 32 bit libs but not 64 bit libs. Its primary 10786 // ABI should be 32 bit. 10787 10788 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10789 pkg.applicationInfo.secondaryCpuAbi = null; 10790 } else if (has32BitLibs && has64BitLibs) { 10791 // The application has both 64 and 32 bit bundled libraries. We check 10792 // here that the app declares multiArch support, and warn if it doesn't. 10793 // 10794 // We will be lenient here and record both ABIs. The primary will be the 10795 // ABI that's higher on the list, i.e, a device that's configured to prefer 10796 // 64 bit apps will see a 64 bit primary ABI, 10797 10798 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10799 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10800 } 10801 10802 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10803 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10804 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10805 } else { 10806 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10807 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10808 } 10809 } else { 10810 pkg.applicationInfo.primaryCpuAbi = null; 10811 pkg.applicationInfo.secondaryCpuAbi = null; 10812 } 10813 } 10814 10815 private void killApplication(String pkgName, int appId, String reason) { 10816 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10817 } 10818 10819 private void killApplication(String pkgName, int appId, int userId, String reason) { 10820 // Request the ActivityManager to kill the process(only for existing packages) 10821 // so that we do not end up in a confused state while the user is still using the older 10822 // version of the application while the new one gets installed. 10823 final long token = Binder.clearCallingIdentity(); 10824 try { 10825 IActivityManager am = ActivityManager.getService(); 10826 if (am != null) { 10827 try { 10828 am.killApplication(pkgName, appId, userId, reason); 10829 } catch (RemoteException e) { 10830 } 10831 } 10832 } finally { 10833 Binder.restoreCallingIdentity(token); 10834 } 10835 } 10836 10837 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10838 // Remove the parent package setting 10839 PackageSetting ps = (PackageSetting) pkg.mExtras; 10840 if (ps != null) { 10841 removePackageLI(ps, chatty); 10842 } 10843 // Remove the child package setting 10844 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10845 for (int i = 0; i < childCount; i++) { 10846 PackageParser.Package childPkg = pkg.childPackages.get(i); 10847 ps = (PackageSetting) childPkg.mExtras; 10848 if (ps != null) { 10849 removePackageLI(ps, chatty); 10850 } 10851 } 10852 } 10853 10854 void removePackageLI(PackageSetting ps, boolean chatty) { 10855 if (DEBUG_INSTALL) { 10856 if (chatty) 10857 Log.d(TAG, "Removing package " + ps.name); 10858 } 10859 10860 // writer 10861 synchronized (mPackages) { 10862 mPackages.remove(ps.name); 10863 final PackageParser.Package pkg = ps.pkg; 10864 if (pkg != null) { 10865 cleanPackageDataStructuresLILPw(pkg, chatty); 10866 } 10867 } 10868 } 10869 10870 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10871 if (DEBUG_INSTALL) { 10872 if (chatty) 10873 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10874 } 10875 10876 // writer 10877 synchronized (mPackages) { 10878 // Remove the parent package 10879 mPackages.remove(pkg.applicationInfo.packageName); 10880 cleanPackageDataStructuresLILPw(pkg, chatty); 10881 10882 // Remove the child packages 10883 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10884 for (int i = 0; i < childCount; i++) { 10885 PackageParser.Package childPkg = pkg.childPackages.get(i); 10886 mPackages.remove(childPkg.applicationInfo.packageName); 10887 cleanPackageDataStructuresLILPw(childPkg, chatty); 10888 } 10889 } 10890 } 10891 10892 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10893 int N = pkg.providers.size(); 10894 StringBuilder r = null; 10895 int i; 10896 for (i=0; i<N; i++) { 10897 PackageParser.Provider p = pkg.providers.get(i); 10898 mProviders.removeProvider(p); 10899 if (p.info.authority == null) { 10900 10901 /* There was another ContentProvider with this authority when 10902 * this app was installed so this authority is null, 10903 * Ignore it as we don't have to unregister the provider. 10904 */ 10905 continue; 10906 } 10907 String names[] = p.info.authority.split(";"); 10908 for (int j = 0; j < names.length; j++) { 10909 if (mProvidersByAuthority.get(names[j]) == p) { 10910 mProvidersByAuthority.remove(names[j]); 10911 if (DEBUG_REMOVE) { 10912 if (chatty) 10913 Log.d(TAG, "Unregistered content provider: " + names[j] 10914 + ", className = " + p.info.name + ", isSyncable = " 10915 + p.info.isSyncable); 10916 } 10917 } 10918 } 10919 if (DEBUG_REMOVE && chatty) { 10920 if (r == null) { 10921 r = new StringBuilder(256); 10922 } else { 10923 r.append(' '); 10924 } 10925 r.append(p.info.name); 10926 } 10927 } 10928 if (r != null) { 10929 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10930 } 10931 10932 N = pkg.services.size(); 10933 r = null; 10934 for (i=0; i<N; i++) { 10935 PackageParser.Service s = pkg.services.get(i); 10936 mServices.removeService(s); 10937 if (chatty) { 10938 if (r == null) { 10939 r = new StringBuilder(256); 10940 } else { 10941 r.append(' '); 10942 } 10943 r.append(s.info.name); 10944 } 10945 } 10946 if (r != null) { 10947 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10948 } 10949 10950 N = pkg.receivers.size(); 10951 r = null; 10952 for (i=0; i<N; i++) { 10953 PackageParser.Activity a = pkg.receivers.get(i); 10954 mReceivers.removeActivity(a, "receiver"); 10955 if (DEBUG_REMOVE && chatty) { 10956 if (r == null) { 10957 r = new StringBuilder(256); 10958 } else { 10959 r.append(' '); 10960 } 10961 r.append(a.info.name); 10962 } 10963 } 10964 if (r != null) { 10965 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10966 } 10967 10968 N = pkg.activities.size(); 10969 r = null; 10970 for (i=0; i<N; i++) { 10971 PackageParser.Activity a = pkg.activities.get(i); 10972 mActivities.removeActivity(a, "activity"); 10973 if (DEBUG_REMOVE && chatty) { 10974 if (r == null) { 10975 r = new StringBuilder(256); 10976 } else { 10977 r.append(' '); 10978 } 10979 r.append(a.info.name); 10980 } 10981 } 10982 if (r != null) { 10983 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10984 } 10985 10986 N = pkg.permissions.size(); 10987 r = null; 10988 for (i=0; i<N; i++) { 10989 PackageParser.Permission p = pkg.permissions.get(i); 10990 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10991 if (bp == null) { 10992 bp = mSettings.mPermissionTrees.get(p.info.name); 10993 } 10994 if (bp != null && bp.perm == p) { 10995 bp.perm = null; 10996 if (DEBUG_REMOVE && chatty) { 10997 if (r == null) { 10998 r = new StringBuilder(256); 10999 } else { 11000 r.append(' '); 11001 } 11002 r.append(p.info.name); 11003 } 11004 } 11005 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11006 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11007 if (appOpPkgs != null) { 11008 appOpPkgs.remove(pkg.packageName); 11009 } 11010 } 11011 } 11012 if (r != null) { 11013 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11014 } 11015 11016 N = pkg.requestedPermissions.size(); 11017 r = null; 11018 for (i=0; i<N; i++) { 11019 String perm = pkg.requestedPermissions.get(i); 11020 BasePermission bp = mSettings.mPermissions.get(perm); 11021 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11022 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11023 if (appOpPkgs != null) { 11024 appOpPkgs.remove(pkg.packageName); 11025 if (appOpPkgs.isEmpty()) { 11026 mAppOpPermissionPackages.remove(perm); 11027 } 11028 } 11029 } 11030 } 11031 if (r != null) { 11032 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11033 } 11034 11035 N = pkg.instrumentation.size(); 11036 r = null; 11037 for (i=0; i<N; i++) { 11038 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11039 mInstrumentation.remove(a.getComponentName()); 11040 if (DEBUG_REMOVE && chatty) { 11041 if (r == null) { 11042 r = new StringBuilder(256); 11043 } else { 11044 r.append(' '); 11045 } 11046 r.append(a.info.name); 11047 } 11048 } 11049 if (r != null) { 11050 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11051 } 11052 11053 r = null; 11054 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11055 // Only system apps can hold shared libraries. 11056 if (pkg.libraryNames != null) { 11057 for (i = 0; i < pkg.libraryNames.size(); i++) { 11058 String name = pkg.libraryNames.get(i); 11059 if (removeSharedLibraryLPw(name, 0)) { 11060 if (DEBUG_REMOVE && chatty) { 11061 if (r == null) { 11062 r = new StringBuilder(256); 11063 } else { 11064 r.append(' '); 11065 } 11066 r.append(name); 11067 } 11068 } 11069 } 11070 } 11071 } 11072 11073 r = null; 11074 11075 // Any package can hold static shared libraries. 11076 if (pkg.staticSharedLibName != null) { 11077 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11078 if (DEBUG_REMOVE && chatty) { 11079 if (r == null) { 11080 r = new StringBuilder(256); 11081 } else { 11082 r.append(' '); 11083 } 11084 r.append(pkg.staticSharedLibName); 11085 } 11086 } 11087 } 11088 11089 if (r != null) { 11090 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11091 } 11092 } 11093 11094 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11095 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11096 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11097 return true; 11098 } 11099 } 11100 return false; 11101 } 11102 11103 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11104 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11105 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11106 11107 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11108 // Update the parent permissions 11109 updatePermissionsLPw(pkg.packageName, pkg, flags); 11110 // Update the child permissions 11111 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11112 for (int i = 0; i < childCount; i++) { 11113 PackageParser.Package childPkg = pkg.childPackages.get(i); 11114 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11115 } 11116 } 11117 11118 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11119 int flags) { 11120 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11121 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11122 } 11123 11124 private void updatePermissionsLPw(String changingPkg, 11125 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11126 // Make sure there are no dangling permission trees. 11127 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11128 while (it.hasNext()) { 11129 final BasePermission bp = it.next(); 11130 if (bp.packageSetting == null) { 11131 // We may not yet have parsed the package, so just see if 11132 // we still know about its settings. 11133 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11134 } 11135 if (bp.packageSetting == null) { 11136 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11137 + " from package " + bp.sourcePackage); 11138 it.remove(); 11139 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11140 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11141 Slog.i(TAG, "Removing old permission tree: " + bp.name 11142 + " from package " + bp.sourcePackage); 11143 flags |= UPDATE_PERMISSIONS_ALL; 11144 it.remove(); 11145 } 11146 } 11147 } 11148 11149 // Make sure all dynamic permissions have been assigned to a package, 11150 // and make sure there are no dangling permissions. 11151 it = mSettings.mPermissions.values().iterator(); 11152 while (it.hasNext()) { 11153 final BasePermission bp = it.next(); 11154 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11155 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11156 + bp.name + " pkg=" + bp.sourcePackage 11157 + " info=" + bp.pendingInfo); 11158 if (bp.packageSetting == null && bp.pendingInfo != null) { 11159 final BasePermission tree = findPermissionTreeLP(bp.name); 11160 if (tree != null && tree.perm != null) { 11161 bp.packageSetting = tree.packageSetting; 11162 bp.perm = new PackageParser.Permission(tree.perm.owner, 11163 new PermissionInfo(bp.pendingInfo)); 11164 bp.perm.info.packageName = tree.perm.info.packageName; 11165 bp.perm.info.name = bp.name; 11166 bp.uid = tree.uid; 11167 } 11168 } 11169 } 11170 if (bp.packageSetting == null) { 11171 // We may not yet have parsed the package, so just see if 11172 // we still know about its settings. 11173 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11174 } 11175 if (bp.packageSetting == null) { 11176 Slog.w(TAG, "Removing dangling permission: " + bp.name 11177 + " from package " + bp.sourcePackage); 11178 it.remove(); 11179 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11180 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11181 Slog.i(TAG, "Removing old permission: " + bp.name 11182 + " from package " + bp.sourcePackage); 11183 flags |= UPDATE_PERMISSIONS_ALL; 11184 it.remove(); 11185 } 11186 } 11187 } 11188 11189 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11190 // Now update the permissions for all packages, in particular 11191 // replace the granted permissions of the system packages. 11192 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11193 for (PackageParser.Package pkg : mPackages.values()) { 11194 if (pkg != pkgInfo) { 11195 // Only replace for packages on requested volume 11196 final String volumeUuid = getVolumeUuidForPackage(pkg); 11197 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11198 && Objects.equals(replaceVolumeUuid, volumeUuid); 11199 grantPermissionsLPw(pkg, replace, changingPkg); 11200 } 11201 } 11202 } 11203 11204 if (pkgInfo != null) { 11205 // Only replace for packages on requested volume 11206 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11207 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11208 && Objects.equals(replaceVolumeUuid, volumeUuid); 11209 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11210 } 11211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11212 } 11213 11214 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11215 String packageOfInterest) { 11216 // IMPORTANT: There are two types of permissions: install and runtime. 11217 // Install time permissions are granted when the app is installed to 11218 // all device users and users added in the future. Runtime permissions 11219 // are granted at runtime explicitly to specific users. Normal and signature 11220 // protected permissions are install time permissions. Dangerous permissions 11221 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11222 // otherwise they are runtime permissions. This function does not manage 11223 // runtime permissions except for the case an app targeting Lollipop MR1 11224 // being upgraded to target a newer SDK, in which case dangerous permissions 11225 // are transformed from install time to runtime ones. 11226 11227 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11228 if (ps == null) { 11229 return; 11230 } 11231 11232 PermissionsState permissionsState = ps.getPermissionsState(); 11233 PermissionsState origPermissions = permissionsState; 11234 11235 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11236 11237 boolean runtimePermissionsRevoked = false; 11238 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11239 11240 boolean changedInstallPermission = false; 11241 11242 if (replace) { 11243 ps.installPermissionsFixed = false; 11244 if (!ps.isSharedUser()) { 11245 origPermissions = new PermissionsState(permissionsState); 11246 permissionsState.reset(); 11247 } else { 11248 // We need to know only about runtime permission changes since the 11249 // calling code always writes the install permissions state but 11250 // the runtime ones are written only if changed. The only cases of 11251 // changed runtime permissions here are promotion of an install to 11252 // runtime and revocation of a runtime from a shared user. 11253 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11254 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11255 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11256 runtimePermissionsRevoked = true; 11257 } 11258 } 11259 } 11260 11261 permissionsState.setGlobalGids(mGlobalGids); 11262 11263 final int N = pkg.requestedPermissions.size(); 11264 for (int i=0; i<N; i++) { 11265 final String name = pkg.requestedPermissions.get(i); 11266 final BasePermission bp = mSettings.mPermissions.get(name); 11267 11268 if (DEBUG_INSTALL) { 11269 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11270 } 11271 11272 if (bp == null || bp.packageSetting == null) { 11273 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11274 Slog.w(TAG, "Unknown permission " + name 11275 + " in package " + pkg.packageName); 11276 } 11277 continue; 11278 } 11279 11280 11281 // Limit ephemeral apps to ephemeral allowed permissions. 11282 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11283 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11284 + pkg.packageName); 11285 continue; 11286 } 11287 11288 final String perm = bp.name; 11289 boolean allowedSig = false; 11290 int grant = GRANT_DENIED; 11291 11292 // Keep track of app op permissions. 11293 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11294 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11295 if (pkgs == null) { 11296 pkgs = new ArraySet<>(); 11297 mAppOpPermissionPackages.put(bp.name, pkgs); 11298 } 11299 pkgs.add(pkg.packageName); 11300 } 11301 11302 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11303 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11304 >= Build.VERSION_CODES.M; 11305 switch (level) { 11306 case PermissionInfo.PROTECTION_NORMAL: { 11307 // For all apps normal permissions are install time ones. 11308 grant = GRANT_INSTALL; 11309 } break; 11310 11311 case PermissionInfo.PROTECTION_DANGEROUS: { 11312 // If a permission review is required for legacy apps we represent 11313 // their permissions as always granted runtime ones since we need 11314 // to keep the review required permission flag per user while an 11315 // install permission's state is shared across all users. 11316 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11317 // For legacy apps dangerous permissions are install time ones. 11318 grant = GRANT_INSTALL; 11319 } else if (origPermissions.hasInstallPermission(bp.name)) { 11320 // For legacy apps that became modern, install becomes runtime. 11321 grant = GRANT_UPGRADE; 11322 } else if (mPromoteSystemApps 11323 && isSystemApp(ps) 11324 && mExistingSystemPackages.contains(ps.name)) { 11325 // For legacy system apps, install becomes runtime. 11326 // We cannot check hasInstallPermission() for system apps since those 11327 // permissions were granted implicitly and not persisted pre-M. 11328 grant = GRANT_UPGRADE; 11329 } else { 11330 // For modern apps keep runtime permissions unchanged. 11331 grant = GRANT_RUNTIME; 11332 } 11333 } break; 11334 11335 case PermissionInfo.PROTECTION_SIGNATURE: { 11336 // For all apps signature permissions are install time ones. 11337 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11338 if (allowedSig) { 11339 grant = GRANT_INSTALL; 11340 } 11341 } break; 11342 } 11343 11344 if (DEBUG_INSTALL) { 11345 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11346 } 11347 11348 if (grant != GRANT_DENIED) { 11349 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11350 // If this is an existing, non-system package, then 11351 // we can't add any new permissions to it. 11352 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11353 // Except... if this is a permission that was added 11354 // to the platform (note: need to only do this when 11355 // updating the platform). 11356 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11357 grant = GRANT_DENIED; 11358 } 11359 } 11360 } 11361 11362 switch (grant) { 11363 case GRANT_INSTALL: { 11364 // Revoke this as runtime permission to handle the case of 11365 // a runtime permission being downgraded to an install one. 11366 // Also in permission review mode we keep dangerous permissions 11367 // for legacy apps 11368 for (int userId : UserManagerService.getInstance().getUserIds()) { 11369 if (origPermissions.getRuntimePermissionState( 11370 bp.name, userId) != null) { 11371 // Revoke the runtime permission and clear the flags. 11372 origPermissions.revokeRuntimePermission(bp, userId); 11373 origPermissions.updatePermissionFlags(bp, userId, 11374 PackageManager.MASK_PERMISSION_FLAGS, 0); 11375 // If we revoked a permission permission, we have to write. 11376 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11377 changedRuntimePermissionUserIds, userId); 11378 } 11379 } 11380 // Grant an install permission. 11381 if (permissionsState.grantInstallPermission(bp) != 11382 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11383 changedInstallPermission = true; 11384 } 11385 } break; 11386 11387 case GRANT_RUNTIME: { 11388 // Grant previously granted runtime permissions. 11389 for (int userId : UserManagerService.getInstance().getUserIds()) { 11390 PermissionState permissionState = origPermissions 11391 .getRuntimePermissionState(bp.name, userId); 11392 int flags = permissionState != null 11393 ? permissionState.getFlags() : 0; 11394 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11395 // Don't propagate the permission in a permission review mode if 11396 // the former was revoked, i.e. marked to not propagate on upgrade. 11397 // Note that in a permission review mode install permissions are 11398 // represented as constantly granted runtime ones since we need to 11399 // keep a per user state associated with the permission. Also the 11400 // revoke on upgrade flag is no longer applicable and is reset. 11401 final boolean revokeOnUpgrade = (flags & PackageManager 11402 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11403 if (revokeOnUpgrade) { 11404 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11405 // Since we changed the flags, we have to write. 11406 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11407 changedRuntimePermissionUserIds, userId); 11408 } 11409 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11410 if (permissionsState.grantRuntimePermission(bp, userId) == 11411 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11412 // If we cannot put the permission as it was, 11413 // we have to write. 11414 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11415 changedRuntimePermissionUserIds, userId); 11416 } 11417 } 11418 11419 // If the app supports runtime permissions no need for a review. 11420 if (mPermissionReviewRequired 11421 && appSupportsRuntimePermissions 11422 && (flags & PackageManager 11423 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11424 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11425 // Since we changed the flags, we have to write. 11426 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11427 changedRuntimePermissionUserIds, userId); 11428 } 11429 } else if (mPermissionReviewRequired 11430 && !appSupportsRuntimePermissions) { 11431 // For legacy apps that need a permission review, every new 11432 // runtime permission is granted but it is pending a review. 11433 // We also need to review only platform defined runtime 11434 // permissions as these are the only ones the platform knows 11435 // how to disable the API to simulate revocation as legacy 11436 // apps don't expect to run with revoked permissions. 11437 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11438 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11439 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11440 // We changed the flags, hence have to write. 11441 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11442 changedRuntimePermissionUserIds, userId); 11443 } 11444 } 11445 if (permissionsState.grantRuntimePermission(bp, userId) 11446 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11447 // We changed the permission, hence have to write. 11448 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11449 changedRuntimePermissionUserIds, userId); 11450 } 11451 } 11452 // Propagate the permission flags. 11453 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11454 } 11455 } break; 11456 11457 case GRANT_UPGRADE: { 11458 // Grant runtime permissions for a previously held install permission. 11459 PermissionState permissionState = origPermissions 11460 .getInstallPermissionState(bp.name); 11461 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11462 11463 if (origPermissions.revokeInstallPermission(bp) 11464 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11465 // We will be transferring the permission flags, so clear them. 11466 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11467 PackageManager.MASK_PERMISSION_FLAGS, 0); 11468 changedInstallPermission = true; 11469 } 11470 11471 // If the permission is not to be promoted to runtime we ignore it and 11472 // also its other flags as they are not applicable to install permissions. 11473 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11474 for (int userId : currentUserIds) { 11475 if (permissionsState.grantRuntimePermission(bp, userId) != 11476 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11477 // Transfer the permission flags. 11478 permissionsState.updatePermissionFlags(bp, userId, 11479 flags, flags); 11480 // If we granted the permission, we have to write. 11481 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11482 changedRuntimePermissionUserIds, userId); 11483 } 11484 } 11485 } 11486 } break; 11487 11488 default: { 11489 if (packageOfInterest == null 11490 || packageOfInterest.equals(pkg.packageName)) { 11491 Slog.w(TAG, "Not granting permission " + perm 11492 + " to package " + pkg.packageName 11493 + " because it was previously installed without"); 11494 } 11495 } break; 11496 } 11497 } else { 11498 if (permissionsState.revokeInstallPermission(bp) != 11499 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11500 // Also drop the permission flags. 11501 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11502 PackageManager.MASK_PERMISSION_FLAGS, 0); 11503 changedInstallPermission = true; 11504 Slog.i(TAG, "Un-granting permission " + perm 11505 + " from package " + pkg.packageName 11506 + " (protectionLevel=" + bp.protectionLevel 11507 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11508 + ")"); 11509 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11510 // Don't print warning for app op permissions, since it is fine for them 11511 // not to be granted, there is a UI for the user to decide. 11512 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11513 Slog.w(TAG, "Not granting permission " + perm 11514 + " to package " + pkg.packageName 11515 + " (protectionLevel=" + bp.protectionLevel 11516 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11517 + ")"); 11518 } 11519 } 11520 } 11521 } 11522 11523 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11524 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11525 // This is the first that we have heard about this package, so the 11526 // permissions we have now selected are fixed until explicitly 11527 // changed. 11528 ps.installPermissionsFixed = true; 11529 } 11530 11531 // Persist the runtime permissions state for users with changes. If permissions 11532 // were revoked because no app in the shared user declares them we have to 11533 // write synchronously to avoid losing runtime permissions state. 11534 for (int userId : changedRuntimePermissionUserIds) { 11535 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11536 } 11537 } 11538 11539 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11540 boolean allowed = false; 11541 final int NP = PackageParser.NEW_PERMISSIONS.length; 11542 for (int ip=0; ip<NP; ip++) { 11543 final PackageParser.NewPermissionInfo npi 11544 = PackageParser.NEW_PERMISSIONS[ip]; 11545 if (npi.name.equals(perm) 11546 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11547 allowed = true; 11548 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11549 + pkg.packageName); 11550 break; 11551 } 11552 } 11553 return allowed; 11554 } 11555 11556 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11557 BasePermission bp, PermissionsState origPermissions) { 11558 boolean privilegedPermission = (bp.protectionLevel 11559 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11560 boolean privappPermissionsDisable = 11561 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11562 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11563 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11564 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11565 && !platformPackage && platformPermission) { 11566 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11567 .getPrivAppPermissions(pkg.packageName); 11568 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11569 if (!whitelisted) { 11570 Slog.w(TAG, "Privileged permission " + perm + " for package " 11571 + pkg.packageName + " - not in privapp-permissions whitelist"); 11572 // Only report violations for apps on system image 11573 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11574 if (mPrivappPermissionsViolations == null) { 11575 mPrivappPermissionsViolations = new ArraySet<>(); 11576 } 11577 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11578 } 11579 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11580 return false; 11581 } 11582 } 11583 } 11584 boolean allowed = (compareSignatures( 11585 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11586 == PackageManager.SIGNATURE_MATCH) 11587 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11588 == PackageManager.SIGNATURE_MATCH); 11589 if (!allowed && privilegedPermission) { 11590 if (isSystemApp(pkg)) { 11591 // For updated system applications, a system permission 11592 // is granted only if it had been defined by the original application. 11593 if (pkg.isUpdatedSystemApp()) { 11594 final PackageSetting sysPs = mSettings 11595 .getDisabledSystemPkgLPr(pkg.packageName); 11596 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11597 // If the original was granted this permission, we take 11598 // that grant decision as read and propagate it to the 11599 // update. 11600 if (sysPs.isPrivileged()) { 11601 allowed = true; 11602 } 11603 } else { 11604 // The system apk may have been updated with an older 11605 // version of the one on the data partition, but which 11606 // granted a new system permission that it didn't have 11607 // before. In this case we do want to allow the app to 11608 // now get the new permission if the ancestral apk is 11609 // privileged to get it. 11610 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11611 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11612 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11613 allowed = true; 11614 break; 11615 } 11616 } 11617 } 11618 // Also if a privileged parent package on the system image or any of 11619 // its children requested a privileged permission, the updated child 11620 // packages can also get the permission. 11621 if (pkg.parentPackage != null) { 11622 final PackageSetting disabledSysParentPs = mSettings 11623 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11624 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11625 && disabledSysParentPs.isPrivileged()) { 11626 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11627 allowed = true; 11628 } else if (disabledSysParentPs.pkg.childPackages != null) { 11629 final int count = disabledSysParentPs.pkg.childPackages.size(); 11630 for (int i = 0; i < count; i++) { 11631 PackageParser.Package disabledSysChildPkg = 11632 disabledSysParentPs.pkg.childPackages.get(i); 11633 if (isPackageRequestingPermission(disabledSysChildPkg, 11634 perm)) { 11635 allowed = true; 11636 break; 11637 } 11638 } 11639 } 11640 } 11641 } 11642 } 11643 } else { 11644 allowed = isPrivilegedApp(pkg); 11645 } 11646 } 11647 } 11648 if (!allowed) { 11649 if (!allowed && (bp.protectionLevel 11650 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11651 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11652 // If this was a previously normal/dangerous permission that got moved 11653 // to a system permission as part of the runtime permission redesign, then 11654 // we still want to blindly grant it to old apps. 11655 allowed = true; 11656 } 11657 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11658 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11659 // If this permission is to be granted to the system installer and 11660 // this app is an installer, then it gets the permission. 11661 allowed = true; 11662 } 11663 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11664 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11665 // If this permission is to be granted to the system verifier and 11666 // this app is a verifier, then it gets the permission. 11667 allowed = true; 11668 } 11669 if (!allowed && (bp.protectionLevel 11670 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11671 && isSystemApp(pkg)) { 11672 // Any pre-installed system app is allowed to get this permission. 11673 allowed = true; 11674 } 11675 if (!allowed && (bp.protectionLevel 11676 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11677 // For development permissions, a development permission 11678 // is granted only if it was already granted. 11679 allowed = origPermissions.hasInstallPermission(perm); 11680 } 11681 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11682 && pkg.packageName.equals(mSetupWizardPackage)) { 11683 // If this permission is to be granted to the system setup wizard and 11684 // this app is a setup wizard, then it gets the permission. 11685 allowed = true; 11686 } 11687 } 11688 return allowed; 11689 } 11690 11691 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11692 final int permCount = pkg.requestedPermissions.size(); 11693 for (int j = 0; j < permCount; j++) { 11694 String requestedPermission = pkg.requestedPermissions.get(j); 11695 if (permission.equals(requestedPermission)) { 11696 return true; 11697 } 11698 } 11699 return false; 11700 } 11701 11702 final class ActivityIntentResolver 11703 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11704 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11705 boolean defaultOnly, int userId) { 11706 if (!sUserManager.exists(userId)) return null; 11707 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11708 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11709 } 11710 11711 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11712 int userId) { 11713 if (!sUserManager.exists(userId)) return null; 11714 mFlags = flags; 11715 return super.queryIntent(intent, resolvedType, 11716 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11717 userId); 11718 } 11719 11720 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11721 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11722 if (!sUserManager.exists(userId)) return null; 11723 if (packageActivities == null) { 11724 return null; 11725 } 11726 mFlags = flags; 11727 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11728 final int N = packageActivities.size(); 11729 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11730 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11731 11732 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11733 for (int i = 0; i < N; ++i) { 11734 intentFilters = packageActivities.get(i).intents; 11735 if (intentFilters != null && intentFilters.size() > 0) { 11736 PackageParser.ActivityIntentInfo[] array = 11737 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11738 intentFilters.toArray(array); 11739 listCut.add(array); 11740 } 11741 } 11742 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11743 } 11744 11745 /** 11746 * Finds a privileged activity that matches the specified activity names. 11747 */ 11748 private PackageParser.Activity findMatchingActivity( 11749 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11750 for (PackageParser.Activity sysActivity : activityList) { 11751 if (sysActivity.info.name.equals(activityInfo.name)) { 11752 return sysActivity; 11753 } 11754 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11755 return sysActivity; 11756 } 11757 if (sysActivity.info.targetActivity != null) { 11758 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11759 return sysActivity; 11760 } 11761 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11762 return sysActivity; 11763 } 11764 } 11765 } 11766 return null; 11767 } 11768 11769 public class IterGenerator<E> { 11770 public Iterator<E> generate(ActivityIntentInfo info) { 11771 return null; 11772 } 11773 } 11774 11775 public class ActionIterGenerator extends IterGenerator<String> { 11776 @Override 11777 public Iterator<String> generate(ActivityIntentInfo info) { 11778 return info.actionsIterator(); 11779 } 11780 } 11781 11782 public class CategoriesIterGenerator extends IterGenerator<String> { 11783 @Override 11784 public Iterator<String> generate(ActivityIntentInfo info) { 11785 return info.categoriesIterator(); 11786 } 11787 } 11788 11789 public class SchemesIterGenerator extends IterGenerator<String> { 11790 @Override 11791 public Iterator<String> generate(ActivityIntentInfo info) { 11792 return info.schemesIterator(); 11793 } 11794 } 11795 11796 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11797 @Override 11798 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11799 return info.authoritiesIterator(); 11800 } 11801 } 11802 11803 /** 11804 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11805 * MODIFIED. Do not pass in a list that should not be changed. 11806 */ 11807 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11808 IterGenerator<T> generator, Iterator<T> searchIterator) { 11809 // loop through the set of actions; every one must be found in the intent filter 11810 while (searchIterator.hasNext()) { 11811 // we must have at least one filter in the list to consider a match 11812 if (intentList.size() == 0) { 11813 break; 11814 } 11815 11816 final T searchAction = searchIterator.next(); 11817 11818 // loop through the set of intent filters 11819 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11820 while (intentIter.hasNext()) { 11821 final ActivityIntentInfo intentInfo = intentIter.next(); 11822 boolean selectionFound = false; 11823 11824 // loop through the intent filter's selection criteria; at least one 11825 // of them must match the searched criteria 11826 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11827 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11828 final T intentSelection = intentSelectionIter.next(); 11829 if (intentSelection != null && intentSelection.equals(searchAction)) { 11830 selectionFound = true; 11831 break; 11832 } 11833 } 11834 11835 // the selection criteria wasn't found in this filter's set; this filter 11836 // is not a potential match 11837 if (!selectionFound) { 11838 intentIter.remove(); 11839 } 11840 } 11841 } 11842 } 11843 11844 private boolean isProtectedAction(ActivityIntentInfo filter) { 11845 final Iterator<String> actionsIter = filter.actionsIterator(); 11846 while (actionsIter != null && actionsIter.hasNext()) { 11847 final String filterAction = actionsIter.next(); 11848 if (PROTECTED_ACTIONS.contains(filterAction)) { 11849 return true; 11850 } 11851 } 11852 return false; 11853 } 11854 11855 /** 11856 * Adjusts the priority of the given intent filter according to policy. 11857 * <p> 11858 * <ul> 11859 * <li>The priority for non privileged applications is capped to '0'</li> 11860 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11861 * <li>The priority for unbundled updates to privileged applications is capped to the 11862 * priority defined on the system partition</li> 11863 * </ul> 11864 * <p> 11865 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11866 * allowed to obtain any priority on any action. 11867 */ 11868 private void adjustPriority( 11869 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11870 // nothing to do; priority is fine as-is 11871 if (intent.getPriority() <= 0) { 11872 return; 11873 } 11874 11875 final ActivityInfo activityInfo = intent.activity.info; 11876 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11877 11878 final boolean privilegedApp = 11879 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11880 if (!privilegedApp) { 11881 // non-privileged applications can never define a priority >0 11882 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11883 + " package: " + applicationInfo.packageName 11884 + " activity: " + intent.activity.className 11885 + " origPrio: " + intent.getPriority()); 11886 intent.setPriority(0); 11887 return; 11888 } 11889 11890 if (systemActivities == null) { 11891 // the system package is not disabled; we're parsing the system partition 11892 if (isProtectedAction(intent)) { 11893 if (mDeferProtectedFilters) { 11894 // We can't deal with these just yet. No component should ever obtain a 11895 // >0 priority for a protected actions, with ONE exception -- the setup 11896 // wizard. The setup wizard, however, cannot be known until we're able to 11897 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11898 // until all intent filters have been processed. Chicken, meet egg. 11899 // Let the filter temporarily have a high priority and rectify the 11900 // priorities after all system packages have been scanned. 11901 mProtectedFilters.add(intent); 11902 if (DEBUG_FILTERS) { 11903 Slog.i(TAG, "Protected action; save for later;" 11904 + " package: " + applicationInfo.packageName 11905 + " activity: " + intent.activity.className 11906 + " origPrio: " + intent.getPriority()); 11907 } 11908 return; 11909 } else { 11910 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11911 Slog.i(TAG, "No setup wizard;" 11912 + " All protected intents capped to priority 0"); 11913 } 11914 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11915 if (DEBUG_FILTERS) { 11916 Slog.i(TAG, "Found setup wizard;" 11917 + " allow priority " + intent.getPriority() + ";" 11918 + " package: " + intent.activity.info.packageName 11919 + " activity: " + intent.activity.className 11920 + " priority: " + intent.getPriority()); 11921 } 11922 // setup wizard gets whatever it wants 11923 return; 11924 } 11925 Slog.w(TAG, "Protected action; cap priority to 0;" 11926 + " package: " + intent.activity.info.packageName 11927 + " activity: " + intent.activity.className 11928 + " origPrio: " + intent.getPriority()); 11929 intent.setPriority(0); 11930 return; 11931 } 11932 } 11933 // privileged apps on the system image get whatever priority they request 11934 return; 11935 } 11936 11937 // privileged app unbundled update ... try to find the same activity 11938 final PackageParser.Activity foundActivity = 11939 findMatchingActivity(systemActivities, activityInfo); 11940 if (foundActivity == null) { 11941 // this is a new activity; it cannot obtain >0 priority 11942 if (DEBUG_FILTERS) { 11943 Slog.i(TAG, "New activity; cap priority to 0;" 11944 + " package: " + applicationInfo.packageName 11945 + " activity: " + intent.activity.className 11946 + " origPrio: " + intent.getPriority()); 11947 } 11948 intent.setPriority(0); 11949 return; 11950 } 11951 11952 // found activity, now check for filter equivalence 11953 11954 // a shallow copy is enough; we modify the list, not its contents 11955 final List<ActivityIntentInfo> intentListCopy = 11956 new ArrayList<>(foundActivity.intents); 11957 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11958 11959 // find matching action subsets 11960 final Iterator<String> actionsIterator = intent.actionsIterator(); 11961 if (actionsIterator != null) { 11962 getIntentListSubset( 11963 intentListCopy, new ActionIterGenerator(), actionsIterator); 11964 if (intentListCopy.size() == 0) { 11965 // no more intents to match; we're not equivalent 11966 if (DEBUG_FILTERS) { 11967 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11968 + " package: " + applicationInfo.packageName 11969 + " activity: " + intent.activity.className 11970 + " origPrio: " + intent.getPriority()); 11971 } 11972 intent.setPriority(0); 11973 return; 11974 } 11975 } 11976 11977 // find matching category subsets 11978 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11979 if (categoriesIterator != null) { 11980 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11981 categoriesIterator); 11982 if (intentListCopy.size() == 0) { 11983 // no more intents to match; we're not equivalent 11984 if (DEBUG_FILTERS) { 11985 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11986 + " package: " + applicationInfo.packageName 11987 + " activity: " + intent.activity.className 11988 + " origPrio: " + intent.getPriority()); 11989 } 11990 intent.setPriority(0); 11991 return; 11992 } 11993 } 11994 11995 // find matching schemes subsets 11996 final Iterator<String> schemesIterator = intent.schemesIterator(); 11997 if (schemesIterator != null) { 11998 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11999 schemesIterator); 12000 if (intentListCopy.size() == 0) { 12001 // no more intents to match; we're not equivalent 12002 if (DEBUG_FILTERS) { 12003 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12004 + " package: " + applicationInfo.packageName 12005 + " activity: " + intent.activity.className 12006 + " origPrio: " + intent.getPriority()); 12007 } 12008 intent.setPriority(0); 12009 return; 12010 } 12011 } 12012 12013 // find matching authorities subsets 12014 final Iterator<IntentFilter.AuthorityEntry> 12015 authoritiesIterator = intent.authoritiesIterator(); 12016 if (authoritiesIterator != null) { 12017 getIntentListSubset(intentListCopy, 12018 new AuthoritiesIterGenerator(), 12019 authoritiesIterator); 12020 if (intentListCopy.size() == 0) { 12021 // no more intents to match; we're not equivalent 12022 if (DEBUG_FILTERS) { 12023 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12024 + " package: " + applicationInfo.packageName 12025 + " activity: " + intent.activity.className 12026 + " origPrio: " + intent.getPriority()); 12027 } 12028 intent.setPriority(0); 12029 return; 12030 } 12031 } 12032 12033 // we found matching filter(s); app gets the max priority of all intents 12034 int cappedPriority = 0; 12035 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12036 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12037 } 12038 if (intent.getPriority() > cappedPriority) { 12039 if (DEBUG_FILTERS) { 12040 Slog.i(TAG, "Found matching filter(s);" 12041 + " cap priority to " + cappedPriority + ";" 12042 + " package: " + applicationInfo.packageName 12043 + " activity: " + intent.activity.className 12044 + " origPrio: " + intent.getPriority()); 12045 } 12046 intent.setPriority(cappedPriority); 12047 return; 12048 } 12049 // all this for nothing; the requested priority was <= what was on the system 12050 } 12051 12052 public final void addActivity(PackageParser.Activity a, String type) { 12053 mActivities.put(a.getComponentName(), a); 12054 if (DEBUG_SHOW_INFO) 12055 Log.v( 12056 TAG, " " + type + " " + 12057 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12058 if (DEBUG_SHOW_INFO) 12059 Log.v(TAG, " Class=" + a.info.name); 12060 final int NI = a.intents.size(); 12061 for (int j=0; j<NI; j++) { 12062 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12063 if ("activity".equals(type)) { 12064 final PackageSetting ps = 12065 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12066 final List<PackageParser.Activity> systemActivities = 12067 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12068 adjustPriority(systemActivities, intent); 12069 } 12070 if (DEBUG_SHOW_INFO) { 12071 Log.v(TAG, " IntentFilter:"); 12072 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12073 } 12074 if (!intent.debugCheck()) { 12075 Log.w(TAG, "==> For Activity " + a.info.name); 12076 } 12077 addFilter(intent); 12078 } 12079 } 12080 12081 public final void removeActivity(PackageParser.Activity a, String type) { 12082 mActivities.remove(a.getComponentName()); 12083 if (DEBUG_SHOW_INFO) { 12084 Log.v(TAG, " " + type + " " 12085 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12086 : a.info.name) + ":"); 12087 Log.v(TAG, " Class=" + a.info.name); 12088 } 12089 final int NI = a.intents.size(); 12090 for (int j=0; j<NI; j++) { 12091 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12092 if (DEBUG_SHOW_INFO) { 12093 Log.v(TAG, " IntentFilter:"); 12094 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12095 } 12096 removeFilter(intent); 12097 } 12098 } 12099 12100 @Override 12101 protected boolean allowFilterResult( 12102 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12103 ActivityInfo filterAi = filter.activity.info; 12104 for (int i=dest.size()-1; i>=0; i--) { 12105 ActivityInfo destAi = dest.get(i).activityInfo; 12106 if (destAi.name == filterAi.name 12107 && destAi.packageName == filterAi.packageName) { 12108 return false; 12109 } 12110 } 12111 return true; 12112 } 12113 12114 @Override 12115 protected ActivityIntentInfo[] newArray(int size) { 12116 return new ActivityIntentInfo[size]; 12117 } 12118 12119 @Override 12120 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12121 if (!sUserManager.exists(userId)) return true; 12122 PackageParser.Package p = filter.activity.owner; 12123 if (p != null) { 12124 PackageSetting ps = (PackageSetting)p.mExtras; 12125 if (ps != null) { 12126 // System apps are never considered stopped for purposes of 12127 // filtering, because there may be no way for the user to 12128 // actually re-launch them. 12129 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12130 && ps.getStopped(userId); 12131 } 12132 } 12133 return false; 12134 } 12135 12136 @Override 12137 protected boolean isPackageForFilter(String packageName, 12138 PackageParser.ActivityIntentInfo info) { 12139 return packageName.equals(info.activity.owner.packageName); 12140 } 12141 12142 @Override 12143 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12144 int match, int userId) { 12145 if (!sUserManager.exists(userId)) return null; 12146 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12147 return null; 12148 } 12149 final PackageParser.Activity activity = info.activity; 12150 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12151 if (ps == null) { 12152 return null; 12153 } 12154 final PackageUserState userState = ps.readUserState(userId); 12155 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12156 userState, userId); 12157 if (ai == null) { 12158 return null; 12159 } 12160 final boolean matchVisibleToInstantApp = 12161 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12162 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12163 // throw out filters that aren't visible to ephemeral apps 12164 if (matchVisibleToInstantApp 12165 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12166 return null; 12167 } 12168 // throw out ephemeral filters if we're not explicitly requesting them 12169 if (!isInstantApp && userState.instantApp) { 12170 return null; 12171 } 12172 // throw out instant app filters if updates are available; will trigger 12173 // instant app resolution 12174 if (userState.instantApp && ps.isUpdateAvailable()) { 12175 return null; 12176 } 12177 final ResolveInfo res = new ResolveInfo(); 12178 res.activityInfo = ai; 12179 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12180 res.filter = info; 12181 } 12182 if (info != null) { 12183 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12184 } 12185 res.priority = info.getPriority(); 12186 res.preferredOrder = activity.owner.mPreferredOrder; 12187 //System.out.println("Result: " + res.activityInfo.className + 12188 // " = " + res.priority); 12189 res.match = match; 12190 res.isDefault = info.hasDefault; 12191 res.labelRes = info.labelRes; 12192 res.nonLocalizedLabel = info.nonLocalizedLabel; 12193 if (userNeedsBadging(userId)) { 12194 res.noResourceId = true; 12195 } else { 12196 res.icon = info.icon; 12197 } 12198 res.iconResourceId = info.icon; 12199 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12200 res.instantAppAvailable = userState.instantApp; 12201 return res; 12202 } 12203 12204 @Override 12205 protected void sortResults(List<ResolveInfo> results) { 12206 Collections.sort(results, mResolvePrioritySorter); 12207 } 12208 12209 @Override 12210 protected void dumpFilter(PrintWriter out, String prefix, 12211 PackageParser.ActivityIntentInfo filter) { 12212 out.print(prefix); out.print( 12213 Integer.toHexString(System.identityHashCode(filter.activity))); 12214 out.print(' '); 12215 filter.activity.printComponentShortName(out); 12216 out.print(" filter "); 12217 out.println(Integer.toHexString(System.identityHashCode(filter))); 12218 } 12219 12220 @Override 12221 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12222 return filter.activity; 12223 } 12224 12225 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12226 PackageParser.Activity activity = (PackageParser.Activity)label; 12227 out.print(prefix); out.print( 12228 Integer.toHexString(System.identityHashCode(activity))); 12229 out.print(' '); 12230 activity.printComponentShortName(out); 12231 if (count > 1) { 12232 out.print(" ("); out.print(count); out.print(" filters)"); 12233 } 12234 out.println(); 12235 } 12236 12237 // Keys are String (activity class name), values are Activity. 12238 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12239 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12240 private int mFlags; 12241 } 12242 12243 private final class ServiceIntentResolver 12244 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12245 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12246 boolean defaultOnly, int userId) { 12247 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12248 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12249 } 12250 12251 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12252 int userId) { 12253 if (!sUserManager.exists(userId)) return null; 12254 mFlags = flags; 12255 return super.queryIntent(intent, resolvedType, 12256 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12257 userId); 12258 } 12259 12260 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12261 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12262 if (!sUserManager.exists(userId)) return null; 12263 if (packageServices == null) { 12264 return null; 12265 } 12266 mFlags = flags; 12267 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12268 final int N = packageServices.size(); 12269 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12270 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12271 12272 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12273 for (int i = 0; i < N; ++i) { 12274 intentFilters = packageServices.get(i).intents; 12275 if (intentFilters != null && intentFilters.size() > 0) { 12276 PackageParser.ServiceIntentInfo[] array = 12277 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12278 intentFilters.toArray(array); 12279 listCut.add(array); 12280 } 12281 } 12282 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12283 } 12284 12285 public final void addService(PackageParser.Service s) { 12286 mServices.put(s.getComponentName(), s); 12287 if (DEBUG_SHOW_INFO) { 12288 Log.v(TAG, " " 12289 + (s.info.nonLocalizedLabel != null 12290 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12291 Log.v(TAG, " Class=" + s.info.name); 12292 } 12293 final int NI = s.intents.size(); 12294 int j; 12295 for (j=0; j<NI; j++) { 12296 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12297 if (DEBUG_SHOW_INFO) { 12298 Log.v(TAG, " IntentFilter:"); 12299 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12300 } 12301 if (!intent.debugCheck()) { 12302 Log.w(TAG, "==> For Service " + s.info.name); 12303 } 12304 addFilter(intent); 12305 } 12306 } 12307 12308 public final void removeService(PackageParser.Service s) { 12309 mServices.remove(s.getComponentName()); 12310 if (DEBUG_SHOW_INFO) { 12311 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12312 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12313 Log.v(TAG, " Class=" + s.info.name); 12314 } 12315 final int NI = s.intents.size(); 12316 int j; 12317 for (j=0; j<NI; j++) { 12318 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12319 if (DEBUG_SHOW_INFO) { 12320 Log.v(TAG, " IntentFilter:"); 12321 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12322 } 12323 removeFilter(intent); 12324 } 12325 } 12326 12327 @Override 12328 protected boolean allowFilterResult( 12329 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12330 ServiceInfo filterSi = filter.service.info; 12331 for (int i=dest.size()-1; i>=0; i--) { 12332 ServiceInfo destAi = dest.get(i).serviceInfo; 12333 if (destAi.name == filterSi.name 12334 && destAi.packageName == filterSi.packageName) { 12335 return false; 12336 } 12337 } 12338 return true; 12339 } 12340 12341 @Override 12342 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12343 return new PackageParser.ServiceIntentInfo[size]; 12344 } 12345 12346 @Override 12347 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12348 if (!sUserManager.exists(userId)) return true; 12349 PackageParser.Package p = filter.service.owner; 12350 if (p != null) { 12351 PackageSetting ps = (PackageSetting)p.mExtras; 12352 if (ps != null) { 12353 // System apps are never considered stopped for purposes of 12354 // filtering, because there may be no way for the user to 12355 // actually re-launch them. 12356 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12357 && ps.getStopped(userId); 12358 } 12359 } 12360 return false; 12361 } 12362 12363 @Override 12364 protected boolean isPackageForFilter(String packageName, 12365 PackageParser.ServiceIntentInfo info) { 12366 return packageName.equals(info.service.owner.packageName); 12367 } 12368 12369 @Override 12370 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12371 int match, int userId) { 12372 if (!sUserManager.exists(userId)) return null; 12373 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12374 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12375 return null; 12376 } 12377 final PackageParser.Service service = info.service; 12378 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12379 if (ps == null) { 12380 return null; 12381 } 12382 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12383 ps.readUserState(userId), userId); 12384 if (si == null) { 12385 return null; 12386 } 12387 final ResolveInfo res = new ResolveInfo(); 12388 res.serviceInfo = si; 12389 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12390 res.filter = filter; 12391 } 12392 res.priority = info.getPriority(); 12393 res.preferredOrder = service.owner.mPreferredOrder; 12394 res.match = match; 12395 res.isDefault = info.hasDefault; 12396 res.labelRes = info.labelRes; 12397 res.nonLocalizedLabel = info.nonLocalizedLabel; 12398 res.icon = info.icon; 12399 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12400 return res; 12401 } 12402 12403 @Override 12404 protected void sortResults(List<ResolveInfo> results) { 12405 Collections.sort(results, mResolvePrioritySorter); 12406 } 12407 12408 @Override 12409 protected void dumpFilter(PrintWriter out, String prefix, 12410 PackageParser.ServiceIntentInfo filter) { 12411 out.print(prefix); out.print( 12412 Integer.toHexString(System.identityHashCode(filter.service))); 12413 out.print(' '); 12414 filter.service.printComponentShortName(out); 12415 out.print(" filter "); 12416 out.println(Integer.toHexString(System.identityHashCode(filter))); 12417 } 12418 12419 @Override 12420 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12421 return filter.service; 12422 } 12423 12424 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12425 PackageParser.Service service = (PackageParser.Service)label; 12426 out.print(prefix); out.print( 12427 Integer.toHexString(System.identityHashCode(service))); 12428 out.print(' '); 12429 service.printComponentShortName(out); 12430 if (count > 1) { 12431 out.print(" ("); out.print(count); out.print(" filters)"); 12432 } 12433 out.println(); 12434 } 12435 12436// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12437// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12438// final List<ResolveInfo> retList = Lists.newArrayList(); 12439// while (i.hasNext()) { 12440// final ResolveInfo resolveInfo = (ResolveInfo) i; 12441// if (isEnabledLP(resolveInfo.serviceInfo)) { 12442// retList.add(resolveInfo); 12443// } 12444// } 12445// return retList; 12446// } 12447 12448 // Keys are String (activity class name), values are Activity. 12449 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12450 = new ArrayMap<ComponentName, PackageParser.Service>(); 12451 private int mFlags; 12452 } 12453 12454 private final class ProviderIntentResolver 12455 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12456 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12457 boolean defaultOnly, int userId) { 12458 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12459 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12460 } 12461 12462 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12463 int userId) { 12464 if (!sUserManager.exists(userId)) 12465 return null; 12466 mFlags = flags; 12467 return super.queryIntent(intent, resolvedType, 12468 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12469 userId); 12470 } 12471 12472 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12473 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12474 if (!sUserManager.exists(userId)) 12475 return null; 12476 if (packageProviders == null) { 12477 return null; 12478 } 12479 mFlags = flags; 12480 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12481 final int N = packageProviders.size(); 12482 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12483 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12484 12485 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12486 for (int i = 0; i < N; ++i) { 12487 intentFilters = packageProviders.get(i).intents; 12488 if (intentFilters != null && intentFilters.size() > 0) { 12489 PackageParser.ProviderIntentInfo[] array = 12490 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12491 intentFilters.toArray(array); 12492 listCut.add(array); 12493 } 12494 } 12495 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12496 } 12497 12498 public final void addProvider(PackageParser.Provider p) { 12499 if (mProviders.containsKey(p.getComponentName())) { 12500 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12501 return; 12502 } 12503 12504 mProviders.put(p.getComponentName(), p); 12505 if (DEBUG_SHOW_INFO) { 12506 Log.v(TAG, " " 12507 + (p.info.nonLocalizedLabel != null 12508 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12509 Log.v(TAG, " Class=" + p.info.name); 12510 } 12511 final int NI = p.intents.size(); 12512 int j; 12513 for (j = 0; j < NI; j++) { 12514 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12515 if (DEBUG_SHOW_INFO) { 12516 Log.v(TAG, " IntentFilter:"); 12517 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12518 } 12519 if (!intent.debugCheck()) { 12520 Log.w(TAG, "==> For Provider " + p.info.name); 12521 } 12522 addFilter(intent); 12523 } 12524 } 12525 12526 public final void removeProvider(PackageParser.Provider p) { 12527 mProviders.remove(p.getComponentName()); 12528 if (DEBUG_SHOW_INFO) { 12529 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12530 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12531 Log.v(TAG, " Class=" + p.info.name); 12532 } 12533 final int NI = p.intents.size(); 12534 int j; 12535 for (j = 0; j < NI; j++) { 12536 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12537 if (DEBUG_SHOW_INFO) { 12538 Log.v(TAG, " IntentFilter:"); 12539 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12540 } 12541 removeFilter(intent); 12542 } 12543 } 12544 12545 @Override 12546 protected boolean allowFilterResult( 12547 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12548 ProviderInfo filterPi = filter.provider.info; 12549 for (int i = dest.size() - 1; i >= 0; i--) { 12550 ProviderInfo destPi = dest.get(i).providerInfo; 12551 if (destPi.name == filterPi.name 12552 && destPi.packageName == filterPi.packageName) { 12553 return false; 12554 } 12555 } 12556 return true; 12557 } 12558 12559 @Override 12560 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12561 return new PackageParser.ProviderIntentInfo[size]; 12562 } 12563 12564 @Override 12565 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12566 if (!sUserManager.exists(userId)) 12567 return true; 12568 PackageParser.Package p = filter.provider.owner; 12569 if (p != null) { 12570 PackageSetting ps = (PackageSetting) p.mExtras; 12571 if (ps != null) { 12572 // System apps are never considered stopped for purposes of 12573 // filtering, because there may be no way for the user to 12574 // actually re-launch them. 12575 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12576 && ps.getStopped(userId); 12577 } 12578 } 12579 return false; 12580 } 12581 12582 @Override 12583 protected boolean isPackageForFilter(String packageName, 12584 PackageParser.ProviderIntentInfo info) { 12585 return packageName.equals(info.provider.owner.packageName); 12586 } 12587 12588 @Override 12589 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12590 int match, int userId) { 12591 if (!sUserManager.exists(userId)) 12592 return null; 12593 final PackageParser.ProviderIntentInfo info = filter; 12594 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12595 return null; 12596 } 12597 final PackageParser.Provider provider = info.provider; 12598 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12599 if (ps == null) { 12600 return null; 12601 } 12602 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12603 ps.readUserState(userId), userId); 12604 if (pi == null) { 12605 return null; 12606 } 12607 final ResolveInfo res = new ResolveInfo(); 12608 res.providerInfo = pi; 12609 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12610 res.filter = filter; 12611 } 12612 res.priority = info.getPriority(); 12613 res.preferredOrder = provider.owner.mPreferredOrder; 12614 res.match = match; 12615 res.isDefault = info.hasDefault; 12616 res.labelRes = info.labelRes; 12617 res.nonLocalizedLabel = info.nonLocalizedLabel; 12618 res.icon = info.icon; 12619 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12620 return res; 12621 } 12622 12623 @Override 12624 protected void sortResults(List<ResolveInfo> results) { 12625 Collections.sort(results, mResolvePrioritySorter); 12626 } 12627 12628 @Override 12629 protected void dumpFilter(PrintWriter out, String prefix, 12630 PackageParser.ProviderIntentInfo filter) { 12631 out.print(prefix); 12632 out.print( 12633 Integer.toHexString(System.identityHashCode(filter.provider))); 12634 out.print(' '); 12635 filter.provider.printComponentShortName(out); 12636 out.print(" filter "); 12637 out.println(Integer.toHexString(System.identityHashCode(filter))); 12638 } 12639 12640 @Override 12641 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12642 return filter.provider; 12643 } 12644 12645 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12646 PackageParser.Provider provider = (PackageParser.Provider)label; 12647 out.print(prefix); out.print( 12648 Integer.toHexString(System.identityHashCode(provider))); 12649 out.print(' '); 12650 provider.printComponentShortName(out); 12651 if (count > 1) { 12652 out.print(" ("); out.print(count); out.print(" filters)"); 12653 } 12654 out.println(); 12655 } 12656 12657 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12658 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12659 private int mFlags; 12660 } 12661 12662 static final class EphemeralIntentResolver 12663 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12664 /** 12665 * The result that has the highest defined order. Ordering applies on a 12666 * per-package basis. Mapping is from package name to Pair of order and 12667 * EphemeralResolveInfo. 12668 * <p> 12669 * NOTE: This is implemented as a field variable for convenience and efficiency. 12670 * By having a field variable, we're able to track filter ordering as soon as 12671 * a non-zero order is defined. Otherwise, multiple loops across the result set 12672 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12673 * this needs to be contained entirely within {@link #filterResults}. 12674 */ 12675 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12676 12677 @Override 12678 protected AuxiliaryResolveInfo[] newArray(int size) { 12679 return new AuxiliaryResolveInfo[size]; 12680 } 12681 12682 @Override 12683 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12684 return true; 12685 } 12686 12687 @Override 12688 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12689 int userId) { 12690 if (!sUserManager.exists(userId)) { 12691 return null; 12692 } 12693 final String packageName = responseObj.resolveInfo.getPackageName(); 12694 final Integer order = responseObj.getOrder(); 12695 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12696 mOrderResult.get(packageName); 12697 // ordering is enabled and this item's order isn't high enough 12698 if (lastOrderResult != null && lastOrderResult.first >= order) { 12699 return null; 12700 } 12701 final InstantAppResolveInfo res = responseObj.resolveInfo; 12702 if (order > 0) { 12703 // non-zero order, enable ordering 12704 mOrderResult.put(packageName, new Pair<>(order, res)); 12705 } 12706 return responseObj; 12707 } 12708 12709 @Override 12710 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12711 // only do work if ordering is enabled [most of the time it won't be] 12712 if (mOrderResult.size() == 0) { 12713 return; 12714 } 12715 int resultSize = results.size(); 12716 for (int i = 0; i < resultSize; i++) { 12717 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12718 final String packageName = info.getPackageName(); 12719 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12720 if (savedInfo == null) { 12721 // package doesn't having ordering 12722 continue; 12723 } 12724 if (savedInfo.second == info) { 12725 // circled back to the highest ordered item; remove from order list 12726 mOrderResult.remove(savedInfo); 12727 if (mOrderResult.size() == 0) { 12728 // no more ordered items 12729 break; 12730 } 12731 continue; 12732 } 12733 // item has a worse order, remove it from the result list 12734 results.remove(i); 12735 resultSize--; 12736 i--; 12737 } 12738 } 12739 } 12740 12741 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12742 new Comparator<ResolveInfo>() { 12743 public int compare(ResolveInfo r1, ResolveInfo r2) { 12744 int v1 = r1.priority; 12745 int v2 = r2.priority; 12746 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12747 if (v1 != v2) { 12748 return (v1 > v2) ? -1 : 1; 12749 } 12750 v1 = r1.preferredOrder; 12751 v2 = r2.preferredOrder; 12752 if (v1 != v2) { 12753 return (v1 > v2) ? -1 : 1; 12754 } 12755 if (r1.isDefault != r2.isDefault) { 12756 return r1.isDefault ? -1 : 1; 12757 } 12758 v1 = r1.match; 12759 v2 = r2.match; 12760 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12761 if (v1 != v2) { 12762 return (v1 > v2) ? -1 : 1; 12763 } 12764 if (r1.system != r2.system) { 12765 return r1.system ? -1 : 1; 12766 } 12767 if (r1.activityInfo != null) { 12768 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12769 } 12770 if (r1.serviceInfo != null) { 12771 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12772 } 12773 if (r1.providerInfo != null) { 12774 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12775 } 12776 return 0; 12777 } 12778 }; 12779 12780 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12781 new Comparator<ProviderInfo>() { 12782 public int compare(ProviderInfo p1, ProviderInfo p2) { 12783 final int v1 = p1.initOrder; 12784 final int v2 = p2.initOrder; 12785 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12786 } 12787 }; 12788 12789 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12790 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12791 final int[] userIds) { 12792 mHandler.post(new Runnable() { 12793 @Override 12794 public void run() { 12795 try { 12796 final IActivityManager am = ActivityManager.getService(); 12797 if (am == null) return; 12798 final int[] resolvedUserIds; 12799 if (userIds == null) { 12800 resolvedUserIds = am.getRunningUserIds(); 12801 } else { 12802 resolvedUserIds = userIds; 12803 } 12804 for (int id : resolvedUserIds) { 12805 final Intent intent = new Intent(action, 12806 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12807 if (extras != null) { 12808 intent.putExtras(extras); 12809 } 12810 if (targetPkg != null) { 12811 intent.setPackage(targetPkg); 12812 } 12813 // Modify the UID when posting to other users 12814 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12815 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12816 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12817 intent.putExtra(Intent.EXTRA_UID, uid); 12818 } 12819 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12820 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12821 if (DEBUG_BROADCASTS) { 12822 RuntimeException here = new RuntimeException("here"); 12823 here.fillInStackTrace(); 12824 Slog.d(TAG, "Sending to user " + id + ": " 12825 + intent.toShortString(false, true, false, false) 12826 + " " + intent.getExtras(), here); 12827 } 12828 am.broadcastIntent(null, intent, null, finishedReceiver, 12829 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12830 null, finishedReceiver != null, false, id); 12831 } 12832 } catch (RemoteException ex) { 12833 } 12834 } 12835 }); 12836 } 12837 12838 /** 12839 * Check if the external storage media is available. This is true if there 12840 * is a mounted external storage medium or if the external storage is 12841 * emulated. 12842 */ 12843 private boolean isExternalMediaAvailable() { 12844 return mMediaMounted || Environment.isExternalStorageEmulated(); 12845 } 12846 12847 @Override 12848 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12849 // writer 12850 synchronized (mPackages) { 12851 if (!isExternalMediaAvailable()) { 12852 // If the external storage is no longer mounted at this point, 12853 // the caller may not have been able to delete all of this 12854 // packages files and can not delete any more. Bail. 12855 return null; 12856 } 12857 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12858 if (lastPackage != null) { 12859 pkgs.remove(lastPackage); 12860 } 12861 if (pkgs.size() > 0) { 12862 return pkgs.get(0); 12863 } 12864 } 12865 return null; 12866 } 12867 12868 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12869 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12870 userId, andCode ? 1 : 0, packageName); 12871 if (mSystemReady) { 12872 msg.sendToTarget(); 12873 } else { 12874 if (mPostSystemReadyMessages == null) { 12875 mPostSystemReadyMessages = new ArrayList<>(); 12876 } 12877 mPostSystemReadyMessages.add(msg); 12878 } 12879 } 12880 12881 void startCleaningPackages() { 12882 // reader 12883 if (!isExternalMediaAvailable()) { 12884 return; 12885 } 12886 synchronized (mPackages) { 12887 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12888 return; 12889 } 12890 } 12891 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12892 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12893 IActivityManager am = ActivityManager.getService(); 12894 if (am != null) { 12895 try { 12896 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12897 UserHandle.USER_SYSTEM); 12898 } catch (RemoteException e) { 12899 } 12900 } 12901 } 12902 12903 @Override 12904 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12905 int installFlags, String installerPackageName, int userId) { 12906 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12907 12908 final int callingUid = Binder.getCallingUid(); 12909 enforceCrossUserPermission(callingUid, userId, 12910 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12911 12912 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12913 try { 12914 if (observer != null) { 12915 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12916 } 12917 } catch (RemoteException re) { 12918 } 12919 return; 12920 } 12921 12922 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12923 installFlags |= PackageManager.INSTALL_FROM_ADB; 12924 12925 } else { 12926 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12927 // about installerPackageName. 12928 12929 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12930 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12931 } 12932 12933 UserHandle user; 12934 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12935 user = UserHandle.ALL; 12936 } else { 12937 user = new UserHandle(userId); 12938 } 12939 12940 // Only system components can circumvent runtime permissions when installing. 12941 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12942 && mContext.checkCallingOrSelfPermission(Manifest.permission 12943 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12944 throw new SecurityException("You need the " 12945 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12946 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12947 } 12948 12949 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 12950 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12951 throw new IllegalArgumentException( 12952 "New installs into ASEC containers no longer supported"); 12953 } 12954 12955 final File originFile = new File(originPath); 12956 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12957 12958 final Message msg = mHandler.obtainMessage(INIT_COPY); 12959 final VerificationInfo verificationInfo = new VerificationInfo( 12960 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12961 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12962 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12963 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12964 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12965 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12966 msg.obj = params; 12967 12968 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12969 System.identityHashCode(msg.obj)); 12970 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12971 System.identityHashCode(msg.obj)); 12972 12973 mHandler.sendMessage(msg); 12974 } 12975 12976 12977 /** 12978 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12979 * it is acting on behalf on an enterprise or the user). 12980 * 12981 * Note that the ordering of the conditionals in this method is important. The checks we perform 12982 * are as follows, in this order: 12983 * 12984 * 1) If the install is being performed by a system app, we can trust the app to have set the 12985 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12986 * what it is. 12987 * 2) If the install is being performed by a device or profile owner app, the install reason 12988 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12989 * set the install reason correctly. If the app targets an older SDK version where install 12990 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12991 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12992 * 3) In all other cases, the install is being performed by a regular app that is neither part 12993 * of the system nor a device or profile owner. We have no reason to believe that this app is 12994 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12995 * set to enterprise policy and if so, change it to unknown instead. 12996 */ 12997 private int fixUpInstallReason(String installerPackageName, int installerUid, 12998 int installReason) { 12999 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13000 == PERMISSION_GRANTED) { 13001 // If the install is being performed by a system app, we trust that app to have set the 13002 // install reason correctly. 13003 return installReason; 13004 } 13005 13006 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13007 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13008 if (dpm != null) { 13009 ComponentName owner = null; 13010 try { 13011 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13012 if (owner == null) { 13013 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13014 } 13015 } catch (RemoteException e) { 13016 } 13017 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13018 // If the install is being performed by a device or profile owner, the install 13019 // reason should be enterprise policy. 13020 return PackageManager.INSTALL_REASON_POLICY; 13021 } 13022 } 13023 13024 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13025 // If the install is being performed by a regular app (i.e. neither system app nor 13026 // device or profile owner), we have no reason to believe that the app is acting on 13027 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13028 // change it to unknown instead. 13029 return PackageManager.INSTALL_REASON_UNKNOWN; 13030 } 13031 13032 // If the install is being performed by a regular app and the install reason was set to any 13033 // value but enterprise policy, leave the install reason unchanged. 13034 return installReason; 13035 } 13036 13037 void installStage(String packageName, File stagedDir, String stagedCid, 13038 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13039 String installerPackageName, int installerUid, UserHandle user, 13040 Certificate[][] certificates) { 13041 if (DEBUG_EPHEMERAL) { 13042 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13043 Slog.d(TAG, "Ephemeral install of " + packageName); 13044 } 13045 } 13046 final VerificationInfo verificationInfo = new VerificationInfo( 13047 sessionParams.originatingUri, sessionParams.referrerUri, 13048 sessionParams.originatingUid, installerUid); 13049 13050 final OriginInfo origin; 13051 if (stagedDir != null) { 13052 origin = OriginInfo.fromStagedFile(stagedDir); 13053 } else { 13054 origin = OriginInfo.fromStagedContainer(stagedCid); 13055 } 13056 13057 final Message msg = mHandler.obtainMessage(INIT_COPY); 13058 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13059 sessionParams.installReason); 13060 final InstallParams params = new InstallParams(origin, null, observer, 13061 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13062 verificationInfo, user, sessionParams.abiOverride, 13063 sessionParams.grantedRuntimePermissions, certificates, installReason); 13064 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13065 msg.obj = params; 13066 13067 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13068 System.identityHashCode(msg.obj)); 13069 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13070 System.identityHashCode(msg.obj)); 13071 13072 mHandler.sendMessage(msg); 13073 } 13074 13075 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13076 int userId) { 13077 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13078 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13079 } 13080 13081 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13082 int appId, int... userIds) { 13083 if (ArrayUtils.isEmpty(userIds)) { 13084 return; 13085 } 13086 Bundle extras = new Bundle(1); 13087 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13088 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13089 13090 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13091 packageName, extras, 0, null, null, userIds); 13092 if (isSystem) { 13093 mHandler.post(() -> { 13094 for (int userId : userIds) { 13095 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13096 } 13097 } 13098 ); 13099 } 13100 } 13101 13102 /** 13103 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13104 * automatically without needing an explicit launch. 13105 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13106 */ 13107 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13108 // If user is not running, the app didn't miss any broadcast 13109 if (!mUserManagerInternal.isUserRunning(userId)) { 13110 return; 13111 } 13112 final IActivityManager am = ActivityManager.getService(); 13113 try { 13114 // Deliver LOCKED_BOOT_COMPLETED first 13115 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13116 .setPackage(packageName); 13117 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13118 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13119 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13120 13121 // Deliver BOOT_COMPLETED only if user is unlocked 13122 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13123 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13124 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13125 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13126 } 13127 } catch (RemoteException e) { 13128 throw e.rethrowFromSystemServer(); 13129 } 13130 } 13131 13132 @Override 13133 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13134 int userId) { 13135 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13136 PackageSetting pkgSetting; 13137 final int uid = Binder.getCallingUid(); 13138 enforceCrossUserPermission(uid, userId, 13139 true /* requireFullPermission */, true /* checkShell */, 13140 "setApplicationHiddenSetting for user " + userId); 13141 13142 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13143 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13144 return false; 13145 } 13146 13147 long callingId = Binder.clearCallingIdentity(); 13148 try { 13149 boolean sendAdded = false; 13150 boolean sendRemoved = false; 13151 // writer 13152 synchronized (mPackages) { 13153 pkgSetting = mSettings.mPackages.get(packageName); 13154 if (pkgSetting == null) { 13155 return false; 13156 } 13157 // Do not allow "android" is being disabled 13158 if ("android".equals(packageName)) { 13159 Slog.w(TAG, "Cannot hide package: android"); 13160 return false; 13161 } 13162 // Cannot hide static shared libs as they are considered 13163 // a part of the using app (emulating static linking). Also 13164 // static libs are installed always on internal storage. 13165 PackageParser.Package pkg = mPackages.get(packageName); 13166 if (pkg != null && pkg.staticSharedLibName != null) { 13167 Slog.w(TAG, "Cannot hide package: " + packageName 13168 + " providing static shared library: " 13169 + pkg.staticSharedLibName); 13170 return false; 13171 } 13172 // Only allow protected packages to hide themselves. 13173 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13174 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13175 Slog.w(TAG, "Not hiding protected package: " + packageName); 13176 return false; 13177 } 13178 13179 if (pkgSetting.getHidden(userId) != hidden) { 13180 pkgSetting.setHidden(hidden, userId); 13181 mSettings.writePackageRestrictionsLPr(userId); 13182 if (hidden) { 13183 sendRemoved = true; 13184 } else { 13185 sendAdded = true; 13186 } 13187 } 13188 } 13189 if (sendAdded) { 13190 sendPackageAddedForUser(packageName, pkgSetting, userId); 13191 return true; 13192 } 13193 if (sendRemoved) { 13194 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13195 "hiding pkg"); 13196 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13197 return true; 13198 } 13199 } finally { 13200 Binder.restoreCallingIdentity(callingId); 13201 } 13202 return false; 13203 } 13204 13205 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13206 int userId) { 13207 final PackageRemovedInfo info = new PackageRemovedInfo(); 13208 info.removedPackage = packageName; 13209 info.removedUsers = new int[] {userId}; 13210 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13211 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13212 } 13213 13214 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13215 if (pkgList.length > 0) { 13216 Bundle extras = new Bundle(1); 13217 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13218 13219 sendPackageBroadcast( 13220 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13221 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13222 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13223 new int[] {userId}); 13224 } 13225 } 13226 13227 /** 13228 * Returns true if application is not found or there was an error. Otherwise it returns 13229 * the hidden state of the package for the given user. 13230 */ 13231 @Override 13232 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13233 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13235 true /* requireFullPermission */, false /* checkShell */, 13236 "getApplicationHidden for user " + userId); 13237 PackageSetting pkgSetting; 13238 long callingId = Binder.clearCallingIdentity(); 13239 try { 13240 // writer 13241 synchronized (mPackages) { 13242 pkgSetting = mSettings.mPackages.get(packageName); 13243 if (pkgSetting == null) { 13244 return true; 13245 } 13246 return pkgSetting.getHidden(userId); 13247 } 13248 } finally { 13249 Binder.restoreCallingIdentity(callingId); 13250 } 13251 } 13252 13253 /** 13254 * @hide 13255 */ 13256 @Override 13257 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13258 int installReason) { 13259 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13260 null); 13261 PackageSetting pkgSetting; 13262 final int uid = Binder.getCallingUid(); 13263 enforceCrossUserPermission(uid, userId, 13264 true /* requireFullPermission */, true /* checkShell */, 13265 "installExistingPackage for user " + userId); 13266 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13267 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13268 } 13269 13270 long callingId = Binder.clearCallingIdentity(); 13271 try { 13272 boolean installed = false; 13273 final boolean instantApp = 13274 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13275 final boolean fullApp = 13276 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13277 13278 // writer 13279 synchronized (mPackages) { 13280 pkgSetting = mSettings.mPackages.get(packageName); 13281 if (pkgSetting == null) { 13282 return PackageManager.INSTALL_FAILED_INVALID_URI; 13283 } 13284 if (!pkgSetting.getInstalled(userId)) { 13285 pkgSetting.setInstalled(true, userId); 13286 pkgSetting.setHidden(false, userId); 13287 pkgSetting.setInstallReason(installReason, userId); 13288 mSettings.writePackageRestrictionsLPr(userId); 13289 mSettings.writeKernelMappingLPr(pkgSetting); 13290 installed = true; 13291 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13292 // upgrade app from instant to full; we don't allow app downgrade 13293 installed = true; 13294 } 13295 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13296 } 13297 13298 if (installed) { 13299 if (pkgSetting.pkg != null) { 13300 synchronized (mInstallLock) { 13301 // We don't need to freeze for a brand new install 13302 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13303 } 13304 } 13305 sendPackageAddedForUser(packageName, pkgSetting, userId); 13306 synchronized (mPackages) { 13307 updateSequenceNumberLP(packageName, new int[]{ userId }); 13308 } 13309 } 13310 } finally { 13311 Binder.restoreCallingIdentity(callingId); 13312 } 13313 13314 return PackageManager.INSTALL_SUCCEEDED; 13315 } 13316 13317 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13318 boolean instantApp, boolean fullApp) { 13319 // no state specified; do nothing 13320 if (!instantApp && !fullApp) { 13321 return; 13322 } 13323 if (userId != UserHandle.USER_ALL) { 13324 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13325 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13326 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13327 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13328 } 13329 } else { 13330 for (int currentUserId : sUserManager.getUserIds()) { 13331 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13332 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13333 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13334 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13335 } 13336 } 13337 } 13338 } 13339 13340 boolean isUserRestricted(int userId, String restrictionKey) { 13341 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13342 if (restrictions.getBoolean(restrictionKey, false)) { 13343 Log.w(TAG, "User is restricted: " + restrictionKey); 13344 return true; 13345 } 13346 return false; 13347 } 13348 13349 @Override 13350 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13351 int userId) { 13352 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13353 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13354 true /* requireFullPermission */, true /* checkShell */, 13355 "setPackagesSuspended for user " + userId); 13356 13357 if (ArrayUtils.isEmpty(packageNames)) { 13358 return packageNames; 13359 } 13360 13361 // List of package names for whom the suspended state has changed. 13362 List<String> changedPackages = new ArrayList<>(packageNames.length); 13363 // List of package names for whom the suspended state is not set as requested in this 13364 // method. 13365 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13366 long callingId = Binder.clearCallingIdentity(); 13367 try { 13368 for (int i = 0; i < packageNames.length; i++) { 13369 String packageName = packageNames[i]; 13370 boolean changed = false; 13371 final int appId; 13372 synchronized (mPackages) { 13373 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13374 if (pkgSetting == null) { 13375 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13376 + "\". Skipping suspending/un-suspending."); 13377 unactionedPackages.add(packageName); 13378 continue; 13379 } 13380 appId = pkgSetting.appId; 13381 if (pkgSetting.getSuspended(userId) != suspended) { 13382 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13383 unactionedPackages.add(packageName); 13384 continue; 13385 } 13386 pkgSetting.setSuspended(suspended, userId); 13387 mSettings.writePackageRestrictionsLPr(userId); 13388 changed = true; 13389 changedPackages.add(packageName); 13390 } 13391 } 13392 13393 if (changed && suspended) { 13394 killApplication(packageName, UserHandle.getUid(userId, appId), 13395 "suspending package"); 13396 } 13397 } 13398 } finally { 13399 Binder.restoreCallingIdentity(callingId); 13400 } 13401 13402 if (!changedPackages.isEmpty()) { 13403 sendPackagesSuspendedForUser(changedPackages.toArray( 13404 new String[changedPackages.size()]), userId, suspended); 13405 } 13406 13407 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13408 } 13409 13410 @Override 13411 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13412 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13413 true /* requireFullPermission */, false /* checkShell */, 13414 "isPackageSuspendedForUser for user " + userId); 13415 synchronized (mPackages) { 13416 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13417 if (pkgSetting == null) { 13418 throw new IllegalArgumentException("Unknown target package: " + packageName); 13419 } 13420 return pkgSetting.getSuspended(userId); 13421 } 13422 } 13423 13424 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13425 if (isPackageDeviceAdmin(packageName, userId)) { 13426 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13427 + "\": has an active device admin"); 13428 return false; 13429 } 13430 13431 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13432 if (packageName.equals(activeLauncherPackageName)) { 13433 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13434 + "\": contains the active launcher"); 13435 return false; 13436 } 13437 13438 if (packageName.equals(mRequiredInstallerPackage)) { 13439 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13440 + "\": required for package installation"); 13441 return false; 13442 } 13443 13444 if (packageName.equals(mRequiredUninstallerPackage)) { 13445 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13446 + "\": required for package uninstallation"); 13447 return false; 13448 } 13449 13450 if (packageName.equals(mRequiredVerifierPackage)) { 13451 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13452 + "\": required for package verification"); 13453 return false; 13454 } 13455 13456 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13457 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13458 + "\": is the default dialer"); 13459 return false; 13460 } 13461 13462 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13463 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13464 + "\": protected package"); 13465 return false; 13466 } 13467 13468 // Cannot suspend static shared libs as they are considered 13469 // a part of the using app (emulating static linking). Also 13470 // static libs are installed always on internal storage. 13471 PackageParser.Package pkg = mPackages.get(packageName); 13472 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13473 Slog.w(TAG, "Cannot suspend package: " + packageName 13474 + " providing static shared library: " 13475 + pkg.staticSharedLibName); 13476 return false; 13477 } 13478 13479 return true; 13480 } 13481 13482 private String getActiveLauncherPackageName(int userId) { 13483 Intent intent = new Intent(Intent.ACTION_MAIN); 13484 intent.addCategory(Intent.CATEGORY_HOME); 13485 ResolveInfo resolveInfo = resolveIntent( 13486 intent, 13487 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13488 PackageManager.MATCH_DEFAULT_ONLY, 13489 userId); 13490 13491 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13492 } 13493 13494 private String getDefaultDialerPackageName(int userId) { 13495 synchronized (mPackages) { 13496 return mSettings.getDefaultDialerPackageNameLPw(userId); 13497 } 13498 } 13499 13500 @Override 13501 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13502 mContext.enforceCallingOrSelfPermission( 13503 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13504 "Only package verification agents can verify applications"); 13505 13506 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13507 final PackageVerificationResponse response = new PackageVerificationResponse( 13508 verificationCode, Binder.getCallingUid()); 13509 msg.arg1 = id; 13510 msg.obj = response; 13511 mHandler.sendMessage(msg); 13512 } 13513 13514 @Override 13515 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13516 long millisecondsToDelay) { 13517 mContext.enforceCallingOrSelfPermission( 13518 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13519 "Only package verification agents can extend verification timeouts"); 13520 13521 final PackageVerificationState state = mPendingVerification.get(id); 13522 final PackageVerificationResponse response = new PackageVerificationResponse( 13523 verificationCodeAtTimeout, Binder.getCallingUid()); 13524 13525 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13526 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13527 } 13528 if (millisecondsToDelay < 0) { 13529 millisecondsToDelay = 0; 13530 } 13531 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13532 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13533 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13534 } 13535 13536 if ((state != null) && !state.timeoutExtended()) { 13537 state.extendTimeout(); 13538 13539 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13540 msg.arg1 = id; 13541 msg.obj = response; 13542 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13543 } 13544 } 13545 13546 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13547 int verificationCode, UserHandle user) { 13548 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13549 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13550 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13551 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13552 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13553 13554 mContext.sendBroadcastAsUser(intent, user, 13555 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13556 } 13557 13558 private ComponentName matchComponentForVerifier(String packageName, 13559 List<ResolveInfo> receivers) { 13560 ActivityInfo targetReceiver = null; 13561 13562 final int NR = receivers.size(); 13563 for (int i = 0; i < NR; i++) { 13564 final ResolveInfo info = receivers.get(i); 13565 if (info.activityInfo == null) { 13566 continue; 13567 } 13568 13569 if (packageName.equals(info.activityInfo.packageName)) { 13570 targetReceiver = info.activityInfo; 13571 break; 13572 } 13573 } 13574 13575 if (targetReceiver == null) { 13576 return null; 13577 } 13578 13579 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13580 } 13581 13582 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13583 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13584 if (pkgInfo.verifiers.length == 0) { 13585 return null; 13586 } 13587 13588 final int N = pkgInfo.verifiers.length; 13589 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13590 for (int i = 0; i < N; i++) { 13591 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13592 13593 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13594 receivers); 13595 if (comp == null) { 13596 continue; 13597 } 13598 13599 final int verifierUid = getUidForVerifier(verifierInfo); 13600 if (verifierUid == -1) { 13601 continue; 13602 } 13603 13604 if (DEBUG_VERIFY) { 13605 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13606 + " with the correct signature"); 13607 } 13608 sufficientVerifiers.add(comp); 13609 verificationState.addSufficientVerifier(verifierUid); 13610 } 13611 13612 return sufficientVerifiers; 13613 } 13614 13615 private int getUidForVerifier(VerifierInfo verifierInfo) { 13616 synchronized (mPackages) { 13617 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13618 if (pkg == null) { 13619 return -1; 13620 } else if (pkg.mSignatures.length != 1) { 13621 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13622 + " has more than one signature; ignoring"); 13623 return -1; 13624 } 13625 13626 /* 13627 * If the public key of the package's signature does not match 13628 * our expected public key, then this is a different package and 13629 * we should skip. 13630 */ 13631 13632 final byte[] expectedPublicKey; 13633 try { 13634 final Signature verifierSig = pkg.mSignatures[0]; 13635 final PublicKey publicKey = verifierSig.getPublicKey(); 13636 expectedPublicKey = publicKey.getEncoded(); 13637 } catch (CertificateException e) { 13638 return -1; 13639 } 13640 13641 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13642 13643 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13644 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13645 + " does not have the expected public key; ignoring"); 13646 return -1; 13647 } 13648 13649 return pkg.applicationInfo.uid; 13650 } 13651 } 13652 13653 @Override 13654 public void finishPackageInstall(int token, boolean didLaunch) { 13655 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13656 13657 if (DEBUG_INSTALL) { 13658 Slog.v(TAG, "BM finishing package install for " + token); 13659 } 13660 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13661 13662 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13663 mHandler.sendMessage(msg); 13664 } 13665 13666 /** 13667 * Get the verification agent timeout. 13668 * 13669 * @return verification timeout in milliseconds 13670 */ 13671 private long getVerificationTimeout() { 13672 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13673 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13674 DEFAULT_VERIFICATION_TIMEOUT); 13675 } 13676 13677 /** 13678 * Get the default verification agent response code. 13679 * 13680 * @return default verification response code 13681 */ 13682 private int getDefaultVerificationResponse() { 13683 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13684 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13685 DEFAULT_VERIFICATION_RESPONSE); 13686 } 13687 13688 /** 13689 * Check whether or not package verification has been enabled. 13690 * 13691 * @return true if verification should be performed 13692 */ 13693 private boolean isVerificationEnabled(int userId, int installFlags) { 13694 if (!DEFAULT_VERIFY_ENABLE) { 13695 return false; 13696 } 13697 13698 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13699 13700 // Check if installing from ADB 13701 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13702 // Do not run verification in a test harness environment 13703 if (ActivityManager.isRunningInTestHarness()) { 13704 return false; 13705 } 13706 if (ensureVerifyAppsEnabled) { 13707 return true; 13708 } 13709 // Check if the developer does not want package verification for ADB installs 13710 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13711 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13712 return false; 13713 } 13714 } 13715 13716 if (ensureVerifyAppsEnabled) { 13717 return true; 13718 } 13719 13720 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13721 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13722 } 13723 13724 @Override 13725 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13726 throws RemoteException { 13727 mContext.enforceCallingOrSelfPermission( 13728 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13729 "Only intentfilter verification agents can verify applications"); 13730 13731 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13732 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13733 Binder.getCallingUid(), verificationCode, failedDomains); 13734 msg.arg1 = id; 13735 msg.obj = response; 13736 mHandler.sendMessage(msg); 13737 } 13738 13739 @Override 13740 public int getIntentVerificationStatus(String packageName, int userId) { 13741 synchronized (mPackages) { 13742 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13743 } 13744 } 13745 13746 @Override 13747 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13748 mContext.enforceCallingOrSelfPermission( 13749 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13750 13751 boolean result = false; 13752 synchronized (mPackages) { 13753 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13754 } 13755 if (result) { 13756 scheduleWritePackageRestrictionsLocked(userId); 13757 } 13758 return result; 13759 } 13760 13761 @Override 13762 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13763 String packageName) { 13764 synchronized (mPackages) { 13765 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13766 } 13767 } 13768 13769 @Override 13770 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13771 if (TextUtils.isEmpty(packageName)) { 13772 return ParceledListSlice.emptyList(); 13773 } 13774 synchronized (mPackages) { 13775 PackageParser.Package pkg = mPackages.get(packageName); 13776 if (pkg == null || pkg.activities == null) { 13777 return ParceledListSlice.emptyList(); 13778 } 13779 final int count = pkg.activities.size(); 13780 ArrayList<IntentFilter> result = new ArrayList<>(); 13781 for (int n=0; n<count; n++) { 13782 PackageParser.Activity activity = pkg.activities.get(n); 13783 if (activity.intents != null && activity.intents.size() > 0) { 13784 result.addAll(activity.intents); 13785 } 13786 } 13787 return new ParceledListSlice<>(result); 13788 } 13789 } 13790 13791 @Override 13792 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13793 mContext.enforceCallingOrSelfPermission( 13794 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13795 13796 synchronized (mPackages) { 13797 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13798 if (packageName != null) { 13799 result |= updateIntentVerificationStatus(packageName, 13800 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13801 userId); 13802 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13803 packageName, userId); 13804 } 13805 return result; 13806 } 13807 } 13808 13809 @Override 13810 public String getDefaultBrowserPackageName(int userId) { 13811 synchronized (mPackages) { 13812 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13813 } 13814 } 13815 13816 /** 13817 * Get the "allow unknown sources" setting. 13818 * 13819 * @return the current "allow unknown sources" setting 13820 */ 13821 private int getUnknownSourcesSettings() { 13822 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13823 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13824 -1); 13825 } 13826 13827 @Override 13828 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13829 final int uid = Binder.getCallingUid(); 13830 // writer 13831 synchronized (mPackages) { 13832 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13833 if (targetPackageSetting == null) { 13834 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13835 } 13836 13837 PackageSetting installerPackageSetting; 13838 if (installerPackageName != null) { 13839 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13840 if (installerPackageSetting == null) { 13841 throw new IllegalArgumentException("Unknown installer package: " 13842 + installerPackageName); 13843 } 13844 } else { 13845 installerPackageSetting = null; 13846 } 13847 13848 Signature[] callerSignature; 13849 Object obj = mSettings.getUserIdLPr(uid); 13850 if (obj != null) { 13851 if (obj instanceof SharedUserSetting) { 13852 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13853 } else if (obj instanceof PackageSetting) { 13854 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13855 } else { 13856 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13857 } 13858 } else { 13859 throw new SecurityException("Unknown calling UID: " + uid); 13860 } 13861 13862 // Verify: can't set installerPackageName to a package that is 13863 // not signed with the same cert as the caller. 13864 if (installerPackageSetting != null) { 13865 if (compareSignatures(callerSignature, 13866 installerPackageSetting.signatures.mSignatures) 13867 != PackageManager.SIGNATURE_MATCH) { 13868 throw new SecurityException( 13869 "Caller does not have same cert as new installer package " 13870 + installerPackageName); 13871 } 13872 } 13873 13874 // Verify: if target already has an installer package, it must 13875 // be signed with the same cert as the caller. 13876 if (targetPackageSetting.installerPackageName != null) { 13877 PackageSetting setting = mSettings.mPackages.get( 13878 targetPackageSetting.installerPackageName); 13879 // If the currently set package isn't valid, then it's always 13880 // okay to change it. 13881 if (setting != null) { 13882 if (compareSignatures(callerSignature, 13883 setting.signatures.mSignatures) 13884 != PackageManager.SIGNATURE_MATCH) { 13885 throw new SecurityException( 13886 "Caller does not have same cert as old installer package " 13887 + targetPackageSetting.installerPackageName); 13888 } 13889 } 13890 } 13891 13892 // Okay! 13893 targetPackageSetting.installerPackageName = installerPackageName; 13894 if (installerPackageName != null) { 13895 mSettings.mInstallerPackages.add(installerPackageName); 13896 } 13897 scheduleWriteSettingsLocked(); 13898 } 13899 } 13900 13901 @Override 13902 public void setApplicationCategoryHint(String packageName, int categoryHint, 13903 String callerPackageName) { 13904 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13905 callerPackageName); 13906 synchronized (mPackages) { 13907 PackageSetting ps = mSettings.mPackages.get(packageName); 13908 if (ps == null) { 13909 throw new IllegalArgumentException("Unknown target package " + packageName); 13910 } 13911 13912 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13913 throw new IllegalArgumentException("Calling package " + callerPackageName 13914 + " is not installer for " + packageName); 13915 } 13916 13917 if (ps.categoryHint != categoryHint) { 13918 ps.categoryHint = categoryHint; 13919 scheduleWriteSettingsLocked(); 13920 } 13921 } 13922 } 13923 13924 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13925 // Queue up an async operation since the package installation may take a little while. 13926 mHandler.post(new Runnable() { 13927 public void run() { 13928 mHandler.removeCallbacks(this); 13929 // Result object to be returned 13930 PackageInstalledInfo res = new PackageInstalledInfo(); 13931 res.setReturnCode(currentStatus); 13932 res.uid = -1; 13933 res.pkg = null; 13934 res.removedInfo = null; 13935 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13936 args.doPreInstall(res.returnCode); 13937 synchronized (mInstallLock) { 13938 installPackageTracedLI(args, res); 13939 } 13940 args.doPostInstall(res.returnCode, res.uid); 13941 } 13942 13943 // A restore should be performed at this point if (a) the install 13944 // succeeded, (b) the operation is not an update, and (c) the new 13945 // package has not opted out of backup participation. 13946 final boolean update = res.removedInfo != null 13947 && res.removedInfo.removedPackage != null; 13948 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13949 boolean doRestore = !update 13950 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13951 13952 // Set up the post-install work request bookkeeping. This will be used 13953 // and cleaned up by the post-install event handling regardless of whether 13954 // there's a restore pass performed. Token values are >= 1. 13955 int token; 13956 if (mNextInstallToken < 0) mNextInstallToken = 1; 13957 token = mNextInstallToken++; 13958 13959 PostInstallData data = new PostInstallData(args, res); 13960 mRunningInstalls.put(token, data); 13961 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13962 13963 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13964 // Pass responsibility to the Backup Manager. It will perform a 13965 // restore if appropriate, then pass responsibility back to the 13966 // Package Manager to run the post-install observer callbacks 13967 // and broadcasts. 13968 IBackupManager bm = IBackupManager.Stub.asInterface( 13969 ServiceManager.getService(Context.BACKUP_SERVICE)); 13970 if (bm != null) { 13971 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13972 + " to BM for possible restore"); 13973 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13974 try { 13975 // TODO: http://b/22388012 13976 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13977 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13978 } else { 13979 doRestore = false; 13980 } 13981 } catch (RemoteException e) { 13982 // can't happen; the backup manager is local 13983 } catch (Exception e) { 13984 Slog.e(TAG, "Exception trying to enqueue restore", e); 13985 doRestore = false; 13986 } 13987 } else { 13988 Slog.e(TAG, "Backup Manager not found!"); 13989 doRestore = false; 13990 } 13991 } 13992 13993 if (!doRestore) { 13994 // No restore possible, or the Backup Manager was mysteriously not 13995 // available -- just fire the post-install work request directly. 13996 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13997 13998 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13999 14000 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14001 mHandler.sendMessage(msg); 14002 } 14003 } 14004 }); 14005 } 14006 14007 /** 14008 * Callback from PackageSettings whenever an app is first transitioned out of the 14009 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14010 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14011 * here whether the app is the target of an ongoing install, and only send the 14012 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14013 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14014 * handling. 14015 */ 14016 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14017 // Serialize this with the rest of the install-process message chain. In the 14018 // restore-at-install case, this Runnable will necessarily run before the 14019 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14020 // are coherent. In the non-restore case, the app has already completed install 14021 // and been launched through some other means, so it is not in a problematic 14022 // state for observers to see the FIRST_LAUNCH signal. 14023 mHandler.post(new Runnable() { 14024 @Override 14025 public void run() { 14026 for (int i = 0; i < mRunningInstalls.size(); i++) { 14027 final PostInstallData data = mRunningInstalls.valueAt(i); 14028 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14029 continue; 14030 } 14031 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14032 // right package; but is it for the right user? 14033 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14034 if (userId == data.res.newUsers[uIndex]) { 14035 if (DEBUG_BACKUP) { 14036 Slog.i(TAG, "Package " + pkgName 14037 + " being restored so deferring FIRST_LAUNCH"); 14038 } 14039 return; 14040 } 14041 } 14042 } 14043 } 14044 // didn't find it, so not being restored 14045 if (DEBUG_BACKUP) { 14046 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14047 } 14048 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14049 } 14050 }); 14051 } 14052 14053 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14054 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14055 installerPkg, null, userIds); 14056 } 14057 14058 private abstract class HandlerParams { 14059 private static final int MAX_RETRIES = 4; 14060 14061 /** 14062 * Number of times startCopy() has been attempted and had a non-fatal 14063 * error. 14064 */ 14065 private int mRetries = 0; 14066 14067 /** User handle for the user requesting the information or installation. */ 14068 private final UserHandle mUser; 14069 String traceMethod; 14070 int traceCookie; 14071 14072 HandlerParams(UserHandle user) { 14073 mUser = user; 14074 } 14075 14076 UserHandle getUser() { 14077 return mUser; 14078 } 14079 14080 HandlerParams setTraceMethod(String traceMethod) { 14081 this.traceMethod = traceMethod; 14082 return this; 14083 } 14084 14085 HandlerParams setTraceCookie(int traceCookie) { 14086 this.traceCookie = traceCookie; 14087 return this; 14088 } 14089 14090 final boolean startCopy() { 14091 boolean res; 14092 try { 14093 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14094 14095 if (++mRetries > MAX_RETRIES) { 14096 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14097 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14098 handleServiceError(); 14099 return false; 14100 } else { 14101 handleStartCopy(); 14102 res = true; 14103 } 14104 } catch (RemoteException e) { 14105 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14106 mHandler.sendEmptyMessage(MCS_RECONNECT); 14107 res = false; 14108 } 14109 handleReturnCode(); 14110 return res; 14111 } 14112 14113 final void serviceError() { 14114 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14115 handleServiceError(); 14116 handleReturnCode(); 14117 } 14118 14119 abstract void handleStartCopy() throws RemoteException; 14120 abstract void handleServiceError(); 14121 abstract void handleReturnCode(); 14122 } 14123 14124 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14125 for (File path : paths) { 14126 try { 14127 mcs.clearDirectory(path.getAbsolutePath()); 14128 } catch (RemoteException e) { 14129 } 14130 } 14131 } 14132 14133 static class OriginInfo { 14134 /** 14135 * Location where install is coming from, before it has been 14136 * copied/renamed into place. This could be a single monolithic APK 14137 * file, or a cluster directory. This location may be untrusted. 14138 */ 14139 final File file; 14140 final String cid; 14141 14142 /** 14143 * Flag indicating that {@link #file} or {@link #cid} has already been 14144 * staged, meaning downstream users don't need to defensively copy the 14145 * contents. 14146 */ 14147 final boolean staged; 14148 14149 /** 14150 * Flag indicating that {@link #file} or {@link #cid} is an already 14151 * installed app that is being moved. 14152 */ 14153 final boolean existing; 14154 14155 final String resolvedPath; 14156 final File resolvedFile; 14157 14158 static OriginInfo fromNothing() { 14159 return new OriginInfo(null, null, false, false); 14160 } 14161 14162 static OriginInfo fromUntrustedFile(File file) { 14163 return new OriginInfo(file, null, false, false); 14164 } 14165 14166 static OriginInfo fromExistingFile(File file) { 14167 return new OriginInfo(file, null, false, true); 14168 } 14169 14170 static OriginInfo fromStagedFile(File file) { 14171 return new OriginInfo(file, null, true, false); 14172 } 14173 14174 static OriginInfo fromStagedContainer(String cid) { 14175 return new OriginInfo(null, cid, true, false); 14176 } 14177 14178 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14179 this.file = file; 14180 this.cid = cid; 14181 this.staged = staged; 14182 this.existing = existing; 14183 14184 if (cid != null) { 14185 resolvedPath = PackageHelper.getSdDir(cid); 14186 resolvedFile = new File(resolvedPath); 14187 } else if (file != null) { 14188 resolvedPath = file.getAbsolutePath(); 14189 resolvedFile = file; 14190 } else { 14191 resolvedPath = null; 14192 resolvedFile = null; 14193 } 14194 } 14195 } 14196 14197 static class MoveInfo { 14198 final int moveId; 14199 final String fromUuid; 14200 final String toUuid; 14201 final String packageName; 14202 final String dataAppName; 14203 final int appId; 14204 final String seinfo; 14205 final int targetSdkVersion; 14206 14207 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14208 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14209 this.moveId = moveId; 14210 this.fromUuid = fromUuid; 14211 this.toUuid = toUuid; 14212 this.packageName = packageName; 14213 this.dataAppName = dataAppName; 14214 this.appId = appId; 14215 this.seinfo = seinfo; 14216 this.targetSdkVersion = targetSdkVersion; 14217 } 14218 } 14219 14220 static class VerificationInfo { 14221 /** A constant used to indicate that a uid value is not present. */ 14222 public static final int NO_UID = -1; 14223 14224 /** URI referencing where the package was downloaded from. */ 14225 final Uri originatingUri; 14226 14227 /** HTTP referrer URI associated with the originatingURI. */ 14228 final Uri referrer; 14229 14230 /** UID of the application that the install request originated from. */ 14231 final int originatingUid; 14232 14233 /** UID of application requesting the install */ 14234 final int installerUid; 14235 14236 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14237 this.originatingUri = originatingUri; 14238 this.referrer = referrer; 14239 this.originatingUid = originatingUid; 14240 this.installerUid = installerUid; 14241 } 14242 } 14243 14244 class InstallParams extends HandlerParams { 14245 final OriginInfo origin; 14246 final MoveInfo move; 14247 final IPackageInstallObserver2 observer; 14248 int installFlags; 14249 final String installerPackageName; 14250 final String volumeUuid; 14251 private InstallArgs mArgs; 14252 private int mRet; 14253 final String packageAbiOverride; 14254 final String[] grantedRuntimePermissions; 14255 final VerificationInfo verificationInfo; 14256 final Certificate[][] certificates; 14257 final int installReason; 14258 14259 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14260 int installFlags, String installerPackageName, String volumeUuid, 14261 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14262 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14263 super(user); 14264 this.origin = origin; 14265 this.move = move; 14266 this.observer = observer; 14267 this.installFlags = installFlags; 14268 this.installerPackageName = installerPackageName; 14269 this.volumeUuid = volumeUuid; 14270 this.verificationInfo = verificationInfo; 14271 this.packageAbiOverride = packageAbiOverride; 14272 this.grantedRuntimePermissions = grantedPermissions; 14273 this.certificates = certificates; 14274 this.installReason = installReason; 14275 } 14276 14277 @Override 14278 public String toString() { 14279 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14280 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14281 } 14282 14283 private int installLocationPolicy(PackageInfoLite pkgLite) { 14284 String packageName = pkgLite.packageName; 14285 int installLocation = pkgLite.installLocation; 14286 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14287 // reader 14288 synchronized (mPackages) { 14289 // Currently installed package which the new package is attempting to replace or 14290 // null if no such package is installed. 14291 PackageParser.Package installedPkg = mPackages.get(packageName); 14292 // Package which currently owns the data which the new package will own if installed. 14293 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14294 // will be null whereas dataOwnerPkg will contain information about the package 14295 // which was uninstalled while keeping its data. 14296 PackageParser.Package dataOwnerPkg = installedPkg; 14297 if (dataOwnerPkg == null) { 14298 PackageSetting ps = mSettings.mPackages.get(packageName); 14299 if (ps != null) { 14300 dataOwnerPkg = ps.pkg; 14301 } 14302 } 14303 14304 if (dataOwnerPkg != null) { 14305 // If installed, the package will get access to data left on the device by its 14306 // predecessor. As a security measure, this is permited only if this is not a 14307 // version downgrade or if the predecessor package is marked as debuggable and 14308 // a downgrade is explicitly requested. 14309 // 14310 // On debuggable platform builds, downgrades are permitted even for 14311 // non-debuggable packages to make testing easier. Debuggable platform builds do 14312 // not offer security guarantees and thus it's OK to disable some security 14313 // mechanisms to make debugging/testing easier on those builds. However, even on 14314 // debuggable builds downgrades of packages are permitted only if requested via 14315 // installFlags. This is because we aim to keep the behavior of debuggable 14316 // platform builds as close as possible to the behavior of non-debuggable 14317 // platform builds. 14318 final boolean downgradeRequested = 14319 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14320 final boolean packageDebuggable = 14321 (dataOwnerPkg.applicationInfo.flags 14322 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14323 final boolean downgradePermitted = 14324 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14325 if (!downgradePermitted) { 14326 try { 14327 checkDowngrade(dataOwnerPkg, pkgLite); 14328 } catch (PackageManagerException e) { 14329 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14330 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14331 } 14332 } 14333 } 14334 14335 if (installedPkg != null) { 14336 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14337 // Check for updated system application. 14338 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14339 if (onSd) { 14340 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14341 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14342 } 14343 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14344 } else { 14345 if (onSd) { 14346 // Install flag overrides everything. 14347 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14348 } 14349 // If current upgrade specifies particular preference 14350 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14351 // Application explicitly specified internal. 14352 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14353 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14354 // App explictly prefers external. Let policy decide 14355 } else { 14356 // Prefer previous location 14357 if (isExternal(installedPkg)) { 14358 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14359 } 14360 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14361 } 14362 } 14363 } else { 14364 // Invalid install. Return error code 14365 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14366 } 14367 } 14368 } 14369 // All the special cases have been taken care of. 14370 // Return result based on recommended install location. 14371 if (onSd) { 14372 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14373 } 14374 return pkgLite.recommendedInstallLocation; 14375 } 14376 14377 /* 14378 * Invoke remote method to get package information and install 14379 * location values. Override install location based on default 14380 * policy if needed and then create install arguments based 14381 * on the install location. 14382 */ 14383 public void handleStartCopy() throws RemoteException { 14384 int ret = PackageManager.INSTALL_SUCCEEDED; 14385 14386 // If we're already staged, we've firmly committed to an install location 14387 if (origin.staged) { 14388 if (origin.file != null) { 14389 installFlags |= PackageManager.INSTALL_INTERNAL; 14390 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14391 } else if (origin.cid != null) { 14392 installFlags |= PackageManager.INSTALL_EXTERNAL; 14393 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14394 } else { 14395 throw new IllegalStateException("Invalid stage location"); 14396 } 14397 } 14398 14399 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14400 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14401 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14402 PackageInfoLite pkgLite = null; 14403 14404 if (onInt && onSd) { 14405 // Check if both bits are set. 14406 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14407 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14408 } else if (onSd && ephemeral) { 14409 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14410 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14411 } else { 14412 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14413 packageAbiOverride); 14414 14415 if (DEBUG_EPHEMERAL && ephemeral) { 14416 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14417 } 14418 14419 /* 14420 * If we have too little free space, try to free cache 14421 * before giving up. 14422 */ 14423 if (!origin.staged && pkgLite.recommendedInstallLocation 14424 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14425 // TODO: focus freeing disk space on the target device 14426 final StorageManager storage = StorageManager.from(mContext); 14427 final long lowThreshold = storage.getStorageLowBytes( 14428 Environment.getDataDirectory()); 14429 14430 final long sizeBytes = mContainerService.calculateInstalledSize( 14431 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14432 14433 try { 14434 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14435 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14436 installFlags, packageAbiOverride); 14437 } catch (InstallerException e) { 14438 Slog.w(TAG, "Failed to free cache", e); 14439 } 14440 14441 /* 14442 * The cache free must have deleted the file we 14443 * downloaded to install. 14444 * 14445 * TODO: fix the "freeCache" call to not delete 14446 * the file we care about. 14447 */ 14448 if (pkgLite.recommendedInstallLocation 14449 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14450 pkgLite.recommendedInstallLocation 14451 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14452 } 14453 } 14454 } 14455 14456 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14457 int loc = pkgLite.recommendedInstallLocation; 14458 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14459 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14460 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14461 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14462 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14463 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14464 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14465 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14466 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14467 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14468 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14469 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14470 } else { 14471 // Override with defaults if needed. 14472 loc = installLocationPolicy(pkgLite); 14473 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14474 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14475 } else if (!onSd && !onInt) { 14476 // Override install location with flags 14477 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14478 // Set the flag to install on external media. 14479 installFlags |= PackageManager.INSTALL_EXTERNAL; 14480 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14481 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14482 if (DEBUG_EPHEMERAL) { 14483 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14484 } 14485 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14486 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14487 |PackageManager.INSTALL_INTERNAL); 14488 } else { 14489 // Make sure the flag for installing on external 14490 // media is unset 14491 installFlags |= PackageManager.INSTALL_INTERNAL; 14492 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14493 } 14494 } 14495 } 14496 } 14497 14498 final InstallArgs args = createInstallArgs(this); 14499 mArgs = args; 14500 14501 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14502 // TODO: http://b/22976637 14503 // Apps installed for "all" users use the device owner to verify the app 14504 UserHandle verifierUser = getUser(); 14505 if (verifierUser == UserHandle.ALL) { 14506 verifierUser = UserHandle.SYSTEM; 14507 } 14508 14509 /* 14510 * Determine if we have any installed package verifiers. If we 14511 * do, then we'll defer to them to verify the packages. 14512 */ 14513 final int requiredUid = mRequiredVerifierPackage == null ? -1 14514 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14515 verifierUser.getIdentifier()); 14516 if (!origin.existing && requiredUid != -1 14517 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14518 final Intent verification = new Intent( 14519 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14520 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14521 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14522 PACKAGE_MIME_TYPE); 14523 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14524 14525 // Query all live verifiers based on current user state 14526 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14527 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14528 14529 if (DEBUG_VERIFY) { 14530 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14531 + verification.toString() + " with " + pkgLite.verifiers.length 14532 + " optional verifiers"); 14533 } 14534 14535 final int verificationId = mPendingVerificationToken++; 14536 14537 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14538 14539 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14540 installerPackageName); 14541 14542 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14543 installFlags); 14544 14545 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14546 pkgLite.packageName); 14547 14548 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14549 pkgLite.versionCode); 14550 14551 if (verificationInfo != null) { 14552 if (verificationInfo.originatingUri != null) { 14553 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14554 verificationInfo.originatingUri); 14555 } 14556 if (verificationInfo.referrer != null) { 14557 verification.putExtra(Intent.EXTRA_REFERRER, 14558 verificationInfo.referrer); 14559 } 14560 if (verificationInfo.originatingUid >= 0) { 14561 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14562 verificationInfo.originatingUid); 14563 } 14564 if (verificationInfo.installerUid >= 0) { 14565 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14566 verificationInfo.installerUid); 14567 } 14568 } 14569 14570 final PackageVerificationState verificationState = new PackageVerificationState( 14571 requiredUid, args); 14572 14573 mPendingVerification.append(verificationId, verificationState); 14574 14575 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14576 receivers, verificationState); 14577 14578 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14579 final long idleDuration = getVerificationTimeout(); 14580 14581 /* 14582 * If any sufficient verifiers were listed in the package 14583 * manifest, attempt to ask them. 14584 */ 14585 if (sufficientVerifiers != null) { 14586 final int N = sufficientVerifiers.size(); 14587 if (N == 0) { 14588 Slog.i(TAG, "Additional verifiers required, but none installed."); 14589 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14590 } else { 14591 for (int i = 0; i < N; i++) { 14592 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14593 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14594 verifierComponent.getPackageName(), idleDuration, 14595 verifierUser.getIdentifier(), false, "package verifier"); 14596 14597 final Intent sufficientIntent = new Intent(verification); 14598 sufficientIntent.setComponent(verifierComponent); 14599 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14600 } 14601 } 14602 } 14603 14604 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14605 mRequiredVerifierPackage, receivers); 14606 if (ret == PackageManager.INSTALL_SUCCEEDED 14607 && mRequiredVerifierPackage != null) { 14608 Trace.asyncTraceBegin( 14609 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14610 /* 14611 * Send the intent to the required verification agent, 14612 * but only start the verification timeout after the 14613 * target BroadcastReceivers have run. 14614 */ 14615 verification.setComponent(requiredVerifierComponent); 14616 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14617 mRequiredVerifierPackage, idleDuration, 14618 verifierUser.getIdentifier(), false, "package verifier"); 14619 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14620 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14621 new BroadcastReceiver() { 14622 @Override 14623 public void onReceive(Context context, Intent intent) { 14624 final Message msg = mHandler 14625 .obtainMessage(CHECK_PENDING_VERIFICATION); 14626 msg.arg1 = verificationId; 14627 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14628 } 14629 }, null, 0, null, null); 14630 14631 /* 14632 * We don't want the copy to proceed until verification 14633 * succeeds, so null out this field. 14634 */ 14635 mArgs = null; 14636 } 14637 } else { 14638 /* 14639 * No package verification is enabled, so immediately start 14640 * the remote call to initiate copy using temporary file. 14641 */ 14642 ret = args.copyApk(mContainerService, true); 14643 } 14644 } 14645 14646 mRet = ret; 14647 } 14648 14649 @Override 14650 void handleReturnCode() { 14651 // If mArgs is null, then MCS couldn't be reached. When it 14652 // reconnects, it will try again to install. At that point, this 14653 // will succeed. 14654 if (mArgs != null) { 14655 processPendingInstall(mArgs, mRet); 14656 } 14657 } 14658 14659 @Override 14660 void handleServiceError() { 14661 mArgs = createInstallArgs(this); 14662 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14663 } 14664 14665 public boolean isForwardLocked() { 14666 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14667 } 14668 } 14669 14670 /** 14671 * Used during creation of InstallArgs 14672 * 14673 * @param installFlags package installation flags 14674 * @return true if should be installed on external storage 14675 */ 14676 private static boolean installOnExternalAsec(int installFlags) { 14677 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14678 return false; 14679 } 14680 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14681 return true; 14682 } 14683 return false; 14684 } 14685 14686 /** 14687 * Used during creation of InstallArgs 14688 * 14689 * @param installFlags package installation flags 14690 * @return true if should be installed as forward locked 14691 */ 14692 private static boolean installForwardLocked(int installFlags) { 14693 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14694 } 14695 14696 private InstallArgs createInstallArgs(InstallParams params) { 14697 if (params.move != null) { 14698 return new MoveInstallArgs(params); 14699 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14700 return new AsecInstallArgs(params); 14701 } else { 14702 return new FileInstallArgs(params); 14703 } 14704 } 14705 14706 /** 14707 * Create args that describe an existing installed package. Typically used 14708 * when cleaning up old installs, or used as a move source. 14709 */ 14710 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14711 String resourcePath, String[] instructionSets) { 14712 final boolean isInAsec; 14713 if (installOnExternalAsec(installFlags)) { 14714 /* Apps on SD card are always in ASEC containers. */ 14715 isInAsec = true; 14716 } else if (installForwardLocked(installFlags) 14717 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14718 /* 14719 * Forward-locked apps are only in ASEC containers if they're the 14720 * new style 14721 */ 14722 isInAsec = true; 14723 } else { 14724 isInAsec = false; 14725 } 14726 14727 if (isInAsec) { 14728 return new AsecInstallArgs(codePath, instructionSets, 14729 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14730 } else { 14731 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14732 } 14733 } 14734 14735 static abstract class InstallArgs { 14736 /** @see InstallParams#origin */ 14737 final OriginInfo origin; 14738 /** @see InstallParams#move */ 14739 final MoveInfo move; 14740 14741 final IPackageInstallObserver2 observer; 14742 // Always refers to PackageManager flags only 14743 final int installFlags; 14744 final String installerPackageName; 14745 final String volumeUuid; 14746 final UserHandle user; 14747 final String abiOverride; 14748 final String[] installGrantPermissions; 14749 /** If non-null, drop an async trace when the install completes */ 14750 final String traceMethod; 14751 final int traceCookie; 14752 final Certificate[][] certificates; 14753 final int installReason; 14754 14755 // The list of instruction sets supported by this app. This is currently 14756 // only used during the rmdex() phase to clean up resources. We can get rid of this 14757 // if we move dex files under the common app path. 14758 /* nullable */ String[] instructionSets; 14759 14760 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14761 int installFlags, String installerPackageName, String volumeUuid, 14762 UserHandle user, String[] instructionSets, 14763 String abiOverride, String[] installGrantPermissions, 14764 String traceMethod, int traceCookie, Certificate[][] certificates, 14765 int installReason) { 14766 this.origin = origin; 14767 this.move = move; 14768 this.installFlags = installFlags; 14769 this.observer = observer; 14770 this.installerPackageName = installerPackageName; 14771 this.volumeUuid = volumeUuid; 14772 this.user = user; 14773 this.instructionSets = instructionSets; 14774 this.abiOverride = abiOverride; 14775 this.installGrantPermissions = installGrantPermissions; 14776 this.traceMethod = traceMethod; 14777 this.traceCookie = traceCookie; 14778 this.certificates = certificates; 14779 this.installReason = installReason; 14780 } 14781 14782 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14783 abstract int doPreInstall(int status); 14784 14785 /** 14786 * Rename package into final resting place. All paths on the given 14787 * scanned package should be updated to reflect the rename. 14788 */ 14789 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14790 abstract int doPostInstall(int status, int uid); 14791 14792 /** @see PackageSettingBase#codePathString */ 14793 abstract String getCodePath(); 14794 /** @see PackageSettingBase#resourcePathString */ 14795 abstract String getResourcePath(); 14796 14797 // Need installer lock especially for dex file removal. 14798 abstract void cleanUpResourcesLI(); 14799 abstract boolean doPostDeleteLI(boolean delete); 14800 14801 /** 14802 * Called before the source arguments are copied. This is used mostly 14803 * for MoveParams when it needs to read the source file to put it in the 14804 * destination. 14805 */ 14806 int doPreCopy() { 14807 return PackageManager.INSTALL_SUCCEEDED; 14808 } 14809 14810 /** 14811 * Called after the source arguments are copied. This is used mostly for 14812 * MoveParams when it needs to read the source file to put it in the 14813 * destination. 14814 */ 14815 int doPostCopy(int uid) { 14816 return PackageManager.INSTALL_SUCCEEDED; 14817 } 14818 14819 protected boolean isFwdLocked() { 14820 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14821 } 14822 14823 protected boolean isExternalAsec() { 14824 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14825 } 14826 14827 protected boolean isEphemeral() { 14828 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14829 } 14830 14831 UserHandle getUser() { 14832 return user; 14833 } 14834 } 14835 14836 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14837 if (!allCodePaths.isEmpty()) { 14838 if (instructionSets == null) { 14839 throw new IllegalStateException("instructionSet == null"); 14840 } 14841 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14842 for (String codePath : allCodePaths) { 14843 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14844 try { 14845 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14846 } catch (InstallerException ignored) { 14847 } 14848 } 14849 } 14850 } 14851 } 14852 14853 /** 14854 * Logic to handle installation of non-ASEC applications, including copying 14855 * and renaming logic. 14856 */ 14857 class FileInstallArgs extends InstallArgs { 14858 private File codeFile; 14859 private File resourceFile; 14860 14861 // Example topology: 14862 // /data/app/com.example/base.apk 14863 // /data/app/com.example/split_foo.apk 14864 // /data/app/com.example/lib/arm/libfoo.so 14865 // /data/app/com.example/lib/arm64/libfoo.so 14866 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14867 14868 /** New install */ 14869 FileInstallArgs(InstallParams params) { 14870 super(params.origin, params.move, params.observer, params.installFlags, 14871 params.installerPackageName, params.volumeUuid, 14872 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14873 params.grantedRuntimePermissions, 14874 params.traceMethod, params.traceCookie, params.certificates, 14875 params.installReason); 14876 if (isFwdLocked()) { 14877 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14878 } 14879 } 14880 14881 /** Existing install */ 14882 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14883 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14884 null, null, null, 0, null /*certificates*/, 14885 PackageManager.INSTALL_REASON_UNKNOWN); 14886 this.codeFile = (codePath != null) ? new File(codePath) : null; 14887 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14888 } 14889 14890 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14891 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14892 try { 14893 return doCopyApk(imcs, temp); 14894 } finally { 14895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14896 } 14897 } 14898 14899 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14900 if (origin.staged) { 14901 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14902 codeFile = origin.file; 14903 resourceFile = origin.file; 14904 return PackageManager.INSTALL_SUCCEEDED; 14905 } 14906 14907 try { 14908 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14909 final File tempDir = 14910 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14911 codeFile = tempDir; 14912 resourceFile = tempDir; 14913 } catch (IOException e) { 14914 Slog.w(TAG, "Failed to create copy file: " + e); 14915 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14916 } 14917 14918 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14919 @Override 14920 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14921 if (!FileUtils.isValidExtFilename(name)) { 14922 throw new IllegalArgumentException("Invalid filename: " + name); 14923 } 14924 try { 14925 final File file = new File(codeFile, name); 14926 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14927 O_RDWR | O_CREAT, 0644); 14928 Os.chmod(file.getAbsolutePath(), 0644); 14929 return new ParcelFileDescriptor(fd); 14930 } catch (ErrnoException e) { 14931 throw new RemoteException("Failed to open: " + e.getMessage()); 14932 } 14933 } 14934 }; 14935 14936 int ret = PackageManager.INSTALL_SUCCEEDED; 14937 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14938 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14939 Slog.e(TAG, "Failed to copy package"); 14940 return ret; 14941 } 14942 14943 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14944 NativeLibraryHelper.Handle handle = null; 14945 try { 14946 handle = NativeLibraryHelper.Handle.create(codeFile); 14947 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14948 abiOverride); 14949 } catch (IOException e) { 14950 Slog.e(TAG, "Copying native libraries failed", e); 14951 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14952 } finally { 14953 IoUtils.closeQuietly(handle); 14954 } 14955 14956 return ret; 14957 } 14958 14959 int doPreInstall(int status) { 14960 if (status != PackageManager.INSTALL_SUCCEEDED) { 14961 cleanUp(); 14962 } 14963 return status; 14964 } 14965 14966 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14967 if (status != PackageManager.INSTALL_SUCCEEDED) { 14968 cleanUp(); 14969 return false; 14970 } 14971 14972 final File targetDir = codeFile.getParentFile(); 14973 final File beforeCodeFile = codeFile; 14974 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14975 14976 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14977 try { 14978 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14979 } catch (ErrnoException e) { 14980 Slog.w(TAG, "Failed to rename", e); 14981 return false; 14982 } 14983 14984 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14985 Slog.w(TAG, "Failed to restorecon"); 14986 return false; 14987 } 14988 14989 // Reflect the rename internally 14990 codeFile = afterCodeFile; 14991 resourceFile = afterCodeFile; 14992 14993 // Reflect the rename in scanned details 14994 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14995 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14996 afterCodeFile, pkg.baseCodePath)); 14997 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14998 afterCodeFile, pkg.splitCodePaths)); 14999 15000 // Reflect the rename in app info 15001 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15002 pkg.setApplicationInfoCodePath(pkg.codePath); 15003 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15004 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15005 pkg.setApplicationInfoResourcePath(pkg.codePath); 15006 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15007 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15008 15009 return true; 15010 } 15011 15012 int doPostInstall(int status, int uid) { 15013 if (status != PackageManager.INSTALL_SUCCEEDED) { 15014 cleanUp(); 15015 } 15016 return status; 15017 } 15018 15019 @Override 15020 String getCodePath() { 15021 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15022 } 15023 15024 @Override 15025 String getResourcePath() { 15026 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15027 } 15028 15029 private boolean cleanUp() { 15030 if (codeFile == null || !codeFile.exists()) { 15031 return false; 15032 } 15033 15034 removeCodePathLI(codeFile); 15035 15036 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15037 resourceFile.delete(); 15038 } 15039 15040 return true; 15041 } 15042 15043 void cleanUpResourcesLI() { 15044 // Try enumerating all code paths before deleting 15045 List<String> allCodePaths = Collections.EMPTY_LIST; 15046 if (codeFile != null && codeFile.exists()) { 15047 try { 15048 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15049 allCodePaths = pkg.getAllCodePaths(); 15050 } catch (PackageParserException e) { 15051 // Ignored; we tried our best 15052 } 15053 } 15054 15055 cleanUp(); 15056 removeDexFiles(allCodePaths, instructionSets); 15057 } 15058 15059 boolean doPostDeleteLI(boolean delete) { 15060 // XXX err, shouldn't we respect the delete flag? 15061 cleanUpResourcesLI(); 15062 return true; 15063 } 15064 } 15065 15066 private boolean isAsecExternal(String cid) { 15067 final String asecPath = PackageHelper.getSdFilesystem(cid); 15068 return !asecPath.startsWith(mAsecInternalPath); 15069 } 15070 15071 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15072 PackageManagerException { 15073 if (copyRet < 0) { 15074 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15075 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15076 throw new PackageManagerException(copyRet, message); 15077 } 15078 } 15079 } 15080 15081 /** 15082 * Extract the StorageManagerService "container ID" from the full code path of an 15083 * .apk. 15084 */ 15085 static String cidFromCodePath(String fullCodePath) { 15086 int eidx = fullCodePath.lastIndexOf("/"); 15087 String subStr1 = fullCodePath.substring(0, eidx); 15088 int sidx = subStr1.lastIndexOf("/"); 15089 return subStr1.substring(sidx+1, eidx); 15090 } 15091 15092 /** 15093 * Logic to handle installation of ASEC applications, including copying and 15094 * renaming logic. 15095 */ 15096 class AsecInstallArgs extends InstallArgs { 15097 static final String RES_FILE_NAME = "pkg.apk"; 15098 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15099 15100 String cid; 15101 String packagePath; 15102 String resourcePath; 15103 15104 /** New install */ 15105 AsecInstallArgs(InstallParams params) { 15106 super(params.origin, params.move, params.observer, params.installFlags, 15107 params.installerPackageName, params.volumeUuid, 15108 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15109 params.grantedRuntimePermissions, 15110 params.traceMethod, params.traceCookie, params.certificates, 15111 params.installReason); 15112 } 15113 15114 /** Existing install */ 15115 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15116 boolean isExternal, boolean isForwardLocked) { 15117 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15118 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15119 instructionSets, null, null, null, 0, null /*certificates*/, 15120 PackageManager.INSTALL_REASON_UNKNOWN); 15121 // Hackily pretend we're still looking at a full code path 15122 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15123 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15124 } 15125 15126 // Extract cid from fullCodePath 15127 int eidx = fullCodePath.lastIndexOf("/"); 15128 String subStr1 = fullCodePath.substring(0, eidx); 15129 int sidx = subStr1.lastIndexOf("/"); 15130 cid = subStr1.substring(sidx+1, eidx); 15131 setMountPath(subStr1); 15132 } 15133 15134 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15135 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15136 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15137 instructionSets, null, null, null, 0, null /*certificates*/, 15138 PackageManager.INSTALL_REASON_UNKNOWN); 15139 this.cid = cid; 15140 setMountPath(PackageHelper.getSdDir(cid)); 15141 } 15142 15143 void createCopyFile() { 15144 cid = mInstallerService.allocateExternalStageCidLegacy(); 15145 } 15146 15147 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15148 if (origin.staged && origin.cid != null) { 15149 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15150 cid = origin.cid; 15151 setMountPath(PackageHelper.getSdDir(cid)); 15152 return PackageManager.INSTALL_SUCCEEDED; 15153 } 15154 15155 if (temp) { 15156 createCopyFile(); 15157 } else { 15158 /* 15159 * Pre-emptively destroy the container since it's destroyed if 15160 * copying fails due to it existing anyway. 15161 */ 15162 PackageHelper.destroySdDir(cid); 15163 } 15164 15165 final String newMountPath = imcs.copyPackageToContainer( 15166 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15167 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15168 15169 if (newMountPath != null) { 15170 setMountPath(newMountPath); 15171 return PackageManager.INSTALL_SUCCEEDED; 15172 } else { 15173 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15174 } 15175 } 15176 15177 @Override 15178 String getCodePath() { 15179 return packagePath; 15180 } 15181 15182 @Override 15183 String getResourcePath() { 15184 return resourcePath; 15185 } 15186 15187 int doPreInstall(int status) { 15188 if (status != PackageManager.INSTALL_SUCCEEDED) { 15189 // Destroy container 15190 PackageHelper.destroySdDir(cid); 15191 } else { 15192 boolean mounted = PackageHelper.isContainerMounted(cid); 15193 if (!mounted) { 15194 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15195 Process.SYSTEM_UID); 15196 if (newMountPath != null) { 15197 setMountPath(newMountPath); 15198 } else { 15199 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15200 } 15201 } 15202 } 15203 return status; 15204 } 15205 15206 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15207 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15208 String newMountPath = null; 15209 if (PackageHelper.isContainerMounted(cid)) { 15210 // Unmount the container 15211 if (!PackageHelper.unMountSdDir(cid)) { 15212 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15213 return false; 15214 } 15215 } 15216 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15217 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15218 " which might be stale. Will try to clean up."); 15219 // Clean up the stale container and proceed to recreate. 15220 if (!PackageHelper.destroySdDir(newCacheId)) { 15221 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15222 return false; 15223 } 15224 // Successfully cleaned up stale container. Try to rename again. 15225 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15226 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15227 + " inspite of cleaning it up."); 15228 return false; 15229 } 15230 } 15231 if (!PackageHelper.isContainerMounted(newCacheId)) { 15232 Slog.w(TAG, "Mounting container " + newCacheId); 15233 newMountPath = PackageHelper.mountSdDir(newCacheId, 15234 getEncryptKey(), Process.SYSTEM_UID); 15235 } else { 15236 newMountPath = PackageHelper.getSdDir(newCacheId); 15237 } 15238 if (newMountPath == null) { 15239 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15240 return false; 15241 } 15242 Log.i(TAG, "Succesfully renamed " + cid + 15243 " to " + newCacheId + 15244 " at new path: " + newMountPath); 15245 cid = newCacheId; 15246 15247 final File beforeCodeFile = new File(packagePath); 15248 setMountPath(newMountPath); 15249 final File afterCodeFile = new File(packagePath); 15250 15251 // Reflect the rename in scanned details 15252 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15253 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15254 afterCodeFile, pkg.baseCodePath)); 15255 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15256 afterCodeFile, pkg.splitCodePaths)); 15257 15258 // Reflect the rename in app info 15259 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15260 pkg.setApplicationInfoCodePath(pkg.codePath); 15261 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15262 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15263 pkg.setApplicationInfoResourcePath(pkg.codePath); 15264 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15265 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15266 15267 return true; 15268 } 15269 15270 private void setMountPath(String mountPath) { 15271 final File mountFile = new File(mountPath); 15272 15273 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15274 if (monolithicFile.exists()) { 15275 packagePath = monolithicFile.getAbsolutePath(); 15276 if (isFwdLocked()) { 15277 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15278 } else { 15279 resourcePath = packagePath; 15280 } 15281 } else { 15282 packagePath = mountFile.getAbsolutePath(); 15283 resourcePath = packagePath; 15284 } 15285 } 15286 15287 int doPostInstall(int status, int uid) { 15288 if (status != PackageManager.INSTALL_SUCCEEDED) { 15289 cleanUp(); 15290 } else { 15291 final int groupOwner; 15292 final String protectedFile; 15293 if (isFwdLocked()) { 15294 groupOwner = UserHandle.getSharedAppGid(uid); 15295 protectedFile = RES_FILE_NAME; 15296 } else { 15297 groupOwner = -1; 15298 protectedFile = null; 15299 } 15300 15301 if (uid < Process.FIRST_APPLICATION_UID 15302 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15303 Slog.e(TAG, "Failed to finalize " + cid); 15304 PackageHelper.destroySdDir(cid); 15305 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15306 } 15307 15308 boolean mounted = PackageHelper.isContainerMounted(cid); 15309 if (!mounted) { 15310 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15311 } 15312 } 15313 return status; 15314 } 15315 15316 private void cleanUp() { 15317 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15318 15319 // Destroy secure container 15320 PackageHelper.destroySdDir(cid); 15321 } 15322 15323 private List<String> getAllCodePaths() { 15324 final File codeFile = new File(getCodePath()); 15325 if (codeFile != null && codeFile.exists()) { 15326 try { 15327 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15328 return pkg.getAllCodePaths(); 15329 } catch (PackageParserException e) { 15330 // Ignored; we tried our best 15331 } 15332 } 15333 return Collections.EMPTY_LIST; 15334 } 15335 15336 void cleanUpResourcesLI() { 15337 // Enumerate all code paths before deleting 15338 cleanUpResourcesLI(getAllCodePaths()); 15339 } 15340 15341 private void cleanUpResourcesLI(List<String> allCodePaths) { 15342 cleanUp(); 15343 removeDexFiles(allCodePaths, instructionSets); 15344 } 15345 15346 String getPackageName() { 15347 return getAsecPackageName(cid); 15348 } 15349 15350 boolean doPostDeleteLI(boolean delete) { 15351 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15352 final List<String> allCodePaths = getAllCodePaths(); 15353 boolean mounted = PackageHelper.isContainerMounted(cid); 15354 if (mounted) { 15355 // Unmount first 15356 if (PackageHelper.unMountSdDir(cid)) { 15357 mounted = false; 15358 } 15359 } 15360 if (!mounted && delete) { 15361 cleanUpResourcesLI(allCodePaths); 15362 } 15363 return !mounted; 15364 } 15365 15366 @Override 15367 int doPreCopy() { 15368 if (isFwdLocked()) { 15369 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15370 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15371 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15372 } 15373 } 15374 15375 return PackageManager.INSTALL_SUCCEEDED; 15376 } 15377 15378 @Override 15379 int doPostCopy(int uid) { 15380 if (isFwdLocked()) { 15381 if (uid < Process.FIRST_APPLICATION_UID 15382 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15383 RES_FILE_NAME)) { 15384 Slog.e(TAG, "Failed to finalize " + cid); 15385 PackageHelper.destroySdDir(cid); 15386 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15387 } 15388 } 15389 15390 return PackageManager.INSTALL_SUCCEEDED; 15391 } 15392 } 15393 15394 /** 15395 * Logic to handle movement of existing installed applications. 15396 */ 15397 class MoveInstallArgs extends InstallArgs { 15398 private File codeFile; 15399 private File resourceFile; 15400 15401 /** New install */ 15402 MoveInstallArgs(InstallParams params) { 15403 super(params.origin, params.move, params.observer, params.installFlags, 15404 params.installerPackageName, params.volumeUuid, 15405 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15406 params.grantedRuntimePermissions, 15407 params.traceMethod, params.traceCookie, params.certificates, 15408 params.installReason); 15409 } 15410 15411 int copyApk(IMediaContainerService imcs, boolean temp) { 15412 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15413 + move.fromUuid + " to " + move.toUuid); 15414 synchronized (mInstaller) { 15415 try { 15416 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15417 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15418 } catch (InstallerException e) { 15419 Slog.w(TAG, "Failed to move app", e); 15420 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15421 } 15422 } 15423 15424 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15425 resourceFile = codeFile; 15426 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15427 15428 return PackageManager.INSTALL_SUCCEEDED; 15429 } 15430 15431 int doPreInstall(int status) { 15432 if (status != PackageManager.INSTALL_SUCCEEDED) { 15433 cleanUp(move.toUuid); 15434 } 15435 return status; 15436 } 15437 15438 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15439 if (status != PackageManager.INSTALL_SUCCEEDED) { 15440 cleanUp(move.toUuid); 15441 return false; 15442 } 15443 15444 // Reflect the move in app info 15445 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15446 pkg.setApplicationInfoCodePath(pkg.codePath); 15447 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15448 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15449 pkg.setApplicationInfoResourcePath(pkg.codePath); 15450 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15451 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15452 15453 return true; 15454 } 15455 15456 int doPostInstall(int status, int uid) { 15457 if (status == PackageManager.INSTALL_SUCCEEDED) { 15458 cleanUp(move.fromUuid); 15459 } else { 15460 cleanUp(move.toUuid); 15461 } 15462 return status; 15463 } 15464 15465 @Override 15466 String getCodePath() { 15467 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15468 } 15469 15470 @Override 15471 String getResourcePath() { 15472 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15473 } 15474 15475 private boolean cleanUp(String volumeUuid) { 15476 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15477 move.dataAppName); 15478 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15479 final int[] userIds = sUserManager.getUserIds(); 15480 synchronized (mInstallLock) { 15481 // Clean up both app data and code 15482 // All package moves are frozen until finished 15483 for (int userId : userIds) { 15484 try { 15485 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15486 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15487 } catch (InstallerException e) { 15488 Slog.w(TAG, String.valueOf(e)); 15489 } 15490 } 15491 removeCodePathLI(codeFile); 15492 } 15493 return true; 15494 } 15495 15496 void cleanUpResourcesLI() { 15497 throw new UnsupportedOperationException(); 15498 } 15499 15500 boolean doPostDeleteLI(boolean delete) { 15501 throw new UnsupportedOperationException(); 15502 } 15503 } 15504 15505 static String getAsecPackageName(String packageCid) { 15506 int idx = packageCid.lastIndexOf("-"); 15507 if (idx == -1) { 15508 return packageCid; 15509 } 15510 return packageCid.substring(0, idx); 15511 } 15512 15513 // Utility method used to create code paths based on package name and available index. 15514 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15515 String idxStr = ""; 15516 int idx = 1; 15517 // Fall back to default value of idx=1 if prefix is not 15518 // part of oldCodePath 15519 if (oldCodePath != null) { 15520 String subStr = oldCodePath; 15521 // Drop the suffix right away 15522 if (suffix != null && subStr.endsWith(suffix)) { 15523 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15524 } 15525 // If oldCodePath already contains prefix find out the 15526 // ending index to either increment or decrement. 15527 int sidx = subStr.lastIndexOf(prefix); 15528 if (sidx != -1) { 15529 subStr = subStr.substring(sidx + prefix.length()); 15530 if (subStr != null) { 15531 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15532 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15533 } 15534 try { 15535 idx = Integer.parseInt(subStr); 15536 if (idx <= 1) { 15537 idx++; 15538 } else { 15539 idx--; 15540 } 15541 } catch(NumberFormatException e) { 15542 } 15543 } 15544 } 15545 } 15546 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15547 return prefix + idxStr; 15548 } 15549 15550 private File getNextCodePath(File targetDir, String packageName) { 15551 File result; 15552 SecureRandom random = new SecureRandom(); 15553 byte[] bytes = new byte[16]; 15554 do { 15555 random.nextBytes(bytes); 15556 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15557 result = new File(targetDir, packageName + "-" + suffix); 15558 } while (result.exists()); 15559 return result; 15560 } 15561 15562 // Utility method that returns the relative package path with respect 15563 // to the installation directory. Like say for /data/data/com.test-1.apk 15564 // string com.test-1 is returned. 15565 static String deriveCodePathName(String codePath) { 15566 if (codePath == null) { 15567 return null; 15568 } 15569 final File codeFile = new File(codePath); 15570 final String name = codeFile.getName(); 15571 if (codeFile.isDirectory()) { 15572 return name; 15573 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15574 final int lastDot = name.lastIndexOf('.'); 15575 return name.substring(0, lastDot); 15576 } else { 15577 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15578 return null; 15579 } 15580 } 15581 15582 static class PackageInstalledInfo { 15583 String name; 15584 int uid; 15585 // The set of users that originally had this package installed. 15586 int[] origUsers; 15587 // The set of users that now have this package installed. 15588 int[] newUsers; 15589 PackageParser.Package pkg; 15590 int returnCode; 15591 String returnMsg; 15592 PackageRemovedInfo removedInfo; 15593 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15594 15595 public void setError(int code, String msg) { 15596 setReturnCode(code); 15597 setReturnMessage(msg); 15598 Slog.w(TAG, msg); 15599 } 15600 15601 public void setError(String msg, PackageParserException e) { 15602 setReturnCode(e.error); 15603 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15604 Slog.w(TAG, msg, e); 15605 } 15606 15607 public void setError(String msg, PackageManagerException e) { 15608 returnCode = e.error; 15609 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15610 Slog.w(TAG, msg, e); 15611 } 15612 15613 public void setReturnCode(int returnCode) { 15614 this.returnCode = returnCode; 15615 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15616 for (int i = 0; i < childCount; i++) { 15617 addedChildPackages.valueAt(i).returnCode = returnCode; 15618 } 15619 } 15620 15621 private void setReturnMessage(String returnMsg) { 15622 this.returnMsg = returnMsg; 15623 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15624 for (int i = 0; i < childCount; i++) { 15625 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15626 } 15627 } 15628 15629 // In some error cases we want to convey more info back to the observer 15630 String origPackage; 15631 String origPermission; 15632 } 15633 15634 /* 15635 * Install a non-existing package. 15636 */ 15637 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15638 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15639 PackageInstalledInfo res, int installReason) { 15640 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15641 15642 // Remember this for later, in case we need to rollback this install 15643 String pkgName = pkg.packageName; 15644 15645 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15646 15647 synchronized(mPackages) { 15648 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15649 if (renamedPackage != null) { 15650 // A package with the same name is already installed, though 15651 // it has been renamed to an older name. The package we 15652 // are trying to install should be installed as an update to 15653 // the existing one, but that has not been requested, so bail. 15654 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15655 + " without first uninstalling package running as " 15656 + renamedPackage); 15657 return; 15658 } 15659 if (mPackages.containsKey(pkgName)) { 15660 // Don't allow installation over an existing package with the same name. 15661 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15662 + " without first uninstalling."); 15663 return; 15664 } 15665 } 15666 15667 try { 15668 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15669 System.currentTimeMillis(), user); 15670 15671 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15672 15673 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15674 prepareAppDataAfterInstallLIF(newPackage); 15675 15676 } else { 15677 // Remove package from internal structures, but keep around any 15678 // data that might have already existed 15679 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15680 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15681 } 15682 } catch (PackageManagerException e) { 15683 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15684 } 15685 15686 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15687 } 15688 15689 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15690 // Can't rotate keys during boot or if sharedUser. 15691 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15692 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15693 return false; 15694 } 15695 // app is using upgradeKeySets; make sure all are valid 15696 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15697 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15698 for (int i = 0; i < upgradeKeySets.length; i++) { 15699 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15700 Slog.wtf(TAG, "Package " 15701 + (oldPs.name != null ? oldPs.name : "<null>") 15702 + " contains upgrade-key-set reference to unknown key-set: " 15703 + upgradeKeySets[i] 15704 + " reverting to signatures check."); 15705 return false; 15706 } 15707 } 15708 return true; 15709 } 15710 15711 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15712 // Upgrade keysets are being used. Determine if new package has a superset of the 15713 // required keys. 15714 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15715 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15716 for (int i = 0; i < upgradeKeySets.length; i++) { 15717 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15718 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15719 return true; 15720 } 15721 } 15722 return false; 15723 } 15724 15725 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15726 try (DigestInputStream digestStream = 15727 new DigestInputStream(new FileInputStream(file), digest)) { 15728 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15729 } 15730 } 15731 15732 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15733 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15734 int installReason) { 15735 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15736 15737 final PackageParser.Package oldPackage; 15738 final String pkgName = pkg.packageName; 15739 final int[] allUsers; 15740 final int[] installedUsers; 15741 15742 synchronized(mPackages) { 15743 oldPackage = mPackages.get(pkgName); 15744 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15745 15746 // don't allow upgrade to target a release SDK from a pre-release SDK 15747 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15748 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15749 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15750 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15751 if (oldTargetsPreRelease 15752 && !newTargetsPreRelease 15753 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15754 Slog.w(TAG, "Can't install package targeting released sdk"); 15755 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15756 return; 15757 } 15758 15759 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15760 15761 // verify signatures are valid 15762 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15763 if (!checkUpgradeKeySetLP(ps, pkg)) { 15764 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15765 "New package not signed by keys specified by upgrade-keysets: " 15766 + pkgName); 15767 return; 15768 } 15769 } else { 15770 // default to original signature matching 15771 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15772 != PackageManager.SIGNATURE_MATCH) { 15773 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15774 "New package has a different signature: " + pkgName); 15775 return; 15776 } 15777 } 15778 15779 // don't allow a system upgrade unless the upgrade hash matches 15780 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15781 byte[] digestBytes = null; 15782 try { 15783 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15784 updateDigest(digest, new File(pkg.baseCodePath)); 15785 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15786 for (String path : pkg.splitCodePaths) { 15787 updateDigest(digest, new File(path)); 15788 } 15789 } 15790 digestBytes = digest.digest(); 15791 } catch (NoSuchAlgorithmException | IOException e) { 15792 res.setError(INSTALL_FAILED_INVALID_APK, 15793 "Could not compute hash: " + pkgName); 15794 return; 15795 } 15796 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15797 res.setError(INSTALL_FAILED_INVALID_APK, 15798 "New package fails restrict-update check: " + pkgName); 15799 return; 15800 } 15801 // retain upgrade restriction 15802 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15803 } 15804 15805 // Check for shared user id changes 15806 String invalidPackageName = 15807 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15808 if (invalidPackageName != null) { 15809 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15810 "Package " + invalidPackageName + " tried to change user " 15811 + oldPackage.mSharedUserId); 15812 return; 15813 } 15814 15815 // In case of rollback, remember per-user/profile install state 15816 allUsers = sUserManager.getUserIds(); 15817 installedUsers = ps.queryInstalledUsers(allUsers, true); 15818 15819 // don't allow an upgrade from full to ephemeral 15820 if (isInstantApp) { 15821 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15822 for (int currentUser : allUsers) { 15823 if (!ps.getInstantApp(currentUser)) { 15824 // can't downgrade from full to instant 15825 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15826 + " for user: " + currentUser); 15827 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15828 return; 15829 } 15830 } 15831 } else if (!ps.getInstantApp(user.getIdentifier())) { 15832 // can't downgrade from full to instant 15833 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15834 + " for user: " + user.getIdentifier()); 15835 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15836 return; 15837 } 15838 } 15839 } 15840 15841 // Update what is removed 15842 res.removedInfo = new PackageRemovedInfo(); 15843 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15844 res.removedInfo.removedPackage = oldPackage.packageName; 15845 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15846 res.removedInfo.isUpdate = true; 15847 res.removedInfo.origUsers = installedUsers; 15848 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15849 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15850 for (int i = 0; i < installedUsers.length; i++) { 15851 final int userId = installedUsers[i]; 15852 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15853 } 15854 15855 final int childCount = (oldPackage.childPackages != null) 15856 ? oldPackage.childPackages.size() : 0; 15857 for (int i = 0; i < childCount; i++) { 15858 boolean childPackageUpdated = false; 15859 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15860 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15861 if (res.addedChildPackages != null) { 15862 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15863 if (childRes != null) { 15864 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15865 childRes.removedInfo.removedPackage = childPkg.packageName; 15866 childRes.removedInfo.isUpdate = true; 15867 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15868 childPackageUpdated = true; 15869 } 15870 } 15871 if (!childPackageUpdated) { 15872 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15873 childRemovedRes.removedPackage = childPkg.packageName; 15874 childRemovedRes.isUpdate = false; 15875 childRemovedRes.dataRemoved = true; 15876 synchronized (mPackages) { 15877 if (childPs != null) { 15878 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15879 } 15880 } 15881 if (res.removedInfo.removedChildPackages == null) { 15882 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15883 } 15884 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15885 } 15886 } 15887 15888 boolean sysPkg = (isSystemApp(oldPackage)); 15889 if (sysPkg) { 15890 // Set the system/privileged flags as needed 15891 final boolean privileged = 15892 (oldPackage.applicationInfo.privateFlags 15893 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15894 final int systemPolicyFlags = policyFlags 15895 | PackageParser.PARSE_IS_SYSTEM 15896 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15897 15898 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15899 user, allUsers, installerPackageName, res, installReason); 15900 } else { 15901 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15902 user, allUsers, installerPackageName, res, installReason); 15903 } 15904 } 15905 15906 public List<String> getPreviousCodePaths(String packageName) { 15907 final PackageSetting ps = mSettings.mPackages.get(packageName); 15908 final List<String> result = new ArrayList<String>(); 15909 if (ps != null && ps.oldCodePaths != null) { 15910 result.addAll(ps.oldCodePaths); 15911 } 15912 return result; 15913 } 15914 15915 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15916 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15917 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15918 int installReason) { 15919 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15920 + deletedPackage); 15921 15922 String pkgName = deletedPackage.packageName; 15923 boolean deletedPkg = true; 15924 boolean addedPkg = false; 15925 boolean updatedSettings = false; 15926 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15927 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15928 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15929 15930 final long origUpdateTime = (pkg.mExtras != null) 15931 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15932 15933 // First delete the existing package while retaining the data directory 15934 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15935 res.removedInfo, true, pkg)) { 15936 // If the existing package wasn't successfully deleted 15937 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15938 deletedPkg = false; 15939 } else { 15940 // Successfully deleted the old package; proceed with replace. 15941 15942 // If deleted package lived in a container, give users a chance to 15943 // relinquish resources before killing. 15944 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15945 if (DEBUG_INSTALL) { 15946 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15947 } 15948 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15949 final ArrayList<String> pkgList = new ArrayList<String>(1); 15950 pkgList.add(deletedPackage.applicationInfo.packageName); 15951 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15952 } 15953 15954 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15955 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15956 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15957 15958 try { 15959 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15960 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15961 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15962 installReason); 15963 15964 // Update the in-memory copy of the previous code paths. 15965 PackageSetting ps = mSettings.mPackages.get(pkgName); 15966 if (!killApp) { 15967 if (ps.oldCodePaths == null) { 15968 ps.oldCodePaths = new ArraySet<>(); 15969 } 15970 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15971 if (deletedPackage.splitCodePaths != null) { 15972 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15973 } 15974 } else { 15975 ps.oldCodePaths = null; 15976 } 15977 if (ps.childPackageNames != null) { 15978 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15979 final String childPkgName = ps.childPackageNames.get(i); 15980 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15981 childPs.oldCodePaths = ps.oldCodePaths; 15982 } 15983 } 15984 // set instant app status, but, only if it's explicitly specified 15985 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15986 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 15987 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 15988 prepareAppDataAfterInstallLIF(newPackage); 15989 addedPkg = true; 15990 mDexManager.notifyPackageUpdated(newPackage.packageName, 15991 newPackage.baseCodePath, newPackage.splitCodePaths); 15992 } catch (PackageManagerException e) { 15993 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15994 } 15995 } 15996 15997 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15998 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15999 16000 // Revert all internal state mutations and added folders for the failed install 16001 if (addedPkg) { 16002 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16003 res.removedInfo, true, null); 16004 } 16005 16006 // Restore the old package 16007 if (deletedPkg) { 16008 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16009 File restoreFile = new File(deletedPackage.codePath); 16010 // Parse old package 16011 boolean oldExternal = isExternal(deletedPackage); 16012 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16013 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16014 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16015 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16016 try { 16017 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16018 null); 16019 } catch (PackageManagerException e) { 16020 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16021 + e.getMessage()); 16022 return; 16023 } 16024 16025 synchronized (mPackages) { 16026 // Ensure the installer package name up to date 16027 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16028 16029 // Update permissions for restored package 16030 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16031 16032 mSettings.writeLPr(); 16033 } 16034 16035 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16036 } 16037 } else { 16038 synchronized (mPackages) { 16039 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16040 if (ps != null) { 16041 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16042 if (res.removedInfo.removedChildPackages != null) { 16043 final int childCount = res.removedInfo.removedChildPackages.size(); 16044 // Iterate in reverse as we may modify the collection 16045 for (int i = childCount - 1; i >= 0; i--) { 16046 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16047 if (res.addedChildPackages.containsKey(childPackageName)) { 16048 res.removedInfo.removedChildPackages.removeAt(i); 16049 } else { 16050 PackageRemovedInfo childInfo = res.removedInfo 16051 .removedChildPackages.valueAt(i); 16052 childInfo.removedForAllUsers = mPackages.get( 16053 childInfo.removedPackage) == null; 16054 } 16055 } 16056 } 16057 } 16058 } 16059 } 16060 } 16061 16062 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16063 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16064 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16065 int installReason) { 16066 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16067 + ", old=" + deletedPackage); 16068 16069 final boolean disabledSystem; 16070 16071 // Remove existing system package 16072 removePackageLI(deletedPackage, true); 16073 16074 synchronized (mPackages) { 16075 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16076 } 16077 if (!disabledSystem) { 16078 // We didn't need to disable the .apk as a current system package, 16079 // which means we are replacing another update that is already 16080 // installed. We need to make sure to delete the older one's .apk. 16081 res.removedInfo.args = createInstallArgsForExisting(0, 16082 deletedPackage.applicationInfo.getCodePath(), 16083 deletedPackage.applicationInfo.getResourcePath(), 16084 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16085 } else { 16086 res.removedInfo.args = null; 16087 } 16088 16089 // Successfully disabled the old package. Now proceed with re-installation 16090 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16091 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16092 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16093 16094 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16095 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16096 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16097 16098 PackageParser.Package newPackage = null; 16099 try { 16100 // Add the package to the internal data structures 16101 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16102 16103 // Set the update and install times 16104 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16105 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16106 System.currentTimeMillis()); 16107 16108 // Update the package dynamic state if succeeded 16109 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16110 // Now that the install succeeded make sure we remove data 16111 // directories for any child package the update removed. 16112 final int deletedChildCount = (deletedPackage.childPackages != null) 16113 ? deletedPackage.childPackages.size() : 0; 16114 final int newChildCount = (newPackage.childPackages != null) 16115 ? newPackage.childPackages.size() : 0; 16116 for (int i = 0; i < deletedChildCount; i++) { 16117 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16118 boolean childPackageDeleted = true; 16119 for (int j = 0; j < newChildCount; j++) { 16120 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16121 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16122 childPackageDeleted = false; 16123 break; 16124 } 16125 } 16126 if (childPackageDeleted) { 16127 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16128 deletedChildPkg.packageName); 16129 if (ps != null && res.removedInfo.removedChildPackages != null) { 16130 PackageRemovedInfo removedChildRes = res.removedInfo 16131 .removedChildPackages.get(deletedChildPkg.packageName); 16132 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16133 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16134 } 16135 } 16136 } 16137 16138 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16139 installReason); 16140 prepareAppDataAfterInstallLIF(newPackage); 16141 16142 mDexManager.notifyPackageUpdated(newPackage.packageName, 16143 newPackage.baseCodePath, newPackage.splitCodePaths); 16144 } 16145 } catch (PackageManagerException e) { 16146 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16147 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16148 } 16149 16150 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16151 // Re installation failed. Restore old information 16152 // Remove new pkg information 16153 if (newPackage != null) { 16154 removeInstalledPackageLI(newPackage, true); 16155 } 16156 // Add back the old system package 16157 try { 16158 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16159 } catch (PackageManagerException e) { 16160 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16161 } 16162 16163 synchronized (mPackages) { 16164 if (disabledSystem) { 16165 enableSystemPackageLPw(deletedPackage); 16166 } 16167 16168 // Ensure the installer package name up to date 16169 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16170 16171 // Update permissions for restored package 16172 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16173 16174 mSettings.writeLPr(); 16175 } 16176 16177 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16178 + " after failed upgrade"); 16179 } 16180 } 16181 16182 /** 16183 * Checks whether the parent or any of the child packages have a change shared 16184 * user. For a package to be a valid update the shred users of the parent and 16185 * the children should match. We may later support changing child shared users. 16186 * @param oldPkg The updated package. 16187 * @param newPkg The update package. 16188 * @return The shared user that change between the versions. 16189 */ 16190 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16191 PackageParser.Package newPkg) { 16192 // Check parent shared user 16193 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16194 return newPkg.packageName; 16195 } 16196 // Check child shared users 16197 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16198 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16199 for (int i = 0; i < newChildCount; i++) { 16200 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16201 // If this child was present, did it have the same shared user? 16202 for (int j = 0; j < oldChildCount; j++) { 16203 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16204 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16205 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16206 return newChildPkg.packageName; 16207 } 16208 } 16209 } 16210 return null; 16211 } 16212 16213 private void removeNativeBinariesLI(PackageSetting ps) { 16214 // Remove the lib path for the parent package 16215 if (ps != null) { 16216 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16217 // Remove the lib path for the child packages 16218 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16219 for (int i = 0; i < childCount; i++) { 16220 PackageSetting childPs = null; 16221 synchronized (mPackages) { 16222 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16223 } 16224 if (childPs != null) { 16225 NativeLibraryHelper.removeNativeBinariesLI(childPs 16226 .legacyNativeLibraryPathString); 16227 } 16228 } 16229 } 16230 } 16231 16232 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16233 // Enable the parent package 16234 mSettings.enableSystemPackageLPw(pkg.packageName); 16235 // Enable the child packages 16236 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16237 for (int i = 0; i < childCount; i++) { 16238 PackageParser.Package childPkg = pkg.childPackages.get(i); 16239 mSettings.enableSystemPackageLPw(childPkg.packageName); 16240 } 16241 } 16242 16243 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16244 PackageParser.Package newPkg) { 16245 // Disable the parent package (parent always replaced) 16246 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16247 // Disable the child packages 16248 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16249 for (int i = 0; i < childCount; i++) { 16250 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16251 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16252 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16253 } 16254 return disabled; 16255 } 16256 16257 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16258 String installerPackageName) { 16259 // Enable the parent package 16260 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16261 // Enable the child packages 16262 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16263 for (int i = 0; i < childCount; i++) { 16264 PackageParser.Package childPkg = pkg.childPackages.get(i); 16265 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16266 } 16267 } 16268 16269 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16270 // Collect all used permissions in the UID 16271 ArraySet<String> usedPermissions = new ArraySet<>(); 16272 final int packageCount = su.packages.size(); 16273 for (int i = 0; i < packageCount; i++) { 16274 PackageSetting ps = su.packages.valueAt(i); 16275 if (ps.pkg == null) { 16276 continue; 16277 } 16278 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16279 for (int j = 0; j < requestedPermCount; j++) { 16280 String permission = ps.pkg.requestedPermissions.get(j); 16281 BasePermission bp = mSettings.mPermissions.get(permission); 16282 if (bp != null) { 16283 usedPermissions.add(permission); 16284 } 16285 } 16286 } 16287 16288 PermissionsState permissionsState = su.getPermissionsState(); 16289 // Prune install permissions 16290 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16291 final int installPermCount = installPermStates.size(); 16292 for (int i = installPermCount - 1; i >= 0; i--) { 16293 PermissionState permissionState = installPermStates.get(i); 16294 if (!usedPermissions.contains(permissionState.getName())) { 16295 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16296 if (bp != null) { 16297 permissionsState.revokeInstallPermission(bp); 16298 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16299 PackageManager.MASK_PERMISSION_FLAGS, 0); 16300 } 16301 } 16302 } 16303 16304 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16305 16306 // Prune runtime permissions 16307 for (int userId : allUserIds) { 16308 List<PermissionState> runtimePermStates = permissionsState 16309 .getRuntimePermissionStates(userId); 16310 final int runtimePermCount = runtimePermStates.size(); 16311 for (int i = runtimePermCount - 1; i >= 0; i--) { 16312 PermissionState permissionState = runtimePermStates.get(i); 16313 if (!usedPermissions.contains(permissionState.getName())) { 16314 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16315 if (bp != null) { 16316 permissionsState.revokeRuntimePermission(bp, userId); 16317 permissionsState.updatePermissionFlags(bp, userId, 16318 PackageManager.MASK_PERMISSION_FLAGS, 0); 16319 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16320 runtimePermissionChangedUserIds, userId); 16321 } 16322 } 16323 } 16324 } 16325 16326 return runtimePermissionChangedUserIds; 16327 } 16328 16329 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16330 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16331 // Update the parent package setting 16332 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16333 res, user, installReason); 16334 // Update the child packages setting 16335 final int childCount = (newPackage.childPackages != null) 16336 ? newPackage.childPackages.size() : 0; 16337 for (int i = 0; i < childCount; i++) { 16338 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16339 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16340 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16341 childRes.origUsers, childRes, user, installReason); 16342 } 16343 } 16344 16345 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16346 String installerPackageName, int[] allUsers, int[] installedForUsers, 16347 PackageInstalledInfo res, UserHandle user, int installReason) { 16348 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16349 16350 String pkgName = newPackage.packageName; 16351 synchronized (mPackages) { 16352 //write settings. the installStatus will be incomplete at this stage. 16353 //note that the new package setting would have already been 16354 //added to mPackages. It hasn't been persisted yet. 16355 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16356 // TODO: Remove this write? It's also written at the end of this method 16357 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16358 mSettings.writeLPr(); 16359 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16360 } 16361 16362 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16363 synchronized (mPackages) { 16364 updatePermissionsLPw(newPackage.packageName, newPackage, 16365 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16366 ? UPDATE_PERMISSIONS_ALL : 0)); 16367 // For system-bundled packages, we assume that installing an upgraded version 16368 // of the package implies that the user actually wants to run that new code, 16369 // so we enable the package. 16370 PackageSetting ps = mSettings.mPackages.get(pkgName); 16371 final int userId = user.getIdentifier(); 16372 if (ps != null) { 16373 if (isSystemApp(newPackage)) { 16374 if (DEBUG_INSTALL) { 16375 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16376 } 16377 // Enable system package for requested users 16378 if (res.origUsers != null) { 16379 for (int origUserId : res.origUsers) { 16380 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16381 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16382 origUserId, installerPackageName); 16383 } 16384 } 16385 } 16386 // Also convey the prior install/uninstall state 16387 if (allUsers != null && installedForUsers != null) { 16388 for (int currentUserId : allUsers) { 16389 final boolean installed = ArrayUtils.contains( 16390 installedForUsers, currentUserId); 16391 if (DEBUG_INSTALL) { 16392 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16393 } 16394 ps.setInstalled(installed, currentUserId); 16395 } 16396 // these install state changes will be persisted in the 16397 // upcoming call to mSettings.writeLPr(). 16398 } 16399 } 16400 // It's implied that when a user requests installation, they want the app to be 16401 // installed and enabled. 16402 if (userId != UserHandle.USER_ALL) { 16403 ps.setInstalled(true, userId); 16404 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16405 } 16406 16407 // When replacing an existing package, preserve the original install reason for all 16408 // users that had the package installed before. 16409 final Set<Integer> previousUserIds = new ArraySet<>(); 16410 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16411 final int installReasonCount = res.removedInfo.installReasons.size(); 16412 for (int i = 0; i < installReasonCount; i++) { 16413 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16414 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16415 ps.setInstallReason(previousInstallReason, previousUserId); 16416 previousUserIds.add(previousUserId); 16417 } 16418 } 16419 16420 // Set install reason for users that are having the package newly installed. 16421 if (userId == UserHandle.USER_ALL) { 16422 for (int currentUserId : sUserManager.getUserIds()) { 16423 if (!previousUserIds.contains(currentUserId)) { 16424 ps.setInstallReason(installReason, currentUserId); 16425 } 16426 } 16427 } else if (!previousUserIds.contains(userId)) { 16428 ps.setInstallReason(installReason, userId); 16429 } 16430 mSettings.writeKernelMappingLPr(ps); 16431 } 16432 res.name = pkgName; 16433 res.uid = newPackage.applicationInfo.uid; 16434 res.pkg = newPackage; 16435 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16436 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16437 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16438 //to update install status 16439 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16440 mSettings.writeLPr(); 16441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16442 } 16443 16444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16445 } 16446 16447 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16448 try { 16449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16450 installPackageLI(args, res); 16451 } finally { 16452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16453 } 16454 } 16455 16456 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16457 final int installFlags = args.installFlags; 16458 final String installerPackageName = args.installerPackageName; 16459 final String volumeUuid = args.volumeUuid; 16460 final File tmpPackageFile = new File(args.getCodePath()); 16461 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16462 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16463 || (args.volumeUuid != null)); 16464 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16465 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16466 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16467 boolean replace = false; 16468 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16469 if (args.move != null) { 16470 // moving a complete application; perform an initial scan on the new install location 16471 scanFlags |= SCAN_INITIAL; 16472 } 16473 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16474 scanFlags |= SCAN_DONT_KILL_APP; 16475 } 16476 if (instantApp) { 16477 scanFlags |= SCAN_AS_INSTANT_APP; 16478 } 16479 if (fullApp) { 16480 scanFlags |= SCAN_AS_FULL_APP; 16481 } 16482 16483 // Result object to be returned 16484 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16485 16486 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16487 16488 // Sanity check 16489 if (instantApp && (forwardLocked || onExternal)) { 16490 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16491 + " external=" + onExternal); 16492 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16493 return; 16494 } 16495 16496 // Retrieve PackageSettings and parse package 16497 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16498 | PackageParser.PARSE_ENFORCE_CODE 16499 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16500 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16501 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16502 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16503 PackageParser pp = new PackageParser(); 16504 pp.setSeparateProcesses(mSeparateProcesses); 16505 pp.setDisplayMetrics(mMetrics); 16506 pp.setCallback(mPackageParserCallback); 16507 16508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16509 final PackageParser.Package pkg; 16510 try { 16511 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16512 } catch (PackageParserException e) { 16513 res.setError("Failed parse during installPackageLI", e); 16514 return; 16515 } finally { 16516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16517 } 16518 16519 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16520 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16521 Slog.w(TAG, "Instant app package " + pkg.packageName 16522 + " does not target O, this will be a fatal error."); 16523 // STOPSHIP: Make this a fatal error 16524 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16525 } 16526 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16527 Slog.w(TAG, "Instant app package " + pkg.packageName 16528 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16529 // STOPSHIP: Make this a fatal error 16530 pkg.applicationInfo.targetSandboxVersion = 2; 16531 } 16532 16533 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16534 // Static shared libraries have synthetic package names 16535 renameStaticSharedLibraryPackage(pkg); 16536 16537 // No static shared libs on external storage 16538 if (onExternal) { 16539 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16540 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16541 "Packages declaring static-shared libs cannot be updated"); 16542 return; 16543 } 16544 } 16545 16546 // If we are installing a clustered package add results for the children 16547 if (pkg.childPackages != null) { 16548 synchronized (mPackages) { 16549 final int childCount = pkg.childPackages.size(); 16550 for (int i = 0; i < childCount; i++) { 16551 PackageParser.Package childPkg = pkg.childPackages.get(i); 16552 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16553 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16554 childRes.pkg = childPkg; 16555 childRes.name = childPkg.packageName; 16556 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16557 if (childPs != null) { 16558 childRes.origUsers = childPs.queryInstalledUsers( 16559 sUserManager.getUserIds(), true); 16560 } 16561 if ((mPackages.containsKey(childPkg.packageName))) { 16562 childRes.removedInfo = new PackageRemovedInfo(); 16563 childRes.removedInfo.removedPackage = childPkg.packageName; 16564 } 16565 if (res.addedChildPackages == null) { 16566 res.addedChildPackages = new ArrayMap<>(); 16567 } 16568 res.addedChildPackages.put(childPkg.packageName, childRes); 16569 } 16570 } 16571 } 16572 16573 // If package doesn't declare API override, mark that we have an install 16574 // time CPU ABI override. 16575 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16576 pkg.cpuAbiOverride = args.abiOverride; 16577 } 16578 16579 String pkgName = res.name = pkg.packageName; 16580 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16581 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16582 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16583 return; 16584 } 16585 } 16586 16587 try { 16588 // either use what we've been given or parse directly from the APK 16589 if (args.certificates != null) { 16590 try { 16591 PackageParser.populateCertificates(pkg, args.certificates); 16592 } catch (PackageParserException e) { 16593 // there was something wrong with the certificates we were given; 16594 // try to pull them from the APK 16595 PackageParser.collectCertificates(pkg, parseFlags); 16596 } 16597 } else { 16598 PackageParser.collectCertificates(pkg, parseFlags); 16599 } 16600 } catch (PackageParserException e) { 16601 res.setError("Failed collect during installPackageLI", e); 16602 return; 16603 } 16604 16605 // Get rid of all references to package scan path via parser. 16606 pp = null; 16607 String oldCodePath = null; 16608 boolean systemApp = false; 16609 synchronized (mPackages) { 16610 // Check if installing already existing package 16611 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16612 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16613 if (pkg.mOriginalPackages != null 16614 && pkg.mOriginalPackages.contains(oldName) 16615 && mPackages.containsKey(oldName)) { 16616 // This package is derived from an original package, 16617 // and this device has been updating from that original 16618 // name. We must continue using the original name, so 16619 // rename the new package here. 16620 pkg.setPackageName(oldName); 16621 pkgName = pkg.packageName; 16622 replace = true; 16623 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16624 + oldName + " pkgName=" + pkgName); 16625 } else if (mPackages.containsKey(pkgName)) { 16626 // This package, under its official name, already exists 16627 // on the device; we should replace it. 16628 replace = true; 16629 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16630 } 16631 16632 // Child packages are installed through the parent package 16633 if (pkg.parentPackage != null) { 16634 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16635 "Package " + pkg.packageName + " is child of package " 16636 + pkg.parentPackage.parentPackage + ". Child packages " 16637 + "can be updated only through the parent package."); 16638 return; 16639 } 16640 16641 if (replace) { 16642 // Prevent apps opting out from runtime permissions 16643 PackageParser.Package oldPackage = mPackages.get(pkgName); 16644 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16645 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16646 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16647 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16648 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16649 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16650 + " doesn't support runtime permissions but the old" 16651 + " target SDK " + oldTargetSdk + " does."); 16652 return; 16653 } 16654 16655 // Prevent installing of child packages 16656 if (oldPackage.parentPackage != null) { 16657 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16658 "Package " + pkg.packageName + " is child of package " 16659 + oldPackage.parentPackage + ". Child packages " 16660 + "can be updated only through the parent package."); 16661 return; 16662 } 16663 } 16664 } 16665 16666 PackageSetting ps = mSettings.mPackages.get(pkgName); 16667 if (ps != null) { 16668 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16669 16670 // Static shared libs have same package with different versions where 16671 // we internally use a synthetic package name to allow multiple versions 16672 // of the same package, therefore we need to compare signatures against 16673 // the package setting for the latest library version. 16674 PackageSetting signatureCheckPs = ps; 16675 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16676 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16677 if (libraryEntry != null) { 16678 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16679 } 16680 } 16681 16682 // Quick sanity check that we're signed correctly if updating; 16683 // we'll check this again later when scanning, but we want to 16684 // bail early here before tripping over redefined permissions. 16685 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16686 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16687 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16688 + pkg.packageName + " upgrade keys do not match the " 16689 + "previously installed version"); 16690 return; 16691 } 16692 } else { 16693 try { 16694 verifySignaturesLP(signatureCheckPs, pkg); 16695 } catch (PackageManagerException e) { 16696 res.setError(e.error, e.getMessage()); 16697 return; 16698 } 16699 } 16700 16701 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16702 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16703 systemApp = (ps.pkg.applicationInfo.flags & 16704 ApplicationInfo.FLAG_SYSTEM) != 0; 16705 } 16706 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16707 } 16708 16709 int N = pkg.permissions.size(); 16710 for (int i = N-1; i >= 0; i--) { 16711 PackageParser.Permission perm = pkg.permissions.get(i); 16712 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16713 16714 // Don't allow anyone but the platform to define ephemeral permissions. 16715 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16716 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16717 Slog.w(TAG, "Package " + pkg.packageName 16718 + " attempting to delcare ephemeral permission " 16719 + perm.info.name + "; Removing ephemeral."); 16720 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16721 } 16722 // Check whether the newly-scanned package wants to define an already-defined perm 16723 if (bp != null) { 16724 // If the defining package is signed with our cert, it's okay. This 16725 // also includes the "updating the same package" case, of course. 16726 // "updating same package" could also involve key-rotation. 16727 final boolean sigsOk; 16728 if (bp.sourcePackage.equals(pkg.packageName) 16729 && (bp.packageSetting instanceof PackageSetting) 16730 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16731 scanFlags))) { 16732 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16733 } else { 16734 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16735 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16736 } 16737 if (!sigsOk) { 16738 // If the owning package is the system itself, we log but allow 16739 // install to proceed; we fail the install on all other permission 16740 // redefinitions. 16741 if (!bp.sourcePackage.equals("android")) { 16742 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16743 + pkg.packageName + " attempting to redeclare permission " 16744 + perm.info.name + " already owned by " + bp.sourcePackage); 16745 res.origPermission = perm.info.name; 16746 res.origPackage = bp.sourcePackage; 16747 return; 16748 } else { 16749 Slog.w(TAG, "Package " + pkg.packageName 16750 + " attempting to redeclare system permission " 16751 + perm.info.name + "; ignoring new declaration"); 16752 pkg.permissions.remove(i); 16753 } 16754 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16755 // Prevent apps to change protection level to dangerous from any other 16756 // type as this would allow a privilege escalation where an app adds a 16757 // normal/signature permission in other app's group and later redefines 16758 // it as dangerous leading to the group auto-grant. 16759 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16760 == PermissionInfo.PROTECTION_DANGEROUS) { 16761 if (bp != null && !bp.isRuntime()) { 16762 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16763 + "non-runtime permission " + perm.info.name 16764 + " to runtime; keeping old protection level"); 16765 perm.info.protectionLevel = bp.protectionLevel; 16766 } 16767 } 16768 } 16769 } 16770 } 16771 } 16772 16773 if (systemApp) { 16774 if (onExternal) { 16775 // Abort update; system app can't be replaced with app on sdcard 16776 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16777 "Cannot install updates to system apps on sdcard"); 16778 return; 16779 } else if (instantApp) { 16780 // Abort update; system app can't be replaced with an instant app 16781 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16782 "Cannot update a system app with an instant app"); 16783 return; 16784 } 16785 } 16786 16787 if (args.move != null) { 16788 // We did an in-place move, so dex is ready to roll 16789 scanFlags |= SCAN_NO_DEX; 16790 scanFlags |= SCAN_MOVE; 16791 16792 synchronized (mPackages) { 16793 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16794 if (ps == null) { 16795 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16796 "Missing settings for moved package " + pkgName); 16797 } 16798 16799 // We moved the entire application as-is, so bring over the 16800 // previously derived ABI information. 16801 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16802 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16803 } 16804 16805 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16806 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16807 scanFlags |= SCAN_NO_DEX; 16808 16809 try { 16810 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16811 args.abiOverride : pkg.cpuAbiOverride); 16812 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16813 true /*extractLibs*/, mAppLib32InstallDir); 16814 } catch (PackageManagerException pme) { 16815 Slog.e(TAG, "Error deriving application ABI", pme); 16816 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16817 return; 16818 } 16819 16820 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16821 // Do not run PackageDexOptimizer through the local performDexOpt 16822 // method because `pkg` may not be in `mPackages` yet. 16823 // 16824 // Also, don't fail application installs if the dexopt step fails. 16825 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16826 null /* instructionSets */, false /* checkProfiles */, 16827 getCompilerFilterForReason(REASON_INSTALL), 16828 getOrCreateCompilerPackageStats(pkg), 16829 mDexManager.isUsedByOtherApps(pkg.packageName)); 16830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16831 16832 // Notify BackgroundDexOptService that the package has been changed. 16833 // If this is an update of a package which used to fail to compile, 16834 // BDOS will remove it from its blacklist. 16835 // TODO: Layering violation 16836 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16837 } 16838 16839 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16840 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16841 return; 16842 } 16843 16844 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16845 16846 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16847 "installPackageLI")) { 16848 if (replace) { 16849 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16850 // Static libs have a synthetic package name containing the version 16851 // and cannot be updated as an update would get a new package name, 16852 // unless this is the exact same version code which is useful for 16853 // development. 16854 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16855 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16856 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16857 + "static-shared libs cannot be updated"); 16858 return; 16859 } 16860 } 16861 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16862 installerPackageName, res, args.installReason); 16863 } else { 16864 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16865 args.user, installerPackageName, volumeUuid, res, args.installReason); 16866 } 16867 } 16868 synchronized (mPackages) { 16869 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16870 if (ps != null) { 16871 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16872 ps.setUpdateAvailable(false /*updateAvailable*/); 16873 } 16874 16875 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16876 for (int i = 0; i < childCount; i++) { 16877 PackageParser.Package childPkg = pkg.childPackages.get(i); 16878 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16879 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16880 if (childPs != null) { 16881 childRes.newUsers = childPs.queryInstalledUsers( 16882 sUserManager.getUserIds(), true); 16883 } 16884 } 16885 16886 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16887 updateSequenceNumberLP(pkgName, res.newUsers); 16888 } 16889 } 16890 } 16891 16892 private void startIntentFilterVerifications(int userId, boolean replacing, 16893 PackageParser.Package pkg) { 16894 if (mIntentFilterVerifierComponent == null) { 16895 Slog.w(TAG, "No IntentFilter verification will not be done as " 16896 + "there is no IntentFilterVerifier available!"); 16897 return; 16898 } 16899 16900 final int verifierUid = getPackageUid( 16901 mIntentFilterVerifierComponent.getPackageName(), 16902 MATCH_DEBUG_TRIAGED_MISSING, 16903 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16904 16905 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16906 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16907 mHandler.sendMessage(msg); 16908 16909 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16910 for (int i = 0; i < childCount; i++) { 16911 PackageParser.Package childPkg = pkg.childPackages.get(i); 16912 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16913 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16914 mHandler.sendMessage(msg); 16915 } 16916 } 16917 16918 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16919 PackageParser.Package pkg) { 16920 int size = pkg.activities.size(); 16921 if (size == 0) { 16922 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16923 "No activity, so no need to verify any IntentFilter!"); 16924 return; 16925 } 16926 16927 final boolean hasDomainURLs = hasDomainURLs(pkg); 16928 if (!hasDomainURLs) { 16929 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16930 "No domain URLs, so no need to verify any IntentFilter!"); 16931 return; 16932 } 16933 16934 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16935 + " if any IntentFilter from the " + size 16936 + " Activities needs verification ..."); 16937 16938 int count = 0; 16939 final String packageName = pkg.packageName; 16940 16941 synchronized (mPackages) { 16942 // If this is a new install and we see that we've already run verification for this 16943 // package, we have nothing to do: it means the state was restored from backup. 16944 if (!replacing) { 16945 IntentFilterVerificationInfo ivi = 16946 mSettings.getIntentFilterVerificationLPr(packageName); 16947 if (ivi != null) { 16948 if (DEBUG_DOMAIN_VERIFICATION) { 16949 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16950 + ivi.getStatusString()); 16951 } 16952 return; 16953 } 16954 } 16955 16956 // If any filters need to be verified, then all need to be. 16957 boolean needToVerify = false; 16958 for (PackageParser.Activity a : pkg.activities) { 16959 for (ActivityIntentInfo filter : a.intents) { 16960 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16961 if (DEBUG_DOMAIN_VERIFICATION) { 16962 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16963 } 16964 needToVerify = true; 16965 break; 16966 } 16967 } 16968 } 16969 16970 if (needToVerify) { 16971 final int verificationId = mIntentFilterVerificationToken++; 16972 for (PackageParser.Activity a : pkg.activities) { 16973 for (ActivityIntentInfo filter : a.intents) { 16974 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16975 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16976 "Verification needed for IntentFilter:" + filter.toString()); 16977 mIntentFilterVerifier.addOneIntentFilterVerification( 16978 verifierUid, userId, verificationId, filter, packageName); 16979 count++; 16980 } 16981 } 16982 } 16983 } 16984 } 16985 16986 if (count > 0) { 16987 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16988 + " IntentFilter verification" + (count > 1 ? "s" : "") 16989 + " for userId:" + userId); 16990 mIntentFilterVerifier.startVerifications(userId); 16991 } else { 16992 if (DEBUG_DOMAIN_VERIFICATION) { 16993 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16994 } 16995 } 16996 } 16997 16998 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16999 final ComponentName cn = filter.activity.getComponentName(); 17000 final String packageName = cn.getPackageName(); 17001 17002 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17003 packageName); 17004 if (ivi == null) { 17005 return true; 17006 } 17007 int status = ivi.getStatus(); 17008 switch (status) { 17009 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17010 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17011 return true; 17012 17013 default: 17014 // Nothing to do 17015 return false; 17016 } 17017 } 17018 17019 private static boolean isMultiArch(ApplicationInfo info) { 17020 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17021 } 17022 17023 private static boolean isExternal(PackageParser.Package pkg) { 17024 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17025 } 17026 17027 private static boolean isExternal(PackageSetting ps) { 17028 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17029 } 17030 17031 private static boolean isSystemApp(PackageParser.Package pkg) { 17032 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17033 } 17034 17035 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17036 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17037 } 17038 17039 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17040 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17041 } 17042 17043 private static boolean isSystemApp(PackageSetting ps) { 17044 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17045 } 17046 17047 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17048 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17049 } 17050 17051 private int packageFlagsToInstallFlags(PackageSetting ps) { 17052 int installFlags = 0; 17053 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17054 // This existing package was an external ASEC install when we have 17055 // the external flag without a UUID 17056 installFlags |= PackageManager.INSTALL_EXTERNAL; 17057 } 17058 if (ps.isForwardLocked()) { 17059 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17060 } 17061 return installFlags; 17062 } 17063 17064 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17065 if (isExternal(pkg)) { 17066 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17067 return StorageManager.UUID_PRIMARY_PHYSICAL; 17068 } else { 17069 return pkg.volumeUuid; 17070 } 17071 } else { 17072 return StorageManager.UUID_PRIVATE_INTERNAL; 17073 } 17074 } 17075 17076 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17077 if (isExternal(pkg)) { 17078 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17079 return mSettings.getExternalVersion(); 17080 } else { 17081 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17082 } 17083 } else { 17084 return mSettings.getInternalVersion(); 17085 } 17086 } 17087 17088 private void deleteTempPackageFiles() { 17089 final FilenameFilter filter = new FilenameFilter() { 17090 public boolean accept(File dir, String name) { 17091 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17092 } 17093 }; 17094 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17095 file.delete(); 17096 } 17097 } 17098 17099 @Override 17100 public void deletePackageAsUser(String packageName, int versionCode, 17101 IPackageDeleteObserver observer, int userId, int flags) { 17102 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17103 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17104 } 17105 17106 @Override 17107 public void deletePackageVersioned(VersionedPackage versionedPackage, 17108 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17109 mContext.enforceCallingOrSelfPermission( 17110 android.Manifest.permission.DELETE_PACKAGES, null); 17111 Preconditions.checkNotNull(versionedPackage); 17112 Preconditions.checkNotNull(observer); 17113 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17114 PackageManager.VERSION_CODE_HIGHEST, 17115 Integer.MAX_VALUE, "versionCode must be >= -1"); 17116 17117 final String packageName = versionedPackage.getPackageName(); 17118 // TODO: We will change version code to long, so in the new API it is long 17119 final int versionCode = (int) versionedPackage.getVersionCode(); 17120 final String internalPackageName; 17121 synchronized (mPackages) { 17122 // Normalize package name to handle renamed packages and static libs 17123 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17124 // TODO: We will change version code to long, so in the new API it is long 17125 (int) versionedPackage.getVersionCode()); 17126 } 17127 17128 final int uid = Binder.getCallingUid(); 17129 if (!isOrphaned(internalPackageName) 17130 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17131 try { 17132 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17133 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17134 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17135 observer.onUserActionRequired(intent); 17136 } catch (RemoteException re) { 17137 } 17138 return; 17139 } 17140 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17141 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17142 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17143 mContext.enforceCallingOrSelfPermission( 17144 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17145 "deletePackage for user " + userId); 17146 } 17147 17148 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17149 try { 17150 observer.onPackageDeleted(packageName, 17151 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17152 } catch (RemoteException re) { 17153 } 17154 return; 17155 } 17156 17157 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17158 try { 17159 observer.onPackageDeleted(packageName, 17160 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17161 } catch (RemoteException re) { 17162 } 17163 return; 17164 } 17165 17166 if (DEBUG_REMOVE) { 17167 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17168 + " deleteAllUsers: " + deleteAllUsers + " version=" 17169 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17170 ? "VERSION_CODE_HIGHEST" : versionCode)); 17171 } 17172 // Queue up an async operation since the package deletion may take a little while. 17173 mHandler.post(new Runnable() { 17174 public void run() { 17175 mHandler.removeCallbacks(this); 17176 int returnCode; 17177 if (!deleteAllUsers) { 17178 returnCode = deletePackageX(internalPackageName, versionCode, 17179 userId, deleteFlags); 17180 } else { 17181 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17182 internalPackageName, users); 17183 // If nobody is blocking uninstall, proceed with delete for all users 17184 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17185 returnCode = deletePackageX(internalPackageName, versionCode, 17186 userId, deleteFlags); 17187 } else { 17188 // Otherwise uninstall individually for users with blockUninstalls=false 17189 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17190 for (int userId : users) { 17191 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17192 returnCode = deletePackageX(internalPackageName, versionCode, 17193 userId, userFlags); 17194 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17195 Slog.w(TAG, "Package delete failed for user " + userId 17196 + ", returnCode " + returnCode); 17197 } 17198 } 17199 } 17200 // The app has only been marked uninstalled for certain users. 17201 // We still need to report that delete was blocked 17202 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17203 } 17204 } 17205 try { 17206 observer.onPackageDeleted(packageName, returnCode, null); 17207 } catch (RemoteException e) { 17208 Log.i(TAG, "Observer no longer exists."); 17209 } //end catch 17210 } //end run 17211 }); 17212 } 17213 17214 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17215 if (pkg.staticSharedLibName != null) { 17216 return pkg.manifestPackageName; 17217 } 17218 return pkg.packageName; 17219 } 17220 17221 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17222 // Handle renamed packages 17223 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17224 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17225 17226 // Is this a static library? 17227 SparseArray<SharedLibraryEntry> versionedLib = 17228 mStaticLibsByDeclaringPackage.get(packageName); 17229 if (versionedLib == null || versionedLib.size() <= 0) { 17230 return packageName; 17231 } 17232 17233 // Figure out which lib versions the caller can see 17234 SparseIntArray versionsCallerCanSee = null; 17235 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17236 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17237 && callingAppId != Process.ROOT_UID) { 17238 versionsCallerCanSee = new SparseIntArray(); 17239 String libName = versionedLib.valueAt(0).info.getName(); 17240 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17241 if (uidPackages != null) { 17242 for (String uidPackage : uidPackages) { 17243 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17244 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17245 if (libIdx >= 0) { 17246 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17247 versionsCallerCanSee.append(libVersion, libVersion); 17248 } 17249 } 17250 } 17251 } 17252 17253 // Caller can see nothing - done 17254 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17255 return packageName; 17256 } 17257 17258 // Find the version the caller can see and the app version code 17259 SharedLibraryEntry highestVersion = null; 17260 final int versionCount = versionedLib.size(); 17261 for (int i = 0; i < versionCount; i++) { 17262 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17263 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17264 libEntry.info.getVersion()) < 0) { 17265 continue; 17266 } 17267 // TODO: We will change version code to long, so in the new API it is long 17268 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17269 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17270 if (libVersionCode == versionCode) { 17271 return libEntry.apk; 17272 } 17273 } else if (highestVersion == null) { 17274 highestVersion = libEntry; 17275 } else if (libVersionCode > highestVersion.info 17276 .getDeclaringPackage().getVersionCode()) { 17277 highestVersion = libEntry; 17278 } 17279 } 17280 17281 if (highestVersion != null) { 17282 return highestVersion.apk; 17283 } 17284 17285 return packageName; 17286 } 17287 17288 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17289 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17290 || callingUid == Process.SYSTEM_UID) { 17291 return true; 17292 } 17293 final int callingUserId = UserHandle.getUserId(callingUid); 17294 // If the caller installed the pkgName, then allow it to silently uninstall. 17295 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17296 return true; 17297 } 17298 17299 // Allow package verifier to silently uninstall. 17300 if (mRequiredVerifierPackage != null && 17301 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17302 return true; 17303 } 17304 17305 // Allow package uninstaller to silently uninstall. 17306 if (mRequiredUninstallerPackage != null && 17307 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17308 return true; 17309 } 17310 17311 // Allow storage manager to silently uninstall. 17312 if (mStorageManagerPackage != null && 17313 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17314 return true; 17315 } 17316 return false; 17317 } 17318 17319 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17320 int[] result = EMPTY_INT_ARRAY; 17321 for (int userId : userIds) { 17322 if (getBlockUninstallForUser(packageName, userId)) { 17323 result = ArrayUtils.appendInt(result, userId); 17324 } 17325 } 17326 return result; 17327 } 17328 17329 @Override 17330 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17331 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17332 } 17333 17334 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17335 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17336 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17337 try { 17338 if (dpm != null) { 17339 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17340 /* callingUserOnly =*/ false); 17341 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17342 : deviceOwnerComponentName.getPackageName(); 17343 // Does the package contains the device owner? 17344 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17345 // this check is probably not needed, since DO should be registered as a device 17346 // admin on some user too. (Original bug for this: b/17657954) 17347 if (packageName.equals(deviceOwnerPackageName)) { 17348 return true; 17349 } 17350 // Does it contain a device admin for any user? 17351 int[] users; 17352 if (userId == UserHandle.USER_ALL) { 17353 users = sUserManager.getUserIds(); 17354 } else { 17355 users = new int[]{userId}; 17356 } 17357 for (int i = 0; i < users.length; ++i) { 17358 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17359 return true; 17360 } 17361 } 17362 } 17363 } catch (RemoteException e) { 17364 } 17365 return false; 17366 } 17367 17368 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17369 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17370 } 17371 17372 /** 17373 * This method is an internal method that could be get invoked either 17374 * to delete an installed package or to clean up a failed installation. 17375 * After deleting an installed package, a broadcast is sent to notify any 17376 * listeners that the package has been removed. For cleaning up a failed 17377 * installation, the broadcast is not necessary since the package's 17378 * installation wouldn't have sent the initial broadcast either 17379 * The key steps in deleting a package are 17380 * deleting the package information in internal structures like mPackages, 17381 * deleting the packages base directories through installd 17382 * updating mSettings to reflect current status 17383 * persisting settings for later use 17384 * sending a broadcast if necessary 17385 */ 17386 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17387 final PackageRemovedInfo info = new PackageRemovedInfo(); 17388 final boolean res; 17389 17390 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17391 ? UserHandle.USER_ALL : userId; 17392 17393 if (isPackageDeviceAdmin(packageName, removeUser)) { 17394 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17395 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17396 } 17397 17398 PackageSetting uninstalledPs = null; 17399 PackageParser.Package pkg = null; 17400 17401 // for the uninstall-updates case and restricted profiles, remember the per- 17402 // user handle installed state 17403 int[] allUsers; 17404 synchronized (mPackages) { 17405 uninstalledPs = mSettings.mPackages.get(packageName); 17406 if (uninstalledPs == null) { 17407 Slog.w(TAG, "Not removing non-existent package " + packageName); 17408 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17409 } 17410 17411 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17412 && uninstalledPs.versionCode != versionCode) { 17413 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17414 + uninstalledPs.versionCode + " != " + versionCode); 17415 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17416 } 17417 17418 // Static shared libs can be declared by any package, so let us not 17419 // allow removing a package if it provides a lib others depend on. 17420 pkg = mPackages.get(packageName); 17421 if (pkg != null && pkg.staticSharedLibName != null) { 17422 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17423 pkg.staticSharedLibVersion); 17424 if (libEntry != null) { 17425 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17426 libEntry.info, 0, userId); 17427 if (!ArrayUtils.isEmpty(libClientPackages)) { 17428 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17429 + " hosting lib " + libEntry.info.getName() + " version " 17430 + libEntry.info.getVersion() + " used by " + libClientPackages); 17431 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17432 } 17433 } 17434 } 17435 17436 allUsers = sUserManager.getUserIds(); 17437 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17438 } 17439 17440 final int freezeUser; 17441 if (isUpdatedSystemApp(uninstalledPs) 17442 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17443 // We're downgrading a system app, which will apply to all users, so 17444 // freeze them all during the downgrade 17445 freezeUser = UserHandle.USER_ALL; 17446 } else { 17447 freezeUser = removeUser; 17448 } 17449 17450 synchronized (mInstallLock) { 17451 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17452 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17453 deleteFlags, "deletePackageX")) { 17454 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17455 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17456 } 17457 synchronized (mPackages) { 17458 if (res) { 17459 if (pkg != null) { 17460 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17461 } 17462 updateSequenceNumberLP(packageName, info.removedUsers); 17463 } 17464 } 17465 } 17466 17467 if (res) { 17468 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17469 info.sendPackageRemovedBroadcasts(killApp); 17470 info.sendSystemPackageUpdatedBroadcasts(); 17471 info.sendSystemPackageAppearedBroadcasts(); 17472 } 17473 // Force a gc here. 17474 Runtime.getRuntime().gc(); 17475 // Delete the resources here after sending the broadcast to let 17476 // other processes clean up before deleting resources. 17477 if (info.args != null) { 17478 synchronized (mInstallLock) { 17479 info.args.doPostDeleteLI(true); 17480 } 17481 } 17482 17483 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17484 } 17485 17486 class PackageRemovedInfo { 17487 String removedPackage; 17488 int uid = -1; 17489 int removedAppId = -1; 17490 int[] origUsers; 17491 int[] removedUsers = null; 17492 SparseArray<Integer> installReasons; 17493 boolean isRemovedPackageSystemUpdate = false; 17494 boolean isUpdate; 17495 boolean dataRemoved; 17496 boolean removedForAllUsers; 17497 boolean isStaticSharedLib; 17498 // Clean up resources deleted packages. 17499 InstallArgs args = null; 17500 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17501 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17502 17503 void sendPackageRemovedBroadcasts(boolean killApp) { 17504 sendPackageRemovedBroadcastInternal(killApp); 17505 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17506 for (int i = 0; i < childCount; i++) { 17507 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17508 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17509 } 17510 } 17511 17512 void sendSystemPackageUpdatedBroadcasts() { 17513 if (isRemovedPackageSystemUpdate) { 17514 sendSystemPackageUpdatedBroadcastsInternal(); 17515 final int childCount = (removedChildPackages != null) 17516 ? removedChildPackages.size() : 0; 17517 for (int i = 0; i < childCount; i++) { 17518 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17519 if (childInfo.isRemovedPackageSystemUpdate) { 17520 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17521 } 17522 } 17523 } 17524 } 17525 17526 void sendSystemPackageAppearedBroadcasts() { 17527 final int packageCount = (appearedChildPackages != null) 17528 ? appearedChildPackages.size() : 0; 17529 for (int i = 0; i < packageCount; i++) { 17530 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17531 sendPackageAddedForNewUsers(installedInfo.name, true, 17532 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17533 } 17534 } 17535 17536 private void sendSystemPackageUpdatedBroadcastsInternal() { 17537 Bundle extras = new Bundle(2); 17538 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17539 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17540 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17541 extras, 0, null, null, null); 17542 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17543 extras, 0, null, null, null); 17544 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17545 null, 0, removedPackage, null, null); 17546 } 17547 17548 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17549 // Don't send static shared library removal broadcasts as these 17550 // libs are visible only the the apps that depend on them an one 17551 // cannot remove the library if it has a dependency. 17552 if (isStaticSharedLib) { 17553 return; 17554 } 17555 Bundle extras = new Bundle(2); 17556 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17557 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17558 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17559 if (isUpdate || isRemovedPackageSystemUpdate) { 17560 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17561 } 17562 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17563 if (removedPackage != null) { 17564 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17565 extras, 0, null, null, removedUsers); 17566 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17567 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17568 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17569 null, null, removedUsers); 17570 } 17571 } 17572 if (removedAppId >= 0) { 17573 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17574 removedUsers); 17575 } 17576 } 17577 } 17578 17579 /* 17580 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17581 * flag is not set, the data directory is removed as well. 17582 * make sure this flag is set for partially installed apps. If not its meaningless to 17583 * delete a partially installed application. 17584 */ 17585 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17586 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17587 String packageName = ps.name; 17588 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17589 // Retrieve object to delete permissions for shared user later on 17590 final PackageParser.Package deletedPkg; 17591 final PackageSetting deletedPs; 17592 // reader 17593 synchronized (mPackages) { 17594 deletedPkg = mPackages.get(packageName); 17595 deletedPs = mSettings.mPackages.get(packageName); 17596 if (outInfo != null) { 17597 outInfo.removedPackage = packageName; 17598 outInfo.isStaticSharedLib = deletedPkg != null 17599 && deletedPkg.staticSharedLibName != null; 17600 outInfo.removedUsers = deletedPs != null 17601 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17602 : null; 17603 } 17604 } 17605 17606 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17607 17608 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17609 final PackageParser.Package resolvedPkg; 17610 if (deletedPkg != null) { 17611 resolvedPkg = deletedPkg; 17612 } else { 17613 // We don't have a parsed package when it lives on an ejected 17614 // adopted storage device, so fake something together 17615 resolvedPkg = new PackageParser.Package(ps.name); 17616 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17617 } 17618 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17619 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17620 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17621 if (outInfo != null) { 17622 outInfo.dataRemoved = true; 17623 } 17624 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17625 } 17626 17627 int removedAppId = -1; 17628 17629 // writer 17630 synchronized (mPackages) { 17631 boolean installedStateChanged = false; 17632 if (deletedPs != null) { 17633 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17634 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17635 clearDefaultBrowserIfNeeded(packageName); 17636 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17637 removedAppId = mSettings.removePackageLPw(packageName); 17638 if (outInfo != null) { 17639 outInfo.removedAppId = removedAppId; 17640 } 17641 updatePermissionsLPw(deletedPs.name, null, 0); 17642 if (deletedPs.sharedUser != null) { 17643 // Remove permissions associated with package. Since runtime 17644 // permissions are per user we have to kill the removed package 17645 // or packages running under the shared user of the removed 17646 // package if revoking the permissions requested only by the removed 17647 // package is successful and this causes a change in gids. 17648 for (int userId : UserManagerService.getInstance().getUserIds()) { 17649 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17650 userId); 17651 if (userIdToKill == UserHandle.USER_ALL 17652 || userIdToKill >= UserHandle.USER_SYSTEM) { 17653 // If gids changed for this user, kill all affected packages. 17654 mHandler.post(new Runnable() { 17655 @Override 17656 public void run() { 17657 // This has to happen with no lock held. 17658 killApplication(deletedPs.name, deletedPs.appId, 17659 KILL_APP_REASON_GIDS_CHANGED); 17660 } 17661 }); 17662 break; 17663 } 17664 } 17665 } 17666 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17667 } 17668 // make sure to preserve per-user disabled state if this removal was just 17669 // a downgrade of a system app to the factory package 17670 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17671 if (DEBUG_REMOVE) { 17672 Slog.d(TAG, "Propagating install state across downgrade"); 17673 } 17674 for (int userId : allUserHandles) { 17675 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17676 if (DEBUG_REMOVE) { 17677 Slog.d(TAG, " user " + userId + " => " + installed); 17678 } 17679 if (installed != ps.getInstalled(userId)) { 17680 installedStateChanged = true; 17681 } 17682 ps.setInstalled(installed, userId); 17683 } 17684 } 17685 } 17686 // can downgrade to reader 17687 if (writeSettings) { 17688 // Save settings now 17689 mSettings.writeLPr(); 17690 } 17691 if (installedStateChanged) { 17692 mSettings.writeKernelMappingLPr(ps); 17693 } 17694 } 17695 if (removedAppId != -1) { 17696 // A user ID was deleted here. Go through all users and remove it 17697 // from KeyStore. 17698 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17699 } 17700 } 17701 17702 static boolean locationIsPrivileged(File path) { 17703 try { 17704 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17705 .getCanonicalPath(); 17706 return path.getCanonicalPath().startsWith(privilegedAppDir); 17707 } catch (IOException e) { 17708 Slog.e(TAG, "Unable to access code path " + path); 17709 } 17710 return false; 17711 } 17712 17713 /* 17714 * Tries to delete system package. 17715 */ 17716 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17717 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17718 boolean writeSettings) { 17719 if (deletedPs.parentPackageName != null) { 17720 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17721 return false; 17722 } 17723 17724 final boolean applyUserRestrictions 17725 = (allUserHandles != null) && (outInfo.origUsers != null); 17726 final PackageSetting disabledPs; 17727 // Confirm if the system package has been updated 17728 // An updated system app can be deleted. This will also have to restore 17729 // the system pkg from system partition 17730 // reader 17731 synchronized (mPackages) { 17732 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17733 } 17734 17735 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17736 + " disabledPs=" + disabledPs); 17737 17738 if (disabledPs == null) { 17739 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17740 return false; 17741 } else if (DEBUG_REMOVE) { 17742 Slog.d(TAG, "Deleting system pkg from data partition"); 17743 } 17744 17745 if (DEBUG_REMOVE) { 17746 if (applyUserRestrictions) { 17747 Slog.d(TAG, "Remembering install states:"); 17748 for (int userId : allUserHandles) { 17749 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17750 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17751 } 17752 } 17753 } 17754 17755 // Delete the updated package 17756 outInfo.isRemovedPackageSystemUpdate = true; 17757 if (outInfo.removedChildPackages != null) { 17758 final int childCount = (deletedPs.childPackageNames != null) 17759 ? deletedPs.childPackageNames.size() : 0; 17760 for (int i = 0; i < childCount; i++) { 17761 String childPackageName = deletedPs.childPackageNames.get(i); 17762 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17763 .contains(childPackageName)) { 17764 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17765 childPackageName); 17766 if (childInfo != null) { 17767 childInfo.isRemovedPackageSystemUpdate = true; 17768 } 17769 } 17770 } 17771 } 17772 17773 if (disabledPs.versionCode < deletedPs.versionCode) { 17774 // Delete data for downgrades 17775 flags &= ~PackageManager.DELETE_KEEP_DATA; 17776 } else { 17777 // Preserve data by setting flag 17778 flags |= PackageManager.DELETE_KEEP_DATA; 17779 } 17780 17781 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17782 outInfo, writeSettings, disabledPs.pkg); 17783 if (!ret) { 17784 return false; 17785 } 17786 17787 // writer 17788 synchronized (mPackages) { 17789 // Reinstate the old system package 17790 enableSystemPackageLPw(disabledPs.pkg); 17791 // Remove any native libraries from the upgraded package. 17792 removeNativeBinariesLI(deletedPs); 17793 } 17794 17795 // Install the system package 17796 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17797 int parseFlags = mDefParseFlags 17798 | PackageParser.PARSE_MUST_BE_APK 17799 | PackageParser.PARSE_IS_SYSTEM 17800 | PackageParser.PARSE_IS_SYSTEM_DIR; 17801 if (locationIsPrivileged(disabledPs.codePath)) { 17802 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17803 } 17804 17805 final PackageParser.Package newPkg; 17806 try { 17807 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17808 0 /* currentTime */, null); 17809 } catch (PackageManagerException e) { 17810 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17811 + e.getMessage()); 17812 return false; 17813 } 17814 17815 try { 17816 // update shared libraries for the newly re-installed system package 17817 updateSharedLibrariesLPr(newPkg, null); 17818 } catch (PackageManagerException e) { 17819 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17820 } 17821 17822 prepareAppDataAfterInstallLIF(newPkg); 17823 17824 // writer 17825 synchronized (mPackages) { 17826 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17827 17828 // Propagate the permissions state as we do not want to drop on the floor 17829 // runtime permissions. The update permissions method below will take 17830 // care of removing obsolete permissions and grant install permissions. 17831 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17832 updatePermissionsLPw(newPkg.packageName, newPkg, 17833 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17834 17835 if (applyUserRestrictions) { 17836 boolean installedStateChanged = false; 17837 if (DEBUG_REMOVE) { 17838 Slog.d(TAG, "Propagating install state across reinstall"); 17839 } 17840 for (int userId : allUserHandles) { 17841 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17842 if (DEBUG_REMOVE) { 17843 Slog.d(TAG, " user " + userId + " => " + installed); 17844 } 17845 if (installed != ps.getInstalled(userId)) { 17846 installedStateChanged = true; 17847 } 17848 ps.setInstalled(installed, userId); 17849 17850 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17851 } 17852 // Regardless of writeSettings we need to ensure that this restriction 17853 // state propagation is persisted 17854 mSettings.writeAllUsersPackageRestrictionsLPr(); 17855 if (installedStateChanged) { 17856 mSettings.writeKernelMappingLPr(ps); 17857 } 17858 } 17859 // can downgrade to reader here 17860 if (writeSettings) { 17861 mSettings.writeLPr(); 17862 } 17863 } 17864 return true; 17865 } 17866 17867 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17868 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17869 PackageRemovedInfo outInfo, boolean writeSettings, 17870 PackageParser.Package replacingPackage) { 17871 synchronized (mPackages) { 17872 if (outInfo != null) { 17873 outInfo.uid = ps.appId; 17874 } 17875 17876 if (outInfo != null && outInfo.removedChildPackages != null) { 17877 final int childCount = (ps.childPackageNames != null) 17878 ? ps.childPackageNames.size() : 0; 17879 for (int i = 0; i < childCount; i++) { 17880 String childPackageName = ps.childPackageNames.get(i); 17881 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17882 if (childPs == null) { 17883 return false; 17884 } 17885 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17886 childPackageName); 17887 if (childInfo != null) { 17888 childInfo.uid = childPs.appId; 17889 } 17890 } 17891 } 17892 } 17893 17894 // Delete package data from internal structures and also remove data if flag is set 17895 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17896 17897 // Delete the child packages data 17898 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17899 for (int i = 0; i < childCount; i++) { 17900 PackageSetting childPs; 17901 synchronized (mPackages) { 17902 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17903 } 17904 if (childPs != null) { 17905 PackageRemovedInfo childOutInfo = (outInfo != null 17906 && outInfo.removedChildPackages != null) 17907 ? outInfo.removedChildPackages.get(childPs.name) : null; 17908 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17909 && (replacingPackage != null 17910 && !replacingPackage.hasChildPackage(childPs.name)) 17911 ? flags & ~DELETE_KEEP_DATA : flags; 17912 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17913 deleteFlags, writeSettings); 17914 } 17915 } 17916 17917 // Delete application code and resources only for parent packages 17918 if (ps.parentPackageName == null) { 17919 if (deleteCodeAndResources && (outInfo != null)) { 17920 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17921 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17922 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17923 } 17924 } 17925 17926 return true; 17927 } 17928 17929 @Override 17930 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17931 int userId) { 17932 mContext.enforceCallingOrSelfPermission( 17933 android.Manifest.permission.DELETE_PACKAGES, null); 17934 synchronized (mPackages) { 17935 PackageSetting ps = mSettings.mPackages.get(packageName); 17936 if (ps == null) { 17937 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17938 return false; 17939 } 17940 // Cannot block uninstall of static shared libs as they are 17941 // considered a part of the using app (emulating static linking). 17942 // Also static libs are installed always on internal storage. 17943 PackageParser.Package pkg = mPackages.get(packageName); 17944 if (pkg != null && pkg.staticSharedLibName != null) { 17945 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17946 + " providing static shared library: " + pkg.staticSharedLibName); 17947 return false; 17948 } 17949 if (!ps.getInstalled(userId)) { 17950 // Can't block uninstall for an app that is not installed or enabled. 17951 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17952 return false; 17953 } 17954 ps.setBlockUninstall(blockUninstall, userId); 17955 mSettings.writePackageRestrictionsLPr(userId); 17956 } 17957 return true; 17958 } 17959 17960 @Override 17961 public boolean getBlockUninstallForUser(String packageName, int userId) { 17962 synchronized (mPackages) { 17963 PackageSetting ps = mSettings.mPackages.get(packageName); 17964 if (ps == null) { 17965 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 17966 return false; 17967 } 17968 return ps.getBlockUninstall(userId); 17969 } 17970 } 17971 17972 @Override 17973 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 17974 int callingUid = Binder.getCallingUid(); 17975 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 17976 throw new SecurityException( 17977 "setRequiredForSystemUser can only be run by the system or root"); 17978 } 17979 synchronized (mPackages) { 17980 PackageSetting ps = mSettings.mPackages.get(packageName); 17981 if (ps == null) { 17982 Log.w(TAG, "Package doesn't exist: " + packageName); 17983 return false; 17984 } 17985 if (systemUserApp) { 17986 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17987 } else { 17988 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17989 } 17990 mSettings.writeLPr(); 17991 } 17992 return true; 17993 } 17994 17995 /* 17996 * This method handles package deletion in general 17997 */ 17998 private boolean deletePackageLIF(String packageName, UserHandle user, 17999 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18000 PackageRemovedInfo outInfo, boolean writeSettings, 18001 PackageParser.Package replacingPackage) { 18002 if (packageName == null) { 18003 Slog.w(TAG, "Attempt to delete null packageName."); 18004 return false; 18005 } 18006 18007 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18008 18009 PackageSetting ps; 18010 synchronized (mPackages) { 18011 ps = mSettings.mPackages.get(packageName); 18012 if (ps == null) { 18013 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18014 return false; 18015 } 18016 18017 if (ps.parentPackageName != null && (!isSystemApp(ps) 18018 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18019 if (DEBUG_REMOVE) { 18020 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18021 + ((user == null) ? UserHandle.USER_ALL : user)); 18022 } 18023 final int removedUserId = (user != null) ? user.getIdentifier() 18024 : UserHandle.USER_ALL; 18025 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18026 return false; 18027 } 18028 markPackageUninstalledForUserLPw(ps, user); 18029 scheduleWritePackageRestrictionsLocked(user); 18030 return true; 18031 } 18032 } 18033 18034 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18035 && user.getIdentifier() != UserHandle.USER_ALL)) { 18036 // The caller is asking that the package only be deleted for a single 18037 // user. To do this, we just mark its uninstalled state and delete 18038 // its data. If this is a system app, we only allow this to happen if 18039 // they have set the special DELETE_SYSTEM_APP which requests different 18040 // semantics than normal for uninstalling system apps. 18041 markPackageUninstalledForUserLPw(ps, user); 18042 18043 if (!isSystemApp(ps)) { 18044 // Do not uninstall the APK if an app should be cached 18045 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18046 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18047 // Other user still have this package installed, so all 18048 // we need to do is clear this user's data and save that 18049 // it is uninstalled. 18050 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18051 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18052 return false; 18053 } 18054 scheduleWritePackageRestrictionsLocked(user); 18055 return true; 18056 } else { 18057 // We need to set it back to 'installed' so the uninstall 18058 // broadcasts will be sent correctly. 18059 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18060 ps.setInstalled(true, user.getIdentifier()); 18061 mSettings.writeKernelMappingLPr(ps); 18062 } 18063 } else { 18064 // This is a system app, so we assume that the 18065 // other users still have this package installed, so all 18066 // we need to do is clear this user's data and save that 18067 // it is uninstalled. 18068 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18069 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18070 return false; 18071 } 18072 scheduleWritePackageRestrictionsLocked(user); 18073 return true; 18074 } 18075 } 18076 18077 // If we are deleting a composite package for all users, keep track 18078 // of result for each child. 18079 if (ps.childPackageNames != null && outInfo != null) { 18080 synchronized (mPackages) { 18081 final int childCount = ps.childPackageNames.size(); 18082 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18083 for (int i = 0; i < childCount; i++) { 18084 String childPackageName = ps.childPackageNames.get(i); 18085 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18086 childInfo.removedPackage = childPackageName; 18087 outInfo.removedChildPackages.put(childPackageName, childInfo); 18088 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18089 if (childPs != null) { 18090 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18091 } 18092 } 18093 } 18094 } 18095 18096 boolean ret = false; 18097 if (isSystemApp(ps)) { 18098 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18099 // When an updated system application is deleted we delete the existing resources 18100 // as well and fall back to existing code in system partition 18101 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18102 } else { 18103 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18104 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18105 outInfo, writeSettings, replacingPackage); 18106 } 18107 18108 // Take a note whether we deleted the package for all users 18109 if (outInfo != null) { 18110 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18111 if (outInfo.removedChildPackages != null) { 18112 synchronized (mPackages) { 18113 final int childCount = outInfo.removedChildPackages.size(); 18114 for (int i = 0; i < childCount; i++) { 18115 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18116 if (childInfo != null) { 18117 childInfo.removedForAllUsers = mPackages.get( 18118 childInfo.removedPackage) == null; 18119 } 18120 } 18121 } 18122 } 18123 // If we uninstalled an update to a system app there may be some 18124 // child packages that appeared as they are declared in the system 18125 // app but were not declared in the update. 18126 if (isSystemApp(ps)) { 18127 synchronized (mPackages) { 18128 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18129 final int childCount = (updatedPs.childPackageNames != null) 18130 ? updatedPs.childPackageNames.size() : 0; 18131 for (int i = 0; i < childCount; i++) { 18132 String childPackageName = updatedPs.childPackageNames.get(i); 18133 if (outInfo.removedChildPackages == null 18134 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18135 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18136 if (childPs == null) { 18137 continue; 18138 } 18139 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18140 installRes.name = childPackageName; 18141 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18142 installRes.pkg = mPackages.get(childPackageName); 18143 installRes.uid = childPs.pkg.applicationInfo.uid; 18144 if (outInfo.appearedChildPackages == null) { 18145 outInfo.appearedChildPackages = new ArrayMap<>(); 18146 } 18147 outInfo.appearedChildPackages.put(childPackageName, installRes); 18148 } 18149 } 18150 } 18151 } 18152 } 18153 18154 return ret; 18155 } 18156 18157 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18158 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18159 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18160 for (int nextUserId : userIds) { 18161 if (DEBUG_REMOVE) { 18162 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18163 } 18164 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18165 false /*installed*/, 18166 true /*stopped*/, 18167 true /*notLaunched*/, 18168 false /*hidden*/, 18169 false /*suspended*/, 18170 false /*instantApp*/, 18171 null /*lastDisableAppCaller*/, 18172 null /*enabledComponents*/, 18173 null /*disabledComponents*/, 18174 false /*blockUninstall*/, 18175 ps.readUserState(nextUserId).domainVerificationStatus, 18176 0, PackageManager.INSTALL_REASON_UNKNOWN); 18177 } 18178 mSettings.writeKernelMappingLPr(ps); 18179 } 18180 18181 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18182 PackageRemovedInfo outInfo) { 18183 final PackageParser.Package pkg; 18184 synchronized (mPackages) { 18185 pkg = mPackages.get(ps.name); 18186 } 18187 18188 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18189 : new int[] {userId}; 18190 for (int nextUserId : userIds) { 18191 if (DEBUG_REMOVE) { 18192 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18193 + nextUserId); 18194 } 18195 18196 destroyAppDataLIF(pkg, userId, 18197 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18198 destroyAppProfilesLIF(pkg, userId); 18199 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18200 schedulePackageCleaning(ps.name, nextUserId, false); 18201 synchronized (mPackages) { 18202 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18203 scheduleWritePackageRestrictionsLocked(nextUserId); 18204 } 18205 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18206 } 18207 } 18208 18209 if (outInfo != null) { 18210 outInfo.removedPackage = ps.name; 18211 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18212 outInfo.removedAppId = ps.appId; 18213 outInfo.removedUsers = userIds; 18214 } 18215 18216 return true; 18217 } 18218 18219 private final class ClearStorageConnection implements ServiceConnection { 18220 IMediaContainerService mContainerService; 18221 18222 @Override 18223 public void onServiceConnected(ComponentName name, IBinder service) { 18224 synchronized (this) { 18225 mContainerService = IMediaContainerService.Stub 18226 .asInterface(Binder.allowBlocking(service)); 18227 notifyAll(); 18228 } 18229 } 18230 18231 @Override 18232 public void onServiceDisconnected(ComponentName name) { 18233 } 18234 } 18235 18236 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18237 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18238 18239 final boolean mounted; 18240 if (Environment.isExternalStorageEmulated()) { 18241 mounted = true; 18242 } else { 18243 final String status = Environment.getExternalStorageState(); 18244 18245 mounted = status.equals(Environment.MEDIA_MOUNTED) 18246 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18247 } 18248 18249 if (!mounted) { 18250 return; 18251 } 18252 18253 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18254 int[] users; 18255 if (userId == UserHandle.USER_ALL) { 18256 users = sUserManager.getUserIds(); 18257 } else { 18258 users = new int[] { userId }; 18259 } 18260 final ClearStorageConnection conn = new ClearStorageConnection(); 18261 if (mContext.bindServiceAsUser( 18262 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18263 try { 18264 for (int curUser : users) { 18265 long timeout = SystemClock.uptimeMillis() + 5000; 18266 synchronized (conn) { 18267 long now; 18268 while (conn.mContainerService == null && 18269 (now = SystemClock.uptimeMillis()) < timeout) { 18270 try { 18271 conn.wait(timeout - now); 18272 } catch (InterruptedException e) { 18273 } 18274 } 18275 } 18276 if (conn.mContainerService == null) { 18277 return; 18278 } 18279 18280 final UserEnvironment userEnv = new UserEnvironment(curUser); 18281 clearDirectory(conn.mContainerService, 18282 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18283 if (allData) { 18284 clearDirectory(conn.mContainerService, 18285 userEnv.buildExternalStorageAppDataDirs(packageName)); 18286 clearDirectory(conn.mContainerService, 18287 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18288 } 18289 } 18290 } finally { 18291 mContext.unbindService(conn); 18292 } 18293 } 18294 } 18295 18296 @Override 18297 public void clearApplicationProfileData(String packageName) { 18298 enforceSystemOrRoot("Only the system can clear all profile data"); 18299 18300 final PackageParser.Package pkg; 18301 synchronized (mPackages) { 18302 pkg = mPackages.get(packageName); 18303 } 18304 18305 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18306 synchronized (mInstallLock) { 18307 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18308 } 18309 } 18310 } 18311 18312 @Override 18313 public void clearApplicationUserData(final String packageName, 18314 final IPackageDataObserver observer, final int userId) { 18315 mContext.enforceCallingOrSelfPermission( 18316 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18317 18318 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18319 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18320 18321 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18322 throw new SecurityException("Cannot clear data for a protected package: " 18323 + packageName); 18324 } 18325 // Queue up an async operation since the package deletion may take a little while. 18326 mHandler.post(new Runnable() { 18327 public void run() { 18328 mHandler.removeCallbacks(this); 18329 final boolean succeeded; 18330 try (PackageFreezer freezer = freezePackage(packageName, 18331 "clearApplicationUserData")) { 18332 synchronized (mInstallLock) { 18333 succeeded = clearApplicationUserDataLIF(packageName, userId); 18334 } 18335 clearExternalStorageDataSync(packageName, userId, true); 18336 synchronized (mPackages) { 18337 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18338 packageName, userId); 18339 } 18340 } 18341 if (succeeded) { 18342 // invoke DeviceStorageMonitor's update method to clear any notifications 18343 DeviceStorageMonitorInternal dsm = LocalServices 18344 .getService(DeviceStorageMonitorInternal.class); 18345 if (dsm != null) { 18346 dsm.checkMemory(); 18347 } 18348 } 18349 if(observer != null) { 18350 try { 18351 observer.onRemoveCompleted(packageName, succeeded); 18352 } catch (RemoteException e) { 18353 Log.i(TAG, "Observer no longer exists."); 18354 } 18355 } //end if observer 18356 } //end run 18357 }); 18358 } 18359 18360 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18361 if (packageName == null) { 18362 Slog.w(TAG, "Attempt to delete null packageName."); 18363 return false; 18364 } 18365 18366 // Try finding details about the requested package 18367 PackageParser.Package pkg; 18368 synchronized (mPackages) { 18369 pkg = mPackages.get(packageName); 18370 if (pkg == null) { 18371 final PackageSetting ps = mSettings.mPackages.get(packageName); 18372 if (ps != null) { 18373 pkg = ps.pkg; 18374 } 18375 } 18376 18377 if (pkg == null) { 18378 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18379 return false; 18380 } 18381 18382 PackageSetting ps = (PackageSetting) pkg.mExtras; 18383 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18384 } 18385 18386 clearAppDataLIF(pkg, userId, 18387 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18388 18389 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18390 removeKeystoreDataIfNeeded(userId, appId); 18391 18392 UserManagerInternal umInternal = getUserManagerInternal(); 18393 final int flags; 18394 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18395 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18396 } else if (umInternal.isUserRunning(userId)) { 18397 flags = StorageManager.FLAG_STORAGE_DE; 18398 } else { 18399 flags = 0; 18400 } 18401 prepareAppDataContentsLIF(pkg, userId, flags); 18402 18403 return true; 18404 } 18405 18406 /** 18407 * Reverts user permission state changes (permissions and flags) in 18408 * all packages for a given user. 18409 * 18410 * @param userId The device user for which to do a reset. 18411 */ 18412 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18413 final int packageCount = mPackages.size(); 18414 for (int i = 0; i < packageCount; i++) { 18415 PackageParser.Package pkg = mPackages.valueAt(i); 18416 PackageSetting ps = (PackageSetting) pkg.mExtras; 18417 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18418 } 18419 } 18420 18421 private void resetNetworkPolicies(int userId) { 18422 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18423 } 18424 18425 /** 18426 * Reverts user permission state changes (permissions and flags). 18427 * 18428 * @param ps The package for which to reset. 18429 * @param userId The device user for which to do a reset. 18430 */ 18431 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18432 final PackageSetting ps, final int userId) { 18433 if (ps.pkg == null) { 18434 return; 18435 } 18436 18437 // These are flags that can change base on user actions. 18438 final int userSettableMask = FLAG_PERMISSION_USER_SET 18439 | FLAG_PERMISSION_USER_FIXED 18440 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18441 | FLAG_PERMISSION_REVIEW_REQUIRED; 18442 18443 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18444 | FLAG_PERMISSION_POLICY_FIXED; 18445 18446 boolean writeInstallPermissions = false; 18447 boolean writeRuntimePermissions = false; 18448 18449 final int permissionCount = ps.pkg.requestedPermissions.size(); 18450 for (int i = 0; i < permissionCount; i++) { 18451 String permission = ps.pkg.requestedPermissions.get(i); 18452 18453 BasePermission bp = mSettings.mPermissions.get(permission); 18454 if (bp == null) { 18455 continue; 18456 } 18457 18458 // If shared user we just reset the state to which only this app contributed. 18459 if (ps.sharedUser != null) { 18460 boolean used = false; 18461 final int packageCount = ps.sharedUser.packages.size(); 18462 for (int j = 0; j < packageCount; j++) { 18463 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18464 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18465 && pkg.pkg.requestedPermissions.contains(permission)) { 18466 used = true; 18467 break; 18468 } 18469 } 18470 if (used) { 18471 continue; 18472 } 18473 } 18474 18475 PermissionsState permissionsState = ps.getPermissionsState(); 18476 18477 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18478 18479 // Always clear the user settable flags. 18480 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18481 bp.name) != null; 18482 // If permission review is enabled and this is a legacy app, mark the 18483 // permission as requiring a review as this is the initial state. 18484 int flags = 0; 18485 if (mPermissionReviewRequired 18486 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18487 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18488 } 18489 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18490 if (hasInstallState) { 18491 writeInstallPermissions = true; 18492 } else { 18493 writeRuntimePermissions = true; 18494 } 18495 } 18496 18497 // Below is only runtime permission handling. 18498 if (!bp.isRuntime()) { 18499 continue; 18500 } 18501 18502 // Never clobber system or policy. 18503 if ((oldFlags & policyOrSystemFlags) != 0) { 18504 continue; 18505 } 18506 18507 // If this permission was granted by default, make sure it is. 18508 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18509 if (permissionsState.grantRuntimePermission(bp, userId) 18510 != PERMISSION_OPERATION_FAILURE) { 18511 writeRuntimePermissions = true; 18512 } 18513 // If permission review is enabled the permissions for a legacy apps 18514 // are represented as constantly granted runtime ones, so don't revoke. 18515 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18516 // Otherwise, reset the permission. 18517 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18518 switch (revokeResult) { 18519 case PERMISSION_OPERATION_SUCCESS: 18520 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18521 writeRuntimePermissions = true; 18522 final int appId = ps.appId; 18523 mHandler.post(new Runnable() { 18524 @Override 18525 public void run() { 18526 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18527 } 18528 }); 18529 } break; 18530 } 18531 } 18532 } 18533 18534 // Synchronously write as we are taking permissions away. 18535 if (writeRuntimePermissions) { 18536 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18537 } 18538 18539 // Synchronously write as we are taking permissions away. 18540 if (writeInstallPermissions) { 18541 mSettings.writeLPr(); 18542 } 18543 } 18544 18545 /** 18546 * Remove entries from the keystore daemon. Will only remove it if the 18547 * {@code appId} is valid. 18548 */ 18549 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18550 if (appId < 0) { 18551 return; 18552 } 18553 18554 final KeyStore keyStore = KeyStore.getInstance(); 18555 if (keyStore != null) { 18556 if (userId == UserHandle.USER_ALL) { 18557 for (final int individual : sUserManager.getUserIds()) { 18558 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18559 } 18560 } else { 18561 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18562 } 18563 } else { 18564 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18565 } 18566 } 18567 18568 @Override 18569 public void deleteApplicationCacheFiles(final String packageName, 18570 final IPackageDataObserver observer) { 18571 final int userId = UserHandle.getCallingUserId(); 18572 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18573 } 18574 18575 @Override 18576 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18577 final IPackageDataObserver observer) { 18578 mContext.enforceCallingOrSelfPermission( 18579 android.Manifest.permission.DELETE_CACHE_FILES, null); 18580 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18581 /* requireFullPermission= */ true, /* checkShell= */ false, 18582 "delete application cache files"); 18583 18584 final PackageParser.Package pkg; 18585 synchronized (mPackages) { 18586 pkg = mPackages.get(packageName); 18587 } 18588 18589 // Queue up an async operation since the package deletion may take a little while. 18590 mHandler.post(new Runnable() { 18591 public void run() { 18592 synchronized (mInstallLock) { 18593 final int flags = StorageManager.FLAG_STORAGE_DE 18594 | StorageManager.FLAG_STORAGE_CE; 18595 // We're only clearing cache files, so we don't care if the 18596 // app is unfrozen and still able to run 18597 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18598 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18599 } 18600 clearExternalStorageDataSync(packageName, userId, false); 18601 if (observer != null) { 18602 try { 18603 observer.onRemoveCompleted(packageName, true); 18604 } catch (RemoteException e) { 18605 Log.i(TAG, "Observer no longer exists."); 18606 } 18607 } 18608 } 18609 }); 18610 } 18611 18612 @Override 18613 public void getPackageSizeInfo(final String packageName, int userHandle, 18614 final IPackageStatsObserver observer) { 18615 throw new UnsupportedOperationException( 18616 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18617 } 18618 18619 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18620 final PackageSetting ps; 18621 synchronized (mPackages) { 18622 ps = mSettings.mPackages.get(packageName); 18623 if (ps == null) { 18624 Slog.w(TAG, "Failed to find settings for " + packageName); 18625 return false; 18626 } 18627 } 18628 18629 final String[] packageNames = { packageName }; 18630 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18631 final String[] codePaths = { ps.codePathString }; 18632 18633 try { 18634 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18635 ps.appId, ceDataInodes, codePaths, stats); 18636 18637 // For now, ignore code size of packages on system partition 18638 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18639 stats.codeSize = 0; 18640 } 18641 18642 // External clients expect these to be tracked separately 18643 stats.dataSize -= stats.cacheSize; 18644 18645 } catch (InstallerException e) { 18646 Slog.w(TAG, String.valueOf(e)); 18647 return false; 18648 } 18649 18650 return true; 18651 } 18652 18653 private int getUidTargetSdkVersionLockedLPr(int uid) { 18654 Object obj = mSettings.getUserIdLPr(uid); 18655 if (obj instanceof SharedUserSetting) { 18656 final SharedUserSetting sus = (SharedUserSetting) obj; 18657 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18658 final Iterator<PackageSetting> it = sus.packages.iterator(); 18659 while (it.hasNext()) { 18660 final PackageSetting ps = it.next(); 18661 if (ps.pkg != null) { 18662 int v = ps.pkg.applicationInfo.targetSdkVersion; 18663 if (v < vers) vers = v; 18664 } 18665 } 18666 return vers; 18667 } else if (obj instanceof PackageSetting) { 18668 final PackageSetting ps = (PackageSetting) obj; 18669 if (ps.pkg != null) { 18670 return ps.pkg.applicationInfo.targetSdkVersion; 18671 } 18672 } 18673 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18674 } 18675 18676 @Override 18677 public void addPreferredActivity(IntentFilter filter, int match, 18678 ComponentName[] set, ComponentName activity, int userId) { 18679 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18680 "Adding preferred"); 18681 } 18682 18683 private void addPreferredActivityInternal(IntentFilter filter, int match, 18684 ComponentName[] set, ComponentName activity, boolean always, int userId, 18685 String opname) { 18686 // writer 18687 int callingUid = Binder.getCallingUid(); 18688 enforceCrossUserPermission(callingUid, userId, 18689 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18690 if (filter.countActions() == 0) { 18691 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18692 return; 18693 } 18694 synchronized (mPackages) { 18695 if (mContext.checkCallingOrSelfPermission( 18696 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18697 != PackageManager.PERMISSION_GRANTED) { 18698 if (getUidTargetSdkVersionLockedLPr(callingUid) 18699 < Build.VERSION_CODES.FROYO) { 18700 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18701 + callingUid); 18702 return; 18703 } 18704 mContext.enforceCallingOrSelfPermission( 18705 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18706 } 18707 18708 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18709 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18710 + userId + ":"); 18711 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18712 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18713 scheduleWritePackageRestrictionsLocked(userId); 18714 postPreferredActivityChangedBroadcast(userId); 18715 } 18716 } 18717 18718 private void postPreferredActivityChangedBroadcast(int userId) { 18719 mHandler.post(() -> { 18720 final IActivityManager am = ActivityManager.getService(); 18721 if (am == null) { 18722 return; 18723 } 18724 18725 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18726 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18727 try { 18728 am.broadcastIntent(null, intent, null, null, 18729 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18730 null, false, false, userId); 18731 } catch (RemoteException e) { 18732 } 18733 }); 18734 } 18735 18736 @Override 18737 public void replacePreferredActivity(IntentFilter filter, int match, 18738 ComponentName[] set, ComponentName activity, int userId) { 18739 if (filter.countActions() != 1) { 18740 throw new IllegalArgumentException( 18741 "replacePreferredActivity expects filter to have only 1 action."); 18742 } 18743 if (filter.countDataAuthorities() != 0 18744 || filter.countDataPaths() != 0 18745 || filter.countDataSchemes() > 1 18746 || filter.countDataTypes() != 0) { 18747 throw new IllegalArgumentException( 18748 "replacePreferredActivity expects filter to have no data authorities, " + 18749 "paths, or types; and at most one scheme."); 18750 } 18751 18752 final int callingUid = Binder.getCallingUid(); 18753 enforceCrossUserPermission(callingUid, userId, 18754 true /* requireFullPermission */, false /* checkShell */, 18755 "replace preferred activity"); 18756 synchronized (mPackages) { 18757 if (mContext.checkCallingOrSelfPermission( 18758 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18759 != PackageManager.PERMISSION_GRANTED) { 18760 if (getUidTargetSdkVersionLockedLPr(callingUid) 18761 < Build.VERSION_CODES.FROYO) { 18762 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18763 + Binder.getCallingUid()); 18764 return; 18765 } 18766 mContext.enforceCallingOrSelfPermission( 18767 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18768 } 18769 18770 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18771 if (pir != null) { 18772 // Get all of the existing entries that exactly match this filter. 18773 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18774 if (existing != null && existing.size() == 1) { 18775 PreferredActivity cur = existing.get(0); 18776 if (DEBUG_PREFERRED) { 18777 Slog.i(TAG, "Checking replace of preferred:"); 18778 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18779 if (!cur.mPref.mAlways) { 18780 Slog.i(TAG, " -- CUR; not mAlways!"); 18781 } else { 18782 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18783 Slog.i(TAG, " -- CUR: mSet=" 18784 + Arrays.toString(cur.mPref.mSetComponents)); 18785 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18786 Slog.i(TAG, " -- NEW: mMatch=" 18787 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18788 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18789 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18790 } 18791 } 18792 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18793 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18794 && cur.mPref.sameSet(set)) { 18795 // Setting the preferred activity to what it happens to be already 18796 if (DEBUG_PREFERRED) { 18797 Slog.i(TAG, "Replacing with same preferred activity " 18798 + cur.mPref.mShortComponent + " for user " 18799 + userId + ":"); 18800 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18801 } 18802 return; 18803 } 18804 } 18805 18806 if (existing != null) { 18807 if (DEBUG_PREFERRED) { 18808 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18809 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18810 } 18811 for (int i = 0; i < existing.size(); i++) { 18812 PreferredActivity pa = existing.get(i); 18813 if (DEBUG_PREFERRED) { 18814 Slog.i(TAG, "Removing existing preferred activity " 18815 + pa.mPref.mComponent + ":"); 18816 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18817 } 18818 pir.removeFilter(pa); 18819 } 18820 } 18821 } 18822 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18823 "Replacing preferred"); 18824 } 18825 } 18826 18827 @Override 18828 public void clearPackagePreferredActivities(String packageName) { 18829 final int uid = Binder.getCallingUid(); 18830 // writer 18831 synchronized (mPackages) { 18832 PackageParser.Package pkg = mPackages.get(packageName); 18833 if (pkg == null || pkg.applicationInfo.uid != uid) { 18834 if (mContext.checkCallingOrSelfPermission( 18835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18836 != PackageManager.PERMISSION_GRANTED) { 18837 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18838 < Build.VERSION_CODES.FROYO) { 18839 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18840 + Binder.getCallingUid()); 18841 return; 18842 } 18843 mContext.enforceCallingOrSelfPermission( 18844 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18845 } 18846 } 18847 18848 int user = UserHandle.getCallingUserId(); 18849 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18850 scheduleWritePackageRestrictionsLocked(user); 18851 } 18852 } 18853 } 18854 18855 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18856 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18857 ArrayList<PreferredActivity> removed = null; 18858 boolean changed = false; 18859 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18860 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18861 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18862 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18863 continue; 18864 } 18865 Iterator<PreferredActivity> it = pir.filterIterator(); 18866 while (it.hasNext()) { 18867 PreferredActivity pa = it.next(); 18868 // Mark entry for removal only if it matches the package name 18869 // and the entry is of type "always". 18870 if (packageName == null || 18871 (pa.mPref.mComponent.getPackageName().equals(packageName) 18872 && pa.mPref.mAlways)) { 18873 if (removed == null) { 18874 removed = new ArrayList<PreferredActivity>(); 18875 } 18876 removed.add(pa); 18877 } 18878 } 18879 if (removed != null) { 18880 for (int j=0; j<removed.size(); j++) { 18881 PreferredActivity pa = removed.get(j); 18882 pir.removeFilter(pa); 18883 } 18884 changed = true; 18885 } 18886 } 18887 if (changed) { 18888 postPreferredActivityChangedBroadcast(userId); 18889 } 18890 return changed; 18891 } 18892 18893 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18894 private void clearIntentFilterVerificationsLPw(int userId) { 18895 final int packageCount = mPackages.size(); 18896 for (int i = 0; i < packageCount; i++) { 18897 PackageParser.Package pkg = mPackages.valueAt(i); 18898 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18899 } 18900 } 18901 18902 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18903 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18904 if (userId == UserHandle.USER_ALL) { 18905 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18906 sUserManager.getUserIds())) { 18907 for (int oneUserId : sUserManager.getUserIds()) { 18908 scheduleWritePackageRestrictionsLocked(oneUserId); 18909 } 18910 } 18911 } else { 18912 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18913 scheduleWritePackageRestrictionsLocked(userId); 18914 } 18915 } 18916 } 18917 18918 void clearDefaultBrowserIfNeeded(String packageName) { 18919 for (int oneUserId : sUserManager.getUserIds()) { 18920 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18921 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18922 if (packageName.equals(defaultBrowserPackageName)) { 18923 setDefaultBrowserPackageName(null, oneUserId); 18924 } 18925 } 18926 } 18927 18928 @Override 18929 public void resetApplicationPreferences(int userId) { 18930 mContext.enforceCallingOrSelfPermission( 18931 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18932 final long identity = Binder.clearCallingIdentity(); 18933 // writer 18934 try { 18935 synchronized (mPackages) { 18936 clearPackagePreferredActivitiesLPw(null, userId); 18937 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18938 // TODO: We have to reset the default SMS and Phone. This requires 18939 // significant refactoring to keep all default apps in the package 18940 // manager (cleaner but more work) or have the services provide 18941 // callbacks to the package manager to request a default app reset. 18942 applyFactoryDefaultBrowserLPw(userId); 18943 clearIntentFilterVerificationsLPw(userId); 18944 primeDomainVerificationsLPw(userId); 18945 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18946 scheduleWritePackageRestrictionsLocked(userId); 18947 } 18948 resetNetworkPolicies(userId); 18949 } finally { 18950 Binder.restoreCallingIdentity(identity); 18951 } 18952 } 18953 18954 @Override 18955 public int getPreferredActivities(List<IntentFilter> outFilters, 18956 List<ComponentName> outActivities, String packageName) { 18957 18958 int num = 0; 18959 final int userId = UserHandle.getCallingUserId(); 18960 // reader 18961 synchronized (mPackages) { 18962 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18963 if (pir != null) { 18964 final Iterator<PreferredActivity> it = pir.filterIterator(); 18965 while (it.hasNext()) { 18966 final PreferredActivity pa = it.next(); 18967 if (packageName == null 18968 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18969 && pa.mPref.mAlways)) { 18970 if (outFilters != null) { 18971 outFilters.add(new IntentFilter(pa)); 18972 } 18973 if (outActivities != null) { 18974 outActivities.add(pa.mPref.mComponent); 18975 } 18976 } 18977 } 18978 } 18979 } 18980 18981 return num; 18982 } 18983 18984 @Override 18985 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 18986 int userId) { 18987 int callingUid = Binder.getCallingUid(); 18988 if (callingUid != Process.SYSTEM_UID) { 18989 throw new SecurityException( 18990 "addPersistentPreferredActivity can only be run by the system"); 18991 } 18992 if (filter.countActions() == 0) { 18993 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18994 return; 18995 } 18996 synchronized (mPackages) { 18997 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 18998 ":"); 18999 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19000 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19001 new PersistentPreferredActivity(filter, activity)); 19002 scheduleWritePackageRestrictionsLocked(userId); 19003 postPreferredActivityChangedBroadcast(userId); 19004 } 19005 } 19006 19007 @Override 19008 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19009 int callingUid = Binder.getCallingUid(); 19010 if (callingUid != Process.SYSTEM_UID) { 19011 throw new SecurityException( 19012 "clearPackagePersistentPreferredActivities can only be run by the system"); 19013 } 19014 ArrayList<PersistentPreferredActivity> removed = null; 19015 boolean changed = false; 19016 synchronized (mPackages) { 19017 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19018 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19019 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19020 .valueAt(i); 19021 if (userId != thisUserId) { 19022 continue; 19023 } 19024 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19025 while (it.hasNext()) { 19026 PersistentPreferredActivity ppa = it.next(); 19027 // Mark entry for removal only if it matches the package name. 19028 if (ppa.mComponent.getPackageName().equals(packageName)) { 19029 if (removed == null) { 19030 removed = new ArrayList<PersistentPreferredActivity>(); 19031 } 19032 removed.add(ppa); 19033 } 19034 } 19035 if (removed != null) { 19036 for (int j=0; j<removed.size(); j++) { 19037 PersistentPreferredActivity ppa = removed.get(j); 19038 ppir.removeFilter(ppa); 19039 } 19040 changed = true; 19041 } 19042 } 19043 19044 if (changed) { 19045 scheduleWritePackageRestrictionsLocked(userId); 19046 postPreferredActivityChangedBroadcast(userId); 19047 } 19048 } 19049 } 19050 19051 /** 19052 * Common machinery for picking apart a restored XML blob and passing 19053 * it to a caller-supplied functor to be applied to the running system. 19054 */ 19055 private void restoreFromXml(XmlPullParser parser, int userId, 19056 String expectedStartTag, BlobXmlRestorer functor) 19057 throws IOException, XmlPullParserException { 19058 int type; 19059 while ((type = parser.next()) != XmlPullParser.START_TAG 19060 && type != XmlPullParser.END_DOCUMENT) { 19061 } 19062 if (type != XmlPullParser.START_TAG) { 19063 // oops didn't find a start tag?! 19064 if (DEBUG_BACKUP) { 19065 Slog.e(TAG, "Didn't find start tag during restore"); 19066 } 19067 return; 19068 } 19069Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19070 // this is supposed to be TAG_PREFERRED_BACKUP 19071 if (!expectedStartTag.equals(parser.getName())) { 19072 if (DEBUG_BACKUP) { 19073 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19074 } 19075 return; 19076 } 19077 19078 // skip interfering stuff, then we're aligned with the backing implementation 19079 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19080Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19081 functor.apply(parser, userId); 19082 } 19083 19084 private interface BlobXmlRestorer { 19085 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19086 } 19087 19088 /** 19089 * Non-Binder method, support for the backup/restore mechanism: write the 19090 * full set of preferred activities in its canonical XML format. Returns the 19091 * XML output as a byte array, or null if there is none. 19092 */ 19093 @Override 19094 public byte[] getPreferredActivityBackup(int userId) { 19095 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19096 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19097 } 19098 19099 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19100 try { 19101 final XmlSerializer serializer = new FastXmlSerializer(); 19102 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19103 serializer.startDocument(null, true); 19104 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19105 19106 synchronized (mPackages) { 19107 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19108 } 19109 19110 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19111 serializer.endDocument(); 19112 serializer.flush(); 19113 } catch (Exception e) { 19114 if (DEBUG_BACKUP) { 19115 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19116 } 19117 return null; 19118 } 19119 19120 return dataStream.toByteArray(); 19121 } 19122 19123 @Override 19124 public void restorePreferredActivities(byte[] backup, int userId) { 19125 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19126 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19127 } 19128 19129 try { 19130 final XmlPullParser parser = Xml.newPullParser(); 19131 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19132 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19133 new BlobXmlRestorer() { 19134 @Override 19135 public void apply(XmlPullParser parser, int userId) 19136 throws XmlPullParserException, IOException { 19137 synchronized (mPackages) { 19138 mSettings.readPreferredActivitiesLPw(parser, userId); 19139 } 19140 } 19141 } ); 19142 } catch (Exception e) { 19143 if (DEBUG_BACKUP) { 19144 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19145 } 19146 } 19147 } 19148 19149 /** 19150 * Non-Binder method, support for the backup/restore mechanism: write the 19151 * default browser (etc) settings in its canonical XML format. Returns the default 19152 * browser XML representation as a byte array, or null if there is none. 19153 */ 19154 @Override 19155 public byte[] getDefaultAppsBackup(int userId) { 19156 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19157 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19158 } 19159 19160 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19161 try { 19162 final XmlSerializer serializer = new FastXmlSerializer(); 19163 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19164 serializer.startDocument(null, true); 19165 serializer.startTag(null, TAG_DEFAULT_APPS); 19166 19167 synchronized (mPackages) { 19168 mSettings.writeDefaultAppsLPr(serializer, userId); 19169 } 19170 19171 serializer.endTag(null, TAG_DEFAULT_APPS); 19172 serializer.endDocument(); 19173 serializer.flush(); 19174 } catch (Exception e) { 19175 if (DEBUG_BACKUP) { 19176 Slog.e(TAG, "Unable to write default apps for backup", e); 19177 } 19178 return null; 19179 } 19180 19181 return dataStream.toByteArray(); 19182 } 19183 19184 @Override 19185 public void restoreDefaultApps(byte[] backup, int userId) { 19186 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19187 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19188 } 19189 19190 try { 19191 final XmlPullParser parser = Xml.newPullParser(); 19192 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19193 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19194 new BlobXmlRestorer() { 19195 @Override 19196 public void apply(XmlPullParser parser, int userId) 19197 throws XmlPullParserException, IOException { 19198 synchronized (mPackages) { 19199 mSettings.readDefaultAppsLPw(parser, userId); 19200 } 19201 } 19202 } ); 19203 } catch (Exception e) { 19204 if (DEBUG_BACKUP) { 19205 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19206 } 19207 } 19208 } 19209 19210 @Override 19211 public byte[] getIntentFilterVerificationBackup(int userId) { 19212 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19213 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19214 } 19215 19216 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19217 try { 19218 final XmlSerializer serializer = new FastXmlSerializer(); 19219 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19220 serializer.startDocument(null, true); 19221 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19222 19223 synchronized (mPackages) { 19224 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19225 } 19226 19227 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19228 serializer.endDocument(); 19229 serializer.flush(); 19230 } catch (Exception e) { 19231 if (DEBUG_BACKUP) { 19232 Slog.e(TAG, "Unable to write default apps for backup", e); 19233 } 19234 return null; 19235 } 19236 19237 return dataStream.toByteArray(); 19238 } 19239 19240 @Override 19241 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19242 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19243 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19244 } 19245 19246 try { 19247 final XmlPullParser parser = Xml.newPullParser(); 19248 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19249 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19250 new BlobXmlRestorer() { 19251 @Override 19252 public void apply(XmlPullParser parser, int userId) 19253 throws XmlPullParserException, IOException { 19254 synchronized (mPackages) { 19255 mSettings.readAllDomainVerificationsLPr(parser, userId); 19256 mSettings.writeLPr(); 19257 } 19258 } 19259 } ); 19260 } catch (Exception e) { 19261 if (DEBUG_BACKUP) { 19262 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19263 } 19264 } 19265 } 19266 19267 @Override 19268 public byte[] getPermissionGrantBackup(int userId) { 19269 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19270 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19271 } 19272 19273 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19274 try { 19275 final XmlSerializer serializer = new FastXmlSerializer(); 19276 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19277 serializer.startDocument(null, true); 19278 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19279 19280 synchronized (mPackages) { 19281 serializeRuntimePermissionGrantsLPr(serializer, userId); 19282 } 19283 19284 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19285 serializer.endDocument(); 19286 serializer.flush(); 19287 } catch (Exception e) { 19288 if (DEBUG_BACKUP) { 19289 Slog.e(TAG, "Unable to write default apps for backup", e); 19290 } 19291 return null; 19292 } 19293 19294 return dataStream.toByteArray(); 19295 } 19296 19297 @Override 19298 public void restorePermissionGrants(byte[] backup, int userId) { 19299 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19300 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19301 } 19302 19303 try { 19304 final XmlPullParser parser = Xml.newPullParser(); 19305 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19306 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19307 new BlobXmlRestorer() { 19308 @Override 19309 public void apply(XmlPullParser parser, int userId) 19310 throws XmlPullParserException, IOException { 19311 synchronized (mPackages) { 19312 processRestoredPermissionGrantsLPr(parser, userId); 19313 } 19314 } 19315 } ); 19316 } catch (Exception e) { 19317 if (DEBUG_BACKUP) { 19318 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19319 } 19320 } 19321 } 19322 19323 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19324 throws IOException { 19325 serializer.startTag(null, TAG_ALL_GRANTS); 19326 19327 final int N = mSettings.mPackages.size(); 19328 for (int i = 0; i < N; i++) { 19329 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19330 boolean pkgGrantsKnown = false; 19331 19332 PermissionsState packagePerms = ps.getPermissionsState(); 19333 19334 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19335 final int grantFlags = state.getFlags(); 19336 // only look at grants that are not system/policy fixed 19337 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19338 final boolean isGranted = state.isGranted(); 19339 // And only back up the user-twiddled state bits 19340 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19341 final String packageName = mSettings.mPackages.keyAt(i); 19342 if (!pkgGrantsKnown) { 19343 serializer.startTag(null, TAG_GRANT); 19344 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19345 pkgGrantsKnown = true; 19346 } 19347 19348 final boolean userSet = 19349 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19350 final boolean userFixed = 19351 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19352 final boolean revoke = 19353 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19354 19355 serializer.startTag(null, TAG_PERMISSION); 19356 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19357 if (isGranted) { 19358 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19359 } 19360 if (userSet) { 19361 serializer.attribute(null, ATTR_USER_SET, "true"); 19362 } 19363 if (userFixed) { 19364 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19365 } 19366 if (revoke) { 19367 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19368 } 19369 serializer.endTag(null, TAG_PERMISSION); 19370 } 19371 } 19372 } 19373 19374 if (pkgGrantsKnown) { 19375 serializer.endTag(null, TAG_GRANT); 19376 } 19377 } 19378 19379 serializer.endTag(null, TAG_ALL_GRANTS); 19380 } 19381 19382 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19383 throws XmlPullParserException, IOException { 19384 String pkgName = null; 19385 int outerDepth = parser.getDepth(); 19386 int type; 19387 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19388 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19389 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19390 continue; 19391 } 19392 19393 final String tagName = parser.getName(); 19394 if (tagName.equals(TAG_GRANT)) { 19395 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19396 if (DEBUG_BACKUP) { 19397 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19398 } 19399 } else if (tagName.equals(TAG_PERMISSION)) { 19400 19401 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19402 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19403 19404 int newFlagSet = 0; 19405 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19406 newFlagSet |= FLAG_PERMISSION_USER_SET; 19407 } 19408 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19409 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19410 } 19411 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19412 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19413 } 19414 if (DEBUG_BACKUP) { 19415 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19416 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19417 } 19418 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19419 if (ps != null) { 19420 // Already installed so we apply the grant immediately 19421 if (DEBUG_BACKUP) { 19422 Slog.v(TAG, " + already installed; applying"); 19423 } 19424 PermissionsState perms = ps.getPermissionsState(); 19425 BasePermission bp = mSettings.mPermissions.get(permName); 19426 if (bp != null) { 19427 if (isGranted) { 19428 perms.grantRuntimePermission(bp, userId); 19429 } 19430 if (newFlagSet != 0) { 19431 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19432 } 19433 } 19434 } else { 19435 // Need to wait for post-restore install to apply the grant 19436 if (DEBUG_BACKUP) { 19437 Slog.v(TAG, " - not yet installed; saving for later"); 19438 } 19439 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19440 isGranted, newFlagSet, userId); 19441 } 19442 } else { 19443 PackageManagerService.reportSettingsProblem(Log.WARN, 19444 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19445 XmlUtils.skipCurrentTag(parser); 19446 } 19447 } 19448 19449 scheduleWriteSettingsLocked(); 19450 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19451 } 19452 19453 @Override 19454 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19455 int sourceUserId, int targetUserId, int flags) { 19456 mContext.enforceCallingOrSelfPermission( 19457 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19458 int callingUid = Binder.getCallingUid(); 19459 enforceOwnerRights(ownerPackage, callingUid); 19460 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19461 if (intentFilter.countActions() == 0) { 19462 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19463 return; 19464 } 19465 synchronized (mPackages) { 19466 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19467 ownerPackage, targetUserId, flags); 19468 CrossProfileIntentResolver resolver = 19469 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19470 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19471 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19472 if (existing != null) { 19473 int size = existing.size(); 19474 for (int i = 0; i < size; i++) { 19475 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19476 return; 19477 } 19478 } 19479 } 19480 resolver.addFilter(newFilter); 19481 scheduleWritePackageRestrictionsLocked(sourceUserId); 19482 } 19483 } 19484 19485 @Override 19486 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19487 mContext.enforceCallingOrSelfPermission( 19488 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19489 int callingUid = Binder.getCallingUid(); 19490 enforceOwnerRights(ownerPackage, callingUid); 19491 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19492 synchronized (mPackages) { 19493 CrossProfileIntentResolver resolver = 19494 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19495 ArraySet<CrossProfileIntentFilter> set = 19496 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19497 for (CrossProfileIntentFilter filter : set) { 19498 if (filter.getOwnerPackage().equals(ownerPackage)) { 19499 resolver.removeFilter(filter); 19500 } 19501 } 19502 scheduleWritePackageRestrictionsLocked(sourceUserId); 19503 } 19504 } 19505 19506 // Enforcing that callingUid is owning pkg on userId 19507 private void enforceOwnerRights(String pkg, int callingUid) { 19508 // The system owns everything. 19509 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19510 return; 19511 } 19512 int callingUserId = UserHandle.getUserId(callingUid); 19513 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19514 if (pi == null) { 19515 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19516 + callingUserId); 19517 } 19518 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19519 throw new SecurityException("Calling uid " + callingUid 19520 + " does not own package " + pkg); 19521 } 19522 } 19523 19524 @Override 19525 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19526 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19527 } 19528 19529 /** 19530 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19531 * then reports the most likely home activity or null if there are more than one. 19532 */ 19533 public ComponentName getDefaultHomeActivity(int userId) { 19534 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19535 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19536 if (cn != null) { 19537 return cn; 19538 } 19539 19540 // Find the launcher with the highest priority and return that component if there are no 19541 // other home activity with the same priority. 19542 int lastPriority = Integer.MIN_VALUE; 19543 ComponentName lastComponent = null; 19544 final int size = allHomeCandidates.size(); 19545 for (int i = 0; i < size; i++) { 19546 final ResolveInfo ri = allHomeCandidates.get(i); 19547 if (ri.priority > lastPriority) { 19548 lastComponent = ri.activityInfo.getComponentName(); 19549 lastPriority = ri.priority; 19550 } else if (ri.priority == lastPriority) { 19551 // Two components found with same priority. 19552 lastComponent = null; 19553 } 19554 } 19555 return lastComponent; 19556 } 19557 19558 private Intent getHomeIntent() { 19559 Intent intent = new Intent(Intent.ACTION_MAIN); 19560 intent.addCategory(Intent.CATEGORY_HOME); 19561 intent.addCategory(Intent.CATEGORY_DEFAULT); 19562 return intent; 19563 } 19564 19565 private IntentFilter getHomeFilter() { 19566 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19567 filter.addCategory(Intent.CATEGORY_HOME); 19568 filter.addCategory(Intent.CATEGORY_DEFAULT); 19569 return filter; 19570 } 19571 19572 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19573 int userId) { 19574 Intent intent = getHomeIntent(); 19575 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19576 PackageManager.GET_META_DATA, userId); 19577 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19578 true, false, false, userId); 19579 19580 allHomeCandidates.clear(); 19581 if (list != null) { 19582 for (ResolveInfo ri : list) { 19583 allHomeCandidates.add(ri); 19584 } 19585 } 19586 return (preferred == null || preferred.activityInfo == null) 19587 ? null 19588 : new ComponentName(preferred.activityInfo.packageName, 19589 preferred.activityInfo.name); 19590 } 19591 19592 @Override 19593 public void setHomeActivity(ComponentName comp, int userId) { 19594 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19595 getHomeActivitiesAsUser(homeActivities, userId); 19596 19597 boolean found = false; 19598 19599 final int size = homeActivities.size(); 19600 final ComponentName[] set = new ComponentName[size]; 19601 for (int i = 0; i < size; i++) { 19602 final ResolveInfo candidate = homeActivities.get(i); 19603 final ActivityInfo info = candidate.activityInfo; 19604 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19605 set[i] = activityName; 19606 if (!found && activityName.equals(comp)) { 19607 found = true; 19608 } 19609 } 19610 if (!found) { 19611 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19612 + userId); 19613 } 19614 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19615 set, comp, userId); 19616 } 19617 19618 private @Nullable String getSetupWizardPackageName() { 19619 final Intent intent = new Intent(Intent.ACTION_MAIN); 19620 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19621 19622 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19623 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19624 | MATCH_DISABLED_COMPONENTS, 19625 UserHandle.myUserId()); 19626 if (matches.size() == 1) { 19627 return matches.get(0).getComponentInfo().packageName; 19628 } else { 19629 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19630 + ": matches=" + matches); 19631 return null; 19632 } 19633 } 19634 19635 private @Nullable String getStorageManagerPackageName() { 19636 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19637 19638 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19639 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19640 | MATCH_DISABLED_COMPONENTS, 19641 UserHandle.myUserId()); 19642 if (matches.size() == 1) { 19643 return matches.get(0).getComponentInfo().packageName; 19644 } else { 19645 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19646 + matches.size() + ": matches=" + matches); 19647 return null; 19648 } 19649 } 19650 19651 @Override 19652 public void setApplicationEnabledSetting(String appPackageName, 19653 int newState, int flags, int userId, String callingPackage) { 19654 if (!sUserManager.exists(userId)) return; 19655 if (callingPackage == null) { 19656 callingPackage = Integer.toString(Binder.getCallingUid()); 19657 } 19658 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19659 } 19660 19661 @Override 19662 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19663 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19664 synchronized (mPackages) { 19665 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19666 if (pkgSetting != null) { 19667 pkgSetting.setUpdateAvailable(updateAvailable); 19668 } 19669 } 19670 } 19671 19672 @Override 19673 public void setComponentEnabledSetting(ComponentName componentName, 19674 int newState, int flags, int userId) { 19675 if (!sUserManager.exists(userId)) return; 19676 setEnabledSetting(componentName.getPackageName(), 19677 componentName.getClassName(), newState, flags, userId, null); 19678 } 19679 19680 private void setEnabledSetting(final String packageName, String className, int newState, 19681 final int flags, int userId, String callingPackage) { 19682 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19683 || newState == COMPONENT_ENABLED_STATE_ENABLED 19684 || newState == COMPONENT_ENABLED_STATE_DISABLED 19685 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19686 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19687 throw new IllegalArgumentException("Invalid new component state: " 19688 + newState); 19689 } 19690 PackageSetting pkgSetting; 19691 final int uid = Binder.getCallingUid(); 19692 final int permission; 19693 if (uid == Process.SYSTEM_UID) { 19694 permission = PackageManager.PERMISSION_GRANTED; 19695 } else { 19696 permission = mContext.checkCallingOrSelfPermission( 19697 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19698 } 19699 enforceCrossUserPermission(uid, userId, 19700 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19701 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19702 boolean sendNow = false; 19703 boolean isApp = (className == null); 19704 String componentName = isApp ? packageName : className; 19705 int packageUid = -1; 19706 ArrayList<String> components; 19707 19708 // writer 19709 synchronized (mPackages) { 19710 pkgSetting = mSettings.mPackages.get(packageName); 19711 if (pkgSetting == null) { 19712 if (className == null) { 19713 throw new IllegalArgumentException("Unknown package: " + packageName); 19714 } 19715 throw new IllegalArgumentException( 19716 "Unknown component: " + packageName + "/" + className); 19717 } 19718 } 19719 19720 // Limit who can change which apps 19721 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19722 // Don't allow apps that don't have permission to modify other apps 19723 if (!allowedByPermission) { 19724 throw new SecurityException( 19725 "Permission Denial: attempt to change component state from pid=" 19726 + Binder.getCallingPid() 19727 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19728 } 19729 // Don't allow changing protected packages. 19730 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19731 throw new SecurityException("Cannot disable a protected package: " + packageName); 19732 } 19733 } 19734 19735 synchronized (mPackages) { 19736 if (uid == Process.SHELL_UID 19737 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19738 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19739 // unless it is a test package. 19740 int oldState = pkgSetting.getEnabled(userId); 19741 if (className == null 19742 && 19743 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19744 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19745 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19746 && 19747 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19748 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19749 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19750 // ok 19751 } else { 19752 throw new SecurityException( 19753 "Shell cannot change component state for " + packageName + "/" 19754 + className + " to " + newState); 19755 } 19756 } 19757 if (className == null) { 19758 // We're dealing with an application/package level state change 19759 if (pkgSetting.getEnabled(userId) == newState) { 19760 // Nothing to do 19761 return; 19762 } 19763 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19764 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19765 // Don't care about who enables an app. 19766 callingPackage = null; 19767 } 19768 pkgSetting.setEnabled(newState, userId, callingPackage); 19769 // pkgSetting.pkg.mSetEnabled = newState; 19770 } else { 19771 // We're dealing with a component level state change 19772 // First, verify that this is a valid class name. 19773 PackageParser.Package pkg = pkgSetting.pkg; 19774 if (pkg == null || !pkg.hasComponentClassName(className)) { 19775 if (pkg != null && 19776 pkg.applicationInfo.targetSdkVersion >= 19777 Build.VERSION_CODES.JELLY_BEAN) { 19778 throw new IllegalArgumentException("Component class " + className 19779 + " does not exist in " + packageName); 19780 } else { 19781 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19782 + className + " does not exist in " + packageName); 19783 } 19784 } 19785 switch (newState) { 19786 case COMPONENT_ENABLED_STATE_ENABLED: 19787 if (!pkgSetting.enableComponentLPw(className, userId)) { 19788 return; 19789 } 19790 break; 19791 case COMPONENT_ENABLED_STATE_DISABLED: 19792 if (!pkgSetting.disableComponentLPw(className, userId)) { 19793 return; 19794 } 19795 break; 19796 case COMPONENT_ENABLED_STATE_DEFAULT: 19797 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19798 return; 19799 } 19800 break; 19801 default: 19802 Slog.e(TAG, "Invalid new component state: " + newState); 19803 return; 19804 } 19805 } 19806 scheduleWritePackageRestrictionsLocked(userId); 19807 updateSequenceNumberLP(packageName, new int[] { userId }); 19808 components = mPendingBroadcasts.get(userId, packageName); 19809 final boolean newPackage = components == null; 19810 if (newPackage) { 19811 components = new ArrayList<String>(); 19812 } 19813 if (!components.contains(componentName)) { 19814 components.add(componentName); 19815 } 19816 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19817 sendNow = true; 19818 // Purge entry from pending broadcast list if another one exists already 19819 // since we are sending one right away. 19820 mPendingBroadcasts.remove(userId, packageName); 19821 } else { 19822 if (newPackage) { 19823 mPendingBroadcasts.put(userId, packageName, components); 19824 } 19825 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19826 // Schedule a message 19827 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19828 } 19829 } 19830 } 19831 19832 long callingId = Binder.clearCallingIdentity(); 19833 try { 19834 if (sendNow) { 19835 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19836 sendPackageChangedBroadcast(packageName, 19837 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19838 } 19839 } finally { 19840 Binder.restoreCallingIdentity(callingId); 19841 } 19842 } 19843 19844 @Override 19845 public void flushPackageRestrictionsAsUser(int userId) { 19846 if (!sUserManager.exists(userId)) { 19847 return; 19848 } 19849 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19850 false /* checkShell */, "flushPackageRestrictions"); 19851 synchronized (mPackages) { 19852 mSettings.writePackageRestrictionsLPr(userId); 19853 mDirtyUsers.remove(userId); 19854 if (mDirtyUsers.isEmpty()) { 19855 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19856 } 19857 } 19858 } 19859 19860 private void sendPackageChangedBroadcast(String packageName, 19861 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19862 if (DEBUG_INSTALL) 19863 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19864 + componentNames); 19865 Bundle extras = new Bundle(4); 19866 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19867 String nameList[] = new String[componentNames.size()]; 19868 componentNames.toArray(nameList); 19869 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19870 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19871 extras.putInt(Intent.EXTRA_UID, packageUid); 19872 // If this is not reporting a change of the overall package, then only send it 19873 // to registered receivers. We don't want to launch a swath of apps for every 19874 // little component state change. 19875 final int flags = !componentNames.contains(packageName) 19876 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19877 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19878 new int[] {UserHandle.getUserId(packageUid)}); 19879 } 19880 19881 @Override 19882 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19883 if (!sUserManager.exists(userId)) return; 19884 final int uid = Binder.getCallingUid(); 19885 final int permission = mContext.checkCallingOrSelfPermission( 19886 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19887 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19888 enforceCrossUserPermission(uid, userId, 19889 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19890 // writer 19891 synchronized (mPackages) { 19892 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19893 allowedByPermission, uid, userId)) { 19894 scheduleWritePackageRestrictionsLocked(userId); 19895 } 19896 } 19897 } 19898 19899 @Override 19900 public String getInstallerPackageName(String packageName) { 19901 // reader 19902 synchronized (mPackages) { 19903 return mSettings.getInstallerPackageNameLPr(packageName); 19904 } 19905 } 19906 19907 public boolean isOrphaned(String packageName) { 19908 // reader 19909 synchronized (mPackages) { 19910 return mSettings.isOrphaned(packageName); 19911 } 19912 } 19913 19914 @Override 19915 public int getApplicationEnabledSetting(String packageName, int userId) { 19916 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19917 int uid = Binder.getCallingUid(); 19918 enforceCrossUserPermission(uid, userId, 19919 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19920 // reader 19921 synchronized (mPackages) { 19922 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19923 } 19924 } 19925 19926 @Override 19927 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19928 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19929 int uid = Binder.getCallingUid(); 19930 enforceCrossUserPermission(uid, userId, 19931 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19932 // reader 19933 synchronized (mPackages) { 19934 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19935 } 19936 } 19937 19938 @Override 19939 public void enterSafeMode() { 19940 enforceSystemOrRoot("Only the system can request entering safe mode"); 19941 19942 if (!mSystemReady) { 19943 mSafeMode = true; 19944 } 19945 } 19946 19947 @Override 19948 public void systemReady() { 19949 mSystemReady = true; 19950 19951 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19952 // disabled after already being started. 19953 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19954 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19955 19956 // Read the compatibilty setting when the system is ready. 19957 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19958 mContext.getContentResolver(), 19959 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19960 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19961 if (DEBUG_SETTINGS) { 19962 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19963 } 19964 19965 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19966 19967 synchronized (mPackages) { 19968 // Verify that all of the preferred activity components actually 19969 // exist. It is possible for applications to be updated and at 19970 // that point remove a previously declared activity component that 19971 // had been set as a preferred activity. We try to clean this up 19972 // the next time we encounter that preferred activity, but it is 19973 // possible for the user flow to never be able to return to that 19974 // situation so here we do a sanity check to make sure we haven't 19975 // left any junk around. 19976 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 19977 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19978 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19979 removed.clear(); 19980 for (PreferredActivity pa : pir.filterSet()) { 19981 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 19982 removed.add(pa); 19983 } 19984 } 19985 if (removed.size() > 0) { 19986 for (int r=0; r<removed.size(); r++) { 19987 PreferredActivity pa = removed.get(r); 19988 Slog.w(TAG, "Removing dangling preferred activity: " 19989 + pa.mPref.mComponent); 19990 pir.removeFilter(pa); 19991 } 19992 mSettings.writePackageRestrictionsLPr( 19993 mSettings.mPreferredActivities.keyAt(i)); 19994 } 19995 } 19996 19997 for (int userId : UserManagerService.getInstance().getUserIds()) { 19998 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 19999 grantPermissionsUserIds = ArrayUtils.appendInt( 20000 grantPermissionsUserIds, userId); 20001 } 20002 } 20003 } 20004 sUserManager.systemReady(); 20005 20006 // If we upgraded grant all default permissions before kicking off. 20007 for (int userId : grantPermissionsUserIds) { 20008 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20009 } 20010 20011 // If we did not grant default permissions, we preload from this the 20012 // default permission exceptions lazily to ensure we don't hit the 20013 // disk on a new user creation. 20014 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20015 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20016 } 20017 20018 // Kick off any messages waiting for system ready 20019 if (mPostSystemReadyMessages != null) { 20020 for (Message msg : mPostSystemReadyMessages) { 20021 msg.sendToTarget(); 20022 } 20023 mPostSystemReadyMessages = null; 20024 } 20025 20026 // Watch for external volumes that come and go over time 20027 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20028 storage.registerListener(mStorageListener); 20029 20030 mInstallerService.systemReady(); 20031 mPackageDexOptimizer.systemReady(); 20032 20033 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20034 StorageManagerInternal.class); 20035 StorageManagerInternal.addExternalStoragePolicy( 20036 new StorageManagerInternal.ExternalStorageMountPolicy() { 20037 @Override 20038 public int getMountMode(int uid, String packageName) { 20039 if (Process.isIsolated(uid)) { 20040 return Zygote.MOUNT_EXTERNAL_NONE; 20041 } 20042 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20043 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20044 } 20045 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20046 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20047 } 20048 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20049 return Zygote.MOUNT_EXTERNAL_READ; 20050 } 20051 return Zygote.MOUNT_EXTERNAL_WRITE; 20052 } 20053 20054 @Override 20055 public boolean hasExternalStorage(int uid, String packageName) { 20056 return true; 20057 } 20058 }); 20059 20060 // Now that we're mostly running, clean up stale users and apps 20061 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20062 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20063 20064 if (mPrivappPermissionsViolations != null) { 20065 Slog.wtf(TAG,"Signature|privileged permissions not in " 20066 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20067 mPrivappPermissionsViolations = null; 20068 } 20069 } 20070 20071 public void waitForAppDataPrepared() { 20072 if (mPrepareAppDataFuture == null) { 20073 return; 20074 } 20075 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20076 mPrepareAppDataFuture = null; 20077 } 20078 20079 @Override 20080 public boolean isSafeMode() { 20081 return mSafeMode; 20082 } 20083 20084 @Override 20085 public boolean hasSystemUidErrors() { 20086 return mHasSystemUidErrors; 20087 } 20088 20089 static String arrayToString(int[] array) { 20090 StringBuffer buf = new StringBuffer(128); 20091 buf.append('['); 20092 if (array != null) { 20093 for (int i=0; i<array.length; i++) { 20094 if (i > 0) buf.append(", "); 20095 buf.append(array[i]); 20096 } 20097 } 20098 buf.append(']'); 20099 return buf.toString(); 20100 } 20101 20102 static class DumpState { 20103 public static final int DUMP_LIBS = 1 << 0; 20104 public static final int DUMP_FEATURES = 1 << 1; 20105 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20106 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20107 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20108 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20109 public static final int DUMP_PERMISSIONS = 1 << 6; 20110 public static final int DUMP_PACKAGES = 1 << 7; 20111 public static final int DUMP_SHARED_USERS = 1 << 8; 20112 public static final int DUMP_MESSAGES = 1 << 9; 20113 public static final int DUMP_PROVIDERS = 1 << 10; 20114 public static final int DUMP_VERIFIERS = 1 << 11; 20115 public static final int DUMP_PREFERRED = 1 << 12; 20116 public static final int DUMP_PREFERRED_XML = 1 << 13; 20117 public static final int DUMP_KEYSETS = 1 << 14; 20118 public static final int DUMP_VERSION = 1 << 15; 20119 public static final int DUMP_INSTALLS = 1 << 16; 20120 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20121 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20122 public static final int DUMP_FROZEN = 1 << 19; 20123 public static final int DUMP_DEXOPT = 1 << 20; 20124 public static final int DUMP_COMPILER_STATS = 1 << 21; 20125 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20126 20127 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20128 20129 private int mTypes; 20130 20131 private int mOptions; 20132 20133 private boolean mTitlePrinted; 20134 20135 private SharedUserSetting mSharedUser; 20136 20137 public boolean isDumping(int type) { 20138 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20139 return true; 20140 } 20141 20142 return (mTypes & type) != 0; 20143 } 20144 20145 public void setDump(int type) { 20146 mTypes |= type; 20147 } 20148 20149 public boolean isOptionEnabled(int option) { 20150 return (mOptions & option) != 0; 20151 } 20152 20153 public void setOptionEnabled(int option) { 20154 mOptions |= option; 20155 } 20156 20157 public boolean onTitlePrinted() { 20158 final boolean printed = mTitlePrinted; 20159 mTitlePrinted = true; 20160 return printed; 20161 } 20162 20163 public boolean getTitlePrinted() { 20164 return mTitlePrinted; 20165 } 20166 20167 public void setTitlePrinted(boolean enabled) { 20168 mTitlePrinted = enabled; 20169 } 20170 20171 public SharedUserSetting getSharedUser() { 20172 return mSharedUser; 20173 } 20174 20175 public void setSharedUser(SharedUserSetting user) { 20176 mSharedUser = user; 20177 } 20178 } 20179 20180 @Override 20181 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20182 FileDescriptor err, String[] args, ShellCallback callback, 20183 ResultReceiver resultReceiver) { 20184 (new PackageManagerShellCommand(this)).exec( 20185 this, in, out, err, args, callback, resultReceiver); 20186 } 20187 20188 @Override 20189 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20190 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20191 != PackageManager.PERMISSION_GRANTED) { 20192 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20193 + Binder.getCallingPid() 20194 + ", uid=" + Binder.getCallingUid() 20195 + " without permission " 20196 + android.Manifest.permission.DUMP); 20197 return; 20198 } 20199 20200 DumpState dumpState = new DumpState(); 20201 boolean fullPreferred = false; 20202 boolean checkin = false; 20203 20204 String packageName = null; 20205 ArraySet<String> permissionNames = null; 20206 20207 int opti = 0; 20208 while (opti < args.length) { 20209 String opt = args[opti]; 20210 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20211 break; 20212 } 20213 opti++; 20214 20215 if ("-a".equals(opt)) { 20216 // Right now we only know how to print all. 20217 } else if ("-h".equals(opt)) { 20218 pw.println("Package manager dump options:"); 20219 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20220 pw.println(" --checkin: dump for a checkin"); 20221 pw.println(" -f: print details of intent filters"); 20222 pw.println(" -h: print this help"); 20223 pw.println(" cmd may be one of:"); 20224 pw.println(" l[ibraries]: list known shared libraries"); 20225 pw.println(" f[eatures]: list device features"); 20226 pw.println(" k[eysets]: print known keysets"); 20227 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20228 pw.println(" perm[issions]: dump permissions"); 20229 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20230 pw.println(" pref[erred]: print preferred package settings"); 20231 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20232 pw.println(" prov[iders]: dump content providers"); 20233 pw.println(" p[ackages]: dump installed packages"); 20234 pw.println(" s[hared-users]: dump shared user IDs"); 20235 pw.println(" m[essages]: print collected runtime messages"); 20236 pw.println(" v[erifiers]: print package verifier info"); 20237 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20238 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20239 pw.println(" version: print database version info"); 20240 pw.println(" write: write current settings now"); 20241 pw.println(" installs: details about install sessions"); 20242 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20243 pw.println(" dexopt: dump dexopt state"); 20244 pw.println(" compiler-stats: dump compiler statistics"); 20245 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20246 pw.println(" <package.name>: info about given package"); 20247 return; 20248 } else if ("--checkin".equals(opt)) { 20249 checkin = true; 20250 } else if ("-f".equals(opt)) { 20251 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20252 } else if ("--proto".equals(opt)) { 20253 dumpProto(fd); 20254 return; 20255 } else { 20256 pw.println("Unknown argument: " + opt + "; use -h for help"); 20257 } 20258 } 20259 20260 // Is the caller requesting to dump a particular piece of data? 20261 if (opti < args.length) { 20262 String cmd = args[opti]; 20263 opti++; 20264 // Is this a package name? 20265 if ("android".equals(cmd) || cmd.contains(".")) { 20266 packageName = cmd; 20267 // When dumping a single package, we always dump all of its 20268 // filter information since the amount of data will be reasonable. 20269 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20270 } else if ("check-permission".equals(cmd)) { 20271 if (opti >= args.length) { 20272 pw.println("Error: check-permission missing permission argument"); 20273 return; 20274 } 20275 String perm = args[opti]; 20276 opti++; 20277 if (opti >= args.length) { 20278 pw.println("Error: check-permission missing package argument"); 20279 return; 20280 } 20281 20282 String pkg = args[opti]; 20283 opti++; 20284 int user = UserHandle.getUserId(Binder.getCallingUid()); 20285 if (opti < args.length) { 20286 try { 20287 user = Integer.parseInt(args[opti]); 20288 } catch (NumberFormatException e) { 20289 pw.println("Error: check-permission user argument is not a number: " 20290 + args[opti]); 20291 return; 20292 } 20293 } 20294 20295 // Normalize package name to handle renamed packages and static libs 20296 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20297 20298 pw.println(checkPermission(perm, pkg, user)); 20299 return; 20300 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20301 dumpState.setDump(DumpState.DUMP_LIBS); 20302 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20303 dumpState.setDump(DumpState.DUMP_FEATURES); 20304 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20305 if (opti >= args.length) { 20306 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20307 | DumpState.DUMP_SERVICE_RESOLVERS 20308 | DumpState.DUMP_RECEIVER_RESOLVERS 20309 | DumpState.DUMP_CONTENT_RESOLVERS); 20310 } else { 20311 while (opti < args.length) { 20312 String name = args[opti]; 20313 if ("a".equals(name) || "activity".equals(name)) { 20314 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20315 } else if ("s".equals(name) || "service".equals(name)) { 20316 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20317 } else if ("r".equals(name) || "receiver".equals(name)) { 20318 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20319 } else if ("c".equals(name) || "content".equals(name)) { 20320 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20321 } else { 20322 pw.println("Error: unknown resolver table type: " + name); 20323 return; 20324 } 20325 opti++; 20326 } 20327 } 20328 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20329 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20330 } else if ("permission".equals(cmd)) { 20331 if (opti >= args.length) { 20332 pw.println("Error: permission requires permission name"); 20333 return; 20334 } 20335 permissionNames = new ArraySet<>(); 20336 while (opti < args.length) { 20337 permissionNames.add(args[opti]); 20338 opti++; 20339 } 20340 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20341 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20342 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20343 dumpState.setDump(DumpState.DUMP_PREFERRED); 20344 } else if ("preferred-xml".equals(cmd)) { 20345 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20346 if (opti < args.length && "--full".equals(args[opti])) { 20347 fullPreferred = true; 20348 opti++; 20349 } 20350 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20351 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20352 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20353 dumpState.setDump(DumpState.DUMP_PACKAGES); 20354 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20355 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20356 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20357 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20358 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20359 dumpState.setDump(DumpState.DUMP_MESSAGES); 20360 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20361 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20362 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20363 || "intent-filter-verifiers".equals(cmd)) { 20364 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20365 } else if ("version".equals(cmd)) { 20366 dumpState.setDump(DumpState.DUMP_VERSION); 20367 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20368 dumpState.setDump(DumpState.DUMP_KEYSETS); 20369 } else if ("installs".equals(cmd)) { 20370 dumpState.setDump(DumpState.DUMP_INSTALLS); 20371 } else if ("frozen".equals(cmd)) { 20372 dumpState.setDump(DumpState.DUMP_FROZEN); 20373 } else if ("dexopt".equals(cmd)) { 20374 dumpState.setDump(DumpState.DUMP_DEXOPT); 20375 } else if ("compiler-stats".equals(cmd)) { 20376 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20377 } else if ("enabled-overlays".equals(cmd)) { 20378 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20379 } else if ("write".equals(cmd)) { 20380 synchronized (mPackages) { 20381 mSettings.writeLPr(); 20382 pw.println("Settings written."); 20383 return; 20384 } 20385 } 20386 } 20387 20388 if (checkin) { 20389 pw.println("vers,1"); 20390 } 20391 20392 // reader 20393 synchronized (mPackages) { 20394 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20395 if (!checkin) { 20396 if (dumpState.onTitlePrinted()) 20397 pw.println(); 20398 pw.println("Database versions:"); 20399 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20400 } 20401 } 20402 20403 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20404 if (!checkin) { 20405 if (dumpState.onTitlePrinted()) 20406 pw.println(); 20407 pw.println("Verifiers:"); 20408 pw.print(" Required: "); 20409 pw.print(mRequiredVerifierPackage); 20410 pw.print(" (uid="); 20411 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20412 UserHandle.USER_SYSTEM)); 20413 pw.println(")"); 20414 } else if (mRequiredVerifierPackage != null) { 20415 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20416 pw.print(","); 20417 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20418 UserHandle.USER_SYSTEM)); 20419 } 20420 } 20421 20422 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20423 packageName == null) { 20424 if (mIntentFilterVerifierComponent != null) { 20425 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20426 if (!checkin) { 20427 if (dumpState.onTitlePrinted()) 20428 pw.println(); 20429 pw.println("Intent Filter Verifier:"); 20430 pw.print(" Using: "); 20431 pw.print(verifierPackageName); 20432 pw.print(" (uid="); 20433 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20434 UserHandle.USER_SYSTEM)); 20435 pw.println(")"); 20436 } else if (verifierPackageName != null) { 20437 pw.print("ifv,"); pw.print(verifierPackageName); 20438 pw.print(","); 20439 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20440 UserHandle.USER_SYSTEM)); 20441 } 20442 } else { 20443 pw.println(); 20444 pw.println("No Intent Filter Verifier available!"); 20445 } 20446 } 20447 20448 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20449 boolean printedHeader = false; 20450 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20451 while (it.hasNext()) { 20452 String libName = it.next(); 20453 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20454 if (versionedLib == null) { 20455 continue; 20456 } 20457 final int versionCount = versionedLib.size(); 20458 for (int i = 0; i < versionCount; i++) { 20459 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20460 if (!checkin) { 20461 if (!printedHeader) { 20462 if (dumpState.onTitlePrinted()) 20463 pw.println(); 20464 pw.println("Libraries:"); 20465 printedHeader = true; 20466 } 20467 pw.print(" "); 20468 } else { 20469 pw.print("lib,"); 20470 } 20471 pw.print(libEntry.info.getName()); 20472 if (libEntry.info.isStatic()) { 20473 pw.print(" version=" + libEntry.info.getVersion()); 20474 } 20475 if (!checkin) { 20476 pw.print(" -> "); 20477 } 20478 if (libEntry.path != null) { 20479 pw.print(" (jar) "); 20480 pw.print(libEntry.path); 20481 } else { 20482 pw.print(" (apk) "); 20483 pw.print(libEntry.apk); 20484 } 20485 pw.println(); 20486 } 20487 } 20488 } 20489 20490 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20491 if (dumpState.onTitlePrinted()) 20492 pw.println(); 20493 if (!checkin) { 20494 pw.println("Features:"); 20495 } 20496 20497 synchronized (mAvailableFeatures) { 20498 for (FeatureInfo feat : mAvailableFeatures.values()) { 20499 if (checkin) { 20500 pw.print("feat,"); 20501 pw.print(feat.name); 20502 pw.print(","); 20503 pw.println(feat.version); 20504 } else { 20505 pw.print(" "); 20506 pw.print(feat.name); 20507 if (feat.version > 0) { 20508 pw.print(" version="); 20509 pw.print(feat.version); 20510 } 20511 pw.println(); 20512 } 20513 } 20514 } 20515 } 20516 20517 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20518 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20519 : "Activity Resolver Table:", " ", packageName, 20520 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20521 dumpState.setTitlePrinted(true); 20522 } 20523 } 20524 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20525 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20526 : "Receiver Resolver Table:", " ", packageName, 20527 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20528 dumpState.setTitlePrinted(true); 20529 } 20530 } 20531 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20532 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20533 : "Service Resolver Table:", " ", packageName, 20534 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20535 dumpState.setTitlePrinted(true); 20536 } 20537 } 20538 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20539 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20540 : "Provider Resolver Table:", " ", packageName, 20541 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20542 dumpState.setTitlePrinted(true); 20543 } 20544 } 20545 20546 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20547 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20548 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20549 int user = mSettings.mPreferredActivities.keyAt(i); 20550 if (pir.dump(pw, 20551 dumpState.getTitlePrinted() 20552 ? "\nPreferred Activities User " + user + ":" 20553 : "Preferred Activities User " + user + ":", " ", 20554 packageName, true, false)) { 20555 dumpState.setTitlePrinted(true); 20556 } 20557 } 20558 } 20559 20560 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20561 pw.flush(); 20562 FileOutputStream fout = new FileOutputStream(fd); 20563 BufferedOutputStream str = new BufferedOutputStream(fout); 20564 XmlSerializer serializer = new FastXmlSerializer(); 20565 try { 20566 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20567 serializer.startDocument(null, true); 20568 serializer.setFeature( 20569 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20570 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20571 serializer.endDocument(); 20572 serializer.flush(); 20573 } catch (IllegalArgumentException e) { 20574 pw.println("Failed writing: " + e); 20575 } catch (IllegalStateException e) { 20576 pw.println("Failed writing: " + e); 20577 } catch (IOException e) { 20578 pw.println("Failed writing: " + e); 20579 } 20580 } 20581 20582 if (!checkin 20583 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20584 && packageName == null) { 20585 pw.println(); 20586 int count = mSettings.mPackages.size(); 20587 if (count == 0) { 20588 pw.println("No applications!"); 20589 pw.println(); 20590 } else { 20591 final String prefix = " "; 20592 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20593 if (allPackageSettings.size() == 0) { 20594 pw.println("No domain preferred apps!"); 20595 pw.println(); 20596 } else { 20597 pw.println("App verification status:"); 20598 pw.println(); 20599 count = 0; 20600 for (PackageSetting ps : allPackageSettings) { 20601 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20602 if (ivi == null || ivi.getPackageName() == null) continue; 20603 pw.println(prefix + "Package: " + ivi.getPackageName()); 20604 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20605 pw.println(prefix + "Status: " + ivi.getStatusString()); 20606 pw.println(); 20607 count++; 20608 } 20609 if (count == 0) { 20610 pw.println(prefix + "No app verification established."); 20611 pw.println(); 20612 } 20613 for (int userId : sUserManager.getUserIds()) { 20614 pw.println("App linkages for user " + userId + ":"); 20615 pw.println(); 20616 count = 0; 20617 for (PackageSetting ps : allPackageSettings) { 20618 final long status = ps.getDomainVerificationStatusForUser(userId); 20619 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20620 && !DEBUG_DOMAIN_VERIFICATION) { 20621 continue; 20622 } 20623 pw.println(prefix + "Package: " + ps.name); 20624 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20625 String statusStr = IntentFilterVerificationInfo. 20626 getStatusStringFromValue(status); 20627 pw.println(prefix + "Status: " + statusStr); 20628 pw.println(); 20629 count++; 20630 } 20631 if (count == 0) { 20632 pw.println(prefix + "No configured app linkages."); 20633 pw.println(); 20634 } 20635 } 20636 } 20637 } 20638 } 20639 20640 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20641 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20642 if (packageName == null && permissionNames == null) { 20643 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20644 if (iperm == 0) { 20645 if (dumpState.onTitlePrinted()) 20646 pw.println(); 20647 pw.println("AppOp Permissions:"); 20648 } 20649 pw.print(" AppOp Permission "); 20650 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20651 pw.println(":"); 20652 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20653 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20654 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20655 } 20656 } 20657 } 20658 } 20659 20660 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20661 boolean printedSomething = false; 20662 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20663 if (packageName != null && !packageName.equals(p.info.packageName)) { 20664 continue; 20665 } 20666 if (!printedSomething) { 20667 if (dumpState.onTitlePrinted()) 20668 pw.println(); 20669 pw.println("Registered ContentProviders:"); 20670 printedSomething = true; 20671 } 20672 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20673 pw.print(" "); pw.println(p.toString()); 20674 } 20675 printedSomething = false; 20676 for (Map.Entry<String, PackageParser.Provider> entry : 20677 mProvidersByAuthority.entrySet()) { 20678 PackageParser.Provider p = entry.getValue(); 20679 if (packageName != null && !packageName.equals(p.info.packageName)) { 20680 continue; 20681 } 20682 if (!printedSomething) { 20683 if (dumpState.onTitlePrinted()) 20684 pw.println(); 20685 pw.println("ContentProvider Authorities:"); 20686 printedSomething = true; 20687 } 20688 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20689 pw.print(" "); pw.println(p.toString()); 20690 if (p.info != null && p.info.applicationInfo != null) { 20691 final String appInfo = p.info.applicationInfo.toString(); 20692 pw.print(" applicationInfo="); pw.println(appInfo); 20693 } 20694 } 20695 } 20696 20697 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20698 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20699 } 20700 20701 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20702 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20703 } 20704 20705 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20706 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20707 } 20708 20709 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20710 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20711 } 20712 20713 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20714 // XXX should handle packageName != null by dumping only install data that 20715 // the given package is involved with. 20716 if (dumpState.onTitlePrinted()) pw.println(); 20717 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20718 } 20719 20720 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20721 // XXX should handle packageName != null by dumping only install data that 20722 // the given package is involved with. 20723 if (dumpState.onTitlePrinted()) pw.println(); 20724 20725 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20726 ipw.println(); 20727 ipw.println("Frozen packages:"); 20728 ipw.increaseIndent(); 20729 if (mFrozenPackages.size() == 0) { 20730 ipw.println("(none)"); 20731 } else { 20732 for (int i = 0; i < mFrozenPackages.size(); i++) { 20733 ipw.println(mFrozenPackages.valueAt(i)); 20734 } 20735 } 20736 ipw.decreaseIndent(); 20737 } 20738 20739 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20740 if (dumpState.onTitlePrinted()) pw.println(); 20741 dumpDexoptStateLPr(pw, packageName); 20742 } 20743 20744 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20745 if (dumpState.onTitlePrinted()) pw.println(); 20746 dumpCompilerStatsLPr(pw, packageName); 20747 } 20748 20749 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20750 if (dumpState.onTitlePrinted()) pw.println(); 20751 dumpEnabledOverlaysLPr(pw); 20752 } 20753 20754 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20755 if (dumpState.onTitlePrinted()) pw.println(); 20756 mSettings.dumpReadMessagesLPr(pw, dumpState); 20757 20758 pw.println(); 20759 pw.println("Package warning messages:"); 20760 BufferedReader in = null; 20761 String line = null; 20762 try { 20763 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20764 while ((line = in.readLine()) != null) { 20765 if (line.contains("ignored: updated version")) continue; 20766 pw.println(line); 20767 } 20768 } catch (IOException ignored) { 20769 } finally { 20770 IoUtils.closeQuietly(in); 20771 } 20772 } 20773 20774 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20775 BufferedReader in = null; 20776 String line = null; 20777 try { 20778 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20779 while ((line = in.readLine()) != null) { 20780 if (line.contains("ignored: updated version")) continue; 20781 pw.print("msg,"); 20782 pw.println(line); 20783 } 20784 } catch (IOException ignored) { 20785 } finally { 20786 IoUtils.closeQuietly(in); 20787 } 20788 } 20789 } 20790 } 20791 20792 private void dumpProto(FileDescriptor fd) { 20793 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20794 20795 synchronized (mPackages) { 20796 final long requiredVerifierPackageToken = 20797 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20798 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20799 proto.write( 20800 PackageServiceDumpProto.PackageShortProto.UID, 20801 getPackageUid( 20802 mRequiredVerifierPackage, 20803 MATCH_DEBUG_TRIAGED_MISSING, 20804 UserHandle.USER_SYSTEM)); 20805 proto.end(requiredVerifierPackageToken); 20806 20807 if (mIntentFilterVerifierComponent != null) { 20808 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20809 final long verifierPackageToken = 20810 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20811 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20812 proto.write( 20813 PackageServiceDumpProto.PackageShortProto.UID, 20814 getPackageUid( 20815 verifierPackageName, 20816 MATCH_DEBUG_TRIAGED_MISSING, 20817 UserHandle.USER_SYSTEM)); 20818 proto.end(verifierPackageToken); 20819 } 20820 20821 dumpSharedLibrariesProto(proto); 20822 dumpFeaturesProto(proto); 20823 mSettings.dumpPackagesProto(proto); 20824 mSettings.dumpSharedUsersProto(proto); 20825 dumpMessagesProto(proto); 20826 } 20827 proto.flush(); 20828 } 20829 20830 private void dumpMessagesProto(ProtoOutputStream proto) { 20831 BufferedReader in = null; 20832 String line = null; 20833 try { 20834 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20835 while ((line = in.readLine()) != null) { 20836 if (line.contains("ignored: updated version")) continue; 20837 proto.write(PackageServiceDumpProto.MESSAGES, line); 20838 } 20839 } catch (IOException ignored) { 20840 } finally { 20841 IoUtils.closeQuietly(in); 20842 } 20843 } 20844 20845 private void dumpFeaturesProto(ProtoOutputStream proto) { 20846 synchronized (mAvailableFeatures) { 20847 final int count = mAvailableFeatures.size(); 20848 for (int i = 0; i < count; i++) { 20849 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20850 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20851 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20852 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20853 proto.end(featureToken); 20854 } 20855 } 20856 } 20857 20858 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20859 final int count = mSharedLibraries.size(); 20860 for (int i = 0; i < count; i++) { 20861 final String libName = mSharedLibraries.keyAt(i); 20862 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20863 if (versionedLib == null) { 20864 continue; 20865 } 20866 final int versionCount = versionedLib.size(); 20867 for (int j = 0; j < versionCount; j++) { 20868 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20869 final long sharedLibraryToken = 20870 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20871 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20872 final boolean isJar = (libEntry.path != null); 20873 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20874 if (isJar) { 20875 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20876 } else { 20877 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20878 } 20879 proto.end(sharedLibraryToken); 20880 } 20881 } 20882 } 20883 20884 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20885 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20886 ipw.println(); 20887 ipw.println("Dexopt state:"); 20888 ipw.increaseIndent(); 20889 Collection<PackageParser.Package> packages = null; 20890 if (packageName != null) { 20891 PackageParser.Package targetPackage = mPackages.get(packageName); 20892 if (targetPackage != null) { 20893 packages = Collections.singletonList(targetPackage); 20894 } else { 20895 ipw.println("Unable to find package: " + packageName); 20896 return; 20897 } 20898 } else { 20899 packages = mPackages.values(); 20900 } 20901 20902 for (PackageParser.Package pkg : packages) { 20903 ipw.println("[" + pkg.packageName + "]"); 20904 ipw.increaseIndent(); 20905 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20906 ipw.decreaseIndent(); 20907 } 20908 } 20909 20910 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20911 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20912 ipw.println(); 20913 ipw.println("Compiler stats:"); 20914 ipw.increaseIndent(); 20915 Collection<PackageParser.Package> packages = null; 20916 if (packageName != null) { 20917 PackageParser.Package targetPackage = mPackages.get(packageName); 20918 if (targetPackage != null) { 20919 packages = Collections.singletonList(targetPackage); 20920 } else { 20921 ipw.println("Unable to find package: " + packageName); 20922 return; 20923 } 20924 } else { 20925 packages = mPackages.values(); 20926 } 20927 20928 for (PackageParser.Package pkg : packages) { 20929 ipw.println("[" + pkg.packageName + "]"); 20930 ipw.increaseIndent(); 20931 20932 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20933 if (stats == null) { 20934 ipw.println("(No recorded stats)"); 20935 } else { 20936 stats.dump(ipw); 20937 } 20938 ipw.decreaseIndent(); 20939 } 20940 } 20941 20942 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 20943 pw.println("Enabled overlay paths:"); 20944 final int N = mEnabledOverlayPaths.size(); 20945 for (int i = 0; i < N; i++) { 20946 final int userId = mEnabledOverlayPaths.keyAt(i); 20947 pw.println(String.format(" User %d:", userId)); 20948 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 20949 mEnabledOverlayPaths.valueAt(i); 20950 final int M = userSpecificOverlays.size(); 20951 for (int j = 0; j < M; j++) { 20952 final String targetPackageName = userSpecificOverlays.keyAt(j); 20953 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 20954 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 20955 } 20956 } 20957 } 20958 20959 private String dumpDomainString(String packageName) { 20960 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20961 .getList(); 20962 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20963 20964 ArraySet<String> result = new ArraySet<>(); 20965 if (iviList.size() > 0) { 20966 for (IntentFilterVerificationInfo ivi : iviList) { 20967 for (String host : ivi.getDomains()) { 20968 result.add(host); 20969 } 20970 } 20971 } 20972 if (filters != null && filters.size() > 0) { 20973 for (IntentFilter filter : filters) { 20974 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20975 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20976 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20977 result.addAll(filter.getHostsList()); 20978 } 20979 } 20980 } 20981 20982 StringBuilder sb = new StringBuilder(result.size() * 16); 20983 for (String domain : result) { 20984 if (sb.length() > 0) sb.append(" "); 20985 sb.append(domain); 20986 } 20987 return sb.toString(); 20988 } 20989 20990 // ------- apps on sdcard specific code ------- 20991 static final boolean DEBUG_SD_INSTALL = false; 20992 20993 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20994 20995 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20996 20997 private boolean mMediaMounted = false; 20998 20999 static String getEncryptKey() { 21000 try { 21001 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21002 SD_ENCRYPTION_KEYSTORE_NAME); 21003 if (sdEncKey == null) { 21004 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21005 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21006 if (sdEncKey == null) { 21007 Slog.e(TAG, "Failed to create encryption keys"); 21008 return null; 21009 } 21010 } 21011 return sdEncKey; 21012 } catch (NoSuchAlgorithmException nsae) { 21013 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21014 return null; 21015 } catch (IOException ioe) { 21016 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21017 return null; 21018 } 21019 } 21020 21021 /* 21022 * Update media status on PackageManager. 21023 */ 21024 @Override 21025 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21026 int callingUid = Binder.getCallingUid(); 21027 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21028 throw new SecurityException("Media status can only be updated by the system"); 21029 } 21030 // reader; this apparently protects mMediaMounted, but should probably 21031 // be a different lock in that case. 21032 synchronized (mPackages) { 21033 Log.i(TAG, "Updating external media status from " 21034 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21035 + (mediaStatus ? "mounted" : "unmounted")); 21036 if (DEBUG_SD_INSTALL) 21037 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21038 + ", mMediaMounted=" + mMediaMounted); 21039 if (mediaStatus == mMediaMounted) { 21040 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21041 : 0, -1); 21042 mHandler.sendMessage(msg); 21043 return; 21044 } 21045 mMediaMounted = mediaStatus; 21046 } 21047 // Queue up an async operation since the package installation may take a 21048 // little while. 21049 mHandler.post(new Runnable() { 21050 public void run() { 21051 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21052 } 21053 }); 21054 } 21055 21056 /** 21057 * Called by StorageManagerService when the initial ASECs to scan are available. 21058 * Should block until all the ASEC containers are finished being scanned. 21059 */ 21060 public void scanAvailableAsecs() { 21061 updateExternalMediaStatusInner(true, false, false); 21062 } 21063 21064 /* 21065 * Collect information of applications on external media, map them against 21066 * existing containers and update information based on current mount status. 21067 * Please note that we always have to report status if reportStatus has been 21068 * set to true especially when unloading packages. 21069 */ 21070 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21071 boolean externalStorage) { 21072 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21073 int[] uidArr = EmptyArray.INT; 21074 21075 final String[] list = PackageHelper.getSecureContainerList(); 21076 if (ArrayUtils.isEmpty(list)) { 21077 Log.i(TAG, "No secure containers found"); 21078 } else { 21079 // Process list of secure containers and categorize them 21080 // as active or stale based on their package internal state. 21081 21082 // reader 21083 synchronized (mPackages) { 21084 for (String cid : list) { 21085 // Leave stages untouched for now; installer service owns them 21086 if (PackageInstallerService.isStageName(cid)) continue; 21087 21088 if (DEBUG_SD_INSTALL) 21089 Log.i(TAG, "Processing container " + cid); 21090 String pkgName = getAsecPackageName(cid); 21091 if (pkgName == null) { 21092 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21093 continue; 21094 } 21095 if (DEBUG_SD_INSTALL) 21096 Log.i(TAG, "Looking for pkg : " + pkgName); 21097 21098 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21099 if (ps == null) { 21100 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21101 continue; 21102 } 21103 21104 /* 21105 * Skip packages that are not external if we're unmounting 21106 * external storage. 21107 */ 21108 if (externalStorage && !isMounted && !isExternal(ps)) { 21109 continue; 21110 } 21111 21112 final AsecInstallArgs args = new AsecInstallArgs(cid, 21113 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21114 // The package status is changed only if the code path 21115 // matches between settings and the container id. 21116 if (ps.codePathString != null 21117 && ps.codePathString.startsWith(args.getCodePath())) { 21118 if (DEBUG_SD_INSTALL) { 21119 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21120 + " at code path: " + ps.codePathString); 21121 } 21122 21123 // We do have a valid package installed on sdcard 21124 processCids.put(args, ps.codePathString); 21125 final int uid = ps.appId; 21126 if (uid != -1) { 21127 uidArr = ArrayUtils.appendInt(uidArr, uid); 21128 } 21129 } else { 21130 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21131 + ps.codePathString); 21132 } 21133 } 21134 } 21135 21136 Arrays.sort(uidArr); 21137 } 21138 21139 // Process packages with valid entries. 21140 if (isMounted) { 21141 if (DEBUG_SD_INSTALL) 21142 Log.i(TAG, "Loading packages"); 21143 loadMediaPackages(processCids, uidArr, externalStorage); 21144 startCleaningPackages(); 21145 mInstallerService.onSecureContainersAvailable(); 21146 } else { 21147 if (DEBUG_SD_INSTALL) 21148 Log.i(TAG, "Unloading packages"); 21149 unloadMediaPackages(processCids, uidArr, reportStatus); 21150 } 21151 } 21152 21153 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21154 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21155 final int size = infos.size(); 21156 final String[] packageNames = new String[size]; 21157 final int[] packageUids = new int[size]; 21158 for (int i = 0; i < size; i++) { 21159 final ApplicationInfo info = infos.get(i); 21160 packageNames[i] = info.packageName; 21161 packageUids[i] = info.uid; 21162 } 21163 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21164 finishedReceiver); 21165 } 21166 21167 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21168 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21169 sendResourcesChangedBroadcast(mediaStatus, replacing, 21170 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21171 } 21172 21173 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21174 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21175 int size = pkgList.length; 21176 if (size > 0) { 21177 // Send broadcasts here 21178 Bundle extras = new Bundle(); 21179 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21180 if (uidArr != null) { 21181 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21182 } 21183 if (replacing) { 21184 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21185 } 21186 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21187 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21188 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21189 } 21190 } 21191 21192 /* 21193 * Look at potentially valid container ids from processCids If package 21194 * information doesn't match the one on record or package scanning fails, 21195 * the cid is added to list of removeCids. We currently don't delete stale 21196 * containers. 21197 */ 21198 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21199 boolean externalStorage) { 21200 ArrayList<String> pkgList = new ArrayList<String>(); 21201 Set<AsecInstallArgs> keys = processCids.keySet(); 21202 21203 for (AsecInstallArgs args : keys) { 21204 String codePath = processCids.get(args); 21205 if (DEBUG_SD_INSTALL) 21206 Log.i(TAG, "Loading container : " + args.cid); 21207 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21208 try { 21209 // Make sure there are no container errors first. 21210 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21211 Slog.e(TAG, "Failed to mount cid : " + args.cid 21212 + " when installing from sdcard"); 21213 continue; 21214 } 21215 // Check code path here. 21216 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21217 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21218 + " does not match one in settings " + codePath); 21219 continue; 21220 } 21221 // Parse package 21222 int parseFlags = mDefParseFlags; 21223 if (args.isExternalAsec()) { 21224 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21225 } 21226 if (args.isFwdLocked()) { 21227 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21228 } 21229 21230 synchronized (mInstallLock) { 21231 PackageParser.Package pkg = null; 21232 try { 21233 // Sadly we don't know the package name yet to freeze it 21234 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21235 SCAN_IGNORE_FROZEN, 0, null); 21236 } catch (PackageManagerException e) { 21237 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21238 } 21239 // Scan the package 21240 if (pkg != null) { 21241 /* 21242 * TODO why is the lock being held? doPostInstall is 21243 * called in other places without the lock. This needs 21244 * to be straightened out. 21245 */ 21246 // writer 21247 synchronized (mPackages) { 21248 retCode = PackageManager.INSTALL_SUCCEEDED; 21249 pkgList.add(pkg.packageName); 21250 // Post process args 21251 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21252 pkg.applicationInfo.uid); 21253 } 21254 } else { 21255 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21256 } 21257 } 21258 21259 } finally { 21260 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21261 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21262 } 21263 } 21264 } 21265 // writer 21266 synchronized (mPackages) { 21267 // If the platform SDK has changed since the last time we booted, 21268 // we need to re-grant app permission to catch any new ones that 21269 // appear. This is really a hack, and means that apps can in some 21270 // cases get permissions that the user didn't initially explicitly 21271 // allow... it would be nice to have some better way to handle 21272 // this situation. 21273 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21274 : mSettings.getInternalVersion(); 21275 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21276 : StorageManager.UUID_PRIVATE_INTERNAL; 21277 21278 int updateFlags = UPDATE_PERMISSIONS_ALL; 21279 if (ver.sdkVersion != mSdkVersion) { 21280 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21281 + mSdkVersion + "; regranting permissions for external"); 21282 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21283 } 21284 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21285 21286 // Yay, everything is now upgraded 21287 ver.forceCurrent(); 21288 21289 // can downgrade to reader 21290 // Persist settings 21291 mSettings.writeLPr(); 21292 } 21293 // Send a broadcast to let everyone know we are done processing 21294 if (pkgList.size() > 0) { 21295 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21296 } 21297 } 21298 21299 /* 21300 * Utility method to unload a list of specified containers 21301 */ 21302 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21303 // Just unmount all valid containers. 21304 for (AsecInstallArgs arg : cidArgs) { 21305 synchronized (mInstallLock) { 21306 arg.doPostDeleteLI(false); 21307 } 21308 } 21309 } 21310 21311 /* 21312 * Unload packages mounted on external media. This involves deleting package 21313 * data from internal structures, sending broadcasts about disabled packages, 21314 * gc'ing to free up references, unmounting all secure containers 21315 * corresponding to packages on external media, and posting a 21316 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21317 * that we always have to post this message if status has been requested no 21318 * matter what. 21319 */ 21320 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21321 final boolean reportStatus) { 21322 if (DEBUG_SD_INSTALL) 21323 Log.i(TAG, "unloading media packages"); 21324 ArrayList<String> pkgList = new ArrayList<String>(); 21325 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21326 final Set<AsecInstallArgs> keys = processCids.keySet(); 21327 for (AsecInstallArgs args : keys) { 21328 String pkgName = args.getPackageName(); 21329 if (DEBUG_SD_INSTALL) 21330 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21331 // Delete package internally 21332 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21333 synchronized (mInstallLock) { 21334 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21335 final boolean res; 21336 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21337 "unloadMediaPackages")) { 21338 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21339 null); 21340 } 21341 if (res) { 21342 pkgList.add(pkgName); 21343 } else { 21344 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21345 failedList.add(args); 21346 } 21347 } 21348 } 21349 21350 // reader 21351 synchronized (mPackages) { 21352 // We didn't update the settings after removing each package; 21353 // write them now for all packages. 21354 mSettings.writeLPr(); 21355 } 21356 21357 // We have to absolutely send UPDATED_MEDIA_STATUS only 21358 // after confirming that all the receivers processed the ordered 21359 // broadcast when packages get disabled, force a gc to clean things up. 21360 // and unload all the containers. 21361 if (pkgList.size() > 0) { 21362 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21363 new IIntentReceiver.Stub() { 21364 public void performReceive(Intent intent, int resultCode, String data, 21365 Bundle extras, boolean ordered, boolean sticky, 21366 int sendingUser) throws RemoteException { 21367 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21368 reportStatus ? 1 : 0, 1, keys); 21369 mHandler.sendMessage(msg); 21370 } 21371 }); 21372 } else { 21373 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21374 keys); 21375 mHandler.sendMessage(msg); 21376 } 21377 } 21378 21379 private void loadPrivatePackages(final VolumeInfo vol) { 21380 mHandler.post(new Runnable() { 21381 @Override 21382 public void run() { 21383 loadPrivatePackagesInner(vol); 21384 } 21385 }); 21386 } 21387 21388 private void loadPrivatePackagesInner(VolumeInfo vol) { 21389 final String volumeUuid = vol.fsUuid; 21390 if (TextUtils.isEmpty(volumeUuid)) { 21391 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21392 return; 21393 } 21394 21395 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21396 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21397 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21398 21399 final VersionInfo ver; 21400 final List<PackageSetting> packages; 21401 synchronized (mPackages) { 21402 ver = mSettings.findOrCreateVersion(volumeUuid); 21403 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21404 } 21405 21406 for (PackageSetting ps : packages) { 21407 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21408 synchronized (mInstallLock) { 21409 final PackageParser.Package pkg; 21410 try { 21411 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21412 loaded.add(pkg.applicationInfo); 21413 21414 } catch (PackageManagerException e) { 21415 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21416 } 21417 21418 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21419 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21420 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21421 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21422 } 21423 } 21424 } 21425 21426 // Reconcile app data for all started/unlocked users 21427 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21428 final UserManager um = mContext.getSystemService(UserManager.class); 21429 UserManagerInternal umInternal = getUserManagerInternal(); 21430 for (UserInfo user : um.getUsers()) { 21431 final int flags; 21432 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21433 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21434 } else if (umInternal.isUserRunning(user.id)) { 21435 flags = StorageManager.FLAG_STORAGE_DE; 21436 } else { 21437 continue; 21438 } 21439 21440 try { 21441 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21442 synchronized (mInstallLock) { 21443 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21444 } 21445 } catch (IllegalStateException e) { 21446 // Device was probably ejected, and we'll process that event momentarily 21447 Slog.w(TAG, "Failed to prepare storage: " + e); 21448 } 21449 } 21450 21451 synchronized (mPackages) { 21452 int updateFlags = UPDATE_PERMISSIONS_ALL; 21453 if (ver.sdkVersion != mSdkVersion) { 21454 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21455 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21456 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21457 } 21458 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21459 21460 // Yay, everything is now upgraded 21461 ver.forceCurrent(); 21462 21463 mSettings.writeLPr(); 21464 } 21465 21466 for (PackageFreezer freezer : freezers) { 21467 freezer.close(); 21468 } 21469 21470 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21471 sendResourcesChangedBroadcast(true, false, loaded, null); 21472 } 21473 21474 private void unloadPrivatePackages(final VolumeInfo vol) { 21475 mHandler.post(new Runnable() { 21476 @Override 21477 public void run() { 21478 unloadPrivatePackagesInner(vol); 21479 } 21480 }); 21481 } 21482 21483 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21484 final String volumeUuid = vol.fsUuid; 21485 if (TextUtils.isEmpty(volumeUuid)) { 21486 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21487 return; 21488 } 21489 21490 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21491 synchronized (mInstallLock) { 21492 synchronized (mPackages) { 21493 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21494 for (PackageSetting ps : packages) { 21495 if (ps.pkg == null) continue; 21496 21497 final ApplicationInfo info = ps.pkg.applicationInfo; 21498 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21499 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21500 21501 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21502 "unloadPrivatePackagesInner")) { 21503 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21504 false, null)) { 21505 unloaded.add(info); 21506 } else { 21507 Slog.w(TAG, "Failed to unload " + ps.codePath); 21508 } 21509 } 21510 21511 // Try very hard to release any references to this package 21512 // so we don't risk the system server being killed due to 21513 // open FDs 21514 AttributeCache.instance().removePackage(ps.name); 21515 } 21516 21517 mSettings.writeLPr(); 21518 } 21519 } 21520 21521 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21522 sendResourcesChangedBroadcast(false, false, unloaded, null); 21523 21524 // Try very hard to release any references to this path so we don't risk 21525 // the system server being killed due to open FDs 21526 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21527 21528 for (int i = 0; i < 3; i++) { 21529 System.gc(); 21530 System.runFinalization(); 21531 } 21532 } 21533 21534 private void assertPackageKnown(String volumeUuid, String packageName) 21535 throws PackageManagerException { 21536 synchronized (mPackages) { 21537 // Normalize package name to handle renamed packages 21538 packageName = normalizePackageNameLPr(packageName); 21539 21540 final PackageSetting ps = mSettings.mPackages.get(packageName); 21541 if (ps == null) { 21542 throw new PackageManagerException("Package " + packageName + " is unknown"); 21543 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21544 throw new PackageManagerException( 21545 "Package " + packageName + " found on unknown volume " + volumeUuid 21546 + "; expected volume " + ps.volumeUuid); 21547 } 21548 } 21549 } 21550 21551 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21552 throws PackageManagerException { 21553 synchronized (mPackages) { 21554 // Normalize package name to handle renamed packages 21555 packageName = normalizePackageNameLPr(packageName); 21556 21557 final PackageSetting ps = mSettings.mPackages.get(packageName); 21558 if (ps == null) { 21559 throw new PackageManagerException("Package " + packageName + " is unknown"); 21560 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21561 throw new PackageManagerException( 21562 "Package " + packageName + " found on unknown volume " + volumeUuid 21563 + "; expected volume " + ps.volumeUuid); 21564 } else if (!ps.getInstalled(userId)) { 21565 throw new PackageManagerException( 21566 "Package " + packageName + " not installed for user " + userId); 21567 } 21568 } 21569 } 21570 21571 private List<String> collectAbsoluteCodePaths() { 21572 synchronized (mPackages) { 21573 List<String> codePaths = new ArrayList<>(); 21574 final int packageCount = mSettings.mPackages.size(); 21575 for (int i = 0; i < packageCount; i++) { 21576 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21577 codePaths.add(ps.codePath.getAbsolutePath()); 21578 } 21579 return codePaths; 21580 } 21581 } 21582 21583 /** 21584 * Examine all apps present on given mounted volume, and destroy apps that 21585 * aren't expected, either due to uninstallation or reinstallation on 21586 * another volume. 21587 */ 21588 private void reconcileApps(String volumeUuid) { 21589 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21590 List<File> filesToDelete = null; 21591 21592 final File[] files = FileUtils.listFilesOrEmpty( 21593 Environment.getDataAppDirectory(volumeUuid)); 21594 for (File file : files) { 21595 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21596 && !PackageInstallerService.isStageName(file.getName()); 21597 if (!isPackage) { 21598 // Ignore entries which are not packages 21599 continue; 21600 } 21601 21602 String absolutePath = file.getAbsolutePath(); 21603 21604 boolean pathValid = false; 21605 final int absoluteCodePathCount = absoluteCodePaths.size(); 21606 for (int i = 0; i < absoluteCodePathCount; i++) { 21607 String absoluteCodePath = absoluteCodePaths.get(i); 21608 if (absolutePath.startsWith(absoluteCodePath)) { 21609 pathValid = true; 21610 break; 21611 } 21612 } 21613 21614 if (!pathValid) { 21615 if (filesToDelete == null) { 21616 filesToDelete = new ArrayList<>(); 21617 } 21618 filesToDelete.add(file); 21619 } 21620 } 21621 21622 if (filesToDelete != null) { 21623 final int fileToDeleteCount = filesToDelete.size(); 21624 for (int i = 0; i < fileToDeleteCount; i++) { 21625 File fileToDelete = filesToDelete.get(i); 21626 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21627 synchronized (mInstallLock) { 21628 removeCodePathLI(fileToDelete); 21629 } 21630 } 21631 } 21632 } 21633 21634 /** 21635 * Reconcile all app data for the given user. 21636 * <p> 21637 * Verifies that directories exist and that ownership and labeling is 21638 * correct for all installed apps on all mounted volumes. 21639 */ 21640 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21641 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21642 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21643 final String volumeUuid = vol.getFsUuid(); 21644 synchronized (mInstallLock) { 21645 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21646 } 21647 } 21648 } 21649 21650 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21651 boolean migrateAppData) { 21652 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21653 } 21654 21655 /** 21656 * Reconcile all app data on given mounted volume. 21657 * <p> 21658 * Destroys app data that isn't expected, either due to uninstallation or 21659 * reinstallation on another volume. 21660 * <p> 21661 * Verifies that directories exist and that ownership and labeling is 21662 * correct for all installed apps. 21663 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21664 */ 21665 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21666 boolean migrateAppData, boolean onlyCoreApps) { 21667 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21668 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21669 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21670 21671 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21672 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21673 21674 // First look for stale data that doesn't belong, and check if things 21675 // have changed since we did our last restorecon 21676 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21677 if (StorageManager.isFileEncryptedNativeOrEmulated() 21678 && !StorageManager.isUserKeyUnlocked(userId)) { 21679 throw new RuntimeException( 21680 "Yikes, someone asked us to reconcile CE storage while " + userId 21681 + " was still locked; this would have caused massive data loss!"); 21682 } 21683 21684 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21685 for (File file : files) { 21686 final String packageName = file.getName(); 21687 try { 21688 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21689 } catch (PackageManagerException e) { 21690 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21691 try { 21692 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21693 StorageManager.FLAG_STORAGE_CE, 0); 21694 } catch (InstallerException e2) { 21695 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21696 } 21697 } 21698 } 21699 } 21700 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21701 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21702 for (File file : files) { 21703 final String packageName = file.getName(); 21704 try { 21705 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21706 } catch (PackageManagerException e) { 21707 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21708 try { 21709 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21710 StorageManager.FLAG_STORAGE_DE, 0); 21711 } catch (InstallerException e2) { 21712 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21713 } 21714 } 21715 } 21716 } 21717 21718 // Ensure that data directories are ready to roll for all packages 21719 // installed for this volume and user 21720 final List<PackageSetting> packages; 21721 synchronized (mPackages) { 21722 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21723 } 21724 int preparedCount = 0; 21725 for (PackageSetting ps : packages) { 21726 final String packageName = ps.name; 21727 if (ps.pkg == null) { 21728 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21729 // TODO: might be due to legacy ASEC apps; we should circle back 21730 // and reconcile again once they're scanned 21731 continue; 21732 } 21733 // Skip non-core apps if requested 21734 if (onlyCoreApps && !ps.pkg.coreApp) { 21735 result.add(packageName); 21736 continue; 21737 } 21738 21739 if (ps.getInstalled(userId)) { 21740 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21741 preparedCount++; 21742 } 21743 } 21744 21745 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21746 return result; 21747 } 21748 21749 /** 21750 * Prepare app data for the given app just after it was installed or 21751 * upgraded. This method carefully only touches users that it's installed 21752 * for, and it forces a restorecon to handle any seinfo changes. 21753 * <p> 21754 * Verifies that directories exist and that ownership and labeling is 21755 * correct for all installed apps. If there is an ownership mismatch, it 21756 * will try recovering system apps by wiping data; third-party app data is 21757 * left intact. 21758 * <p> 21759 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21760 */ 21761 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21762 final PackageSetting ps; 21763 synchronized (mPackages) { 21764 ps = mSettings.mPackages.get(pkg.packageName); 21765 mSettings.writeKernelMappingLPr(ps); 21766 } 21767 21768 final UserManager um = mContext.getSystemService(UserManager.class); 21769 UserManagerInternal umInternal = getUserManagerInternal(); 21770 for (UserInfo user : um.getUsers()) { 21771 final int flags; 21772 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21773 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21774 } else if (umInternal.isUserRunning(user.id)) { 21775 flags = StorageManager.FLAG_STORAGE_DE; 21776 } else { 21777 continue; 21778 } 21779 21780 if (ps.getInstalled(user.id)) { 21781 // TODO: when user data is locked, mark that we're still dirty 21782 prepareAppDataLIF(pkg, user.id, flags); 21783 } 21784 } 21785 } 21786 21787 /** 21788 * Prepare app data for the given app. 21789 * <p> 21790 * Verifies that directories exist and that ownership and labeling is 21791 * correct for all installed apps. If there is an ownership mismatch, this 21792 * will try recovering system apps by wiping data; third-party app data is 21793 * left intact. 21794 */ 21795 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21796 if (pkg == null) { 21797 Slog.wtf(TAG, "Package was null!", new Throwable()); 21798 return; 21799 } 21800 prepareAppDataLeafLIF(pkg, userId, flags); 21801 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21802 for (int i = 0; i < childCount; i++) { 21803 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21804 } 21805 } 21806 21807 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21808 boolean maybeMigrateAppData) { 21809 prepareAppDataLIF(pkg, userId, flags); 21810 21811 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21812 // We may have just shuffled around app data directories, so 21813 // prepare them one more time 21814 prepareAppDataLIF(pkg, userId, flags); 21815 } 21816 } 21817 21818 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21819 if (DEBUG_APP_DATA) { 21820 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21821 + Integer.toHexString(flags)); 21822 } 21823 21824 final String volumeUuid = pkg.volumeUuid; 21825 final String packageName = pkg.packageName; 21826 final ApplicationInfo app = pkg.applicationInfo; 21827 final int appId = UserHandle.getAppId(app.uid); 21828 21829 Preconditions.checkNotNull(app.seInfo); 21830 21831 long ceDataInode = -1; 21832 try { 21833 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21834 appId, app.seInfo, app.targetSdkVersion); 21835 } catch (InstallerException e) { 21836 if (app.isSystemApp()) { 21837 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21838 + ", but trying to recover: " + e); 21839 destroyAppDataLeafLIF(pkg, userId, flags); 21840 try { 21841 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21842 appId, app.seInfo, app.targetSdkVersion); 21843 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21844 } catch (InstallerException e2) { 21845 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21846 } 21847 } else { 21848 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21849 } 21850 } 21851 21852 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21853 // TODO: mark this structure as dirty so we persist it! 21854 synchronized (mPackages) { 21855 final PackageSetting ps = mSettings.mPackages.get(packageName); 21856 if (ps != null) { 21857 ps.setCeDataInode(ceDataInode, userId); 21858 } 21859 } 21860 } 21861 21862 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21863 } 21864 21865 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21866 if (pkg == null) { 21867 Slog.wtf(TAG, "Package was null!", new Throwable()); 21868 return; 21869 } 21870 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21871 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21872 for (int i = 0; i < childCount; i++) { 21873 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21874 } 21875 } 21876 21877 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21878 final String volumeUuid = pkg.volumeUuid; 21879 final String packageName = pkg.packageName; 21880 final ApplicationInfo app = pkg.applicationInfo; 21881 21882 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21883 // Create a native library symlink only if we have native libraries 21884 // and if the native libraries are 32 bit libraries. We do not provide 21885 // this symlink for 64 bit libraries. 21886 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21887 final String nativeLibPath = app.nativeLibraryDir; 21888 try { 21889 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21890 nativeLibPath, userId); 21891 } catch (InstallerException e) { 21892 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21893 } 21894 } 21895 } 21896 } 21897 21898 /** 21899 * For system apps on non-FBE devices, this method migrates any existing 21900 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21901 * requested by the app. 21902 */ 21903 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21904 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21905 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21906 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21907 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21908 try { 21909 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21910 storageTarget); 21911 } catch (InstallerException e) { 21912 logCriticalInfo(Log.WARN, 21913 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21914 } 21915 return true; 21916 } else { 21917 return false; 21918 } 21919 } 21920 21921 public PackageFreezer freezePackage(String packageName, String killReason) { 21922 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21923 } 21924 21925 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21926 return new PackageFreezer(packageName, userId, killReason); 21927 } 21928 21929 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21930 String killReason) { 21931 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21932 } 21933 21934 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21935 String killReason) { 21936 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21937 return new PackageFreezer(); 21938 } else { 21939 return freezePackage(packageName, userId, killReason); 21940 } 21941 } 21942 21943 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21944 String killReason) { 21945 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21946 } 21947 21948 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21949 String killReason) { 21950 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21951 return new PackageFreezer(); 21952 } else { 21953 return freezePackage(packageName, userId, killReason); 21954 } 21955 } 21956 21957 /** 21958 * Class that freezes and kills the given package upon creation, and 21959 * unfreezes it upon closing. This is typically used when doing surgery on 21960 * app code/data to prevent the app from running while you're working. 21961 */ 21962 private class PackageFreezer implements AutoCloseable { 21963 private final String mPackageName; 21964 private final PackageFreezer[] mChildren; 21965 21966 private final boolean mWeFroze; 21967 21968 private final AtomicBoolean mClosed = new AtomicBoolean(); 21969 private final CloseGuard mCloseGuard = CloseGuard.get(); 21970 21971 /** 21972 * Create and return a stub freezer that doesn't actually do anything, 21973 * typically used when someone requested 21974 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21975 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21976 */ 21977 public PackageFreezer() { 21978 mPackageName = null; 21979 mChildren = null; 21980 mWeFroze = false; 21981 mCloseGuard.open("close"); 21982 } 21983 21984 public PackageFreezer(String packageName, int userId, String killReason) { 21985 synchronized (mPackages) { 21986 mPackageName = packageName; 21987 mWeFroze = mFrozenPackages.add(mPackageName); 21988 21989 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21990 if (ps != null) { 21991 killApplication(ps.name, ps.appId, userId, killReason); 21992 } 21993 21994 final PackageParser.Package p = mPackages.get(packageName); 21995 if (p != null && p.childPackages != null) { 21996 final int N = p.childPackages.size(); 21997 mChildren = new PackageFreezer[N]; 21998 for (int i = 0; i < N; i++) { 21999 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22000 userId, killReason); 22001 } 22002 } else { 22003 mChildren = null; 22004 } 22005 } 22006 mCloseGuard.open("close"); 22007 } 22008 22009 @Override 22010 protected void finalize() throws Throwable { 22011 try { 22012 mCloseGuard.warnIfOpen(); 22013 close(); 22014 } finally { 22015 super.finalize(); 22016 } 22017 } 22018 22019 @Override 22020 public void close() { 22021 mCloseGuard.close(); 22022 if (mClosed.compareAndSet(false, true)) { 22023 synchronized (mPackages) { 22024 if (mWeFroze) { 22025 mFrozenPackages.remove(mPackageName); 22026 } 22027 22028 if (mChildren != null) { 22029 for (PackageFreezer freezer : mChildren) { 22030 freezer.close(); 22031 } 22032 } 22033 } 22034 } 22035 } 22036 } 22037 22038 /** 22039 * Verify that given package is currently frozen. 22040 */ 22041 private void checkPackageFrozen(String packageName) { 22042 synchronized (mPackages) { 22043 if (!mFrozenPackages.contains(packageName)) { 22044 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22045 } 22046 } 22047 } 22048 22049 @Override 22050 public int movePackage(final String packageName, final String volumeUuid) { 22051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22052 22053 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22054 final int moveId = mNextMoveId.getAndIncrement(); 22055 mHandler.post(new Runnable() { 22056 @Override 22057 public void run() { 22058 try { 22059 movePackageInternal(packageName, volumeUuid, moveId, user); 22060 } catch (PackageManagerException e) { 22061 Slog.w(TAG, "Failed to move " + packageName, e); 22062 mMoveCallbacks.notifyStatusChanged(moveId, 22063 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22064 } 22065 } 22066 }); 22067 return moveId; 22068 } 22069 22070 private void movePackageInternal(final String packageName, final String volumeUuid, 22071 final int moveId, UserHandle user) throws PackageManagerException { 22072 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22073 final PackageManager pm = mContext.getPackageManager(); 22074 22075 final boolean currentAsec; 22076 final String currentVolumeUuid; 22077 final File codeFile; 22078 final String installerPackageName; 22079 final String packageAbiOverride; 22080 final int appId; 22081 final String seinfo; 22082 final String label; 22083 final int targetSdkVersion; 22084 final PackageFreezer freezer; 22085 final int[] installedUserIds; 22086 22087 // reader 22088 synchronized (mPackages) { 22089 final PackageParser.Package pkg = mPackages.get(packageName); 22090 final PackageSetting ps = mSettings.mPackages.get(packageName); 22091 if (pkg == null || ps == null) { 22092 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22093 } 22094 22095 if (pkg.applicationInfo.isSystemApp()) { 22096 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22097 "Cannot move system application"); 22098 } 22099 22100 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22101 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22102 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22103 if (isInternalStorage && !allow3rdPartyOnInternal) { 22104 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22105 "3rd party apps are not allowed on internal storage"); 22106 } 22107 22108 if (pkg.applicationInfo.isExternalAsec()) { 22109 currentAsec = true; 22110 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22111 } else if (pkg.applicationInfo.isForwardLocked()) { 22112 currentAsec = true; 22113 currentVolumeUuid = "forward_locked"; 22114 } else { 22115 currentAsec = false; 22116 currentVolumeUuid = ps.volumeUuid; 22117 22118 final File probe = new File(pkg.codePath); 22119 final File probeOat = new File(probe, "oat"); 22120 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22121 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22122 "Move only supported for modern cluster style installs"); 22123 } 22124 } 22125 22126 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22127 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22128 "Package already moved to " + volumeUuid); 22129 } 22130 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22131 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22132 "Device admin cannot be moved"); 22133 } 22134 22135 if (mFrozenPackages.contains(packageName)) { 22136 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22137 "Failed to move already frozen package"); 22138 } 22139 22140 codeFile = new File(pkg.codePath); 22141 installerPackageName = ps.installerPackageName; 22142 packageAbiOverride = ps.cpuAbiOverrideString; 22143 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22144 seinfo = pkg.applicationInfo.seInfo; 22145 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22146 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22147 freezer = freezePackage(packageName, "movePackageInternal"); 22148 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22149 } 22150 22151 final Bundle extras = new Bundle(); 22152 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22153 extras.putString(Intent.EXTRA_TITLE, label); 22154 mMoveCallbacks.notifyCreated(moveId, extras); 22155 22156 int installFlags; 22157 final boolean moveCompleteApp; 22158 final File measurePath; 22159 22160 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22161 installFlags = INSTALL_INTERNAL; 22162 moveCompleteApp = !currentAsec; 22163 measurePath = Environment.getDataAppDirectory(volumeUuid); 22164 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22165 installFlags = INSTALL_EXTERNAL; 22166 moveCompleteApp = false; 22167 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22168 } else { 22169 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22170 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22171 || !volume.isMountedWritable()) { 22172 freezer.close(); 22173 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22174 "Move location not mounted private volume"); 22175 } 22176 22177 Preconditions.checkState(!currentAsec); 22178 22179 installFlags = INSTALL_INTERNAL; 22180 moveCompleteApp = true; 22181 measurePath = Environment.getDataAppDirectory(volumeUuid); 22182 } 22183 22184 final PackageStats stats = new PackageStats(null, -1); 22185 synchronized (mInstaller) { 22186 for (int userId : installedUserIds) { 22187 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22188 freezer.close(); 22189 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22190 "Failed to measure package size"); 22191 } 22192 } 22193 } 22194 22195 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22196 + stats.dataSize); 22197 22198 final long startFreeBytes = measurePath.getFreeSpace(); 22199 final long sizeBytes; 22200 if (moveCompleteApp) { 22201 sizeBytes = stats.codeSize + stats.dataSize; 22202 } else { 22203 sizeBytes = stats.codeSize; 22204 } 22205 22206 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22207 freezer.close(); 22208 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22209 "Not enough free space to move"); 22210 } 22211 22212 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22213 22214 final CountDownLatch installedLatch = new CountDownLatch(1); 22215 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22216 @Override 22217 public void onUserActionRequired(Intent intent) throws RemoteException { 22218 throw new IllegalStateException(); 22219 } 22220 22221 @Override 22222 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22223 Bundle extras) throws RemoteException { 22224 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22225 + PackageManager.installStatusToString(returnCode, msg)); 22226 22227 installedLatch.countDown(); 22228 freezer.close(); 22229 22230 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22231 switch (status) { 22232 case PackageInstaller.STATUS_SUCCESS: 22233 mMoveCallbacks.notifyStatusChanged(moveId, 22234 PackageManager.MOVE_SUCCEEDED); 22235 break; 22236 case PackageInstaller.STATUS_FAILURE_STORAGE: 22237 mMoveCallbacks.notifyStatusChanged(moveId, 22238 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22239 break; 22240 default: 22241 mMoveCallbacks.notifyStatusChanged(moveId, 22242 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22243 break; 22244 } 22245 } 22246 }; 22247 22248 final MoveInfo move; 22249 if (moveCompleteApp) { 22250 // Kick off a thread to report progress estimates 22251 new Thread() { 22252 @Override 22253 public void run() { 22254 while (true) { 22255 try { 22256 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22257 break; 22258 } 22259 } catch (InterruptedException ignored) { 22260 } 22261 22262 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22263 final int progress = 10 + (int) MathUtils.constrain( 22264 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22265 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22266 } 22267 } 22268 }.start(); 22269 22270 final String dataAppName = codeFile.getName(); 22271 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22272 dataAppName, appId, seinfo, targetSdkVersion); 22273 } else { 22274 move = null; 22275 } 22276 22277 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22278 22279 final Message msg = mHandler.obtainMessage(INIT_COPY); 22280 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22281 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22282 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22283 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22284 PackageManager.INSTALL_REASON_UNKNOWN); 22285 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22286 msg.obj = params; 22287 22288 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22289 System.identityHashCode(msg.obj)); 22290 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22291 System.identityHashCode(msg.obj)); 22292 22293 mHandler.sendMessage(msg); 22294 } 22295 22296 @Override 22297 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22298 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22299 22300 final int realMoveId = mNextMoveId.getAndIncrement(); 22301 final Bundle extras = new Bundle(); 22302 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22303 mMoveCallbacks.notifyCreated(realMoveId, extras); 22304 22305 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22306 @Override 22307 public void onCreated(int moveId, Bundle extras) { 22308 // Ignored 22309 } 22310 22311 @Override 22312 public void onStatusChanged(int moveId, int status, long estMillis) { 22313 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22314 } 22315 }; 22316 22317 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22318 storage.setPrimaryStorageUuid(volumeUuid, callback); 22319 return realMoveId; 22320 } 22321 22322 @Override 22323 public int getMoveStatus(int moveId) { 22324 mContext.enforceCallingOrSelfPermission( 22325 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22326 return mMoveCallbacks.mLastStatus.get(moveId); 22327 } 22328 22329 @Override 22330 public void registerMoveCallback(IPackageMoveObserver callback) { 22331 mContext.enforceCallingOrSelfPermission( 22332 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22333 mMoveCallbacks.register(callback); 22334 } 22335 22336 @Override 22337 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22338 mContext.enforceCallingOrSelfPermission( 22339 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22340 mMoveCallbacks.unregister(callback); 22341 } 22342 22343 @Override 22344 public boolean setInstallLocation(int loc) { 22345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22346 null); 22347 if (getInstallLocation() == loc) { 22348 return true; 22349 } 22350 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22351 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22352 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22353 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22354 return true; 22355 } 22356 return false; 22357 } 22358 22359 @Override 22360 public int getInstallLocation() { 22361 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22362 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22363 PackageHelper.APP_INSTALL_AUTO); 22364 } 22365 22366 /** Called by UserManagerService */ 22367 void cleanUpUser(UserManagerService userManager, int userHandle) { 22368 synchronized (mPackages) { 22369 mDirtyUsers.remove(userHandle); 22370 mUserNeedsBadging.delete(userHandle); 22371 mSettings.removeUserLPw(userHandle); 22372 mPendingBroadcasts.remove(userHandle); 22373 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22374 removeUnusedPackagesLPw(userManager, userHandle); 22375 } 22376 } 22377 22378 /** 22379 * We're removing userHandle and would like to remove any downloaded packages 22380 * that are no longer in use by any other user. 22381 * @param userHandle the user being removed 22382 */ 22383 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22384 final boolean DEBUG_CLEAN_APKS = false; 22385 int [] users = userManager.getUserIds(); 22386 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22387 while (psit.hasNext()) { 22388 PackageSetting ps = psit.next(); 22389 if (ps.pkg == null) { 22390 continue; 22391 } 22392 final String packageName = ps.pkg.packageName; 22393 // Skip over if system app 22394 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22395 continue; 22396 } 22397 if (DEBUG_CLEAN_APKS) { 22398 Slog.i(TAG, "Checking package " + packageName); 22399 } 22400 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22401 if (keep) { 22402 if (DEBUG_CLEAN_APKS) { 22403 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22404 } 22405 } else { 22406 for (int i = 0; i < users.length; i++) { 22407 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22408 keep = true; 22409 if (DEBUG_CLEAN_APKS) { 22410 Slog.i(TAG, " Keeping package " + packageName + " for user " 22411 + users[i]); 22412 } 22413 break; 22414 } 22415 } 22416 } 22417 if (!keep) { 22418 if (DEBUG_CLEAN_APKS) { 22419 Slog.i(TAG, " Removing package " + packageName); 22420 } 22421 mHandler.post(new Runnable() { 22422 public void run() { 22423 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22424 userHandle, 0); 22425 } //end run 22426 }); 22427 } 22428 } 22429 } 22430 22431 /** Called by UserManagerService */ 22432 void createNewUser(int userId, String[] disallowedPackages) { 22433 synchronized (mInstallLock) { 22434 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22435 } 22436 synchronized (mPackages) { 22437 scheduleWritePackageRestrictionsLocked(userId); 22438 scheduleWritePackageListLocked(userId); 22439 applyFactoryDefaultBrowserLPw(userId); 22440 primeDomainVerificationsLPw(userId); 22441 } 22442 } 22443 22444 void onNewUserCreated(final int userId) { 22445 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22446 // If permission review for legacy apps is required, we represent 22447 // dagerous permissions for such apps as always granted runtime 22448 // permissions to keep per user flag state whether review is needed. 22449 // Hence, if a new user is added we have to propagate dangerous 22450 // permission grants for these legacy apps. 22451 if (mPermissionReviewRequired) { 22452 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22453 | UPDATE_PERMISSIONS_REPLACE_ALL); 22454 } 22455 } 22456 22457 @Override 22458 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22459 mContext.enforceCallingOrSelfPermission( 22460 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22461 "Only package verification agents can read the verifier device identity"); 22462 22463 synchronized (mPackages) { 22464 return mSettings.getVerifierDeviceIdentityLPw(); 22465 } 22466 } 22467 22468 @Override 22469 public void setPermissionEnforced(String permission, boolean enforced) { 22470 // TODO: Now that we no longer change GID for storage, this should to away. 22471 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22472 "setPermissionEnforced"); 22473 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22474 synchronized (mPackages) { 22475 if (mSettings.mReadExternalStorageEnforced == null 22476 || mSettings.mReadExternalStorageEnforced != enforced) { 22477 mSettings.mReadExternalStorageEnforced = enforced; 22478 mSettings.writeLPr(); 22479 } 22480 } 22481 // kill any non-foreground processes so we restart them and 22482 // grant/revoke the GID. 22483 final IActivityManager am = ActivityManager.getService(); 22484 if (am != null) { 22485 final long token = Binder.clearCallingIdentity(); 22486 try { 22487 am.killProcessesBelowForeground("setPermissionEnforcement"); 22488 } catch (RemoteException e) { 22489 } finally { 22490 Binder.restoreCallingIdentity(token); 22491 } 22492 } 22493 } else { 22494 throw new IllegalArgumentException("No selective enforcement for " + permission); 22495 } 22496 } 22497 22498 @Override 22499 @Deprecated 22500 public boolean isPermissionEnforced(String permission) { 22501 return true; 22502 } 22503 22504 @Override 22505 public boolean isStorageLow() { 22506 final long token = Binder.clearCallingIdentity(); 22507 try { 22508 final DeviceStorageMonitorInternal 22509 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22510 if (dsm != null) { 22511 return dsm.isMemoryLow(); 22512 } else { 22513 return false; 22514 } 22515 } finally { 22516 Binder.restoreCallingIdentity(token); 22517 } 22518 } 22519 22520 @Override 22521 public IPackageInstaller getPackageInstaller() { 22522 return mInstallerService; 22523 } 22524 22525 private boolean userNeedsBadging(int userId) { 22526 int index = mUserNeedsBadging.indexOfKey(userId); 22527 if (index < 0) { 22528 final UserInfo userInfo; 22529 final long token = Binder.clearCallingIdentity(); 22530 try { 22531 userInfo = sUserManager.getUserInfo(userId); 22532 } finally { 22533 Binder.restoreCallingIdentity(token); 22534 } 22535 final boolean b; 22536 if (userInfo != null && userInfo.isManagedProfile()) { 22537 b = true; 22538 } else { 22539 b = false; 22540 } 22541 mUserNeedsBadging.put(userId, b); 22542 return b; 22543 } 22544 return mUserNeedsBadging.valueAt(index); 22545 } 22546 22547 @Override 22548 public KeySet getKeySetByAlias(String packageName, String alias) { 22549 if (packageName == null || alias == null) { 22550 return null; 22551 } 22552 synchronized(mPackages) { 22553 final PackageParser.Package pkg = mPackages.get(packageName); 22554 if (pkg == null) { 22555 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22556 throw new IllegalArgumentException("Unknown package: " + packageName); 22557 } 22558 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22559 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22560 } 22561 } 22562 22563 @Override 22564 public KeySet getSigningKeySet(String packageName) { 22565 if (packageName == null) { 22566 return null; 22567 } 22568 synchronized(mPackages) { 22569 final PackageParser.Package pkg = mPackages.get(packageName); 22570 if (pkg == null) { 22571 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22572 throw new IllegalArgumentException("Unknown package: " + packageName); 22573 } 22574 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22575 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22576 throw new SecurityException("May not access signing KeySet of other apps."); 22577 } 22578 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22579 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22580 } 22581 } 22582 22583 @Override 22584 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22585 if (packageName == null || ks == null) { 22586 return false; 22587 } 22588 synchronized(mPackages) { 22589 final PackageParser.Package pkg = mPackages.get(packageName); 22590 if (pkg == null) { 22591 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22592 throw new IllegalArgumentException("Unknown package: " + packageName); 22593 } 22594 IBinder ksh = ks.getToken(); 22595 if (ksh instanceof KeySetHandle) { 22596 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22597 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22598 } 22599 return false; 22600 } 22601 } 22602 22603 @Override 22604 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22605 if (packageName == null || ks == null) { 22606 return false; 22607 } 22608 synchronized(mPackages) { 22609 final PackageParser.Package pkg = mPackages.get(packageName); 22610 if (pkg == null) { 22611 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22612 throw new IllegalArgumentException("Unknown package: " + packageName); 22613 } 22614 IBinder ksh = ks.getToken(); 22615 if (ksh instanceof KeySetHandle) { 22616 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22617 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22618 } 22619 return false; 22620 } 22621 } 22622 22623 private void deletePackageIfUnusedLPr(final String packageName) { 22624 PackageSetting ps = mSettings.mPackages.get(packageName); 22625 if (ps == null) { 22626 return; 22627 } 22628 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22629 // TODO Implement atomic delete if package is unused 22630 // It is currently possible that the package will be deleted even if it is installed 22631 // after this method returns. 22632 mHandler.post(new Runnable() { 22633 public void run() { 22634 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22635 0, PackageManager.DELETE_ALL_USERS); 22636 } 22637 }); 22638 } 22639 } 22640 22641 /** 22642 * Check and throw if the given before/after packages would be considered a 22643 * downgrade. 22644 */ 22645 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22646 throws PackageManagerException { 22647 if (after.versionCode < before.mVersionCode) { 22648 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22649 "Update version code " + after.versionCode + " is older than current " 22650 + before.mVersionCode); 22651 } else if (after.versionCode == before.mVersionCode) { 22652 if (after.baseRevisionCode < before.baseRevisionCode) { 22653 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22654 "Update base revision code " + after.baseRevisionCode 22655 + " is older than current " + before.baseRevisionCode); 22656 } 22657 22658 if (!ArrayUtils.isEmpty(after.splitNames)) { 22659 for (int i = 0; i < after.splitNames.length; i++) { 22660 final String splitName = after.splitNames[i]; 22661 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22662 if (j != -1) { 22663 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22664 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22665 "Update split " + splitName + " revision code " 22666 + after.splitRevisionCodes[i] + " is older than current " 22667 + before.splitRevisionCodes[j]); 22668 } 22669 } 22670 } 22671 } 22672 } 22673 } 22674 22675 private static class MoveCallbacks extends Handler { 22676 private static final int MSG_CREATED = 1; 22677 private static final int MSG_STATUS_CHANGED = 2; 22678 22679 private final RemoteCallbackList<IPackageMoveObserver> 22680 mCallbacks = new RemoteCallbackList<>(); 22681 22682 private final SparseIntArray mLastStatus = new SparseIntArray(); 22683 22684 public MoveCallbacks(Looper looper) { 22685 super(looper); 22686 } 22687 22688 public void register(IPackageMoveObserver callback) { 22689 mCallbacks.register(callback); 22690 } 22691 22692 public void unregister(IPackageMoveObserver callback) { 22693 mCallbacks.unregister(callback); 22694 } 22695 22696 @Override 22697 public void handleMessage(Message msg) { 22698 final SomeArgs args = (SomeArgs) msg.obj; 22699 final int n = mCallbacks.beginBroadcast(); 22700 for (int i = 0; i < n; i++) { 22701 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22702 try { 22703 invokeCallback(callback, msg.what, args); 22704 } catch (RemoteException ignored) { 22705 } 22706 } 22707 mCallbacks.finishBroadcast(); 22708 args.recycle(); 22709 } 22710 22711 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22712 throws RemoteException { 22713 switch (what) { 22714 case MSG_CREATED: { 22715 callback.onCreated(args.argi1, (Bundle) args.arg2); 22716 break; 22717 } 22718 case MSG_STATUS_CHANGED: { 22719 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22720 break; 22721 } 22722 } 22723 } 22724 22725 private void notifyCreated(int moveId, Bundle extras) { 22726 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22727 22728 final SomeArgs args = SomeArgs.obtain(); 22729 args.argi1 = moveId; 22730 args.arg2 = extras; 22731 obtainMessage(MSG_CREATED, args).sendToTarget(); 22732 } 22733 22734 private void notifyStatusChanged(int moveId, int status) { 22735 notifyStatusChanged(moveId, status, -1); 22736 } 22737 22738 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22739 Slog.v(TAG, "Move " + moveId + " status " + status); 22740 22741 final SomeArgs args = SomeArgs.obtain(); 22742 args.argi1 = moveId; 22743 args.argi2 = status; 22744 args.arg3 = estMillis; 22745 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22746 22747 synchronized (mLastStatus) { 22748 mLastStatus.put(moveId, status); 22749 } 22750 } 22751 } 22752 22753 private final static class OnPermissionChangeListeners extends Handler { 22754 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22755 22756 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22757 new RemoteCallbackList<>(); 22758 22759 public OnPermissionChangeListeners(Looper looper) { 22760 super(looper); 22761 } 22762 22763 @Override 22764 public void handleMessage(Message msg) { 22765 switch (msg.what) { 22766 case MSG_ON_PERMISSIONS_CHANGED: { 22767 final int uid = msg.arg1; 22768 handleOnPermissionsChanged(uid); 22769 } break; 22770 } 22771 } 22772 22773 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22774 mPermissionListeners.register(listener); 22775 22776 } 22777 22778 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22779 mPermissionListeners.unregister(listener); 22780 } 22781 22782 public void onPermissionsChanged(int uid) { 22783 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22784 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22785 } 22786 } 22787 22788 private void handleOnPermissionsChanged(int uid) { 22789 final int count = mPermissionListeners.beginBroadcast(); 22790 try { 22791 for (int i = 0; i < count; i++) { 22792 IOnPermissionsChangeListener callback = mPermissionListeners 22793 .getBroadcastItem(i); 22794 try { 22795 callback.onPermissionsChanged(uid); 22796 } catch (RemoteException e) { 22797 Log.e(TAG, "Permission listener is dead", e); 22798 } 22799 } 22800 } finally { 22801 mPermissionListeners.finishBroadcast(); 22802 } 22803 } 22804 } 22805 22806 private class PackageManagerInternalImpl extends PackageManagerInternal { 22807 @Override 22808 public void setLocationPackagesProvider(PackagesProvider provider) { 22809 synchronized (mPackages) { 22810 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22811 } 22812 } 22813 22814 @Override 22815 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22816 synchronized (mPackages) { 22817 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22818 } 22819 } 22820 22821 @Override 22822 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22823 synchronized (mPackages) { 22824 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22825 } 22826 } 22827 22828 @Override 22829 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22830 synchronized (mPackages) { 22831 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22832 } 22833 } 22834 22835 @Override 22836 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22837 synchronized (mPackages) { 22838 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22839 } 22840 } 22841 22842 @Override 22843 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22844 synchronized (mPackages) { 22845 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22846 } 22847 } 22848 22849 @Override 22850 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22851 synchronized (mPackages) { 22852 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22853 packageName, userId); 22854 } 22855 } 22856 22857 @Override 22858 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22859 synchronized (mPackages) { 22860 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22861 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22862 packageName, userId); 22863 } 22864 } 22865 22866 @Override 22867 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22868 synchronized (mPackages) { 22869 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22870 packageName, userId); 22871 } 22872 } 22873 22874 @Override 22875 public void setKeepUninstalledPackages(final List<String> packageList) { 22876 Preconditions.checkNotNull(packageList); 22877 List<String> removedFromList = null; 22878 synchronized (mPackages) { 22879 if (mKeepUninstalledPackages != null) { 22880 final int packagesCount = mKeepUninstalledPackages.size(); 22881 for (int i = 0; i < packagesCount; i++) { 22882 String oldPackage = mKeepUninstalledPackages.get(i); 22883 if (packageList != null && packageList.contains(oldPackage)) { 22884 continue; 22885 } 22886 if (removedFromList == null) { 22887 removedFromList = new ArrayList<>(); 22888 } 22889 removedFromList.add(oldPackage); 22890 } 22891 } 22892 mKeepUninstalledPackages = new ArrayList<>(packageList); 22893 if (removedFromList != null) { 22894 final int removedCount = removedFromList.size(); 22895 for (int i = 0; i < removedCount; i++) { 22896 deletePackageIfUnusedLPr(removedFromList.get(i)); 22897 } 22898 } 22899 } 22900 } 22901 22902 @Override 22903 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22904 synchronized (mPackages) { 22905 // If we do not support permission review, done. 22906 if (!mPermissionReviewRequired) { 22907 return false; 22908 } 22909 22910 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22911 if (packageSetting == null) { 22912 return false; 22913 } 22914 22915 // Permission review applies only to apps not supporting the new permission model. 22916 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22917 return false; 22918 } 22919 22920 // Legacy apps have the permission and get user consent on launch. 22921 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22922 return permissionsState.isPermissionReviewRequired(userId); 22923 } 22924 } 22925 22926 @Override 22927 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22928 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22929 } 22930 22931 @Override 22932 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22933 int userId) { 22934 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22935 } 22936 22937 @Override 22938 public void setDeviceAndProfileOwnerPackages( 22939 int deviceOwnerUserId, String deviceOwnerPackage, 22940 SparseArray<String> profileOwnerPackages) { 22941 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22942 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22943 } 22944 22945 @Override 22946 public boolean isPackageDataProtected(int userId, String packageName) { 22947 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22948 } 22949 22950 @Override 22951 public boolean isPackageEphemeral(int userId, String packageName) { 22952 synchronized (mPackages) { 22953 final PackageSetting ps = mSettings.mPackages.get(packageName); 22954 return ps != null ? ps.getInstantApp(userId) : false; 22955 } 22956 } 22957 22958 @Override 22959 public boolean wasPackageEverLaunched(String packageName, int userId) { 22960 synchronized (mPackages) { 22961 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22962 } 22963 } 22964 22965 @Override 22966 public void grantRuntimePermission(String packageName, String name, int userId, 22967 boolean overridePolicy) { 22968 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22969 overridePolicy); 22970 } 22971 22972 @Override 22973 public void revokeRuntimePermission(String packageName, String name, int userId, 22974 boolean overridePolicy) { 22975 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22976 overridePolicy); 22977 } 22978 22979 @Override 22980 public String getNameForUid(int uid) { 22981 return PackageManagerService.this.getNameForUid(uid); 22982 } 22983 22984 @Override 22985 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 22986 Intent origIntent, String resolvedType, String callingPackage, int userId) { 22987 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 22988 responseObj, origIntent, resolvedType, callingPackage, userId); 22989 } 22990 22991 @Override 22992 public void grantEphemeralAccess(int userId, Intent intent, 22993 int targetAppId, int ephemeralAppId) { 22994 synchronized (mPackages) { 22995 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22996 targetAppId, ephemeralAppId); 22997 } 22998 } 22999 23000 @Override 23001 public void pruneInstantApps() { 23002 synchronized (mPackages) { 23003 mInstantAppRegistry.pruneInstantAppsLPw(); 23004 } 23005 } 23006 23007 @Override 23008 public String getSetupWizardPackageName() { 23009 return mSetupWizardPackage; 23010 } 23011 23012 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23013 if (policy != null) { 23014 mExternalSourcesPolicy = policy; 23015 } 23016 } 23017 23018 @Override 23019 public boolean isPackagePersistent(String packageName) { 23020 synchronized (mPackages) { 23021 PackageParser.Package pkg = mPackages.get(packageName); 23022 return pkg != null 23023 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23024 | ApplicationInfo.FLAG_PERSISTENT)) == 23025 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23026 : false; 23027 } 23028 } 23029 23030 @Override 23031 public List<PackageInfo> getOverlayPackages(int userId) { 23032 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23033 synchronized (mPackages) { 23034 for (PackageParser.Package p : mPackages.values()) { 23035 if (p.mOverlayTarget != null) { 23036 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23037 if (pkg != null) { 23038 overlayPackages.add(pkg); 23039 } 23040 } 23041 } 23042 } 23043 return overlayPackages; 23044 } 23045 23046 @Override 23047 public List<String> getTargetPackageNames(int userId) { 23048 List<String> targetPackages = new ArrayList<>(); 23049 synchronized (mPackages) { 23050 for (PackageParser.Package p : mPackages.values()) { 23051 if (p.mOverlayTarget == null) { 23052 targetPackages.add(p.packageName); 23053 } 23054 } 23055 } 23056 return targetPackages; 23057 } 23058 23059 @Override 23060 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23061 @Nullable List<String> overlayPackageNames) { 23062 synchronized (mPackages) { 23063 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23064 Slog.e(TAG, "failed to find package " + targetPackageName); 23065 return false; 23066 } 23067 23068 ArrayList<String> paths = null; 23069 if (overlayPackageNames != null) { 23070 final int N = overlayPackageNames.size(); 23071 paths = new ArrayList<>(N); 23072 for (int i = 0; i < N; i++) { 23073 final String packageName = overlayPackageNames.get(i); 23074 final PackageParser.Package pkg = mPackages.get(packageName); 23075 if (pkg == null) { 23076 Slog.e(TAG, "failed to find package " + packageName); 23077 return false; 23078 } 23079 paths.add(pkg.baseCodePath); 23080 } 23081 } 23082 23083 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23084 mEnabledOverlayPaths.get(userId); 23085 if (userSpecificOverlays == null) { 23086 userSpecificOverlays = new ArrayMap<>(); 23087 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23088 } 23089 23090 if (paths != null && paths.size() > 0) { 23091 userSpecificOverlays.put(targetPackageName, paths); 23092 } else { 23093 userSpecificOverlays.remove(targetPackageName); 23094 } 23095 return true; 23096 } 23097 } 23098 23099 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23100 int flags, int userId) { 23101 return resolveIntentInternal( 23102 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23103 } 23104 } 23105 23106 @Override 23107 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23108 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23109 synchronized (mPackages) { 23110 final long identity = Binder.clearCallingIdentity(); 23111 try { 23112 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23113 packageNames, userId); 23114 } finally { 23115 Binder.restoreCallingIdentity(identity); 23116 } 23117 } 23118 } 23119 23120 @Override 23121 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23122 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23123 synchronized (mPackages) { 23124 final long identity = Binder.clearCallingIdentity(); 23125 try { 23126 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23127 packageNames, userId); 23128 } finally { 23129 Binder.restoreCallingIdentity(identity); 23130 } 23131 } 23132 } 23133 23134 private static void enforceSystemOrPhoneCaller(String tag) { 23135 int callingUid = Binder.getCallingUid(); 23136 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23137 throw new SecurityException( 23138 "Cannot call " + tag + " from UID " + callingUid); 23139 } 23140 } 23141 23142 boolean isHistoricalPackageUsageAvailable() { 23143 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23144 } 23145 23146 /** 23147 * Return a <b>copy</b> of the collection of packages known to the package manager. 23148 * @return A copy of the values of mPackages. 23149 */ 23150 Collection<PackageParser.Package> getPackages() { 23151 synchronized (mPackages) { 23152 return new ArrayList<>(mPackages.values()); 23153 } 23154 } 23155 23156 /** 23157 * Logs process start information (including base APK hash) to the security log. 23158 * @hide 23159 */ 23160 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23161 String apkFile, int pid) { 23162 if (!SecurityLog.isLoggingEnabled()) { 23163 return; 23164 } 23165 Bundle data = new Bundle(); 23166 data.putLong("startTimestamp", System.currentTimeMillis()); 23167 data.putString("processName", processName); 23168 data.putInt("uid", uid); 23169 data.putString("seinfo", seinfo); 23170 data.putString("apkFile", apkFile); 23171 data.putInt("pid", pid); 23172 Message msg = mProcessLoggingHandler.obtainMessage( 23173 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23174 msg.setData(data); 23175 mProcessLoggingHandler.sendMessage(msg); 23176 } 23177 23178 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23179 return mCompilerStats.getPackageStats(pkgName); 23180 } 23181 23182 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23183 return getOrCreateCompilerPackageStats(pkg.packageName); 23184 } 23185 23186 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23187 return mCompilerStats.getOrCreatePackageStats(pkgName); 23188 } 23189 23190 public void deleteCompilerPackageStats(String pkgName) { 23191 mCompilerStats.deletePackageStats(pkgName); 23192 } 23193 23194 @Override 23195 public int getInstallReason(String packageName, int userId) { 23196 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23197 true /* requireFullPermission */, false /* checkShell */, 23198 "get install reason"); 23199 synchronized (mPackages) { 23200 final PackageSetting ps = mSettings.mPackages.get(packageName); 23201 if (ps != null) { 23202 return ps.getInstallReason(userId); 23203 } 23204 } 23205 return PackageManager.INSTALL_REASON_UNKNOWN; 23206 } 23207 23208 @Override 23209 public boolean canRequestPackageInstalls(String packageName, int userId) { 23210 int callingUid = Binder.getCallingUid(); 23211 int uid = getPackageUid(packageName, 0, userId); 23212 if (callingUid != uid && callingUid != Process.ROOT_UID 23213 && callingUid != Process.SYSTEM_UID) { 23214 throw new SecurityException( 23215 "Caller uid " + callingUid + " does not own package " + packageName); 23216 } 23217 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23218 if (info == null) { 23219 return false; 23220 } 23221 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23222 throw new UnsupportedOperationException( 23223 "Operation only supported on apps targeting Android O or higher"); 23224 } 23225 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23226 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23227 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23228 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23229 } 23230 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23231 return false; 23232 } 23233 if (mExternalSourcesPolicy != null) { 23234 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23235 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23236 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23237 } 23238 } 23239 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23240 } 23241} 23242