PackageManagerService.java revision a70b1b120365976f5eeb7cb3f577f5f6ff7ad18e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppRequest; 132import android.content.pm.AuxiliaryResolveInfo; 133import android.content.pm.FallbackCategoryProvider; 134import android.content.pm.FeatureInfo; 135import android.content.pm.IOnPermissionsChangeListener; 136import android.content.pm.IPackageDataObserver; 137import android.content.pm.IPackageDeleteObserver; 138import android.content.pm.IPackageDeleteObserver2; 139import android.content.pm.IPackageInstallObserver2; 140import android.content.pm.IPackageInstaller; 141import android.content.pm.IPackageManager; 142import android.content.pm.IPackageMoveObserver; 143import android.content.pm.IPackageStatsObserver; 144import android.content.pm.InstantAppInfo; 145import android.content.pm.InstantAppResolveInfo; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.FastPrintWriter; 258import com.android.internal.util.FastXmlSerializer; 259import com.android.internal.util.IndentingPrintWriter; 260import com.android.internal.util.Preconditions; 261import com.android.internal.util.XmlUtils; 262import com.android.server.AttributeCache; 263import com.android.server.DeviceIdleController; 264import com.android.server.EventLogTags; 265import com.android.server.FgThread; 266import com.android.server.IntentResolver; 267import com.android.server.LocalServices; 268import com.android.server.LockGuard; 269import com.android.server.ServiceThread; 270import com.android.server.SystemConfig; 271import com.android.server.SystemServerInitThreadPool; 272import com.android.server.Watchdog; 273import com.android.server.net.NetworkPolicyManagerInternal; 274import com.android.server.pm.BackgroundDexOptService; 275import com.android.server.pm.Installer.InstallerException; 276import com.android.server.pm.PermissionsState.PermissionState; 277import com.android.server.pm.Settings.DatabaseVersion; 278import com.android.server.pm.Settings.VersionInfo; 279import com.android.server.pm.dex.DexManager; 280import com.android.server.storage.DeviceStorageMonitorInternal; 281 282import dalvik.system.CloseGuard; 283import dalvik.system.DexFile; 284import dalvik.system.VMRuntime; 285 286import libcore.io.IoUtils; 287import libcore.util.EmptyArray; 288 289import org.xmlpull.v1.XmlPullParser; 290import org.xmlpull.v1.XmlPullParserException; 291import org.xmlpull.v1.XmlSerializer; 292 293import java.io.BufferedOutputStream; 294import java.io.BufferedReader; 295import java.io.ByteArrayInputStream; 296import java.io.ByteArrayOutputStream; 297import java.io.File; 298import java.io.FileDescriptor; 299import java.io.FileInputStream; 300import java.io.FileNotFoundException; 301import java.io.FileOutputStream; 302import java.io.FileReader; 303import java.io.FilenameFilter; 304import java.io.IOException; 305import java.io.PrintWriter; 306import java.nio.charset.StandardCharsets; 307import java.security.DigestInputStream; 308import java.security.MessageDigest; 309import java.security.NoSuchAlgorithmException; 310import java.security.PublicKey; 311import java.security.SecureRandom; 312import java.security.cert.Certificate; 313import java.security.cert.CertificateEncodingException; 314import java.security.cert.CertificateException; 315import java.text.SimpleDateFormat; 316import java.util.ArrayList; 317import java.util.Arrays; 318import java.util.Collection; 319import java.util.Collections; 320import java.util.Comparator; 321import java.util.Date; 322import java.util.HashMap; 323import java.util.HashSet; 324import java.util.Iterator; 325import java.util.List; 326import java.util.Map; 327import java.util.Objects; 328import java.util.Set; 329import java.util.concurrent.CountDownLatch; 330import java.util.concurrent.Future; 331import java.util.concurrent.TimeUnit; 332import java.util.concurrent.atomic.AtomicBoolean; 333import java.util.concurrent.atomic.AtomicInteger; 334 335/** 336 * Keep track of all those APKs everywhere. 337 * <p> 338 * Internally there are two important locks: 339 * <ul> 340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 341 * and other related state. It is a fine-grained lock that should only be held 342 * momentarily, as it's one of the most contended locks in the system. 343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 344 * operations typically involve heavy lifting of application data on disk. Since 345 * {@code installd} is single-threaded, and it's operations can often be slow, 346 * this lock should never be acquired while already holding {@link #mPackages}. 347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 348 * holding {@link #mInstallLock}. 349 * </ul> 350 * Many internal methods rely on the caller to hold the appropriate locks, and 351 * this contract is expressed through method name suffixes: 352 * <ul> 353 * <li>fooLI(): the caller must hold {@link #mInstallLock} 354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 355 * being modified must be frozen 356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 358 * </ul> 359 * <p> 360 * Because this class is very central to the platform's security; please run all 361 * CTS and unit tests whenever making modifications: 362 * 363 * <pre> 364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 366 * </pre> 367 */ 368public class PackageManagerService extends IPackageManager.Stub { 369 static final String TAG = "PackageManager"; 370 static final boolean DEBUG_SETTINGS = false; 371 static final boolean DEBUG_PREFERRED = false; 372 static final boolean DEBUG_UPGRADE = false; 373 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 374 private static final boolean DEBUG_BACKUP = false; 375 private static final boolean DEBUG_INSTALL = false; 376 private static final boolean DEBUG_REMOVE = false; 377 private static final boolean DEBUG_BROADCASTS = false; 378 private static final boolean DEBUG_SHOW_INFO = false; 379 private static final boolean DEBUG_PACKAGE_INFO = false; 380 private static final boolean DEBUG_INTENT_MATCHING = false; 381 private static final boolean DEBUG_PACKAGE_SCANNING = false; 382 private static final boolean DEBUG_VERIFY = false; 383 private static final boolean DEBUG_FILTERS = false; 384 385 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 386 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 387 // user, but by default initialize to this. 388 public static final boolean DEBUG_DEXOPT = false; 389 390 private static final boolean DEBUG_ABI_SELECTION = false; 391 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 392 private static final boolean DEBUG_TRIAGED_MISSING = false; 393 private static final boolean DEBUG_APP_DATA = false; 394 395 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 396 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 397 398 private static final boolean DISABLE_EPHEMERAL_APPS = false; 399 private static final boolean HIDE_EPHEMERAL_APIS = false; 400 401 private static final boolean ENABLE_FREE_CACHE_V2 = 402 SystemProperties.getBoolean("fw.free_cache_v2", true); 403 404 private static final int RADIO_UID = Process.PHONE_UID; 405 private static final int LOG_UID = Process.LOG_UID; 406 private static final int NFC_UID = Process.NFC_UID; 407 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 408 private static final int SHELL_UID = Process.SHELL_UID; 409 410 // Cap the size of permission trees that 3rd party apps can define 411 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 412 413 // Suffix used during package installation when copying/moving 414 // package apks to install directory. 415 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 416 417 static final int SCAN_NO_DEX = 1<<1; 418 static final int SCAN_FORCE_DEX = 1<<2; 419 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 420 static final int SCAN_NEW_INSTALL = 1<<4; 421 static final int SCAN_UPDATE_TIME = 1<<5; 422 static final int SCAN_BOOTING = 1<<6; 423 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 424 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 425 static final int SCAN_REPLACING = 1<<9; 426 static final int SCAN_REQUIRE_KNOWN = 1<<10; 427 static final int SCAN_MOVE = 1<<11; 428 static final int SCAN_INITIAL = 1<<12; 429 static final int SCAN_CHECK_ONLY = 1<<13; 430 static final int SCAN_DONT_KILL_APP = 1<<14; 431 static final int SCAN_IGNORE_FROZEN = 1<<15; 432 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 433 static final int SCAN_AS_INSTANT_APP = 1<<17; 434 static final int SCAN_AS_FULL_APP = 1<<18; 435 /** Should not be with the scan flags */ 436 static final int FLAGS_REMOVE_CHATTY = 1<<31; 437 438 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 439 440 private static final int[] EMPTY_INT_ARRAY = new int[0]; 441 442 /** 443 * Timeout (in milliseconds) after which the watchdog should declare that 444 * our handler thread is wedged. The usual default for such things is one 445 * minute but we sometimes do very lengthy I/O operations on this thread, 446 * such as installing multi-gigabyte applications, so ours needs to be longer. 447 */ 448 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 449 450 /** 451 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 452 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 453 * settings entry if available, otherwise we use the hardcoded default. If it's been 454 * more than this long since the last fstrim, we force one during the boot sequence. 455 * 456 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 457 * one gets run at the next available charging+idle time. This final mandatory 458 * no-fstrim check kicks in only of the other scheduling criteria is never met. 459 */ 460 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 461 462 /** 463 * Whether verification is enabled by default. 464 */ 465 private static final boolean DEFAULT_VERIFY_ENABLE = true; 466 467 /** 468 * The default maximum time to wait for the verification agent to return in 469 * milliseconds. 470 */ 471 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 472 473 /** 474 * The default response for package verification timeout. 475 * 476 * This can be either PackageManager.VERIFICATION_ALLOW or 477 * PackageManager.VERIFICATION_REJECT. 478 */ 479 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 480 481 static final String PLATFORM_PACKAGE_NAME = "android"; 482 483 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 484 485 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 486 DEFAULT_CONTAINER_PACKAGE, 487 "com.android.defcontainer.DefaultContainerService"); 488 489 private static final String KILL_APP_REASON_GIDS_CHANGED = 490 "permission grant or revoke changed gids"; 491 492 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 493 "permissions revoked"; 494 495 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 496 497 private static final String PACKAGE_SCHEME = "package"; 498 499 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 500 501 /** Permission grant: not grant the permission. */ 502 private static final int GRANT_DENIED = 1; 503 504 /** Permission grant: grant the permission as an install permission. */ 505 private static final int GRANT_INSTALL = 2; 506 507 /** Permission grant: grant the permission as a runtime one. */ 508 private static final int GRANT_RUNTIME = 3; 509 510 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 511 private static final int GRANT_UPGRADE = 4; 512 513 /** Canonical intent used to identify what counts as a "web browser" app */ 514 private static final Intent sBrowserIntent; 515 static { 516 sBrowserIntent = new Intent(); 517 sBrowserIntent.setAction(Intent.ACTION_VIEW); 518 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 519 sBrowserIntent.setData(Uri.parse("http:")); 520 } 521 522 /** 523 * The set of all protected actions [i.e. those actions for which a high priority 524 * intent filter is disallowed]. 525 */ 526 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 527 static { 528 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 531 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 532 } 533 534 // Compilation reasons. 535 public static final int REASON_FIRST_BOOT = 0; 536 public static final int REASON_BOOT = 1; 537 public static final int REASON_INSTALL = 2; 538 public static final int REASON_BACKGROUND_DEXOPT = 3; 539 public static final int REASON_AB_OTA = 4; 540 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 541 public static final int REASON_SHARED_APK = 6; 542 public static final int REASON_FORCED_DEXOPT = 7; 543 public static final int REASON_CORE_APP = 8; 544 545 public static final int REASON_LAST = REASON_CORE_APP; 546 547 /** All dangerous permission names in the same order as the events in MetricsEvent */ 548 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 549 Manifest.permission.READ_CALENDAR, 550 Manifest.permission.WRITE_CALENDAR, 551 Manifest.permission.CAMERA, 552 Manifest.permission.READ_CONTACTS, 553 Manifest.permission.WRITE_CONTACTS, 554 Manifest.permission.GET_ACCOUNTS, 555 Manifest.permission.ACCESS_FINE_LOCATION, 556 Manifest.permission.ACCESS_COARSE_LOCATION, 557 Manifest.permission.RECORD_AUDIO, 558 Manifest.permission.READ_PHONE_STATE, 559 Manifest.permission.CALL_PHONE, 560 Manifest.permission.READ_CALL_LOG, 561 Manifest.permission.WRITE_CALL_LOG, 562 Manifest.permission.ADD_VOICEMAIL, 563 Manifest.permission.USE_SIP, 564 Manifest.permission.PROCESS_OUTGOING_CALLS, 565 Manifest.permission.READ_CELL_BROADCASTS, 566 Manifest.permission.BODY_SENSORS, 567 Manifest.permission.SEND_SMS, 568 Manifest.permission.RECEIVE_SMS, 569 Manifest.permission.READ_SMS, 570 Manifest.permission.RECEIVE_WAP_PUSH, 571 Manifest.permission.RECEIVE_MMS, 572 Manifest.permission.READ_EXTERNAL_STORAGE, 573 Manifest.permission.WRITE_EXTERNAL_STORAGE, 574 Manifest.permission.READ_PHONE_NUMBER, 575 Manifest.permission.ANSWER_PHONE_CALLS); 576 577 578 /** 579 * Version number for the package parser cache. Increment this whenever the format or 580 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 581 */ 582 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 583 584 /** 585 * Whether the package parser cache is enabled. 586 */ 587 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 588 589 final ServiceThread mHandlerThread; 590 591 final PackageHandler mHandler; 592 593 private final ProcessLoggingHandler mProcessLoggingHandler; 594 595 /** 596 * Messages for {@link #mHandler} that need to wait for system ready before 597 * being dispatched. 598 */ 599 private ArrayList<Message> mPostSystemReadyMessages; 600 601 final int mSdkVersion = Build.VERSION.SDK_INT; 602 603 final Context mContext; 604 final boolean mFactoryTest; 605 final boolean mOnlyCore; 606 final DisplayMetrics mMetrics; 607 final int mDefParseFlags; 608 final String[] mSeparateProcesses; 609 final boolean mIsUpgrade; 610 final boolean mIsPreNUpgrade; 611 final boolean mIsPreNMR1Upgrade; 612 613 @GuardedBy("mPackages") 614 private boolean mDexOptDialogShown; 615 616 /** The location for ASEC container files on internal storage. */ 617 final String mAsecInternalPath; 618 619 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 620 // LOCK HELD. Can be called with mInstallLock held. 621 @GuardedBy("mInstallLock") 622 final Installer mInstaller; 623 624 /** Directory where installed third-party apps stored */ 625 final File mAppInstallDir; 626 627 /** 628 * Directory to which applications installed internally have their 629 * 32 bit native libraries copied. 630 */ 631 private File mAppLib32InstallDir; 632 633 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 634 // apps. 635 final File mDrmAppPrivateInstallDir; 636 637 // ---------------------------------------------------------------- 638 639 // Lock for state used when installing and doing other long running 640 // operations. Methods that must be called with this lock held have 641 // the suffix "LI". 642 final Object mInstallLock = new Object(); 643 644 // ---------------------------------------------------------------- 645 646 // Keys are String (package name), values are Package. This also serves 647 // as the lock for the global state. Methods that must be called with 648 // this lock held have the prefix "LP". 649 @GuardedBy("mPackages") 650 final ArrayMap<String, PackageParser.Package> mPackages = 651 new ArrayMap<String, PackageParser.Package>(); 652 653 final ArrayMap<String, Set<String>> mKnownCodebase = 654 new ArrayMap<String, Set<String>>(); 655 656 // List of APK paths to load for each user and package. This data is never 657 // persisted by the package manager. Instead, the overlay manager will 658 // ensure the data is up-to-date in runtime. 659 @GuardedBy("mPackages") 660 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 661 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 662 663 /** 664 * Tracks new system packages [received in an OTA] that we expect to 665 * find updated user-installed versions. Keys are package name, values 666 * are package location. 667 */ 668 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 669 /** 670 * Tracks high priority intent filters for protected actions. During boot, certain 671 * filter actions are protected and should never be allowed to have a high priority 672 * intent filter for them. However, there is one, and only one exception -- the 673 * setup wizard. It must be able to define a high priority intent filter for these 674 * actions to ensure there are no escapes from the wizard. We need to delay processing 675 * of these during boot as we need to look at all of the system packages in order 676 * to know which component is the setup wizard. 677 */ 678 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 679 /** 680 * Whether or not processing protected filters should be deferred. 681 */ 682 private boolean mDeferProtectedFilters = true; 683 684 /** 685 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 686 */ 687 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 688 /** 689 * Whether or not system app permissions should be promoted from install to runtime. 690 */ 691 boolean mPromoteSystemApps; 692 693 @GuardedBy("mPackages") 694 final Settings mSettings; 695 696 /** 697 * Set of package names that are currently "frozen", which means active 698 * surgery is being done on the code/data for that package. The platform 699 * will refuse to launch frozen packages to avoid race conditions. 700 * 701 * @see PackageFreezer 702 */ 703 @GuardedBy("mPackages") 704 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 705 706 final ProtectedPackages mProtectedPackages; 707 708 boolean mFirstBoot; 709 710 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 711 712 // System configuration read by SystemConfig. 713 final int[] mGlobalGids; 714 final SparseArray<ArraySet<String>> mSystemPermissions; 715 @GuardedBy("mAvailableFeatures") 716 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 717 718 // If mac_permissions.xml was found for seinfo labeling. 719 boolean mFoundPolicyFile; 720 721 private final InstantAppRegistry mInstantAppRegistry; 722 723 @GuardedBy("mPackages") 724 int mChangedPackagesSequenceNumber; 725 /** 726 * List of changed [installed, removed or updated] packages. 727 * mapping from user id -> sequence number -> package name 728 */ 729 @GuardedBy("mPackages") 730 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 731 /** 732 * The sequence number of the last change to a package. 733 * mapping from user id -> package name -> sequence number 734 */ 735 @GuardedBy("mPackages") 736 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 737 738 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 739 @Override public boolean hasFeature(String feature) { 740 return PackageManagerService.this.hasSystemFeature(feature, 0); 741 } 742 }; 743 744 public static final class SharedLibraryEntry { 745 public final String path; 746 public final String apk; 747 public final SharedLibraryInfo info; 748 749 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 750 String declaringPackageName, int declaringPackageVersionCode) { 751 path = _path; 752 apk = _apk; 753 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 754 declaringPackageName, declaringPackageVersionCode), null); 755 } 756 } 757 758 // Currently known shared libraries. 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 760 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 761 new ArrayMap<>(); 762 763 // All available activities, for your resolving pleasure. 764 final ActivityIntentResolver mActivities = 765 new ActivityIntentResolver(); 766 767 // All available receivers, for your resolving pleasure. 768 final ActivityIntentResolver mReceivers = 769 new ActivityIntentResolver(); 770 771 // All available services, for your resolving pleasure. 772 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 773 774 // All available providers, for your resolving pleasure. 775 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 776 777 // Mapping from provider base names (first directory in content URI codePath) 778 // to the provider information. 779 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 780 new ArrayMap<String, PackageParser.Provider>(); 781 782 // Mapping from instrumentation class names to info about them. 783 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 784 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 785 786 // Mapping from permission names to info about them. 787 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 788 new ArrayMap<String, PackageParser.PermissionGroup>(); 789 790 // Packages whose data we have transfered into another package, thus 791 // should no longer exist. 792 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 793 794 // Broadcast actions that are only available to the system. 795 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 796 797 /** List of packages waiting for verification. */ 798 final SparseArray<PackageVerificationState> mPendingVerification 799 = new SparseArray<PackageVerificationState>(); 800 801 /** Set of packages associated with each app op permission. */ 802 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 803 804 final PackageInstallerService mInstallerService; 805 806 private final PackageDexOptimizer mPackageDexOptimizer; 807 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 808 // is used by other apps). 809 private final DexManager mDexManager; 810 811 private AtomicInteger mNextMoveId = new AtomicInteger(); 812 private final MoveCallbacks mMoveCallbacks; 813 814 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 815 816 // Cache of users who need badging. 817 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 818 819 /** Token for keys in mPendingVerification. */ 820 private int mPendingVerificationToken = 0; 821 822 volatile boolean mSystemReady; 823 volatile boolean mSafeMode; 824 volatile boolean mHasSystemUidErrors; 825 826 ApplicationInfo mAndroidApplication; 827 final ActivityInfo mResolveActivity = new ActivityInfo(); 828 final ResolveInfo mResolveInfo = new ResolveInfo(); 829 ComponentName mResolveComponentName; 830 PackageParser.Package mPlatformPackage; 831 ComponentName mCustomResolverComponentName; 832 833 boolean mResolverReplaced = false; 834 835 private final @Nullable ComponentName mIntentFilterVerifierComponent; 836 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 837 838 private int mIntentFilterVerificationToken = 0; 839 840 /** The service connection to the ephemeral resolver */ 841 final EphemeralResolverConnection mInstantAppResolverConnection; 842 843 /** Component used to install ephemeral applications */ 844 ComponentName mInstantAppInstallerComponent; 845 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 846 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 847 848 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 849 = new SparseArray<IntentFilterVerificationState>(); 850 851 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 852 853 // List of packages names to keep cached, even if they are uninstalled for all users 854 private List<String> mKeepUninstalledPackages; 855 856 private UserManagerInternal mUserManagerInternal; 857 858 private DeviceIdleController.LocalService mDeviceIdleController; 859 860 private File mCacheDir; 861 862 private ArraySet<String> mPrivappPermissionsViolations; 863 864 private Future<?> mPrepareAppDataFuture; 865 866 private static class IFVerificationParams { 867 PackageParser.Package pkg; 868 boolean replacing; 869 int userId; 870 int verifierUid; 871 872 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 873 int _userId, int _verifierUid) { 874 pkg = _pkg; 875 replacing = _replacing; 876 userId = _userId; 877 replacing = _replacing; 878 verifierUid = _verifierUid; 879 } 880 } 881 882 private interface IntentFilterVerifier<T extends IntentFilter> { 883 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 884 T filter, String packageName); 885 void startVerifications(int userId); 886 void receiveVerificationResponse(int verificationId); 887 } 888 889 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 890 private Context mContext; 891 private ComponentName mIntentFilterVerifierComponent; 892 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 893 894 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 895 mContext = context; 896 mIntentFilterVerifierComponent = verifierComponent; 897 } 898 899 private String getDefaultScheme() { 900 return IntentFilter.SCHEME_HTTPS; 901 } 902 903 @Override 904 public void startVerifications(int userId) { 905 // Launch verifications requests 906 int count = mCurrentIntentFilterVerifications.size(); 907 for (int n=0; n<count; n++) { 908 int verificationId = mCurrentIntentFilterVerifications.get(n); 909 final IntentFilterVerificationState ivs = 910 mIntentFilterVerificationStates.get(verificationId); 911 912 String packageName = ivs.getPackageName(); 913 914 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 915 final int filterCount = filters.size(); 916 ArraySet<String> domainsSet = new ArraySet<>(); 917 for (int m=0; m<filterCount; m++) { 918 PackageParser.ActivityIntentInfo filter = filters.get(m); 919 domainsSet.addAll(filter.getHostsList()); 920 } 921 synchronized (mPackages) { 922 if (mSettings.createIntentFilterVerificationIfNeededLPw( 923 packageName, domainsSet) != null) { 924 scheduleWriteSettingsLocked(); 925 } 926 } 927 sendVerificationRequest(userId, verificationId, ivs); 928 } 929 mCurrentIntentFilterVerifications.clear(); 930 } 931 932 private void sendVerificationRequest(int userId, int verificationId, 933 IntentFilterVerificationState ivs) { 934 935 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 936 verificationIntent.putExtra( 937 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 938 verificationId); 939 verificationIntent.putExtra( 940 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 941 getDefaultScheme()); 942 verificationIntent.putExtra( 943 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 944 ivs.getHostsString()); 945 verificationIntent.putExtra( 946 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 947 ivs.getPackageName()); 948 verificationIntent.setComponent(mIntentFilterVerifierComponent); 949 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 950 951 UserHandle user = new UserHandle(userId); 952 mContext.sendBroadcastAsUser(verificationIntent, user); 953 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 954 "Sending IntentFilter verification broadcast"); 955 } 956 957 public void receiveVerificationResponse(int verificationId) { 958 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 959 960 final boolean verified = ivs.isVerified(); 961 962 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 963 final int count = filters.size(); 964 if (DEBUG_DOMAIN_VERIFICATION) { 965 Slog.i(TAG, "Received verification response " + verificationId 966 + " for " + count + " filters, verified=" + verified); 967 } 968 for (int n=0; n<count; n++) { 969 PackageParser.ActivityIntentInfo filter = filters.get(n); 970 filter.setVerified(verified); 971 972 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 973 + " verified with result:" + verified + " and hosts:" 974 + ivs.getHostsString()); 975 } 976 977 mIntentFilterVerificationStates.remove(verificationId); 978 979 final String packageName = ivs.getPackageName(); 980 IntentFilterVerificationInfo ivi = null; 981 982 synchronized (mPackages) { 983 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 984 } 985 if (ivi == null) { 986 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 987 + verificationId + " packageName:" + packageName); 988 return; 989 } 990 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 991 "Updating IntentFilterVerificationInfo for package " + packageName 992 +" verificationId:" + verificationId); 993 994 synchronized (mPackages) { 995 if (verified) { 996 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 997 } else { 998 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 999 } 1000 scheduleWriteSettingsLocked(); 1001 1002 final int userId = ivs.getUserId(); 1003 if (userId != UserHandle.USER_ALL) { 1004 final int userStatus = 1005 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1006 1007 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1008 boolean needUpdate = false; 1009 1010 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1011 // already been set by the User thru the Disambiguation dialog 1012 switch (userStatus) { 1013 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1014 if (verified) { 1015 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1016 } else { 1017 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1018 } 1019 needUpdate = true; 1020 break; 1021 1022 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1023 if (verified) { 1024 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1025 needUpdate = true; 1026 } 1027 break; 1028 1029 default: 1030 // Nothing to do 1031 } 1032 1033 if (needUpdate) { 1034 mSettings.updateIntentFilterVerificationStatusLPw( 1035 packageName, updatedStatus, userId); 1036 scheduleWritePackageRestrictionsLocked(userId); 1037 } 1038 } 1039 } 1040 } 1041 1042 @Override 1043 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1044 ActivityIntentInfo filter, String packageName) { 1045 if (!hasValidDomains(filter)) { 1046 return false; 1047 } 1048 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1049 if (ivs == null) { 1050 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1051 packageName); 1052 } 1053 if (DEBUG_DOMAIN_VERIFICATION) { 1054 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1055 } 1056 ivs.addFilter(filter); 1057 return true; 1058 } 1059 1060 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1061 int userId, int verificationId, String packageName) { 1062 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1063 verifierUid, userId, packageName); 1064 ivs.setPendingState(); 1065 synchronized (mPackages) { 1066 mIntentFilterVerificationStates.append(verificationId, ivs); 1067 mCurrentIntentFilterVerifications.add(verificationId); 1068 } 1069 return ivs; 1070 } 1071 } 1072 1073 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1074 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1075 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1076 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1077 } 1078 1079 // Set of pending broadcasts for aggregating enable/disable of components. 1080 static class PendingPackageBroadcasts { 1081 // for each user id, a map of <package name -> components within that package> 1082 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1083 1084 public PendingPackageBroadcasts() { 1085 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1086 } 1087 1088 public ArrayList<String> get(int userId, String packageName) { 1089 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1090 return packages.get(packageName); 1091 } 1092 1093 public void put(int userId, String packageName, ArrayList<String> components) { 1094 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1095 packages.put(packageName, components); 1096 } 1097 1098 public void remove(int userId, String packageName) { 1099 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1100 if (packages != null) { 1101 packages.remove(packageName); 1102 } 1103 } 1104 1105 public void remove(int userId) { 1106 mUidMap.remove(userId); 1107 } 1108 1109 public int userIdCount() { 1110 return mUidMap.size(); 1111 } 1112 1113 public int userIdAt(int n) { 1114 return mUidMap.keyAt(n); 1115 } 1116 1117 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1118 return mUidMap.get(userId); 1119 } 1120 1121 public int size() { 1122 // total number of pending broadcast entries across all userIds 1123 int num = 0; 1124 for (int i = 0; i< mUidMap.size(); i++) { 1125 num += mUidMap.valueAt(i).size(); 1126 } 1127 return num; 1128 } 1129 1130 public void clear() { 1131 mUidMap.clear(); 1132 } 1133 1134 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1135 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1136 if (map == null) { 1137 map = new ArrayMap<String, ArrayList<String>>(); 1138 mUidMap.put(userId, map); 1139 } 1140 return map; 1141 } 1142 } 1143 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1144 1145 // Service Connection to remote media container service to copy 1146 // package uri's from external media onto secure containers 1147 // or internal storage. 1148 private IMediaContainerService mContainerService = null; 1149 1150 static final int SEND_PENDING_BROADCAST = 1; 1151 static final int MCS_BOUND = 3; 1152 static final int END_COPY = 4; 1153 static final int INIT_COPY = 5; 1154 static final int MCS_UNBIND = 6; 1155 static final int START_CLEANING_PACKAGE = 7; 1156 static final int FIND_INSTALL_LOC = 8; 1157 static final int POST_INSTALL = 9; 1158 static final int MCS_RECONNECT = 10; 1159 static final int MCS_GIVE_UP = 11; 1160 static final int UPDATED_MEDIA_STATUS = 12; 1161 static final int WRITE_SETTINGS = 13; 1162 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1163 static final int PACKAGE_VERIFIED = 15; 1164 static final int CHECK_PENDING_VERIFICATION = 16; 1165 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1166 static final int INTENT_FILTER_VERIFIED = 18; 1167 static final int WRITE_PACKAGE_LIST = 19; 1168 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1169 1170 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1171 1172 // Delay time in millisecs 1173 static final int BROADCAST_DELAY = 10 * 1000; 1174 1175 static UserManagerService sUserManager; 1176 1177 // Stores a list of users whose package restrictions file needs to be updated 1178 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1179 1180 final private DefaultContainerConnection mDefContainerConn = 1181 new DefaultContainerConnection(); 1182 class DefaultContainerConnection implements ServiceConnection { 1183 public void onServiceConnected(ComponentName name, IBinder service) { 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1185 final IMediaContainerService imcs = IMediaContainerService.Stub 1186 .asInterface(Binder.allowBlocking(service)); 1187 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1188 } 1189 1190 public void onServiceDisconnected(ComponentName name) { 1191 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1192 } 1193 } 1194 1195 // Recordkeeping of restore-after-install operations that are currently in flight 1196 // between the Package Manager and the Backup Manager 1197 static class PostInstallData { 1198 public InstallArgs args; 1199 public PackageInstalledInfo res; 1200 1201 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1202 args = _a; 1203 res = _r; 1204 } 1205 } 1206 1207 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1208 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1209 1210 // XML tags for backup/restore of various bits of state 1211 private static final String TAG_PREFERRED_BACKUP = "pa"; 1212 private static final String TAG_DEFAULT_APPS = "da"; 1213 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1214 1215 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1216 private static final String TAG_ALL_GRANTS = "rt-grants"; 1217 private static final String TAG_GRANT = "grant"; 1218 private static final String ATTR_PACKAGE_NAME = "pkg"; 1219 1220 private static final String TAG_PERMISSION = "perm"; 1221 private static final String ATTR_PERMISSION_NAME = "name"; 1222 private static final String ATTR_IS_GRANTED = "g"; 1223 private static final String ATTR_USER_SET = "set"; 1224 private static final String ATTR_USER_FIXED = "fixed"; 1225 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1226 1227 // System/policy permission grants are not backed up 1228 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1229 FLAG_PERMISSION_POLICY_FIXED 1230 | FLAG_PERMISSION_SYSTEM_FIXED 1231 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1232 1233 // And we back up these user-adjusted states 1234 private static final int USER_RUNTIME_GRANT_MASK = 1235 FLAG_PERMISSION_USER_SET 1236 | FLAG_PERMISSION_USER_FIXED 1237 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1238 1239 final @Nullable String mRequiredVerifierPackage; 1240 final @NonNull String mRequiredInstallerPackage; 1241 final @NonNull String mRequiredUninstallerPackage; 1242 final @Nullable String mSetupWizardPackage; 1243 final @Nullable String mStorageManagerPackage; 1244 final @NonNull String mServicesSystemSharedLibraryPackageName; 1245 final @NonNull String mSharedSystemSharedLibraryPackageName; 1246 1247 final boolean mPermissionReviewRequired; 1248 1249 private final PackageUsage mPackageUsage = new PackageUsage(); 1250 private final CompilerStats mCompilerStats = new CompilerStats(); 1251 1252 class PackageHandler extends Handler { 1253 private boolean mBound = false; 1254 final ArrayList<HandlerParams> mPendingInstalls = 1255 new ArrayList<HandlerParams>(); 1256 1257 private boolean connectToService() { 1258 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1259 " DefaultContainerService"); 1260 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1261 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1262 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1263 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1264 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1265 mBound = true; 1266 return true; 1267 } 1268 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1269 return false; 1270 } 1271 1272 private void disconnectService() { 1273 mContainerService = null; 1274 mBound = false; 1275 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1276 mContext.unbindService(mDefContainerConn); 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1278 } 1279 1280 PackageHandler(Looper looper) { 1281 super(looper); 1282 } 1283 1284 public void handleMessage(Message msg) { 1285 try { 1286 doHandleMessage(msg); 1287 } finally { 1288 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1289 } 1290 } 1291 1292 void doHandleMessage(Message msg) { 1293 switch (msg.what) { 1294 case INIT_COPY: { 1295 HandlerParams params = (HandlerParams) msg.obj; 1296 int idx = mPendingInstalls.size(); 1297 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1298 // If a bind was already initiated we dont really 1299 // need to do anything. The pending install 1300 // will be processed later on. 1301 if (!mBound) { 1302 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1303 System.identityHashCode(mHandler)); 1304 // If this is the only one pending we might 1305 // have to bind to the service again. 1306 if (!connectToService()) { 1307 Slog.e(TAG, "Failed to bind to media container service"); 1308 params.serviceError(); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1310 System.identityHashCode(mHandler)); 1311 if (params.traceMethod != null) { 1312 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1313 params.traceCookie); 1314 } 1315 return; 1316 } else { 1317 // Once we bind to the service, the first 1318 // pending request will be processed. 1319 mPendingInstalls.add(idx, params); 1320 } 1321 } else { 1322 mPendingInstalls.add(idx, params); 1323 // Already bound to the service. Just make 1324 // sure we trigger off processing the first request. 1325 if (idx == 0) { 1326 mHandler.sendEmptyMessage(MCS_BOUND); 1327 } 1328 } 1329 break; 1330 } 1331 case MCS_BOUND: { 1332 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1333 if (msg.obj != null) { 1334 mContainerService = (IMediaContainerService) msg.obj; 1335 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1336 System.identityHashCode(mHandler)); 1337 } 1338 if (mContainerService == null) { 1339 if (!mBound) { 1340 // Something seriously wrong since we are not bound and we are not 1341 // waiting for connection. Bail out. 1342 Slog.e(TAG, "Cannot bind to media container service"); 1343 for (HandlerParams params : mPendingInstalls) { 1344 // Indicate service bind error 1345 params.serviceError(); 1346 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1347 System.identityHashCode(params)); 1348 if (params.traceMethod != null) { 1349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1350 params.traceMethod, params.traceCookie); 1351 } 1352 return; 1353 } 1354 mPendingInstalls.clear(); 1355 } else { 1356 Slog.w(TAG, "Waiting to connect to media container service"); 1357 } 1358 } else if (mPendingInstalls.size() > 0) { 1359 HandlerParams params = mPendingInstalls.get(0); 1360 if (params != null) { 1361 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1362 System.identityHashCode(params)); 1363 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1364 if (params.startCopy()) { 1365 // We are done... look for more work or to 1366 // go idle. 1367 if (DEBUG_SD_INSTALL) Log.i(TAG, 1368 "Checking for more work or unbind..."); 1369 // Delete pending install 1370 if (mPendingInstalls.size() > 0) { 1371 mPendingInstalls.remove(0); 1372 } 1373 if (mPendingInstalls.size() == 0) { 1374 if (mBound) { 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, 1376 "Posting delayed MCS_UNBIND"); 1377 removeMessages(MCS_UNBIND); 1378 Message ubmsg = obtainMessage(MCS_UNBIND); 1379 // Unbind after a little delay, to avoid 1380 // continual thrashing. 1381 sendMessageDelayed(ubmsg, 10000); 1382 } 1383 } else { 1384 // There are more pending requests in queue. 1385 // Just post MCS_BOUND message to trigger processing 1386 // of next pending install. 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, 1388 "Posting MCS_BOUND for next work"); 1389 mHandler.sendEmptyMessage(MCS_BOUND); 1390 } 1391 } 1392 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1393 } 1394 } else { 1395 // Should never happen ideally. 1396 Slog.w(TAG, "Empty queue"); 1397 } 1398 break; 1399 } 1400 case MCS_RECONNECT: { 1401 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1402 if (mPendingInstalls.size() > 0) { 1403 if (mBound) { 1404 disconnectService(); 1405 } 1406 if (!connectToService()) { 1407 Slog.e(TAG, "Failed to bind to media container service"); 1408 for (HandlerParams params : mPendingInstalls) { 1409 // Indicate service bind error 1410 params.serviceError(); 1411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1412 System.identityHashCode(params)); 1413 } 1414 mPendingInstalls.clear(); 1415 } 1416 } 1417 break; 1418 } 1419 case MCS_UNBIND: { 1420 // If there is no actual work left, then time to unbind. 1421 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1422 1423 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1424 if (mBound) { 1425 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1426 1427 disconnectService(); 1428 } 1429 } else if (mPendingInstalls.size() > 0) { 1430 // There are more pending requests in queue. 1431 // Just post MCS_BOUND message to trigger processing 1432 // of next pending install. 1433 mHandler.sendEmptyMessage(MCS_BOUND); 1434 } 1435 1436 break; 1437 } 1438 case MCS_GIVE_UP: { 1439 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1440 HandlerParams params = mPendingInstalls.remove(0); 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1442 System.identityHashCode(params)); 1443 break; 1444 } 1445 case SEND_PENDING_BROADCAST: { 1446 String packages[]; 1447 ArrayList<String> components[]; 1448 int size = 0; 1449 int uids[]; 1450 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1451 synchronized (mPackages) { 1452 if (mPendingBroadcasts == null) { 1453 return; 1454 } 1455 size = mPendingBroadcasts.size(); 1456 if (size <= 0) { 1457 // Nothing to be done. Just return 1458 return; 1459 } 1460 packages = new String[size]; 1461 components = new ArrayList[size]; 1462 uids = new int[size]; 1463 int i = 0; // filling out the above arrays 1464 1465 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1466 int packageUserId = mPendingBroadcasts.userIdAt(n); 1467 Iterator<Map.Entry<String, ArrayList<String>>> it 1468 = mPendingBroadcasts.packagesForUserId(packageUserId) 1469 .entrySet().iterator(); 1470 while (it.hasNext() && i < size) { 1471 Map.Entry<String, ArrayList<String>> ent = it.next(); 1472 packages[i] = ent.getKey(); 1473 components[i] = ent.getValue(); 1474 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1475 uids[i] = (ps != null) 1476 ? UserHandle.getUid(packageUserId, ps.appId) 1477 : -1; 1478 i++; 1479 } 1480 } 1481 size = i; 1482 mPendingBroadcasts.clear(); 1483 } 1484 // Send broadcasts 1485 for (int i = 0; i < size; i++) { 1486 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1487 } 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1489 break; 1490 } 1491 case START_CLEANING_PACKAGE: { 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1493 final String packageName = (String)msg.obj; 1494 final int userId = msg.arg1; 1495 final boolean andCode = msg.arg2 != 0; 1496 synchronized (mPackages) { 1497 if (userId == UserHandle.USER_ALL) { 1498 int[] users = sUserManager.getUserIds(); 1499 for (int user : users) { 1500 mSettings.addPackageToCleanLPw( 1501 new PackageCleanItem(user, packageName, andCode)); 1502 } 1503 } else { 1504 mSettings.addPackageToCleanLPw( 1505 new PackageCleanItem(userId, packageName, andCode)); 1506 } 1507 } 1508 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1509 startCleaningPackages(); 1510 } break; 1511 case POST_INSTALL: { 1512 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1513 1514 PostInstallData data = mRunningInstalls.get(msg.arg1); 1515 final boolean didRestore = (msg.arg2 != 0); 1516 mRunningInstalls.delete(msg.arg1); 1517 1518 if (data != null) { 1519 InstallArgs args = data.args; 1520 PackageInstalledInfo parentRes = data.res; 1521 1522 final boolean grantPermissions = (args.installFlags 1523 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1524 final boolean killApp = (args.installFlags 1525 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1526 final String[] grantedPermissions = args.installGrantPermissions; 1527 1528 // Handle the parent package 1529 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1530 grantedPermissions, didRestore, args.installerPackageName, 1531 args.observer); 1532 1533 // Handle the child packages 1534 final int childCount = (parentRes.addedChildPackages != null) 1535 ? parentRes.addedChildPackages.size() : 0; 1536 for (int i = 0; i < childCount; i++) { 1537 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1538 handlePackagePostInstall(childRes, grantPermissions, killApp, 1539 grantedPermissions, false, args.installerPackageName, 1540 args.observer); 1541 } 1542 1543 // Log tracing if needed 1544 if (args.traceMethod != null) { 1545 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1546 args.traceCookie); 1547 } 1548 } else { 1549 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1550 } 1551 1552 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1553 } break; 1554 case UPDATED_MEDIA_STATUS: { 1555 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1556 boolean reportStatus = msg.arg1 == 1; 1557 boolean doGc = msg.arg2 == 1; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1559 if (doGc) { 1560 // Force a gc to clear up stale containers. 1561 Runtime.getRuntime().gc(); 1562 } 1563 if (msg.obj != null) { 1564 @SuppressWarnings("unchecked") 1565 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1566 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1567 // Unload containers 1568 unloadAllContainers(args); 1569 } 1570 if (reportStatus) { 1571 try { 1572 if (DEBUG_SD_INSTALL) Log.i(TAG, 1573 "Invoking StorageManagerService call back"); 1574 PackageHelper.getStorageManager().finishMediaUpdate(); 1575 } catch (RemoteException e) { 1576 Log.e(TAG, "StorageManagerService not running?"); 1577 } 1578 } 1579 } break; 1580 case WRITE_SETTINGS: { 1581 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1582 synchronized (mPackages) { 1583 removeMessages(WRITE_SETTINGS); 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 mSettings.writeLPr(); 1586 mDirtyUsers.clear(); 1587 } 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1589 } break; 1590 case WRITE_PACKAGE_RESTRICTIONS: { 1591 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1592 synchronized (mPackages) { 1593 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1594 for (int userId : mDirtyUsers) { 1595 mSettings.writePackageRestrictionsLPr(userId); 1596 } 1597 mDirtyUsers.clear(); 1598 } 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1600 } break; 1601 case WRITE_PACKAGE_LIST: { 1602 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1603 synchronized (mPackages) { 1604 removeMessages(WRITE_PACKAGE_LIST); 1605 mSettings.writePackageListLPr(msg.arg1); 1606 } 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1608 } break; 1609 case CHECK_PENDING_VERIFICATION: { 1610 final int verificationId = msg.arg1; 1611 final PackageVerificationState state = mPendingVerification.get(verificationId); 1612 1613 if ((state != null) && !state.timeoutExtended()) { 1614 final InstallArgs args = state.getInstallArgs(); 1615 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1616 1617 Slog.i(TAG, "Verification timed out for " + originUri); 1618 mPendingVerification.remove(verificationId); 1619 1620 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1621 1622 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1623 Slog.i(TAG, "Continuing with installation of " + originUri); 1624 state.setVerifierResponse(Binder.getCallingUid(), 1625 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1626 broadcastPackageVerified(verificationId, originUri, 1627 PackageManager.VERIFICATION_ALLOW, 1628 state.getInstallArgs().getUser()); 1629 try { 1630 ret = args.copyApk(mContainerService, true); 1631 } catch (RemoteException e) { 1632 Slog.e(TAG, "Could not contact the ContainerService"); 1633 } 1634 } else { 1635 broadcastPackageVerified(verificationId, originUri, 1636 PackageManager.VERIFICATION_REJECT, 1637 state.getInstallArgs().getUser()); 1638 } 1639 1640 Trace.asyncTraceEnd( 1641 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1642 1643 processPendingInstall(args, ret); 1644 mHandler.sendEmptyMessage(MCS_UNBIND); 1645 } 1646 break; 1647 } 1648 case PACKAGE_VERIFIED: { 1649 final int verificationId = msg.arg1; 1650 1651 final PackageVerificationState state = mPendingVerification.get(verificationId); 1652 if (state == null) { 1653 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1654 break; 1655 } 1656 1657 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1658 1659 state.setVerifierResponse(response.callerUid, response.code); 1660 1661 if (state.isVerificationComplete()) { 1662 mPendingVerification.remove(verificationId); 1663 1664 final InstallArgs args = state.getInstallArgs(); 1665 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1666 1667 int ret; 1668 if (state.isInstallAllowed()) { 1669 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1670 broadcastPackageVerified(verificationId, originUri, 1671 response.code, state.getInstallArgs().getUser()); 1672 try { 1673 ret = args.copyApk(mContainerService, true); 1674 } catch (RemoteException e) { 1675 Slog.e(TAG, "Could not contact the ContainerService"); 1676 } 1677 } else { 1678 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1679 } 1680 1681 Trace.asyncTraceEnd( 1682 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1683 1684 processPendingInstall(args, ret); 1685 mHandler.sendEmptyMessage(MCS_UNBIND); 1686 } 1687 1688 break; 1689 } 1690 case START_INTENT_FILTER_VERIFICATIONS: { 1691 IFVerificationParams params = (IFVerificationParams) msg.obj; 1692 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1693 params.replacing, params.pkg); 1694 break; 1695 } 1696 case INTENT_FILTER_VERIFIED: { 1697 final int verificationId = msg.arg1; 1698 1699 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1700 verificationId); 1701 if (state == null) { 1702 Slog.w(TAG, "Invalid IntentFilter verification token " 1703 + verificationId + " received"); 1704 break; 1705 } 1706 1707 final int userId = state.getUserId(); 1708 1709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1710 "Processing IntentFilter verification with token:" 1711 + verificationId + " and userId:" + userId); 1712 1713 final IntentFilterVerificationResponse response = 1714 (IntentFilterVerificationResponse) msg.obj; 1715 1716 state.setVerifierResponse(response.callerUid, response.code); 1717 1718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1719 "IntentFilter verification with token:" + verificationId 1720 + " and userId:" + userId 1721 + " is settings verifier response with response code:" 1722 + response.code); 1723 1724 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1725 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1726 + response.getFailedDomainsString()); 1727 } 1728 1729 if (state.isVerificationComplete()) { 1730 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1731 } else { 1732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1733 "IntentFilter verification with token:" + verificationId 1734 + " was not said to be complete"); 1735 } 1736 1737 break; 1738 } 1739 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1740 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1741 mInstantAppResolverConnection, 1742 (InstantAppRequest) msg.obj, 1743 mInstantAppInstallerActivity, 1744 mHandler); 1745 } 1746 } 1747 } 1748 } 1749 1750 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1751 boolean killApp, String[] grantedPermissions, 1752 boolean launchedForRestore, String installerPackage, 1753 IPackageInstallObserver2 installObserver) { 1754 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1755 // Send the removed broadcasts 1756 if (res.removedInfo != null) { 1757 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1758 } 1759 1760 // Now that we successfully installed the package, grant runtime 1761 // permissions if requested before broadcasting the install. Also 1762 // for legacy apps in permission review mode we clear the permission 1763 // review flag which is used to emulate runtime permissions for 1764 // legacy apps. 1765 if (grantPermissions) { 1766 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1767 } 1768 1769 final boolean update = res.removedInfo != null 1770 && res.removedInfo.removedPackage != null; 1771 1772 // If this is the first time we have child packages for a disabled privileged 1773 // app that had no children, we grant requested runtime permissions to the new 1774 // children if the parent on the system image had them already granted. 1775 if (res.pkg.parentPackage != null) { 1776 synchronized (mPackages) { 1777 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1778 } 1779 } 1780 1781 synchronized (mPackages) { 1782 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1783 } 1784 1785 final String packageName = res.pkg.applicationInfo.packageName; 1786 1787 // Determine the set of users who are adding this package for 1788 // the first time vs. those who are seeing an update. 1789 int[] firstUsers = EMPTY_INT_ARRAY; 1790 int[] updateUsers = EMPTY_INT_ARRAY; 1791 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1792 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1793 for (int newUser : res.newUsers) { 1794 if (ps.getInstantApp(newUser)) { 1795 continue; 1796 } 1797 if (allNewUsers) { 1798 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1799 continue; 1800 } 1801 boolean isNew = true; 1802 for (int origUser : res.origUsers) { 1803 if (origUser == newUser) { 1804 isNew = false; 1805 break; 1806 } 1807 } 1808 if (isNew) { 1809 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1810 } else { 1811 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1812 } 1813 } 1814 1815 // Send installed broadcasts if the package is not a static shared lib. 1816 if (res.pkg.staticSharedLibName == null) { 1817 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1818 1819 // Send added for users that see the package for the first time 1820 // sendPackageAddedForNewUsers also deals with system apps 1821 int appId = UserHandle.getAppId(res.uid); 1822 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1823 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1824 1825 // Send added for users that don't see the package for the first time 1826 Bundle extras = new Bundle(1); 1827 extras.putInt(Intent.EXTRA_UID, res.uid); 1828 if (update) { 1829 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1830 } 1831 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1832 extras, 0 /*flags*/, null /*targetPackage*/, 1833 null /*finishedReceiver*/, updateUsers); 1834 1835 // Send replaced for users that don't see the package for the first time 1836 if (update) { 1837 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1838 packageName, extras, 0 /*flags*/, 1839 null /*targetPackage*/, null /*finishedReceiver*/, 1840 updateUsers); 1841 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1842 null /*package*/, null /*extras*/, 0 /*flags*/, 1843 packageName /*targetPackage*/, 1844 null /*finishedReceiver*/, updateUsers); 1845 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1846 // First-install and we did a restore, so we're responsible for the 1847 // first-launch broadcast. 1848 if (DEBUG_BACKUP) { 1849 Slog.i(TAG, "Post-restore of " + packageName 1850 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1851 } 1852 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1853 } 1854 1855 // Send broadcast package appeared if forward locked/external for all users 1856 // treat asec-hosted packages like removable media on upgrade 1857 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1858 if (DEBUG_INSTALL) { 1859 Slog.i(TAG, "upgrading pkg " + res.pkg 1860 + " is ASEC-hosted -> AVAILABLE"); 1861 } 1862 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1863 ArrayList<String> pkgList = new ArrayList<>(1); 1864 pkgList.add(packageName); 1865 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1866 } 1867 } 1868 1869 // Work that needs to happen on first install within each user 1870 if (firstUsers != null && firstUsers.length > 0) { 1871 synchronized (mPackages) { 1872 for (int userId : firstUsers) { 1873 // If this app is a browser and it's newly-installed for some 1874 // users, clear any default-browser state in those users. The 1875 // app's nature doesn't depend on the user, so we can just check 1876 // its browser nature in any user and generalize. 1877 if (packageIsBrowser(packageName, userId)) { 1878 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1879 } 1880 1881 // We may also need to apply pending (restored) runtime 1882 // permission grants within these users. 1883 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1884 } 1885 } 1886 } 1887 1888 // Log current value of "unknown sources" setting 1889 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1890 getUnknownSourcesSettings()); 1891 1892 // Force a gc to clear up things 1893 Runtime.getRuntime().gc(); 1894 1895 // Remove the replaced package's older resources safely now 1896 // We delete after a gc for applications on sdcard. 1897 if (res.removedInfo != null && res.removedInfo.args != null) { 1898 synchronized (mInstallLock) { 1899 res.removedInfo.args.doPostDeleteLI(true); 1900 } 1901 } 1902 1903 // Notify DexManager that the package was installed for new users. 1904 // The updated users should already be indexed and the package code paths 1905 // should not change. 1906 // Don't notify the manager for ephemeral apps as they are not expected to 1907 // survive long enough to benefit of background optimizations. 1908 for (int userId : firstUsers) { 1909 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1910 mDexManager.notifyPackageInstalled(info, userId); 1911 } 1912 } 1913 1914 // If someone is watching installs - notify them 1915 if (installObserver != null) { 1916 try { 1917 Bundle extras = extrasForInstallResult(res); 1918 installObserver.onPackageInstalled(res.name, res.returnCode, 1919 res.returnMsg, extras); 1920 } catch (RemoteException e) { 1921 Slog.i(TAG, "Observer no longer exists."); 1922 } 1923 } 1924 } 1925 1926 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1927 PackageParser.Package pkg) { 1928 if (pkg.parentPackage == null) { 1929 return; 1930 } 1931 if (pkg.requestedPermissions == null) { 1932 return; 1933 } 1934 final PackageSetting disabledSysParentPs = mSettings 1935 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1936 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1937 || !disabledSysParentPs.isPrivileged() 1938 || (disabledSysParentPs.childPackageNames != null 1939 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1940 return; 1941 } 1942 final int[] allUserIds = sUserManager.getUserIds(); 1943 final int permCount = pkg.requestedPermissions.size(); 1944 for (int i = 0; i < permCount; i++) { 1945 String permission = pkg.requestedPermissions.get(i); 1946 BasePermission bp = mSettings.mPermissions.get(permission); 1947 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1948 continue; 1949 } 1950 for (int userId : allUserIds) { 1951 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1952 permission, userId)) { 1953 grantRuntimePermission(pkg.packageName, permission, userId); 1954 } 1955 } 1956 } 1957 } 1958 1959 private StorageEventListener mStorageListener = new StorageEventListener() { 1960 @Override 1961 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1962 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1963 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1964 final String volumeUuid = vol.getFsUuid(); 1965 1966 // Clean up any users or apps that were removed or recreated 1967 // while this volume was missing 1968 sUserManager.reconcileUsers(volumeUuid); 1969 reconcileApps(volumeUuid); 1970 1971 // Clean up any install sessions that expired or were 1972 // cancelled while this volume was missing 1973 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1974 1975 loadPrivatePackages(vol); 1976 1977 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1978 unloadPrivatePackages(vol); 1979 } 1980 } 1981 1982 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1983 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1984 updateExternalMediaStatus(true, false); 1985 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1986 updateExternalMediaStatus(false, false); 1987 } 1988 } 1989 } 1990 1991 @Override 1992 public void onVolumeForgotten(String fsUuid) { 1993 if (TextUtils.isEmpty(fsUuid)) { 1994 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1995 return; 1996 } 1997 1998 // Remove any apps installed on the forgotten volume 1999 synchronized (mPackages) { 2000 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2001 for (PackageSetting ps : packages) { 2002 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2003 deletePackageVersioned(new VersionedPackage(ps.name, 2004 PackageManager.VERSION_CODE_HIGHEST), 2005 new LegacyPackageDeleteObserver(null).getBinder(), 2006 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2007 // Try very hard to release any references to this package 2008 // so we don't risk the system server being killed due to 2009 // open FDs 2010 AttributeCache.instance().removePackage(ps.name); 2011 } 2012 2013 mSettings.onVolumeForgotten(fsUuid); 2014 mSettings.writeLPr(); 2015 } 2016 } 2017 }; 2018 2019 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2020 String[] grantedPermissions) { 2021 for (int userId : userIds) { 2022 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2023 } 2024 } 2025 2026 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2027 String[] grantedPermissions) { 2028 SettingBase sb = (SettingBase) pkg.mExtras; 2029 if (sb == null) { 2030 return; 2031 } 2032 2033 PermissionsState permissionsState = sb.getPermissionsState(); 2034 2035 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2036 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2037 2038 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2039 >= Build.VERSION_CODES.M; 2040 2041 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2042 2043 for (String permission : pkg.requestedPermissions) { 2044 final BasePermission bp; 2045 synchronized (mPackages) { 2046 bp = mSettings.mPermissions.get(permission); 2047 } 2048 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2049 && (!instantApp || bp.isInstant()) 2050 && (grantedPermissions == null 2051 || ArrayUtils.contains(grantedPermissions, permission))) { 2052 final int flags = permissionsState.getPermissionFlags(permission, userId); 2053 if (supportsRuntimePermissions) { 2054 // Installer cannot change immutable permissions. 2055 if ((flags & immutableFlags) == 0) { 2056 grantRuntimePermission(pkg.packageName, permission, userId); 2057 } 2058 } else if (mPermissionReviewRequired) { 2059 // In permission review mode we clear the review flag when we 2060 // are asked to install the app with all permissions granted. 2061 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2062 updatePermissionFlags(permission, pkg.packageName, 2063 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2064 } 2065 } 2066 } 2067 } 2068 } 2069 2070 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2071 Bundle extras = null; 2072 switch (res.returnCode) { 2073 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2074 extras = new Bundle(); 2075 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2076 res.origPermission); 2077 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2078 res.origPackage); 2079 break; 2080 } 2081 case PackageManager.INSTALL_SUCCEEDED: { 2082 extras = new Bundle(); 2083 extras.putBoolean(Intent.EXTRA_REPLACING, 2084 res.removedInfo != null && res.removedInfo.removedPackage != null); 2085 break; 2086 } 2087 } 2088 return extras; 2089 } 2090 2091 void scheduleWriteSettingsLocked() { 2092 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2093 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2094 } 2095 } 2096 2097 void scheduleWritePackageListLocked(int userId) { 2098 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2099 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2100 msg.arg1 = userId; 2101 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2102 } 2103 } 2104 2105 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2106 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2107 scheduleWritePackageRestrictionsLocked(userId); 2108 } 2109 2110 void scheduleWritePackageRestrictionsLocked(int userId) { 2111 final int[] userIds = (userId == UserHandle.USER_ALL) 2112 ? sUserManager.getUserIds() : new int[]{userId}; 2113 for (int nextUserId : userIds) { 2114 if (!sUserManager.exists(nextUserId)) return; 2115 mDirtyUsers.add(nextUserId); 2116 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2117 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2118 } 2119 } 2120 } 2121 2122 public static PackageManagerService main(Context context, Installer installer, 2123 boolean factoryTest, boolean onlyCore) { 2124 // Self-check for initial settings. 2125 PackageManagerServiceCompilerMapping.checkProperties(); 2126 2127 PackageManagerService m = new PackageManagerService(context, installer, 2128 factoryTest, onlyCore); 2129 m.enableSystemUserPackages(); 2130 ServiceManager.addService("package", m); 2131 return m; 2132 } 2133 2134 private void enableSystemUserPackages() { 2135 if (!UserManager.isSplitSystemUser()) { 2136 return; 2137 } 2138 // For system user, enable apps based on the following conditions: 2139 // - app is whitelisted or belong to one of these groups: 2140 // -- system app which has no launcher icons 2141 // -- system app which has INTERACT_ACROSS_USERS permission 2142 // -- system IME app 2143 // - app is not in the blacklist 2144 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2145 Set<String> enableApps = new ArraySet<>(); 2146 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2147 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2148 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2149 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2150 enableApps.addAll(wlApps); 2151 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2152 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2153 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2154 enableApps.removeAll(blApps); 2155 Log.i(TAG, "Applications installed for system user: " + enableApps); 2156 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2157 UserHandle.SYSTEM); 2158 final int allAppsSize = allAps.size(); 2159 synchronized (mPackages) { 2160 for (int i = 0; i < allAppsSize; i++) { 2161 String pName = allAps.get(i); 2162 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2163 // Should not happen, but we shouldn't be failing if it does 2164 if (pkgSetting == null) { 2165 continue; 2166 } 2167 boolean install = enableApps.contains(pName); 2168 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2169 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2170 + " for system user"); 2171 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2172 } 2173 } 2174 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2175 } 2176 } 2177 2178 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2179 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2180 Context.DISPLAY_SERVICE); 2181 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2182 } 2183 2184 /** 2185 * Requests that files preopted on a secondary system partition be copied to the data partition 2186 * if possible. Note that the actual copying of the files is accomplished by init for security 2187 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2188 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2189 */ 2190 private static void requestCopyPreoptedFiles() { 2191 final int WAIT_TIME_MS = 100; 2192 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2193 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2194 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2195 // We will wait for up to 100 seconds. 2196 final long timeStart = SystemClock.uptimeMillis(); 2197 final long timeEnd = timeStart + 100 * 1000; 2198 long timeNow = timeStart; 2199 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2200 try { 2201 Thread.sleep(WAIT_TIME_MS); 2202 } catch (InterruptedException e) { 2203 // Do nothing 2204 } 2205 timeNow = SystemClock.uptimeMillis(); 2206 if (timeNow > timeEnd) { 2207 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2208 Slog.wtf(TAG, "cppreopt did not finish!"); 2209 break; 2210 } 2211 } 2212 2213 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2214 } 2215 } 2216 2217 public PackageManagerService(Context context, Installer installer, 2218 boolean factoryTest, boolean onlyCore) { 2219 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2221 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2222 SystemClock.uptimeMillis()); 2223 2224 if (mSdkVersion <= 0) { 2225 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2226 } 2227 2228 mContext = context; 2229 2230 mPermissionReviewRequired = context.getResources().getBoolean( 2231 R.bool.config_permissionReviewRequired); 2232 2233 mFactoryTest = factoryTest; 2234 mOnlyCore = onlyCore; 2235 mMetrics = new DisplayMetrics(); 2236 mSettings = new Settings(mPackages); 2237 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2242 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2243 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2244 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2245 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2246 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2247 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2248 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2249 2250 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2251 if (separateProcesses != null && separateProcesses.length() > 0) { 2252 if ("*".equals(separateProcesses)) { 2253 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2254 mSeparateProcesses = null; 2255 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2256 } else { 2257 mDefParseFlags = 0; 2258 mSeparateProcesses = separateProcesses.split(","); 2259 Slog.w(TAG, "Running with debug.separate_processes: " 2260 + separateProcesses); 2261 } 2262 } else { 2263 mDefParseFlags = 0; 2264 mSeparateProcesses = null; 2265 } 2266 2267 mInstaller = installer; 2268 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2269 "*dexopt*"); 2270 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2271 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2272 2273 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2274 FgThread.get().getLooper()); 2275 2276 getDefaultDisplayMetrics(context, mMetrics); 2277 2278 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2279 SystemConfig systemConfig = SystemConfig.getInstance(); 2280 mGlobalGids = systemConfig.getGlobalGids(); 2281 mSystemPermissions = systemConfig.getSystemPermissions(); 2282 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2284 2285 mProtectedPackages = new ProtectedPackages(mContext); 2286 2287 synchronized (mInstallLock) { 2288 // writer 2289 synchronized (mPackages) { 2290 mHandlerThread = new ServiceThread(TAG, 2291 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2292 mHandlerThread.start(); 2293 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2294 mProcessLoggingHandler = new ProcessLoggingHandler(); 2295 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2296 2297 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2298 mInstantAppRegistry = new InstantAppRegistry(this); 2299 2300 File dataDir = Environment.getDataDirectory(); 2301 mAppInstallDir = new File(dataDir, "app"); 2302 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2303 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2304 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2305 sUserManager = new UserManagerService(context, this, 2306 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2307 2308 // Propagate permission configuration in to package manager. 2309 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2310 = systemConfig.getPermissions(); 2311 for (int i=0; i<permConfig.size(); i++) { 2312 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2313 BasePermission bp = mSettings.mPermissions.get(perm.name); 2314 if (bp == null) { 2315 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2316 mSettings.mPermissions.put(perm.name, bp); 2317 } 2318 if (perm.gids != null) { 2319 bp.setGids(perm.gids, perm.perUser); 2320 } 2321 } 2322 2323 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2324 final int builtInLibCount = libConfig.size(); 2325 for (int i = 0; i < builtInLibCount; i++) { 2326 String name = libConfig.keyAt(i); 2327 String path = libConfig.valueAt(i); 2328 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2329 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2330 } 2331 2332 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2333 2334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2335 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2336 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2337 2338 // Clean up orphaned packages for which the code path doesn't exist 2339 // and they are an update to a system app - caused by bug/32321269 2340 final int packageSettingCount = mSettings.mPackages.size(); 2341 for (int i = packageSettingCount - 1; i >= 0; i--) { 2342 PackageSetting ps = mSettings.mPackages.valueAt(i); 2343 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2344 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2345 mSettings.mPackages.removeAt(i); 2346 mSettings.enableSystemPackageLPw(ps.name); 2347 } 2348 } 2349 2350 if (mFirstBoot) { 2351 requestCopyPreoptedFiles(); 2352 } 2353 2354 String customResolverActivity = Resources.getSystem().getString( 2355 R.string.config_customResolverActivity); 2356 if (TextUtils.isEmpty(customResolverActivity)) { 2357 customResolverActivity = null; 2358 } else { 2359 mCustomResolverComponentName = ComponentName.unflattenFromString( 2360 customResolverActivity); 2361 } 2362 2363 long startTime = SystemClock.uptimeMillis(); 2364 2365 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2366 startTime); 2367 2368 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2369 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2370 2371 if (bootClassPath == null) { 2372 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2373 } 2374 2375 if (systemServerClassPath == null) { 2376 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2377 } 2378 2379 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2380 final String[] dexCodeInstructionSets = 2381 getDexCodeInstructionSets( 2382 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2383 2384 /** 2385 * Ensure all external libraries have had dexopt run on them. 2386 */ 2387 if (mSharedLibraries.size() > 0) { 2388 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2389 // NOTE: For now, we're compiling these system "shared libraries" 2390 // (and framework jars) into all available architectures. It's possible 2391 // to compile them only when we come across an app that uses them (there's 2392 // already logic for that in scanPackageLI) but that adds some complexity. 2393 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2394 final int libCount = mSharedLibraries.size(); 2395 for (int i = 0; i < libCount; i++) { 2396 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2397 final int versionCount = versionedLib.size(); 2398 for (int j = 0; j < versionCount; j++) { 2399 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2400 final String libPath = libEntry.path != null 2401 ? libEntry.path : libEntry.apk; 2402 if (libPath == null) { 2403 continue; 2404 } 2405 try { 2406 // Shared libraries do not have profiles so we perform a full 2407 // AOT compilation (if needed). 2408 int dexoptNeeded = DexFile.getDexOptNeeded( 2409 libPath, dexCodeInstructionSet, 2410 getCompilerFilterForReason(REASON_SHARED_APK), 2411 false /* newProfile */); 2412 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2413 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2414 dexCodeInstructionSet, dexoptNeeded, null, 2415 DEXOPT_PUBLIC, 2416 getCompilerFilterForReason(REASON_SHARED_APK), 2417 StorageManager.UUID_PRIVATE_INTERNAL, 2418 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2419 } 2420 } catch (FileNotFoundException e) { 2421 Slog.w(TAG, "Library not found: " + libPath); 2422 } catch (IOException | InstallerException e) { 2423 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2424 + e.getMessage()); 2425 } 2426 } 2427 } 2428 } 2429 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2430 } 2431 2432 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2433 2434 final VersionInfo ver = mSettings.getInternalVersion(); 2435 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2436 2437 // when upgrading from pre-M, promote system app permissions from install to runtime 2438 mPromoteSystemApps = 2439 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2440 2441 // When upgrading from pre-N, we need to handle package extraction like first boot, 2442 // as there is no profiling data available. 2443 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2444 2445 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2446 2447 // save off the names of pre-existing system packages prior to scanning; we don't 2448 // want to automatically grant runtime permissions for new system apps 2449 if (mPromoteSystemApps) { 2450 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2451 while (pkgSettingIter.hasNext()) { 2452 PackageSetting ps = pkgSettingIter.next(); 2453 if (isSystemApp(ps)) { 2454 mExistingSystemPackages.add(ps.name); 2455 } 2456 } 2457 } 2458 2459 mCacheDir = preparePackageParserCache(mIsUpgrade); 2460 2461 // Set flag to monitor and not change apk file paths when 2462 // scanning install directories. 2463 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2464 2465 if (mIsUpgrade || mFirstBoot) { 2466 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2467 } 2468 2469 // Collect vendor overlay packages. (Do this before scanning any apps.) 2470 // For security and version matching reason, only consider 2471 // overlay packages if they reside in the right directory. 2472 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2476 2477 // Find base frameworks (resource packages without code). 2478 scanDirTracedLI(frameworkDir, mDefParseFlags 2479 | PackageParser.PARSE_IS_SYSTEM 2480 | PackageParser.PARSE_IS_SYSTEM_DIR 2481 | PackageParser.PARSE_IS_PRIVILEGED, 2482 scanFlags | SCAN_NO_DEX, 0); 2483 2484 // Collected privileged system packages. 2485 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2486 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR 2489 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2490 2491 // Collect ordinary system packages. 2492 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2493 scanDirTracedLI(systemAppDir, mDefParseFlags 2494 | PackageParser.PARSE_IS_SYSTEM 2495 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2496 2497 // Collect all vendor packages. 2498 File vendorAppDir = new File("/vendor/app"); 2499 try { 2500 vendorAppDir = vendorAppDir.getCanonicalFile(); 2501 } catch (IOException e) { 2502 // failed to look up canonical path, continue with original one 2503 } 2504 scanDirTracedLI(vendorAppDir, mDefParseFlags 2505 | PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2507 2508 // Collect all OEM packages. 2509 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2510 scanDirTracedLI(oemAppDir, mDefParseFlags 2511 | PackageParser.PARSE_IS_SYSTEM 2512 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2513 2514 // Prune any system packages that no longer exist. 2515 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2516 if (!mOnlyCore) { 2517 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2518 while (psit.hasNext()) { 2519 PackageSetting ps = psit.next(); 2520 2521 /* 2522 * If this is not a system app, it can't be a 2523 * disable system app. 2524 */ 2525 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2526 continue; 2527 } 2528 2529 /* 2530 * If the package is scanned, it's not erased. 2531 */ 2532 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2533 if (scannedPkg != null) { 2534 /* 2535 * If the system app is both scanned and in the 2536 * disabled packages list, then it must have been 2537 * added via OTA. Remove it from the currently 2538 * scanned package so the previously user-installed 2539 * application can be scanned. 2540 */ 2541 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2542 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2543 + ps.name + "; removing system app. Last known codePath=" 2544 + ps.codePathString + ", installStatus=" + ps.installStatus 2545 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2546 + scannedPkg.mVersionCode); 2547 removePackageLI(scannedPkg, true); 2548 mExpectingBetter.put(ps.name, ps.codePath); 2549 } 2550 2551 continue; 2552 } 2553 2554 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2555 psit.remove(); 2556 logCriticalInfo(Log.WARN, "System package " + ps.name 2557 + " no longer exists; it's data will be wiped"); 2558 // Actual deletion of code and data will be handled by later 2559 // reconciliation step 2560 } else { 2561 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2562 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2563 possiblyDeletedUpdatedSystemApps.add(ps.name); 2564 } 2565 } 2566 } 2567 } 2568 2569 //look for any incomplete package installations 2570 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2571 for (int i = 0; i < deletePkgsList.size(); i++) { 2572 // Actual deletion of code and data will be handled by later 2573 // reconciliation step 2574 final String packageName = deletePkgsList.get(i).name; 2575 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2576 synchronized (mPackages) { 2577 mSettings.removePackageLPw(packageName); 2578 } 2579 } 2580 2581 //delete tmp files 2582 deleteTempPackageFiles(); 2583 2584 // Remove any shared userIDs that have no associated packages 2585 mSettings.pruneSharedUsersLPw(); 2586 2587 if (!mOnlyCore) { 2588 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2589 SystemClock.uptimeMillis()); 2590 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2591 2592 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2593 | PackageParser.PARSE_FORWARD_LOCK, 2594 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2595 2596 /** 2597 * Remove disable package settings for any updated system 2598 * apps that were removed via an OTA. If they're not a 2599 * previously-updated app, remove them completely. 2600 * Otherwise, just revoke their system-level permissions. 2601 */ 2602 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2603 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2604 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2605 2606 String msg; 2607 if (deletedPkg == null) { 2608 msg = "Updated system package " + deletedAppName 2609 + " no longer exists; it's data will be wiped"; 2610 // Actual deletion of code and data will be handled by later 2611 // reconciliation step 2612 } else { 2613 msg = "Updated system app + " + deletedAppName 2614 + " no longer present; removing system privileges for " 2615 + deletedAppName; 2616 2617 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 2619 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2620 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2621 } 2622 logCriticalInfo(Log.WARN, msg); 2623 } 2624 2625 /** 2626 * Make sure all system apps that we expected to appear on 2627 * the userdata partition actually showed up. If they never 2628 * appeared, crawl back and revive the system version. 2629 */ 2630 for (int i = 0; i < mExpectingBetter.size(); i++) { 2631 final String packageName = mExpectingBetter.keyAt(i); 2632 if (!mPackages.containsKey(packageName)) { 2633 final File scanFile = mExpectingBetter.valueAt(i); 2634 2635 logCriticalInfo(Log.WARN, "Expected better " + packageName 2636 + " but never showed up; reverting to system"); 2637 2638 int reparseFlags = mDefParseFlags; 2639 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2640 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2641 | PackageParser.PARSE_IS_SYSTEM_DIR 2642 | PackageParser.PARSE_IS_PRIVILEGED; 2643 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2650 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2651 | PackageParser.PARSE_IS_SYSTEM_DIR; 2652 } else { 2653 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2654 continue; 2655 } 2656 2657 mSettings.enableSystemPackageLPw(packageName); 2658 2659 try { 2660 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2661 } catch (PackageManagerException e) { 2662 Slog.e(TAG, "Failed to parse original system package: " 2663 + e.getMessage()); 2664 } 2665 } 2666 } 2667 } 2668 mExpectingBetter.clear(); 2669 2670 // Resolve the storage manager. 2671 mStorageManagerPackage = getStorageManagerPackageName(); 2672 2673 // Resolve protected action filters. Only the setup wizard is allowed to 2674 // have a high priority filter for these actions. 2675 mSetupWizardPackage = getSetupWizardPackageName(); 2676 if (mProtectedFilters.size() > 0) { 2677 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2678 Slog.i(TAG, "No setup wizard;" 2679 + " All protected intents capped to priority 0"); 2680 } 2681 for (ActivityIntentInfo filter : mProtectedFilters) { 2682 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2683 if (DEBUG_FILTERS) { 2684 Slog.i(TAG, "Found setup wizard;" 2685 + " allow priority " + filter.getPriority() + ";" 2686 + " package: " + filter.activity.info.packageName 2687 + " activity: " + filter.activity.className 2688 + " priority: " + filter.getPriority()); 2689 } 2690 // skip setup wizard; allow it to keep the high priority filter 2691 continue; 2692 } 2693 Slog.w(TAG, "Protected action; cap priority to 0;" 2694 + " package: " + filter.activity.info.packageName 2695 + " activity: " + filter.activity.className 2696 + " origPrio: " + filter.getPriority()); 2697 filter.setPriority(0); 2698 } 2699 } 2700 mDeferProtectedFilters = false; 2701 mProtectedFilters.clear(); 2702 2703 // Now that we know all of the shared libraries, update all clients to have 2704 // the correct library paths. 2705 updateAllSharedLibrariesLPw(null); 2706 2707 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2708 // NOTE: We ignore potential failures here during a system scan (like 2709 // the rest of the commands above) because there's precious little we 2710 // can do about it. A settings error is reported, though. 2711 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2712 } 2713 2714 // Now that we know all the packages we are keeping, 2715 // read and update their last usage times. 2716 mPackageUsage.read(mPackages); 2717 mCompilerStats.read(); 2718 2719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2720 SystemClock.uptimeMillis()); 2721 Slog.i(TAG, "Time to scan packages: " 2722 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2723 + " seconds"); 2724 2725 // If the platform SDK has changed since the last time we booted, 2726 // we need to re-grant app permission to catch any new ones that 2727 // appear. This is really a hack, and means that apps can in some 2728 // cases get permissions that the user didn't initially explicitly 2729 // allow... it would be nice to have some better way to handle 2730 // this situation. 2731 int updateFlags = UPDATE_PERMISSIONS_ALL; 2732 if (ver.sdkVersion != mSdkVersion) { 2733 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2734 + mSdkVersion + "; regranting permissions for internal storage"); 2735 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2736 } 2737 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2738 ver.sdkVersion = mSdkVersion; 2739 2740 // If this is the first boot or an update from pre-M, and it is a normal 2741 // boot, then we need to initialize the default preferred apps across 2742 // all defined users. 2743 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2744 for (UserInfo user : sUserManager.getUsers(true)) { 2745 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2746 applyFactoryDefaultBrowserLPw(user.id); 2747 primeDomainVerificationsLPw(user.id); 2748 } 2749 } 2750 2751 // Prepare storage for system user really early during boot, 2752 // since core system apps like SettingsProvider and SystemUI 2753 // can't wait for user to start 2754 final int storageFlags; 2755 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2756 storageFlags = StorageManager.FLAG_STORAGE_DE; 2757 } else { 2758 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2759 } 2760 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2761 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2762 true /* onlyCoreApps */); 2763 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2764 if (deferPackages == null || deferPackages.isEmpty()) { 2765 return; 2766 } 2767 int count = 0; 2768 for (String pkgName : deferPackages) { 2769 PackageParser.Package pkg = null; 2770 synchronized (mPackages) { 2771 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2772 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2773 pkg = ps.pkg; 2774 } 2775 } 2776 if (pkg != null) { 2777 synchronized (mInstallLock) { 2778 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2779 true /* maybeMigrateAppData */); 2780 } 2781 count++; 2782 } 2783 } 2784 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2785 }, "prepareAppData"); 2786 2787 // If this is first boot after an OTA, and a normal boot, then 2788 // we need to clear code cache directories. 2789 // Note that we do *not* clear the application profiles. These remain valid 2790 // across OTAs and are used to drive profile verification (post OTA) and 2791 // profile compilation (without waiting to collect a fresh set of profiles). 2792 if (mIsUpgrade && !onlyCore) { 2793 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2794 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2795 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2796 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2797 // No apps are running this early, so no need to freeze 2798 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2799 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2800 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2801 } 2802 } 2803 ver.fingerprint = Build.FINGERPRINT; 2804 } 2805 2806 checkDefaultBrowser(); 2807 2808 // clear only after permissions and other defaults have been updated 2809 mExistingSystemPackages.clear(); 2810 mPromoteSystemApps = false; 2811 2812 // All the changes are done during package scanning. 2813 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2814 2815 // can downgrade to reader 2816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2817 mSettings.writeLPr(); 2818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2819 2820 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2821 // early on (before the package manager declares itself as early) because other 2822 // components in the system server might ask for package contexts for these apps. 2823 // 2824 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2825 // (i.e, that the data partition is unavailable). 2826 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2827 long start = System.nanoTime(); 2828 List<PackageParser.Package> coreApps = new ArrayList<>(); 2829 for (PackageParser.Package pkg : mPackages.values()) { 2830 if (pkg.coreApp) { 2831 coreApps.add(pkg); 2832 } 2833 } 2834 2835 int[] stats = performDexOptUpgrade(coreApps, false, 2836 getCompilerFilterForReason(REASON_CORE_APP)); 2837 2838 final int elapsedTimeSeconds = 2839 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2840 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2841 2842 if (DEBUG_DEXOPT) { 2843 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2844 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2845 } 2846 2847 2848 // TODO: Should we log these stats to tron too ? 2849 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2850 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2851 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2852 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2853 } 2854 2855 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2856 SystemClock.uptimeMillis()); 2857 2858 if (!mOnlyCore) { 2859 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2860 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2861 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2862 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2863 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2864 mIntentFilterVerifierComponent); 2865 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2866 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2867 SharedLibraryInfo.VERSION_UNDEFINED); 2868 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2869 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2870 SharedLibraryInfo.VERSION_UNDEFINED); 2871 } else { 2872 mRequiredVerifierPackage = null; 2873 mRequiredInstallerPackage = null; 2874 mRequiredUninstallerPackage = null; 2875 mIntentFilterVerifierComponent = null; 2876 mIntentFilterVerifier = null; 2877 mServicesSystemSharedLibraryPackageName = null; 2878 mSharedSystemSharedLibraryPackageName = null; 2879 } 2880 2881 mInstallerService = new PackageInstallerService(context, this); 2882 2883 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2884 if (ephemeralResolverComponent != null) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2887 } 2888 mInstantAppResolverConnection = 2889 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2890 } else { 2891 mInstantAppResolverConnection = null; 2892 } 2893 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2894 if (mInstantAppInstallerComponent != null) { 2895 if (DEBUG_EPHEMERAL) { 2896 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2897 } 2898 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2899 } 2900 2901 // Read and update the usage of dex files. 2902 // Do this at the end of PM init so that all the packages have their 2903 // data directory reconciled. 2904 // At this point we know the code paths of the packages, so we can validate 2905 // the disk file and build the internal cache. 2906 // The usage file is expected to be small so loading and verifying it 2907 // should take a fairly small time compare to the other activities (e.g. package 2908 // scanning). 2909 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2910 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2911 for (int userId : currentUserIds) { 2912 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2913 } 2914 mDexManager.load(userPackages); 2915 } // synchronized (mPackages) 2916 } // synchronized (mInstallLock) 2917 2918 // Now after opening every single application zip, make sure they 2919 // are all flushed. Not really needed, but keeps things nice and 2920 // tidy. 2921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2922 Runtime.getRuntime().gc(); 2923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2924 2925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2926 FallbackCategoryProvider.loadFallbacks(); 2927 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2928 2929 // The initial scanning above does many calls into installd while 2930 // holding the mPackages lock, but we're mostly interested in yelling 2931 // once we have a booted system. 2932 mInstaller.setWarnIfHeld(mPackages); 2933 2934 // Expose private service for system components to use. 2935 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2936 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2937 } 2938 2939 private static File preparePackageParserCache(boolean isUpgrade) { 2940 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2941 return null; 2942 } 2943 2944 // Disable package parsing on eng builds to allow for faster incremental development. 2945 if ("eng".equals(Build.TYPE)) { 2946 return null; 2947 } 2948 2949 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2950 Slog.i(TAG, "Disabling package parser cache due to system property."); 2951 return null; 2952 } 2953 2954 // The base directory for the package parser cache lives under /data/system/. 2955 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2956 "package_cache"); 2957 if (cacheBaseDir == null) { 2958 return null; 2959 } 2960 2961 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2962 // This also serves to "GC" unused entries when the package cache version changes (which 2963 // can only happen during upgrades). 2964 if (isUpgrade) { 2965 FileUtils.deleteContents(cacheBaseDir); 2966 } 2967 2968 2969 // Return the versioned package cache directory. This is something like 2970 // "/data/system/package_cache/1" 2971 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2972 2973 // The following is a workaround to aid development on non-numbered userdebug 2974 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2975 // the system partition is newer. 2976 // 2977 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2978 // that starts with "eng." to signify that this is an engineering build and not 2979 // destined for release. 2980 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2981 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2982 2983 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2984 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2985 // in general and should not be used for production changes. In this specific case, 2986 // we know that they will work. 2987 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2988 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2989 FileUtils.deleteContents(cacheBaseDir); 2990 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2991 } 2992 } 2993 2994 return cacheDir; 2995 } 2996 2997 @Override 2998 public boolean isFirstBoot() { 2999 return mFirstBoot; 3000 } 3001 3002 @Override 3003 public boolean isOnlyCoreApps() { 3004 return mOnlyCore; 3005 } 3006 3007 @Override 3008 public boolean isUpgrade() { 3009 return mIsUpgrade; 3010 } 3011 3012 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3013 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3014 3015 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3016 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3017 UserHandle.USER_SYSTEM); 3018 if (matches.size() == 1) { 3019 return matches.get(0).getComponentInfo().packageName; 3020 } else if (matches.size() == 0) { 3021 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3022 return null; 3023 } 3024 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3025 } 3026 3027 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3028 synchronized (mPackages) { 3029 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3030 if (libraryEntry == null) { 3031 throw new IllegalStateException("Missing required shared library:" + name); 3032 } 3033 return libraryEntry.apk; 3034 } 3035 } 3036 3037 private @NonNull String getRequiredInstallerLPr() { 3038 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3039 intent.addCategory(Intent.CATEGORY_DEFAULT); 3040 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3041 3042 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3043 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3044 UserHandle.USER_SYSTEM); 3045 if (matches.size() == 1) { 3046 ResolveInfo resolveInfo = matches.get(0); 3047 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3048 throw new RuntimeException("The installer must be a privileged app"); 3049 } 3050 return matches.get(0).getComponentInfo().packageName; 3051 } else { 3052 throw new RuntimeException("There must be exactly one installer; found " + matches); 3053 } 3054 } 3055 3056 private @NonNull String getRequiredUninstallerLPr() { 3057 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3058 intent.addCategory(Intent.CATEGORY_DEFAULT); 3059 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3060 3061 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3062 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3063 UserHandle.USER_SYSTEM); 3064 if (resolveInfo == null || 3065 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3066 throw new RuntimeException("There must be exactly one uninstaller; found " 3067 + resolveInfo); 3068 } 3069 return resolveInfo.getComponentInfo().packageName; 3070 } 3071 3072 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3073 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3074 3075 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3076 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3077 UserHandle.USER_SYSTEM); 3078 ResolveInfo best = null; 3079 final int N = matches.size(); 3080 for (int i = 0; i < N; i++) { 3081 final ResolveInfo cur = matches.get(i); 3082 final String packageName = cur.getComponentInfo().packageName; 3083 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3084 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3085 continue; 3086 } 3087 3088 if (best == null || cur.priority > best.priority) { 3089 best = cur; 3090 } 3091 } 3092 3093 if (best != null) { 3094 return best.getComponentInfo().getComponentName(); 3095 } else { 3096 throw new RuntimeException("There must be at least one intent filter verifier"); 3097 } 3098 } 3099 3100 private @Nullable ComponentName getEphemeralResolverLPr() { 3101 final String[] packageArray = 3102 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3103 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3104 if (DEBUG_EPHEMERAL) { 3105 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3106 } 3107 return null; 3108 } 3109 3110 final int resolveFlags = 3111 MATCH_DIRECT_BOOT_AWARE 3112 | MATCH_DIRECT_BOOT_UNAWARE 3113 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3114 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3115 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3116 resolveFlags, UserHandle.USER_SYSTEM); 3117 3118 final int N = resolvers.size(); 3119 if (N == 0) { 3120 if (DEBUG_EPHEMERAL) { 3121 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3122 } 3123 return null; 3124 } 3125 3126 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3127 for (int i = 0; i < N; i++) { 3128 final ResolveInfo info = resolvers.get(i); 3129 3130 if (info.serviceInfo == null) { 3131 continue; 3132 } 3133 3134 final String packageName = info.serviceInfo.packageName; 3135 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3136 if (DEBUG_EPHEMERAL) { 3137 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3138 + " pkg: " + packageName + ", info:" + info); 3139 } 3140 continue; 3141 } 3142 3143 if (DEBUG_EPHEMERAL) { 3144 Slog.v(TAG, "Ephemeral resolver found;" 3145 + " pkg: " + packageName + ", info:" + info); 3146 } 3147 return new ComponentName(packageName, info.serviceInfo.name); 3148 } 3149 if (DEBUG_EPHEMERAL) { 3150 Slog.v(TAG, "Ephemeral resolver NOT found"); 3151 } 3152 return null; 3153 } 3154 3155 private @Nullable ComponentName getEphemeralInstallerLPr() { 3156 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3157 intent.addCategory(Intent.CATEGORY_DEFAULT); 3158 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3159 3160 final int resolveFlags = 3161 MATCH_DIRECT_BOOT_AWARE 3162 | MATCH_DIRECT_BOOT_UNAWARE 3163 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3164 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3165 resolveFlags, UserHandle.USER_SYSTEM); 3166 Iterator<ResolveInfo> iter = matches.iterator(); 3167 while (iter.hasNext()) { 3168 final ResolveInfo rInfo = iter.next(); 3169 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3170 if (ps != null) { 3171 final PermissionsState permissionsState = ps.getPermissionsState(); 3172 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3173 continue; 3174 } 3175 } 3176 iter.remove(); 3177 } 3178 if (matches.size() == 0) { 3179 return null; 3180 } else if (matches.size() == 1) { 3181 return matches.get(0).getComponentInfo().getComponentName(); 3182 } else { 3183 throw new RuntimeException( 3184 "There must be at most one ephemeral installer; found " + matches); 3185 } 3186 } 3187 3188 private void primeDomainVerificationsLPw(int userId) { 3189 if (DEBUG_DOMAIN_VERIFICATION) { 3190 Slog.d(TAG, "Priming domain verifications in user " + userId); 3191 } 3192 3193 SystemConfig systemConfig = SystemConfig.getInstance(); 3194 ArraySet<String> packages = systemConfig.getLinkedApps(); 3195 3196 for (String packageName : packages) { 3197 PackageParser.Package pkg = mPackages.get(packageName); 3198 if (pkg != null) { 3199 if (!pkg.isSystemApp()) { 3200 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3201 continue; 3202 } 3203 3204 ArraySet<String> domains = null; 3205 for (PackageParser.Activity a : pkg.activities) { 3206 for (ActivityIntentInfo filter : a.intents) { 3207 if (hasValidDomains(filter)) { 3208 if (domains == null) { 3209 domains = new ArraySet<String>(); 3210 } 3211 domains.addAll(filter.getHostsList()); 3212 } 3213 } 3214 } 3215 3216 if (domains != null && domains.size() > 0) { 3217 if (DEBUG_DOMAIN_VERIFICATION) { 3218 Slog.v(TAG, " + " + packageName); 3219 } 3220 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3221 // state w.r.t. the formal app-linkage "no verification attempted" state; 3222 // and then 'always' in the per-user state actually used for intent resolution. 3223 final IntentFilterVerificationInfo ivi; 3224 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3225 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3226 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3227 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3228 } else { 3229 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3230 + "' does not handle web links"); 3231 } 3232 } else { 3233 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3234 } 3235 } 3236 3237 scheduleWritePackageRestrictionsLocked(userId); 3238 scheduleWriteSettingsLocked(); 3239 } 3240 3241 private void applyFactoryDefaultBrowserLPw(int userId) { 3242 // The default browser app's package name is stored in a string resource, 3243 // with a product-specific overlay used for vendor customization. 3244 String browserPkg = mContext.getResources().getString( 3245 com.android.internal.R.string.default_browser); 3246 if (!TextUtils.isEmpty(browserPkg)) { 3247 // non-empty string => required to be a known package 3248 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3249 if (ps == null) { 3250 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3251 browserPkg = null; 3252 } else { 3253 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3254 } 3255 } 3256 3257 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3258 // default. If there's more than one, just leave everything alone. 3259 if (browserPkg == null) { 3260 calculateDefaultBrowserLPw(userId); 3261 } 3262 } 3263 3264 private void calculateDefaultBrowserLPw(int userId) { 3265 List<String> allBrowsers = resolveAllBrowserApps(userId); 3266 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3267 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3268 } 3269 3270 private List<String> resolveAllBrowserApps(int userId) { 3271 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3272 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3273 PackageManager.MATCH_ALL, userId); 3274 3275 final int count = list.size(); 3276 List<String> result = new ArrayList<String>(count); 3277 for (int i=0; i<count; i++) { 3278 ResolveInfo info = list.get(i); 3279 if (info.activityInfo == null 3280 || !info.handleAllWebDataURI 3281 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3282 || result.contains(info.activityInfo.packageName)) { 3283 continue; 3284 } 3285 result.add(info.activityInfo.packageName); 3286 } 3287 3288 return result; 3289 } 3290 3291 private boolean packageIsBrowser(String packageName, int userId) { 3292 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3293 PackageManager.MATCH_ALL, userId); 3294 final int N = list.size(); 3295 for (int i = 0; i < N; i++) { 3296 ResolveInfo info = list.get(i); 3297 if (packageName.equals(info.activityInfo.packageName)) { 3298 return true; 3299 } 3300 } 3301 return false; 3302 } 3303 3304 private void checkDefaultBrowser() { 3305 final int myUserId = UserHandle.myUserId(); 3306 final String packageName = getDefaultBrowserPackageName(myUserId); 3307 if (packageName != null) { 3308 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3309 if (info == null) { 3310 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3311 synchronized (mPackages) { 3312 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3313 } 3314 } 3315 } 3316 } 3317 3318 @Override 3319 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3320 throws RemoteException { 3321 try { 3322 return super.onTransact(code, data, reply, flags); 3323 } catch (RuntimeException e) { 3324 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3325 Slog.wtf(TAG, "Package Manager Crash", e); 3326 } 3327 throw e; 3328 } 3329 } 3330 3331 static int[] appendInts(int[] cur, int[] add) { 3332 if (add == null) return cur; 3333 if (cur == null) return add; 3334 final int N = add.length; 3335 for (int i=0; i<N; i++) { 3336 cur = appendInt(cur, add[i]); 3337 } 3338 return cur; 3339 } 3340 3341 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3342 if (!sUserManager.exists(userId)) return null; 3343 if (ps == null) { 3344 return null; 3345 } 3346 final PackageParser.Package p = ps.pkg; 3347 if (p == null) { 3348 return null; 3349 } 3350 // Filter out ephemeral app metadata: 3351 // * The system/shell/root can see metadata for any app 3352 // * An installed app can see metadata for 1) other installed apps 3353 // and 2) ephemeral apps that have explicitly interacted with it 3354 // * Ephemeral apps can only see their own metadata 3355 // * Holding a signature permission allows seeing instant apps 3356 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3357 if (callingAppId != Process.SYSTEM_UID 3358 && callingAppId != Process.SHELL_UID 3359 && callingAppId != Process.ROOT_UID 3360 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3361 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3362 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3363 if (instantAppPackageName != null) { 3364 // ephemeral apps can only get information on themselves 3365 if (!instantAppPackageName.equals(p.packageName)) { 3366 return null; 3367 } 3368 } else { 3369 if (ps.getInstantApp(userId)) { 3370 // only get access to the ephemeral app if we've been granted access 3371 if (!mInstantAppRegistry.isInstantAccessGranted( 3372 userId, callingAppId, ps.appId)) { 3373 return null; 3374 } 3375 } 3376 } 3377 } 3378 3379 final PermissionsState permissionsState = ps.getPermissionsState(); 3380 3381 // Compute GIDs only if requested 3382 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3383 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3384 // Compute granted permissions only if package has requested permissions 3385 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3386 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3387 final PackageUserState state = ps.readUserState(userId); 3388 3389 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3390 && ps.isSystem()) { 3391 flags |= MATCH_ANY_USER; 3392 } 3393 3394 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3395 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3396 3397 if (packageInfo == null) { 3398 return null; 3399 } 3400 3401 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3402 3403 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3404 resolveExternalPackageNameLPr(p); 3405 3406 return packageInfo; 3407 } 3408 3409 @Override 3410 public void checkPackageStartable(String packageName, int userId) { 3411 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3412 3413 synchronized (mPackages) { 3414 final PackageSetting ps = mSettings.mPackages.get(packageName); 3415 if (ps == null) { 3416 throw new SecurityException("Package " + packageName + " was not found!"); 3417 } 3418 3419 if (!ps.getInstalled(userId)) { 3420 throw new SecurityException( 3421 "Package " + packageName + " was not installed for user " + userId + "!"); 3422 } 3423 3424 if (mSafeMode && !ps.isSystem()) { 3425 throw new SecurityException("Package " + packageName + " not a system app!"); 3426 } 3427 3428 if (mFrozenPackages.contains(packageName)) { 3429 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3430 } 3431 3432 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3433 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3434 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3435 } 3436 } 3437 } 3438 3439 @Override 3440 public boolean isPackageAvailable(String packageName, int userId) { 3441 if (!sUserManager.exists(userId)) return false; 3442 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3443 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3444 synchronized (mPackages) { 3445 PackageParser.Package p = mPackages.get(packageName); 3446 if (p != null) { 3447 final PackageSetting ps = (PackageSetting) p.mExtras; 3448 if (ps != null) { 3449 final PackageUserState state = ps.readUserState(userId); 3450 if (state != null) { 3451 return PackageParser.isAvailable(state); 3452 } 3453 } 3454 } 3455 } 3456 return false; 3457 } 3458 3459 @Override 3460 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3461 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3462 flags, userId); 3463 } 3464 3465 @Override 3466 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3467 int flags, int userId) { 3468 return getPackageInfoInternal(versionedPackage.getPackageName(), 3469 // TODO: We will change version code to long, so in the new API it is long 3470 (int) versionedPackage.getVersionCode(), flags, userId); 3471 } 3472 3473 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3474 int flags, int userId) { 3475 if (!sUserManager.exists(userId)) return null; 3476 flags = updateFlagsForPackage(flags, userId, packageName); 3477 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3478 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3479 3480 // reader 3481 synchronized (mPackages) { 3482 // Normalize package name to handle renamed packages and static libs 3483 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3484 3485 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3486 if (matchFactoryOnly) { 3487 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3488 if (ps != null) { 3489 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3490 return null; 3491 } 3492 return generatePackageInfo(ps, flags, userId); 3493 } 3494 } 3495 3496 PackageParser.Package p = mPackages.get(packageName); 3497 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3498 return null; 3499 } 3500 if (DEBUG_PACKAGE_INFO) 3501 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3502 if (p != null) { 3503 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3504 Binder.getCallingUid(), userId)) { 3505 return null; 3506 } 3507 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3508 } 3509 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3510 final PackageSetting ps = mSettings.mPackages.get(packageName); 3511 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3512 return null; 3513 } 3514 return generatePackageInfo(ps, flags, userId); 3515 } 3516 } 3517 return null; 3518 } 3519 3520 3521 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3522 // System/shell/root get to see all static libs 3523 final int appId = UserHandle.getAppId(uid); 3524 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3525 || appId == Process.ROOT_UID) { 3526 return false; 3527 } 3528 3529 // No package means no static lib as it is always on internal storage 3530 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3531 return false; 3532 } 3533 3534 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3535 ps.pkg.staticSharedLibVersion); 3536 if (libEntry == null) { 3537 return false; 3538 } 3539 3540 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3541 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3542 if (uidPackageNames == null) { 3543 return true; 3544 } 3545 3546 for (String uidPackageName : uidPackageNames) { 3547 if (ps.name.equals(uidPackageName)) { 3548 return false; 3549 } 3550 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3551 if (uidPs != null) { 3552 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3553 libEntry.info.getName()); 3554 if (index < 0) { 3555 continue; 3556 } 3557 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3558 return false; 3559 } 3560 } 3561 } 3562 return true; 3563 } 3564 3565 @Override 3566 public String[] currentToCanonicalPackageNames(String[] names) { 3567 String[] out = new String[names.length]; 3568 // reader 3569 synchronized (mPackages) { 3570 for (int i=names.length-1; i>=0; i--) { 3571 PackageSetting ps = mSettings.mPackages.get(names[i]); 3572 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3573 } 3574 } 3575 return out; 3576 } 3577 3578 @Override 3579 public String[] canonicalToCurrentPackageNames(String[] names) { 3580 String[] out = new String[names.length]; 3581 // reader 3582 synchronized (mPackages) { 3583 for (int i=names.length-1; i>=0; i--) { 3584 String cur = mSettings.getRenamedPackageLPr(names[i]); 3585 out[i] = cur != null ? cur : names[i]; 3586 } 3587 } 3588 return out; 3589 } 3590 3591 @Override 3592 public int getPackageUid(String packageName, int flags, int userId) { 3593 if (!sUserManager.exists(userId)) return -1; 3594 flags = updateFlagsForPackage(flags, userId, packageName); 3595 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3596 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3597 3598 // reader 3599 synchronized (mPackages) { 3600 final PackageParser.Package p = mPackages.get(packageName); 3601 if (p != null && p.isMatch(flags)) { 3602 return UserHandle.getUid(userId, p.applicationInfo.uid); 3603 } 3604 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3605 final PackageSetting ps = mSettings.mPackages.get(packageName); 3606 if (ps != null && ps.isMatch(flags)) { 3607 return UserHandle.getUid(userId, ps.appId); 3608 } 3609 } 3610 } 3611 3612 return -1; 3613 } 3614 3615 @Override 3616 public int[] getPackageGids(String packageName, int flags, int userId) { 3617 if (!sUserManager.exists(userId)) return null; 3618 flags = updateFlagsForPackage(flags, userId, packageName); 3619 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3620 false /* requireFullPermission */, false /* checkShell */, 3621 "getPackageGids"); 3622 3623 // reader 3624 synchronized (mPackages) { 3625 final PackageParser.Package p = mPackages.get(packageName); 3626 if (p != null && p.isMatch(flags)) { 3627 PackageSetting ps = (PackageSetting) p.mExtras; 3628 // TODO: Shouldn't this be checking for package installed state for userId and 3629 // return null? 3630 return ps.getPermissionsState().computeGids(userId); 3631 } 3632 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3633 final PackageSetting ps = mSettings.mPackages.get(packageName); 3634 if (ps != null && ps.isMatch(flags)) { 3635 return ps.getPermissionsState().computeGids(userId); 3636 } 3637 } 3638 } 3639 3640 return null; 3641 } 3642 3643 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3644 if (bp.perm != null) { 3645 return PackageParser.generatePermissionInfo(bp.perm, flags); 3646 } 3647 PermissionInfo pi = new PermissionInfo(); 3648 pi.name = bp.name; 3649 pi.packageName = bp.sourcePackage; 3650 pi.nonLocalizedLabel = bp.name; 3651 pi.protectionLevel = bp.protectionLevel; 3652 return pi; 3653 } 3654 3655 @Override 3656 public PermissionInfo getPermissionInfo(String name, int flags) { 3657 // reader 3658 synchronized (mPackages) { 3659 final BasePermission p = mSettings.mPermissions.get(name); 3660 if (p != null) { 3661 return generatePermissionInfo(p, flags); 3662 } 3663 return null; 3664 } 3665 } 3666 3667 @Override 3668 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3669 int flags) { 3670 // reader 3671 synchronized (mPackages) { 3672 if (group != null && !mPermissionGroups.containsKey(group)) { 3673 // This is thrown as NameNotFoundException 3674 return null; 3675 } 3676 3677 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3678 for (BasePermission p : mSettings.mPermissions.values()) { 3679 if (group == null) { 3680 if (p.perm == null || p.perm.info.group == null) { 3681 out.add(generatePermissionInfo(p, flags)); 3682 } 3683 } else { 3684 if (p.perm != null && group.equals(p.perm.info.group)) { 3685 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3686 } 3687 } 3688 } 3689 return new ParceledListSlice<>(out); 3690 } 3691 } 3692 3693 @Override 3694 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3695 // reader 3696 synchronized (mPackages) { 3697 return PackageParser.generatePermissionGroupInfo( 3698 mPermissionGroups.get(name), flags); 3699 } 3700 } 3701 3702 @Override 3703 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3704 // reader 3705 synchronized (mPackages) { 3706 final int N = mPermissionGroups.size(); 3707 ArrayList<PermissionGroupInfo> out 3708 = new ArrayList<PermissionGroupInfo>(N); 3709 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3710 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3711 } 3712 return new ParceledListSlice<>(out); 3713 } 3714 } 3715 3716 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3717 int uid, int userId) { 3718 if (!sUserManager.exists(userId)) return null; 3719 PackageSetting ps = mSettings.mPackages.get(packageName); 3720 if (ps != null) { 3721 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3722 return null; 3723 } 3724 if (ps.pkg == null) { 3725 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3726 if (pInfo != null) { 3727 return pInfo.applicationInfo; 3728 } 3729 return null; 3730 } 3731 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3732 ps.readUserState(userId), userId); 3733 if (ai != null) { 3734 rebaseEnabledOverlays(ai, userId); 3735 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3736 } 3737 return ai; 3738 } 3739 return null; 3740 } 3741 3742 @Override 3743 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3744 if (!sUserManager.exists(userId)) return null; 3745 flags = updateFlagsForApplication(flags, userId, packageName); 3746 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3747 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3748 3749 // writer 3750 synchronized (mPackages) { 3751 // Normalize package name to handle renamed packages and static libs 3752 packageName = resolveInternalPackageNameLPr(packageName, 3753 PackageManager.VERSION_CODE_HIGHEST); 3754 3755 PackageParser.Package p = mPackages.get(packageName); 3756 if (DEBUG_PACKAGE_INFO) Log.v( 3757 TAG, "getApplicationInfo " + packageName 3758 + ": " + p); 3759 if (p != null) { 3760 PackageSetting ps = mSettings.mPackages.get(packageName); 3761 if (ps == null) return null; 3762 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3763 return null; 3764 } 3765 // Note: isEnabledLP() does not apply here - always return info 3766 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3767 p, flags, ps.readUserState(userId), userId); 3768 if (ai != null) { 3769 rebaseEnabledOverlays(ai, userId); 3770 ai.packageName = resolveExternalPackageNameLPr(p); 3771 } 3772 return ai; 3773 } 3774 if ("android".equals(packageName)||"system".equals(packageName)) { 3775 return mAndroidApplication; 3776 } 3777 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3778 // Already generates the external package name 3779 return generateApplicationInfoFromSettingsLPw(packageName, 3780 Binder.getCallingUid(), flags, userId); 3781 } 3782 } 3783 return null; 3784 } 3785 3786 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3787 List<String> paths = new ArrayList<>(); 3788 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3789 mEnabledOverlayPaths.get(userId); 3790 if (userSpecificOverlays != null) { 3791 if (!"android".equals(ai.packageName)) { 3792 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3793 if (frameworkOverlays != null) { 3794 paths.addAll(frameworkOverlays); 3795 } 3796 } 3797 3798 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3799 if (appOverlays != null) { 3800 paths.addAll(appOverlays); 3801 } 3802 } 3803 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3804 } 3805 3806 private String normalizePackageNameLPr(String packageName) { 3807 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3808 return normalizedPackageName != null ? normalizedPackageName : packageName; 3809 } 3810 3811 @Override 3812 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3813 final IPackageDataObserver observer) { 3814 mContext.enforceCallingOrSelfPermission( 3815 android.Manifest.permission.CLEAR_APP_CACHE, null); 3816 mHandler.post(() -> { 3817 boolean success = false; 3818 try { 3819 freeStorage(volumeUuid, freeStorageSize, 0); 3820 success = true; 3821 } catch (IOException e) { 3822 Slog.w(TAG, e); 3823 } 3824 if (observer != null) { 3825 try { 3826 observer.onRemoveCompleted(null, success); 3827 } catch (RemoteException e) { 3828 Slog.w(TAG, e); 3829 } 3830 } 3831 }); 3832 } 3833 3834 @Override 3835 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3836 final IntentSender pi) { 3837 mContext.enforceCallingOrSelfPermission( 3838 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3839 mHandler.post(() -> { 3840 boolean success = false; 3841 try { 3842 freeStorage(volumeUuid, freeStorageSize, 0); 3843 success = true; 3844 } catch (IOException e) { 3845 Slog.w(TAG, e); 3846 } 3847 if (pi != null) { 3848 try { 3849 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3850 } catch (SendIntentException e) { 3851 Slog.w(TAG, e); 3852 } 3853 } 3854 }); 3855 } 3856 3857 /** 3858 * Blocking call to clear various types of cached data across the system 3859 * until the requested bytes are available. 3860 */ 3861 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3862 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3863 final File file = storage.findPathForUuid(volumeUuid); 3864 3865 if (ENABLE_FREE_CACHE_V2) { 3866 final boolean aggressive = (storageFlags 3867 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3868 3869 // 1. Pre-flight to determine if we have any chance to succeed 3870 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3871 3872 // 3. Consider parsed APK data (aggressive only) 3873 if (aggressive) { 3874 FileUtils.deleteContents(mCacheDir); 3875 } 3876 if (file.getUsableSpace() >= bytes) return; 3877 3878 // 4. Consider cached app data (above quotas) 3879 try { 3880 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3881 } catch (InstallerException ignored) { 3882 } 3883 if (file.getUsableSpace() >= bytes) return; 3884 3885 // 5. Consider shared libraries with refcount=0 and age>2h 3886 // 6. Consider dexopt output (aggressive only) 3887 // 7. Consider ephemeral apps not used in last week 3888 3889 // 8. Consider cached app data (below quotas) 3890 try { 3891 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3892 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3893 } catch (InstallerException ignored) { 3894 } 3895 if (file.getUsableSpace() >= bytes) return; 3896 3897 // 9. Consider DropBox entries 3898 // 10. Consider ephemeral cookies 3899 3900 } else { 3901 try { 3902 mInstaller.freeCache(volumeUuid, bytes, 0); 3903 } catch (InstallerException ignored) { 3904 } 3905 if (file.getUsableSpace() >= bytes) return; 3906 } 3907 3908 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3909 } 3910 3911 /** 3912 * Update given flags based on encryption status of current user. 3913 */ 3914 private int updateFlags(int flags, int userId) { 3915 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3916 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3917 // Caller expressed an explicit opinion about what encryption 3918 // aware/unaware components they want to see, so fall through and 3919 // give them what they want 3920 } else { 3921 // Caller expressed no opinion, so match based on user state 3922 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3923 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3924 } else { 3925 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3926 } 3927 } 3928 return flags; 3929 } 3930 3931 private UserManagerInternal getUserManagerInternal() { 3932 if (mUserManagerInternal == null) { 3933 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3934 } 3935 return mUserManagerInternal; 3936 } 3937 3938 private DeviceIdleController.LocalService getDeviceIdleController() { 3939 if (mDeviceIdleController == null) { 3940 mDeviceIdleController = 3941 LocalServices.getService(DeviceIdleController.LocalService.class); 3942 } 3943 return mDeviceIdleController; 3944 } 3945 3946 /** 3947 * Update given flags when being used to request {@link PackageInfo}. 3948 */ 3949 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3950 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3951 boolean triaged = true; 3952 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3953 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3954 // Caller is asking for component details, so they'd better be 3955 // asking for specific encryption matching behavior, or be triaged 3956 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3957 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3958 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3959 triaged = false; 3960 } 3961 } 3962 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3963 | PackageManager.MATCH_SYSTEM_ONLY 3964 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3965 triaged = false; 3966 } 3967 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3968 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3969 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3970 + Debug.getCallers(5)); 3971 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3972 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3973 // If the caller wants all packages and has a restricted profile associated with it, 3974 // then match all users. This is to make sure that launchers that need to access work 3975 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3976 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3977 flags |= PackageManager.MATCH_ANY_USER; 3978 } 3979 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3980 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3981 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3982 } 3983 return updateFlags(flags, userId); 3984 } 3985 3986 /** 3987 * Update given flags when being used to request {@link ApplicationInfo}. 3988 */ 3989 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3990 return updateFlagsForPackage(flags, userId, cookie); 3991 } 3992 3993 /** 3994 * Update given flags when being used to request {@link ComponentInfo}. 3995 */ 3996 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3997 if (cookie instanceof Intent) { 3998 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3999 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4000 } 4001 } 4002 4003 boolean triaged = true; 4004 // Caller is asking for component details, so they'd better be 4005 // asking for specific encryption matching behavior, or be triaged 4006 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4007 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4008 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4009 triaged = false; 4010 } 4011 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4012 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4013 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4014 } 4015 4016 return updateFlags(flags, userId); 4017 } 4018 4019 /** 4020 * Update given intent when being used to request {@link ResolveInfo}. 4021 */ 4022 private Intent updateIntentForResolve(Intent intent) { 4023 if (intent.getSelector() != null) { 4024 intent = intent.getSelector(); 4025 } 4026 if (DEBUG_PREFERRED) { 4027 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4028 } 4029 return intent; 4030 } 4031 4032 /** 4033 * Update given flags when being used to request {@link ResolveInfo}. 4034 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4035 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4036 * flag set. However, this flag is only honoured in three circumstances: 4037 * <ul> 4038 * <li>when called from a system process</li> 4039 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4040 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4041 * action and a {@code android.intent.category.BROWSABLE} category</li> 4042 * </ul> 4043 */ 4044 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4045 // Safe mode means we shouldn't match any third-party components 4046 if (mSafeMode) { 4047 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4048 } 4049 final int callingUid = Binder.getCallingUid(); 4050 if (getInstantAppPackageName(callingUid) != null) { 4051 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4052 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4053 flags |= PackageManager.MATCH_INSTANT; 4054 } else { 4055 // Otherwise, prevent leaking ephemeral components 4056 final boolean isSpecialProcess = 4057 callingUid == Process.SYSTEM_UID 4058 || callingUid == Process.SHELL_UID 4059 || callingUid == 0; 4060 final boolean allowMatchInstant = 4061 (includeInstantApp 4062 && Intent.ACTION_VIEW.equals(intent.getAction()) 4063 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4064 && hasWebURI(intent)) 4065 || isSpecialProcess 4066 || mContext.checkCallingOrSelfPermission( 4067 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4068 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4069 if (!allowMatchInstant) { 4070 flags &= ~PackageManager.MATCH_INSTANT; 4071 } 4072 } 4073 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4074 } 4075 4076 @Override 4077 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4078 if (!sUserManager.exists(userId)) return null; 4079 flags = updateFlagsForComponent(flags, userId, component); 4080 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4081 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4082 synchronized (mPackages) { 4083 PackageParser.Activity a = mActivities.mActivities.get(component); 4084 4085 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4086 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4087 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4088 if (ps == null) return null; 4089 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4090 userId); 4091 } 4092 if (mResolveComponentName.equals(component)) { 4093 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4094 new PackageUserState(), userId); 4095 } 4096 } 4097 return null; 4098 } 4099 4100 @Override 4101 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4102 String resolvedType) { 4103 synchronized (mPackages) { 4104 if (component.equals(mResolveComponentName)) { 4105 // The resolver supports EVERYTHING! 4106 return true; 4107 } 4108 PackageParser.Activity a = mActivities.mActivities.get(component); 4109 if (a == null) { 4110 return false; 4111 } 4112 for (int i=0; i<a.intents.size(); i++) { 4113 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4114 intent.getData(), intent.getCategories(), TAG) >= 0) { 4115 return true; 4116 } 4117 } 4118 return false; 4119 } 4120 } 4121 4122 @Override 4123 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4124 if (!sUserManager.exists(userId)) return null; 4125 flags = updateFlagsForComponent(flags, userId, component); 4126 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4127 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4128 synchronized (mPackages) { 4129 PackageParser.Activity a = mReceivers.mActivities.get(component); 4130 if (DEBUG_PACKAGE_INFO) Log.v( 4131 TAG, "getReceiverInfo " + component + ": " + a); 4132 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4133 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4134 if (ps == null) return null; 4135 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4136 ps.readUserState(userId), userId); 4137 if (ri != null) { 4138 rebaseEnabledOverlays(ri.applicationInfo, userId); 4139 } 4140 return ri; 4141 } 4142 } 4143 return null; 4144 } 4145 4146 @Override 4147 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4148 if (!sUserManager.exists(userId)) return null; 4149 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4150 4151 flags = updateFlagsForPackage(flags, userId, null); 4152 4153 final boolean canSeeStaticLibraries = 4154 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4155 == PERMISSION_GRANTED 4156 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4157 == PERMISSION_GRANTED 4158 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4159 == PERMISSION_GRANTED 4160 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4161 == PERMISSION_GRANTED; 4162 4163 synchronized (mPackages) { 4164 List<SharedLibraryInfo> result = null; 4165 4166 final int libCount = mSharedLibraries.size(); 4167 for (int i = 0; i < libCount; i++) { 4168 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4169 if (versionedLib == null) { 4170 continue; 4171 } 4172 4173 final int versionCount = versionedLib.size(); 4174 for (int j = 0; j < versionCount; j++) { 4175 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4176 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4177 break; 4178 } 4179 final long identity = Binder.clearCallingIdentity(); 4180 try { 4181 // TODO: We will change version code to long, so in the new API it is long 4182 PackageInfo packageInfo = getPackageInfoVersioned( 4183 libInfo.getDeclaringPackage(), flags, userId); 4184 if (packageInfo == null) { 4185 continue; 4186 } 4187 } finally { 4188 Binder.restoreCallingIdentity(identity); 4189 } 4190 4191 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4192 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4193 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4194 4195 if (result == null) { 4196 result = new ArrayList<>(); 4197 } 4198 result.add(resLibInfo); 4199 } 4200 } 4201 4202 return result != null ? new ParceledListSlice<>(result) : null; 4203 } 4204 } 4205 4206 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4207 SharedLibraryInfo libInfo, int flags, int userId) { 4208 List<VersionedPackage> versionedPackages = null; 4209 final int packageCount = mSettings.mPackages.size(); 4210 for (int i = 0; i < packageCount; i++) { 4211 PackageSetting ps = mSettings.mPackages.valueAt(i); 4212 4213 if (ps == null) { 4214 continue; 4215 } 4216 4217 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4218 continue; 4219 } 4220 4221 final String libName = libInfo.getName(); 4222 if (libInfo.isStatic()) { 4223 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4224 if (libIdx < 0) { 4225 continue; 4226 } 4227 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4228 continue; 4229 } 4230 if (versionedPackages == null) { 4231 versionedPackages = new ArrayList<>(); 4232 } 4233 // If the dependent is a static shared lib, use the public package name 4234 String dependentPackageName = ps.name; 4235 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4236 dependentPackageName = ps.pkg.manifestPackageName; 4237 } 4238 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4239 } else if (ps.pkg != null) { 4240 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4241 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4242 if (versionedPackages == null) { 4243 versionedPackages = new ArrayList<>(); 4244 } 4245 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4246 } 4247 } 4248 } 4249 4250 return versionedPackages; 4251 } 4252 4253 @Override 4254 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4255 if (!sUserManager.exists(userId)) return null; 4256 flags = updateFlagsForComponent(flags, userId, component); 4257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4258 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4259 synchronized (mPackages) { 4260 PackageParser.Service s = mServices.mServices.get(component); 4261 if (DEBUG_PACKAGE_INFO) Log.v( 4262 TAG, "getServiceInfo " + component + ": " + s); 4263 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4264 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4265 if (ps == null) return null; 4266 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4267 ps.readUserState(userId), userId); 4268 if (si != null) { 4269 rebaseEnabledOverlays(si.applicationInfo, userId); 4270 } 4271 return si; 4272 } 4273 } 4274 return null; 4275 } 4276 4277 @Override 4278 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4279 if (!sUserManager.exists(userId)) return null; 4280 flags = updateFlagsForComponent(flags, userId, component); 4281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4282 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4283 synchronized (mPackages) { 4284 PackageParser.Provider p = mProviders.mProviders.get(component); 4285 if (DEBUG_PACKAGE_INFO) Log.v( 4286 TAG, "getProviderInfo " + component + ": " + p); 4287 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4288 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4289 if (ps == null) return null; 4290 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4291 ps.readUserState(userId), userId); 4292 if (pi != null) { 4293 rebaseEnabledOverlays(pi.applicationInfo, userId); 4294 } 4295 return pi; 4296 } 4297 } 4298 return null; 4299 } 4300 4301 @Override 4302 public String[] getSystemSharedLibraryNames() { 4303 synchronized (mPackages) { 4304 Set<String> libs = null; 4305 final int libCount = mSharedLibraries.size(); 4306 for (int i = 0; i < libCount; i++) { 4307 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4308 if (versionedLib == null) { 4309 continue; 4310 } 4311 final int versionCount = versionedLib.size(); 4312 for (int j = 0; j < versionCount; j++) { 4313 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4314 if (!libEntry.info.isStatic()) { 4315 if (libs == null) { 4316 libs = new ArraySet<>(); 4317 } 4318 libs.add(libEntry.info.getName()); 4319 break; 4320 } 4321 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4322 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4323 UserHandle.getUserId(Binder.getCallingUid()))) { 4324 if (libs == null) { 4325 libs = new ArraySet<>(); 4326 } 4327 libs.add(libEntry.info.getName()); 4328 break; 4329 } 4330 } 4331 } 4332 4333 if (libs != null) { 4334 String[] libsArray = new String[libs.size()]; 4335 libs.toArray(libsArray); 4336 return libsArray; 4337 } 4338 4339 return null; 4340 } 4341 } 4342 4343 @Override 4344 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4345 synchronized (mPackages) { 4346 return mServicesSystemSharedLibraryPackageName; 4347 } 4348 } 4349 4350 @Override 4351 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4352 synchronized (mPackages) { 4353 return mSharedSystemSharedLibraryPackageName; 4354 } 4355 } 4356 4357 private void updateSequenceNumberLP(String packageName, int[] userList) { 4358 for (int i = userList.length - 1; i >= 0; --i) { 4359 final int userId = userList[i]; 4360 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4361 if (changedPackages == null) { 4362 changedPackages = new SparseArray<>(); 4363 mChangedPackages.put(userId, changedPackages); 4364 } 4365 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4366 if (sequenceNumbers == null) { 4367 sequenceNumbers = new HashMap<>(); 4368 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4369 } 4370 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4371 if (sequenceNumber != null) { 4372 changedPackages.remove(sequenceNumber); 4373 } 4374 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4375 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4376 } 4377 mChangedPackagesSequenceNumber++; 4378 } 4379 4380 @Override 4381 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4382 synchronized (mPackages) { 4383 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4384 return null; 4385 } 4386 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4387 if (changedPackages == null) { 4388 return null; 4389 } 4390 final List<String> packageNames = 4391 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4392 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4393 final String packageName = changedPackages.get(i); 4394 if (packageName != null) { 4395 packageNames.add(packageName); 4396 } 4397 } 4398 return packageNames.isEmpty() 4399 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4400 } 4401 } 4402 4403 @Override 4404 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4405 ArrayList<FeatureInfo> res; 4406 synchronized (mAvailableFeatures) { 4407 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4408 res.addAll(mAvailableFeatures.values()); 4409 } 4410 final FeatureInfo fi = new FeatureInfo(); 4411 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4412 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4413 res.add(fi); 4414 4415 return new ParceledListSlice<>(res); 4416 } 4417 4418 @Override 4419 public boolean hasSystemFeature(String name, int version) { 4420 synchronized (mAvailableFeatures) { 4421 final FeatureInfo feat = mAvailableFeatures.get(name); 4422 if (feat == null) { 4423 return false; 4424 } else { 4425 return feat.version >= version; 4426 } 4427 } 4428 } 4429 4430 @Override 4431 public int checkPermission(String permName, String pkgName, int userId) { 4432 if (!sUserManager.exists(userId)) { 4433 return PackageManager.PERMISSION_DENIED; 4434 } 4435 4436 synchronized (mPackages) { 4437 final PackageParser.Package p = mPackages.get(pkgName); 4438 if (p != null && p.mExtras != null) { 4439 final PackageSetting ps = (PackageSetting) p.mExtras; 4440 final PermissionsState permissionsState = ps.getPermissionsState(); 4441 if (permissionsState.hasPermission(permName, userId)) { 4442 return PackageManager.PERMISSION_GRANTED; 4443 } 4444 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4445 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4446 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4447 return PackageManager.PERMISSION_GRANTED; 4448 } 4449 } 4450 } 4451 4452 return PackageManager.PERMISSION_DENIED; 4453 } 4454 4455 @Override 4456 public int checkUidPermission(String permName, int uid) { 4457 final int userId = UserHandle.getUserId(uid); 4458 4459 if (!sUserManager.exists(userId)) { 4460 return PackageManager.PERMISSION_DENIED; 4461 } 4462 4463 synchronized (mPackages) { 4464 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4465 if (obj != null) { 4466 final SettingBase ps = (SettingBase) obj; 4467 final PermissionsState permissionsState = ps.getPermissionsState(); 4468 if (permissionsState.hasPermission(permName, userId)) { 4469 return PackageManager.PERMISSION_GRANTED; 4470 } 4471 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4472 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4473 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4474 return PackageManager.PERMISSION_GRANTED; 4475 } 4476 } else { 4477 ArraySet<String> perms = mSystemPermissions.get(uid); 4478 if (perms != null) { 4479 if (perms.contains(permName)) { 4480 return PackageManager.PERMISSION_GRANTED; 4481 } 4482 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4483 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4484 return PackageManager.PERMISSION_GRANTED; 4485 } 4486 } 4487 } 4488 } 4489 4490 return PackageManager.PERMISSION_DENIED; 4491 } 4492 4493 @Override 4494 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4495 if (UserHandle.getCallingUserId() != userId) { 4496 mContext.enforceCallingPermission( 4497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4498 "isPermissionRevokedByPolicy for user " + userId); 4499 } 4500 4501 if (checkPermission(permission, packageName, userId) 4502 == PackageManager.PERMISSION_GRANTED) { 4503 return false; 4504 } 4505 4506 final long identity = Binder.clearCallingIdentity(); 4507 try { 4508 final int flags = getPermissionFlags(permission, packageName, userId); 4509 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4510 } finally { 4511 Binder.restoreCallingIdentity(identity); 4512 } 4513 } 4514 4515 @Override 4516 public String getPermissionControllerPackageName() { 4517 synchronized (mPackages) { 4518 return mRequiredInstallerPackage; 4519 } 4520 } 4521 4522 /** 4523 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4524 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4525 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4526 * @param message the message to log on security exception 4527 */ 4528 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4529 boolean checkShell, String message) { 4530 if (userId < 0) { 4531 throw new IllegalArgumentException("Invalid userId " + userId); 4532 } 4533 if (checkShell) { 4534 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4535 } 4536 if (userId == UserHandle.getUserId(callingUid)) return; 4537 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4538 if (requireFullPermission) { 4539 mContext.enforceCallingOrSelfPermission( 4540 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4541 } else { 4542 try { 4543 mContext.enforceCallingOrSelfPermission( 4544 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4545 } catch (SecurityException se) { 4546 mContext.enforceCallingOrSelfPermission( 4547 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4548 } 4549 } 4550 } 4551 } 4552 4553 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4554 if (callingUid == Process.SHELL_UID) { 4555 if (userHandle >= 0 4556 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4557 throw new SecurityException("Shell does not have permission to access user " 4558 + userHandle); 4559 } else if (userHandle < 0) { 4560 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4561 + Debug.getCallers(3)); 4562 } 4563 } 4564 } 4565 4566 private BasePermission findPermissionTreeLP(String permName) { 4567 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4568 if (permName.startsWith(bp.name) && 4569 permName.length() > bp.name.length() && 4570 permName.charAt(bp.name.length()) == '.') { 4571 return bp; 4572 } 4573 } 4574 return null; 4575 } 4576 4577 private BasePermission checkPermissionTreeLP(String permName) { 4578 if (permName != null) { 4579 BasePermission bp = findPermissionTreeLP(permName); 4580 if (bp != null) { 4581 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4582 return bp; 4583 } 4584 throw new SecurityException("Calling uid " 4585 + Binder.getCallingUid() 4586 + " is not allowed to add to permission tree " 4587 + bp.name + " owned by uid " + bp.uid); 4588 } 4589 } 4590 throw new SecurityException("No permission tree found for " + permName); 4591 } 4592 4593 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4594 if (s1 == null) { 4595 return s2 == null; 4596 } 4597 if (s2 == null) { 4598 return false; 4599 } 4600 if (s1.getClass() != s2.getClass()) { 4601 return false; 4602 } 4603 return s1.equals(s2); 4604 } 4605 4606 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4607 if (pi1.icon != pi2.icon) return false; 4608 if (pi1.logo != pi2.logo) return false; 4609 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4610 if (!compareStrings(pi1.name, pi2.name)) return false; 4611 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4612 // We'll take care of setting this one. 4613 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4614 // These are not currently stored in settings. 4615 //if (!compareStrings(pi1.group, pi2.group)) return false; 4616 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4617 //if (pi1.labelRes != pi2.labelRes) return false; 4618 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4619 return true; 4620 } 4621 4622 int permissionInfoFootprint(PermissionInfo info) { 4623 int size = info.name.length(); 4624 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4625 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4626 return size; 4627 } 4628 4629 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4630 int size = 0; 4631 for (BasePermission perm : mSettings.mPermissions.values()) { 4632 if (perm.uid == tree.uid) { 4633 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4634 } 4635 } 4636 return size; 4637 } 4638 4639 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4640 // We calculate the max size of permissions defined by this uid and throw 4641 // if that plus the size of 'info' would exceed our stated maximum. 4642 if (tree.uid != Process.SYSTEM_UID) { 4643 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4644 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4645 throw new SecurityException("Permission tree size cap exceeded"); 4646 } 4647 } 4648 } 4649 4650 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4651 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4652 throw new SecurityException("Label must be specified in permission"); 4653 } 4654 BasePermission tree = checkPermissionTreeLP(info.name); 4655 BasePermission bp = mSettings.mPermissions.get(info.name); 4656 boolean added = bp == null; 4657 boolean changed = true; 4658 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4659 if (added) { 4660 enforcePermissionCapLocked(info, tree); 4661 bp = new BasePermission(info.name, tree.sourcePackage, 4662 BasePermission.TYPE_DYNAMIC); 4663 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4664 throw new SecurityException( 4665 "Not allowed to modify non-dynamic permission " 4666 + info.name); 4667 } else { 4668 if (bp.protectionLevel == fixedLevel 4669 && bp.perm.owner.equals(tree.perm.owner) 4670 && bp.uid == tree.uid 4671 && comparePermissionInfos(bp.perm.info, info)) { 4672 changed = false; 4673 } 4674 } 4675 bp.protectionLevel = fixedLevel; 4676 info = new PermissionInfo(info); 4677 info.protectionLevel = fixedLevel; 4678 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4679 bp.perm.info.packageName = tree.perm.info.packageName; 4680 bp.uid = tree.uid; 4681 if (added) { 4682 mSettings.mPermissions.put(info.name, bp); 4683 } 4684 if (changed) { 4685 if (!async) { 4686 mSettings.writeLPr(); 4687 } else { 4688 scheduleWriteSettingsLocked(); 4689 } 4690 } 4691 return added; 4692 } 4693 4694 @Override 4695 public boolean addPermission(PermissionInfo info) { 4696 synchronized (mPackages) { 4697 return addPermissionLocked(info, false); 4698 } 4699 } 4700 4701 @Override 4702 public boolean addPermissionAsync(PermissionInfo info) { 4703 synchronized (mPackages) { 4704 return addPermissionLocked(info, true); 4705 } 4706 } 4707 4708 @Override 4709 public void removePermission(String name) { 4710 synchronized (mPackages) { 4711 checkPermissionTreeLP(name); 4712 BasePermission bp = mSettings.mPermissions.get(name); 4713 if (bp != null) { 4714 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4715 throw new SecurityException( 4716 "Not allowed to modify non-dynamic permission " 4717 + name); 4718 } 4719 mSettings.mPermissions.remove(name); 4720 mSettings.writeLPr(); 4721 } 4722 } 4723 } 4724 4725 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4726 BasePermission bp) { 4727 int index = pkg.requestedPermissions.indexOf(bp.name); 4728 if (index == -1) { 4729 throw new SecurityException("Package " + pkg.packageName 4730 + " has not requested permission " + bp.name); 4731 } 4732 if (!bp.isRuntime() && !bp.isDevelopment()) { 4733 throw new SecurityException("Permission " + bp.name 4734 + " is not a changeable permission type"); 4735 } 4736 } 4737 4738 @Override 4739 public void grantRuntimePermission(String packageName, String name, final int userId) { 4740 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4741 } 4742 4743 private void grantRuntimePermission(String packageName, String name, final int userId, 4744 boolean overridePolicy) { 4745 if (!sUserManager.exists(userId)) { 4746 Log.e(TAG, "No such user:" + userId); 4747 return; 4748 } 4749 4750 mContext.enforceCallingOrSelfPermission( 4751 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4752 "grantRuntimePermission"); 4753 4754 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4755 true /* requireFullPermission */, true /* checkShell */, 4756 "grantRuntimePermission"); 4757 4758 final int uid; 4759 final SettingBase sb; 4760 4761 synchronized (mPackages) { 4762 final PackageParser.Package pkg = mPackages.get(packageName); 4763 if (pkg == null) { 4764 throw new IllegalArgumentException("Unknown package: " + packageName); 4765 } 4766 4767 final BasePermission bp = mSettings.mPermissions.get(name); 4768 if (bp == null) { 4769 throw new IllegalArgumentException("Unknown permission: " + name); 4770 } 4771 4772 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4773 4774 // If a permission review is required for legacy apps we represent 4775 // their permissions as always granted runtime ones since we need 4776 // to keep the review required permission flag per user while an 4777 // install permission's state is shared across all users. 4778 if (mPermissionReviewRequired 4779 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4780 && bp.isRuntime()) { 4781 return; 4782 } 4783 4784 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4785 sb = (SettingBase) pkg.mExtras; 4786 if (sb == null) { 4787 throw new IllegalArgumentException("Unknown package: " + packageName); 4788 } 4789 4790 final PermissionsState permissionsState = sb.getPermissionsState(); 4791 4792 final int flags = permissionsState.getPermissionFlags(name, userId); 4793 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4794 throw new SecurityException("Cannot grant system fixed permission " 4795 + name + " for package " + packageName); 4796 } 4797 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4798 throw new SecurityException("Cannot grant policy fixed permission " 4799 + name + " for package " + packageName); 4800 } 4801 4802 if (bp.isDevelopment()) { 4803 // Development permissions must be handled specially, since they are not 4804 // normal runtime permissions. For now they apply to all users. 4805 if (permissionsState.grantInstallPermission(bp) != 4806 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4807 scheduleWriteSettingsLocked(); 4808 } 4809 return; 4810 } 4811 4812 final PackageSetting ps = mSettings.mPackages.get(packageName); 4813 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4814 throw new SecurityException("Cannot grant non-ephemeral permission" 4815 + name + " for package " + packageName); 4816 } 4817 4818 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4819 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4820 return; 4821 } 4822 4823 final int result = permissionsState.grantRuntimePermission(bp, userId); 4824 switch (result) { 4825 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4826 return; 4827 } 4828 4829 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4830 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4831 mHandler.post(new Runnable() { 4832 @Override 4833 public void run() { 4834 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4835 } 4836 }); 4837 } 4838 break; 4839 } 4840 4841 if (bp.isRuntime()) { 4842 logPermissionGranted(mContext, name, packageName); 4843 } 4844 4845 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4846 4847 // Not critical if that is lost - app has to request again. 4848 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4849 } 4850 4851 // Only need to do this if user is initialized. Otherwise it's a new user 4852 // and there are no processes running as the user yet and there's no need 4853 // to make an expensive call to remount processes for the changed permissions. 4854 if (READ_EXTERNAL_STORAGE.equals(name) 4855 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4856 final long token = Binder.clearCallingIdentity(); 4857 try { 4858 if (sUserManager.isInitialized(userId)) { 4859 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4860 StorageManagerInternal.class); 4861 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4862 } 4863 } finally { 4864 Binder.restoreCallingIdentity(token); 4865 } 4866 } 4867 } 4868 4869 @Override 4870 public void revokeRuntimePermission(String packageName, String name, int userId) { 4871 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4872 } 4873 4874 private void revokeRuntimePermission(String packageName, String name, int userId, 4875 boolean overridePolicy) { 4876 if (!sUserManager.exists(userId)) { 4877 Log.e(TAG, "No such user:" + userId); 4878 return; 4879 } 4880 4881 mContext.enforceCallingOrSelfPermission( 4882 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4883 "revokeRuntimePermission"); 4884 4885 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4886 true /* requireFullPermission */, true /* checkShell */, 4887 "revokeRuntimePermission"); 4888 4889 final int appId; 4890 4891 synchronized (mPackages) { 4892 final PackageParser.Package pkg = mPackages.get(packageName); 4893 if (pkg == null) { 4894 throw new IllegalArgumentException("Unknown package: " + packageName); 4895 } 4896 4897 final BasePermission bp = mSettings.mPermissions.get(name); 4898 if (bp == null) { 4899 throw new IllegalArgumentException("Unknown permission: " + name); 4900 } 4901 4902 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4903 4904 // If a permission review is required for legacy apps we represent 4905 // their permissions as always granted runtime ones since we need 4906 // to keep the review required permission flag per user while an 4907 // install permission's state is shared across all users. 4908 if (mPermissionReviewRequired 4909 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4910 && bp.isRuntime()) { 4911 return; 4912 } 4913 4914 SettingBase sb = (SettingBase) pkg.mExtras; 4915 if (sb == null) { 4916 throw new IllegalArgumentException("Unknown package: " + packageName); 4917 } 4918 4919 final PermissionsState permissionsState = sb.getPermissionsState(); 4920 4921 final int flags = permissionsState.getPermissionFlags(name, userId); 4922 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4923 throw new SecurityException("Cannot revoke system fixed permission " 4924 + name + " for package " + packageName); 4925 } 4926 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4927 throw new SecurityException("Cannot revoke policy fixed permission " 4928 + name + " for package " + packageName); 4929 } 4930 4931 if (bp.isDevelopment()) { 4932 // Development permissions must be handled specially, since they are not 4933 // normal runtime permissions. For now they apply to all users. 4934 if (permissionsState.revokeInstallPermission(bp) != 4935 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4936 scheduleWriteSettingsLocked(); 4937 } 4938 return; 4939 } 4940 4941 if (permissionsState.revokeRuntimePermission(bp, userId) == 4942 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4943 return; 4944 } 4945 4946 if (bp.isRuntime()) { 4947 logPermissionRevoked(mContext, name, packageName); 4948 } 4949 4950 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4951 4952 // Critical, after this call app should never have the permission. 4953 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4954 4955 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4956 } 4957 4958 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4959 } 4960 4961 /** 4962 * Get the first event id for the permission. 4963 * 4964 * <p>There are four events for each permission: <ul> 4965 * <li>Request permission: first id + 0</li> 4966 * <li>Grant permission: first id + 1</li> 4967 * <li>Request for permission denied: first id + 2</li> 4968 * <li>Revoke permission: first id + 3</li> 4969 * </ul></p> 4970 * 4971 * @param name name of the permission 4972 * 4973 * @return The first event id for the permission 4974 */ 4975 private static int getBaseEventId(@NonNull String name) { 4976 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4977 4978 if (eventIdIndex == -1) { 4979 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4980 || "user".equals(Build.TYPE)) { 4981 Log.i(TAG, "Unknown permission " + name); 4982 4983 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4984 } else { 4985 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4986 // 4987 // Also update 4988 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4989 // - metrics_constants.proto 4990 throw new IllegalStateException("Unknown permission " + name); 4991 } 4992 } 4993 4994 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4995 } 4996 4997 /** 4998 * Log that a permission was revoked. 4999 * 5000 * @param context Context of the caller 5001 * @param name name of the permission 5002 * @param packageName package permission if for 5003 */ 5004 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5005 @NonNull String packageName) { 5006 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5007 } 5008 5009 /** 5010 * Log that a permission request was granted. 5011 * 5012 * @param context Context of the caller 5013 * @param name name of the permission 5014 * @param packageName package permission if for 5015 */ 5016 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5017 @NonNull String packageName) { 5018 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5019 } 5020 5021 @Override 5022 public void resetRuntimePermissions() { 5023 mContext.enforceCallingOrSelfPermission( 5024 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5025 "revokeRuntimePermission"); 5026 5027 int callingUid = Binder.getCallingUid(); 5028 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5029 mContext.enforceCallingOrSelfPermission( 5030 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5031 "resetRuntimePermissions"); 5032 } 5033 5034 synchronized (mPackages) { 5035 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5036 for (int userId : UserManagerService.getInstance().getUserIds()) { 5037 final int packageCount = mPackages.size(); 5038 for (int i = 0; i < packageCount; i++) { 5039 PackageParser.Package pkg = mPackages.valueAt(i); 5040 if (!(pkg.mExtras instanceof PackageSetting)) { 5041 continue; 5042 } 5043 PackageSetting ps = (PackageSetting) pkg.mExtras; 5044 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5045 } 5046 } 5047 } 5048 } 5049 5050 @Override 5051 public int getPermissionFlags(String name, String packageName, int userId) { 5052 if (!sUserManager.exists(userId)) { 5053 return 0; 5054 } 5055 5056 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5057 5058 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5059 true /* requireFullPermission */, false /* checkShell */, 5060 "getPermissionFlags"); 5061 5062 synchronized (mPackages) { 5063 final PackageParser.Package pkg = mPackages.get(packageName); 5064 if (pkg == null) { 5065 return 0; 5066 } 5067 5068 final BasePermission bp = mSettings.mPermissions.get(name); 5069 if (bp == null) { 5070 return 0; 5071 } 5072 5073 SettingBase sb = (SettingBase) pkg.mExtras; 5074 if (sb == null) { 5075 return 0; 5076 } 5077 5078 PermissionsState permissionsState = sb.getPermissionsState(); 5079 return permissionsState.getPermissionFlags(name, userId); 5080 } 5081 } 5082 5083 @Override 5084 public void updatePermissionFlags(String name, String packageName, int flagMask, 5085 int flagValues, int userId) { 5086 if (!sUserManager.exists(userId)) { 5087 return; 5088 } 5089 5090 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5091 5092 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5093 true /* requireFullPermission */, true /* checkShell */, 5094 "updatePermissionFlags"); 5095 5096 // Only the system can change these flags and nothing else. 5097 if (getCallingUid() != Process.SYSTEM_UID) { 5098 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5099 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5100 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5101 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5102 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5103 } 5104 5105 synchronized (mPackages) { 5106 final PackageParser.Package pkg = mPackages.get(packageName); 5107 if (pkg == null) { 5108 throw new IllegalArgumentException("Unknown package: " + packageName); 5109 } 5110 5111 final BasePermission bp = mSettings.mPermissions.get(name); 5112 if (bp == null) { 5113 throw new IllegalArgumentException("Unknown permission: " + name); 5114 } 5115 5116 SettingBase sb = (SettingBase) pkg.mExtras; 5117 if (sb == null) { 5118 throw new IllegalArgumentException("Unknown package: " + packageName); 5119 } 5120 5121 PermissionsState permissionsState = sb.getPermissionsState(); 5122 5123 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5124 5125 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5126 // Install and runtime permissions are stored in different places, 5127 // so figure out what permission changed and persist the change. 5128 if (permissionsState.getInstallPermissionState(name) != null) { 5129 scheduleWriteSettingsLocked(); 5130 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5131 || hadState) { 5132 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5133 } 5134 } 5135 } 5136 } 5137 5138 /** 5139 * Update the permission flags for all packages and runtime permissions of a user in order 5140 * to allow device or profile owner to remove POLICY_FIXED. 5141 */ 5142 @Override 5143 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5144 if (!sUserManager.exists(userId)) { 5145 return; 5146 } 5147 5148 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5149 5150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5151 true /* requireFullPermission */, true /* checkShell */, 5152 "updatePermissionFlagsForAllApps"); 5153 5154 // Only the system can change system fixed flags. 5155 if (getCallingUid() != Process.SYSTEM_UID) { 5156 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5157 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5158 } 5159 5160 synchronized (mPackages) { 5161 boolean changed = false; 5162 final int packageCount = mPackages.size(); 5163 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5164 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5165 SettingBase sb = (SettingBase) pkg.mExtras; 5166 if (sb == null) { 5167 continue; 5168 } 5169 PermissionsState permissionsState = sb.getPermissionsState(); 5170 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5171 userId, flagMask, flagValues); 5172 } 5173 if (changed) { 5174 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5175 } 5176 } 5177 } 5178 5179 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5180 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5181 != PackageManager.PERMISSION_GRANTED 5182 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5183 != PackageManager.PERMISSION_GRANTED) { 5184 throw new SecurityException(message + " requires " 5185 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5186 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5187 } 5188 } 5189 5190 @Override 5191 public boolean shouldShowRequestPermissionRationale(String permissionName, 5192 String packageName, int userId) { 5193 if (UserHandle.getCallingUserId() != userId) { 5194 mContext.enforceCallingPermission( 5195 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5196 "canShowRequestPermissionRationale for user " + userId); 5197 } 5198 5199 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5200 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5201 return false; 5202 } 5203 5204 if (checkPermission(permissionName, packageName, userId) 5205 == PackageManager.PERMISSION_GRANTED) { 5206 return false; 5207 } 5208 5209 final int flags; 5210 5211 final long identity = Binder.clearCallingIdentity(); 5212 try { 5213 flags = getPermissionFlags(permissionName, 5214 packageName, userId); 5215 } finally { 5216 Binder.restoreCallingIdentity(identity); 5217 } 5218 5219 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5220 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5221 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5222 5223 if ((flags & fixedFlags) != 0) { 5224 return false; 5225 } 5226 5227 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5228 } 5229 5230 @Override 5231 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5232 mContext.enforceCallingOrSelfPermission( 5233 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5234 "addOnPermissionsChangeListener"); 5235 5236 synchronized (mPackages) { 5237 mOnPermissionChangeListeners.addListenerLocked(listener); 5238 } 5239 } 5240 5241 @Override 5242 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5243 synchronized (mPackages) { 5244 mOnPermissionChangeListeners.removeListenerLocked(listener); 5245 } 5246 } 5247 5248 @Override 5249 public boolean isProtectedBroadcast(String actionName) { 5250 synchronized (mPackages) { 5251 if (mProtectedBroadcasts.contains(actionName)) { 5252 return true; 5253 } else if (actionName != null) { 5254 // TODO: remove these terrible hacks 5255 if (actionName.startsWith("android.net.netmon.lingerExpired") 5256 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5257 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5258 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5259 return true; 5260 } 5261 } 5262 } 5263 return false; 5264 } 5265 5266 @Override 5267 public int checkSignatures(String pkg1, String pkg2) { 5268 synchronized (mPackages) { 5269 final PackageParser.Package p1 = mPackages.get(pkg1); 5270 final PackageParser.Package p2 = mPackages.get(pkg2); 5271 if (p1 == null || p1.mExtras == null 5272 || p2 == null || p2.mExtras == null) { 5273 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5274 } 5275 return compareSignatures(p1.mSignatures, p2.mSignatures); 5276 } 5277 } 5278 5279 @Override 5280 public int checkUidSignatures(int uid1, int uid2) { 5281 // Map to base uids. 5282 uid1 = UserHandle.getAppId(uid1); 5283 uid2 = UserHandle.getAppId(uid2); 5284 // reader 5285 synchronized (mPackages) { 5286 Signature[] s1; 5287 Signature[] s2; 5288 Object obj = mSettings.getUserIdLPr(uid1); 5289 if (obj != null) { 5290 if (obj instanceof SharedUserSetting) { 5291 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5292 } else if (obj instanceof PackageSetting) { 5293 s1 = ((PackageSetting)obj).signatures.mSignatures; 5294 } else { 5295 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5296 } 5297 } else { 5298 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5299 } 5300 obj = mSettings.getUserIdLPr(uid2); 5301 if (obj != null) { 5302 if (obj instanceof SharedUserSetting) { 5303 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5304 } else if (obj instanceof PackageSetting) { 5305 s2 = ((PackageSetting)obj).signatures.mSignatures; 5306 } else { 5307 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5308 } 5309 } else { 5310 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5311 } 5312 return compareSignatures(s1, s2); 5313 } 5314 } 5315 5316 /** 5317 * This method should typically only be used when granting or revoking 5318 * permissions, since the app may immediately restart after this call. 5319 * <p> 5320 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5321 * guard your work against the app being relaunched. 5322 */ 5323 private void killUid(int appId, int userId, String reason) { 5324 final long identity = Binder.clearCallingIdentity(); 5325 try { 5326 IActivityManager am = ActivityManager.getService(); 5327 if (am != null) { 5328 try { 5329 am.killUid(appId, userId, reason); 5330 } catch (RemoteException e) { 5331 /* ignore - same process */ 5332 } 5333 } 5334 } finally { 5335 Binder.restoreCallingIdentity(identity); 5336 } 5337 } 5338 5339 /** 5340 * Compares two sets of signatures. Returns: 5341 * <br /> 5342 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5343 * <br /> 5344 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5345 * <br /> 5346 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5347 * <br /> 5348 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5349 * <br /> 5350 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5351 */ 5352 static int compareSignatures(Signature[] s1, Signature[] s2) { 5353 if (s1 == null) { 5354 return s2 == null 5355 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5356 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5357 } 5358 5359 if (s2 == null) { 5360 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5361 } 5362 5363 if (s1.length != s2.length) { 5364 return PackageManager.SIGNATURE_NO_MATCH; 5365 } 5366 5367 // Since both signature sets are of size 1, we can compare without HashSets. 5368 if (s1.length == 1) { 5369 return s1[0].equals(s2[0]) ? 5370 PackageManager.SIGNATURE_MATCH : 5371 PackageManager.SIGNATURE_NO_MATCH; 5372 } 5373 5374 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5375 for (Signature sig : s1) { 5376 set1.add(sig); 5377 } 5378 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5379 for (Signature sig : s2) { 5380 set2.add(sig); 5381 } 5382 // Make sure s2 contains all signatures in s1. 5383 if (set1.equals(set2)) { 5384 return PackageManager.SIGNATURE_MATCH; 5385 } 5386 return PackageManager.SIGNATURE_NO_MATCH; 5387 } 5388 5389 /** 5390 * If the database version for this type of package (internal storage or 5391 * external storage) is less than the version where package signatures 5392 * were updated, return true. 5393 */ 5394 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5395 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5396 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5397 } 5398 5399 /** 5400 * Used for backward compatibility to make sure any packages with 5401 * certificate chains get upgraded to the new style. {@code existingSigs} 5402 * will be in the old format (since they were stored on disk from before the 5403 * system upgrade) and {@code scannedSigs} will be in the newer format. 5404 */ 5405 private int compareSignaturesCompat(PackageSignatures existingSigs, 5406 PackageParser.Package scannedPkg) { 5407 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5408 return PackageManager.SIGNATURE_NO_MATCH; 5409 } 5410 5411 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5412 for (Signature sig : existingSigs.mSignatures) { 5413 existingSet.add(sig); 5414 } 5415 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5416 for (Signature sig : scannedPkg.mSignatures) { 5417 try { 5418 Signature[] chainSignatures = sig.getChainSignatures(); 5419 for (Signature chainSig : chainSignatures) { 5420 scannedCompatSet.add(chainSig); 5421 } 5422 } catch (CertificateEncodingException e) { 5423 scannedCompatSet.add(sig); 5424 } 5425 } 5426 /* 5427 * Make sure the expanded scanned set contains all signatures in the 5428 * existing one. 5429 */ 5430 if (scannedCompatSet.equals(existingSet)) { 5431 // Migrate the old signatures to the new scheme. 5432 existingSigs.assignSignatures(scannedPkg.mSignatures); 5433 // The new KeySets will be re-added later in the scanning process. 5434 synchronized (mPackages) { 5435 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5436 } 5437 return PackageManager.SIGNATURE_MATCH; 5438 } 5439 return PackageManager.SIGNATURE_NO_MATCH; 5440 } 5441 5442 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5443 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5444 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5445 } 5446 5447 private int compareSignaturesRecover(PackageSignatures existingSigs, 5448 PackageParser.Package scannedPkg) { 5449 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5450 return PackageManager.SIGNATURE_NO_MATCH; 5451 } 5452 5453 String msg = null; 5454 try { 5455 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5456 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5457 + scannedPkg.packageName); 5458 return PackageManager.SIGNATURE_MATCH; 5459 } 5460 } catch (CertificateException e) { 5461 msg = e.getMessage(); 5462 } 5463 5464 logCriticalInfo(Log.INFO, 5465 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5466 return PackageManager.SIGNATURE_NO_MATCH; 5467 } 5468 5469 @Override 5470 public List<String> getAllPackages() { 5471 synchronized (mPackages) { 5472 return new ArrayList<String>(mPackages.keySet()); 5473 } 5474 } 5475 5476 @Override 5477 public String[] getPackagesForUid(int uid) { 5478 final int userId = UserHandle.getUserId(uid); 5479 uid = UserHandle.getAppId(uid); 5480 // reader 5481 synchronized (mPackages) { 5482 Object obj = mSettings.getUserIdLPr(uid); 5483 if (obj instanceof SharedUserSetting) { 5484 final SharedUserSetting sus = (SharedUserSetting) obj; 5485 final int N = sus.packages.size(); 5486 String[] res = new String[N]; 5487 final Iterator<PackageSetting> it = sus.packages.iterator(); 5488 int i = 0; 5489 while (it.hasNext()) { 5490 PackageSetting ps = it.next(); 5491 if (ps.getInstalled(userId)) { 5492 res[i++] = ps.name; 5493 } else { 5494 res = ArrayUtils.removeElement(String.class, res, res[i]); 5495 } 5496 } 5497 return res; 5498 } else if (obj instanceof PackageSetting) { 5499 final PackageSetting ps = (PackageSetting) obj; 5500 if (ps.getInstalled(userId)) { 5501 return new String[]{ps.name}; 5502 } 5503 } 5504 } 5505 return null; 5506 } 5507 5508 @Override 5509 public String getNameForUid(int uid) { 5510 // reader 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.name + ":" + sus.userId; 5516 } else if (obj instanceof PackageSetting) { 5517 final PackageSetting ps = (PackageSetting) obj; 5518 return ps.name; 5519 } 5520 } 5521 return null; 5522 } 5523 5524 @Override 5525 public int getUidForSharedUser(String sharedUserName) { 5526 if(sharedUserName == null) { 5527 return -1; 5528 } 5529 // reader 5530 synchronized (mPackages) { 5531 SharedUserSetting suid; 5532 try { 5533 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5534 if (suid != null) { 5535 return suid.userId; 5536 } 5537 } catch (PackageManagerException ignore) { 5538 // can't happen, but, still need to catch it 5539 } 5540 return -1; 5541 } 5542 } 5543 5544 @Override 5545 public int getFlagsForUid(int uid) { 5546 synchronized (mPackages) { 5547 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5548 if (obj instanceof SharedUserSetting) { 5549 final SharedUserSetting sus = (SharedUserSetting) obj; 5550 return sus.pkgFlags; 5551 } else if (obj instanceof PackageSetting) { 5552 final PackageSetting ps = (PackageSetting) obj; 5553 return ps.pkgFlags; 5554 } 5555 } 5556 return 0; 5557 } 5558 5559 @Override 5560 public int getPrivateFlagsForUid(int uid) { 5561 synchronized (mPackages) { 5562 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5563 if (obj instanceof SharedUserSetting) { 5564 final SharedUserSetting sus = (SharedUserSetting) obj; 5565 return sus.pkgPrivateFlags; 5566 } else if (obj instanceof PackageSetting) { 5567 final PackageSetting ps = (PackageSetting) obj; 5568 return ps.pkgPrivateFlags; 5569 } 5570 } 5571 return 0; 5572 } 5573 5574 @Override 5575 public boolean isUidPrivileged(int uid) { 5576 uid = UserHandle.getAppId(uid); 5577 // reader 5578 synchronized (mPackages) { 5579 Object obj = mSettings.getUserIdLPr(uid); 5580 if (obj instanceof SharedUserSetting) { 5581 final SharedUserSetting sus = (SharedUserSetting) obj; 5582 final Iterator<PackageSetting> it = sus.packages.iterator(); 5583 while (it.hasNext()) { 5584 if (it.next().isPrivileged()) { 5585 return true; 5586 } 5587 } 5588 } else if (obj instanceof PackageSetting) { 5589 final PackageSetting ps = (PackageSetting) obj; 5590 return ps.isPrivileged(); 5591 } 5592 } 5593 return false; 5594 } 5595 5596 @Override 5597 public String[] getAppOpPermissionPackages(String permissionName) { 5598 synchronized (mPackages) { 5599 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5600 if (pkgs == null) { 5601 return null; 5602 } 5603 return pkgs.toArray(new String[pkgs.size()]); 5604 } 5605 } 5606 5607 @Override 5608 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5609 int flags, int userId) { 5610 return resolveIntentInternal( 5611 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5612 } 5613 5614 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5615 int flags, int userId, boolean includeInstantApp) { 5616 try { 5617 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5618 5619 if (!sUserManager.exists(userId)) return null; 5620 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5622 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5623 5624 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5625 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5626 flags, userId, includeInstantApp); 5627 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5628 5629 final ResolveInfo bestChoice = 5630 chooseBestActivity(intent, resolvedType, flags, query, userId); 5631 return bestChoice; 5632 } finally { 5633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5634 } 5635 } 5636 5637 @Override 5638 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5639 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5640 throw new SecurityException( 5641 "findPersistentPreferredActivity can only be run by the system"); 5642 } 5643 if (!sUserManager.exists(userId)) { 5644 return null; 5645 } 5646 intent = updateIntentForResolve(intent); 5647 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5648 final int flags = updateFlagsForResolve(0, userId, intent, false); 5649 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5650 userId); 5651 synchronized (mPackages) { 5652 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5653 userId); 5654 } 5655 } 5656 5657 @Override 5658 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5659 IntentFilter filter, int match, ComponentName activity) { 5660 final int userId = UserHandle.getCallingUserId(); 5661 if (DEBUG_PREFERRED) { 5662 Log.v(TAG, "setLastChosenActivity intent=" + intent 5663 + " resolvedType=" + resolvedType 5664 + " flags=" + flags 5665 + " filter=" + filter 5666 + " match=" + match 5667 + " activity=" + activity); 5668 filter.dump(new PrintStreamPrinter(System.out), " "); 5669 } 5670 intent.setComponent(null); 5671 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5672 userId); 5673 // Find any earlier preferred or last chosen entries and nuke them 5674 findPreferredActivity(intent, resolvedType, 5675 flags, query, 0, false, true, false, userId); 5676 // Add the new activity as the last chosen for this filter 5677 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5678 "Setting last chosen"); 5679 } 5680 5681 @Override 5682 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5683 final int userId = UserHandle.getCallingUserId(); 5684 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5685 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5686 userId); 5687 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5688 false, false, false, userId); 5689 } 5690 5691 /** 5692 * Returns whether or not instant apps have been disabled remotely. 5693 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5694 * held. Otherwise we run the risk of deadlock. 5695 */ 5696 private boolean isEphemeralDisabled() { 5697 // ephemeral apps have been disabled across the board 5698 if (DISABLE_EPHEMERAL_APPS) { 5699 return true; 5700 } 5701 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5702 if (!mSystemReady) { 5703 return true; 5704 } 5705 // we can't get a content resolver until the system is ready; these checks must happen last 5706 final ContentResolver resolver = mContext.getContentResolver(); 5707 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5708 return true; 5709 } 5710 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5711 } 5712 5713 private boolean isEphemeralAllowed( 5714 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5715 boolean skipPackageCheck) { 5716 final int callingUser = UserHandle.getCallingUserId(); 5717 if (callingUser != UserHandle.USER_SYSTEM) { 5718 return false; 5719 } 5720 if (mInstantAppResolverConnection == null) { 5721 return false; 5722 } 5723 if (mInstantAppInstallerComponent == null) { 5724 return false; 5725 } 5726 if (intent.getComponent() != null) { 5727 return false; 5728 } 5729 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5730 return false; 5731 } 5732 if (!skipPackageCheck && intent.getPackage() != null) { 5733 return false; 5734 } 5735 final boolean isWebUri = hasWebURI(intent); 5736 if (!isWebUri || intent.getData().getHost() == null) { 5737 return false; 5738 } 5739 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5740 // Or if there's already an ephemeral app installed that handles the action 5741 synchronized (mPackages) { 5742 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5743 for (int n = 0; n < count; n++) { 5744 ResolveInfo info = resolvedActivities.get(n); 5745 String packageName = info.activityInfo.packageName; 5746 PackageSetting ps = mSettings.mPackages.get(packageName); 5747 if (ps != null) { 5748 // Try to get the status from User settings first 5749 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5750 int status = (int) (packedStatus >> 32); 5751 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5752 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5753 if (DEBUG_EPHEMERAL) { 5754 Slog.v(TAG, "DENY ephemeral apps;" 5755 + " pkg: " + packageName + ", status: " + status); 5756 } 5757 return false; 5758 } 5759 if (ps.getInstantApp(userId)) { 5760 return false; 5761 } 5762 } 5763 } 5764 } 5765 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5766 return true; 5767 } 5768 5769 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5770 Intent origIntent, String resolvedType, String callingPackage, 5771 int userId) { 5772 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5773 new InstantAppRequest(responseObj, origIntent, resolvedType, 5774 callingPackage, userId)); 5775 mHandler.sendMessage(msg); 5776 } 5777 5778 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5779 int flags, List<ResolveInfo> query, int userId) { 5780 if (query != null) { 5781 final int N = query.size(); 5782 if (N == 1) { 5783 return query.get(0); 5784 } else if (N > 1) { 5785 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5786 // If there is more than one activity with the same priority, 5787 // then let the user decide between them. 5788 ResolveInfo r0 = query.get(0); 5789 ResolveInfo r1 = query.get(1); 5790 if (DEBUG_INTENT_MATCHING || debug) { 5791 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5792 + r1.activityInfo.name + "=" + r1.priority); 5793 } 5794 // If the first activity has a higher priority, or a different 5795 // default, then it is always desirable to pick it. 5796 if (r0.priority != r1.priority 5797 || r0.preferredOrder != r1.preferredOrder 5798 || r0.isDefault != r1.isDefault) { 5799 return query.get(0); 5800 } 5801 // If we have saved a preference for a preferred activity for 5802 // this Intent, use that. 5803 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5804 flags, query, r0.priority, true, false, debug, userId); 5805 if (ri != null) { 5806 return ri; 5807 } 5808 // If we have an ephemeral app, use it 5809 for (int i = 0; i < N; i++) { 5810 ri = query.get(i); 5811 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5812 return ri; 5813 } 5814 } 5815 ri = new ResolveInfo(mResolveInfo); 5816 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5817 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5818 // If all of the options come from the same package, show the application's 5819 // label and icon instead of the generic resolver's. 5820 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5821 // and then throw away the ResolveInfo itself, meaning that the caller loses 5822 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5823 // a fallback for this case; we only set the target package's resources on 5824 // the ResolveInfo, not the ActivityInfo. 5825 final String intentPackage = intent.getPackage(); 5826 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5827 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5828 ri.resolvePackageName = intentPackage; 5829 if (userNeedsBadging(userId)) { 5830 ri.noResourceId = true; 5831 } else { 5832 ri.icon = appi.icon; 5833 } 5834 ri.iconResourceId = appi.icon; 5835 ri.labelRes = appi.labelRes; 5836 } 5837 ri.activityInfo.applicationInfo = new ApplicationInfo( 5838 ri.activityInfo.applicationInfo); 5839 if (userId != 0) { 5840 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5841 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5842 } 5843 // Make sure that the resolver is displayable in car mode 5844 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5845 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5846 return ri; 5847 } 5848 } 5849 return null; 5850 } 5851 5852 /** 5853 * Return true if the given list is not empty and all of its contents have 5854 * an activityInfo with the given package name. 5855 */ 5856 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5857 if (ArrayUtils.isEmpty(list)) { 5858 return false; 5859 } 5860 for (int i = 0, N = list.size(); i < N; i++) { 5861 final ResolveInfo ri = list.get(i); 5862 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5863 if (ai == null || !packageName.equals(ai.packageName)) { 5864 return false; 5865 } 5866 } 5867 return true; 5868 } 5869 5870 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5871 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5872 final int N = query.size(); 5873 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5874 .get(userId); 5875 // Get the list of persistent preferred activities that handle the intent 5876 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5877 List<PersistentPreferredActivity> pprefs = ppir != null 5878 ? ppir.queryIntent(intent, resolvedType, 5879 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5880 userId) 5881 : null; 5882 if (pprefs != null && pprefs.size() > 0) { 5883 final int M = pprefs.size(); 5884 for (int i=0; i<M; i++) { 5885 final PersistentPreferredActivity ppa = pprefs.get(i); 5886 if (DEBUG_PREFERRED || debug) { 5887 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5888 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5889 + "\n component=" + ppa.mComponent); 5890 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5891 } 5892 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5893 flags | MATCH_DISABLED_COMPONENTS, userId); 5894 if (DEBUG_PREFERRED || debug) { 5895 Slog.v(TAG, "Found persistent preferred activity:"); 5896 if (ai != null) { 5897 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5898 } else { 5899 Slog.v(TAG, " null"); 5900 } 5901 } 5902 if (ai == null) { 5903 // This previously registered persistent preferred activity 5904 // component is no longer known. Ignore it and do NOT remove it. 5905 continue; 5906 } 5907 for (int j=0; j<N; j++) { 5908 final ResolveInfo ri = query.get(j); 5909 if (!ri.activityInfo.applicationInfo.packageName 5910 .equals(ai.applicationInfo.packageName)) { 5911 continue; 5912 } 5913 if (!ri.activityInfo.name.equals(ai.name)) { 5914 continue; 5915 } 5916 // Found a persistent preference that can handle the intent. 5917 if (DEBUG_PREFERRED || debug) { 5918 Slog.v(TAG, "Returning persistent preferred activity: " + 5919 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5920 } 5921 return ri; 5922 } 5923 } 5924 } 5925 return null; 5926 } 5927 5928 // TODO: handle preferred activities missing while user has amnesia 5929 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5930 List<ResolveInfo> query, int priority, boolean always, 5931 boolean removeMatches, boolean debug, int userId) { 5932 if (!sUserManager.exists(userId)) return null; 5933 flags = updateFlagsForResolve(flags, userId, intent, false); 5934 intent = updateIntentForResolve(intent); 5935 // writer 5936 synchronized (mPackages) { 5937 // Try to find a matching persistent preferred activity. 5938 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5939 debug, userId); 5940 5941 // If a persistent preferred activity matched, use it. 5942 if (pri != null) { 5943 return pri; 5944 } 5945 5946 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5947 // Get the list of preferred activities that handle the intent 5948 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5949 List<PreferredActivity> prefs = pir != null 5950 ? pir.queryIntent(intent, resolvedType, 5951 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5952 userId) 5953 : null; 5954 if (prefs != null && prefs.size() > 0) { 5955 boolean changed = false; 5956 try { 5957 // First figure out how good the original match set is. 5958 // We will only allow preferred activities that came 5959 // from the same match quality. 5960 int match = 0; 5961 5962 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5963 5964 final int N = query.size(); 5965 for (int j=0; j<N; j++) { 5966 final ResolveInfo ri = query.get(j); 5967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5968 + ": 0x" + Integer.toHexString(match)); 5969 if (ri.match > match) { 5970 match = ri.match; 5971 } 5972 } 5973 5974 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5975 + Integer.toHexString(match)); 5976 5977 match &= IntentFilter.MATCH_CATEGORY_MASK; 5978 final int M = prefs.size(); 5979 for (int i=0; i<M; i++) { 5980 final PreferredActivity pa = prefs.get(i); 5981 if (DEBUG_PREFERRED || debug) { 5982 Slog.v(TAG, "Checking PreferredActivity ds=" 5983 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5984 + "\n component=" + pa.mPref.mComponent); 5985 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5986 } 5987 if (pa.mPref.mMatch != match) { 5988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5989 + Integer.toHexString(pa.mPref.mMatch)); 5990 continue; 5991 } 5992 // If it's not an "always" type preferred activity and that's what we're 5993 // looking for, skip it. 5994 if (always && !pa.mPref.mAlways) { 5995 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5996 continue; 5997 } 5998 final ActivityInfo ai = getActivityInfo( 5999 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6000 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6001 userId); 6002 if (DEBUG_PREFERRED || debug) { 6003 Slog.v(TAG, "Found preferred activity:"); 6004 if (ai != null) { 6005 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6006 } else { 6007 Slog.v(TAG, " null"); 6008 } 6009 } 6010 if (ai == null) { 6011 // This previously registered preferred activity 6012 // component is no longer known. Most likely an update 6013 // to the app was installed and in the new version this 6014 // component no longer exists. Clean it up by removing 6015 // it from the preferred activities list, and skip it. 6016 Slog.w(TAG, "Removing dangling preferred activity: " 6017 + pa.mPref.mComponent); 6018 pir.removeFilter(pa); 6019 changed = true; 6020 continue; 6021 } 6022 for (int j=0; j<N; j++) { 6023 final ResolveInfo ri = query.get(j); 6024 if (!ri.activityInfo.applicationInfo.packageName 6025 .equals(ai.applicationInfo.packageName)) { 6026 continue; 6027 } 6028 if (!ri.activityInfo.name.equals(ai.name)) { 6029 continue; 6030 } 6031 6032 if (removeMatches) { 6033 pir.removeFilter(pa); 6034 changed = true; 6035 if (DEBUG_PREFERRED) { 6036 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6037 } 6038 break; 6039 } 6040 6041 // Okay we found a previously set preferred or last chosen app. 6042 // If the result set is different from when this 6043 // was created, we need to clear it and re-ask the 6044 // user their preference, if we're looking for an "always" type entry. 6045 if (always && !pa.mPref.sameSet(query)) { 6046 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6047 + intent + " type " + resolvedType); 6048 if (DEBUG_PREFERRED) { 6049 Slog.v(TAG, "Removing preferred activity since set changed " 6050 + pa.mPref.mComponent); 6051 } 6052 pir.removeFilter(pa); 6053 // Re-add the filter as a "last chosen" entry (!always) 6054 PreferredActivity lastChosen = new PreferredActivity( 6055 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6056 pir.addFilter(lastChosen); 6057 changed = true; 6058 return null; 6059 } 6060 6061 // Yay! Either the set matched or we're looking for the last chosen 6062 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6063 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6064 return ri; 6065 } 6066 } 6067 } finally { 6068 if (changed) { 6069 if (DEBUG_PREFERRED) { 6070 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6071 } 6072 scheduleWritePackageRestrictionsLocked(userId); 6073 } 6074 } 6075 } 6076 } 6077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6078 return null; 6079 } 6080 6081 /* 6082 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6083 */ 6084 @Override 6085 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6086 int targetUserId) { 6087 mContext.enforceCallingOrSelfPermission( 6088 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6089 List<CrossProfileIntentFilter> matches = 6090 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6091 if (matches != null) { 6092 int size = matches.size(); 6093 for (int i = 0; i < size; i++) { 6094 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6095 } 6096 } 6097 if (hasWebURI(intent)) { 6098 // cross-profile app linking works only towards the parent. 6099 final UserInfo parent = getProfileParent(sourceUserId); 6100 synchronized(mPackages) { 6101 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6102 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6103 intent, resolvedType, flags, sourceUserId, parent.id); 6104 return xpDomainInfo != null; 6105 } 6106 } 6107 return false; 6108 } 6109 6110 private UserInfo getProfileParent(int userId) { 6111 final long identity = Binder.clearCallingIdentity(); 6112 try { 6113 return sUserManager.getProfileParent(userId); 6114 } finally { 6115 Binder.restoreCallingIdentity(identity); 6116 } 6117 } 6118 6119 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6120 String resolvedType, int userId) { 6121 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6122 if (resolver != null) { 6123 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6124 } 6125 return null; 6126 } 6127 6128 @Override 6129 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6130 String resolvedType, int flags, int userId) { 6131 try { 6132 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6133 6134 return new ParceledListSlice<>( 6135 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6136 } finally { 6137 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6138 } 6139 } 6140 6141 /** 6142 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6143 * instant, returns {@code null}. 6144 */ 6145 private String getInstantAppPackageName(int callingUid) { 6146 final int appId = UserHandle.getAppId(callingUid); 6147 synchronized (mPackages) { 6148 final Object obj = mSettings.getUserIdLPr(appId); 6149 if (obj instanceof PackageSetting) { 6150 final PackageSetting ps = (PackageSetting) obj; 6151 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6152 return isInstantApp ? ps.pkg.packageName : null; 6153 } 6154 } 6155 return null; 6156 } 6157 6158 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6159 String resolvedType, int flags, int userId) { 6160 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6161 } 6162 6163 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6164 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6165 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6166 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6167 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6169 false /* requireFullPermission */, false /* checkShell */, 6170 "query intent activities"); 6171 ComponentName comp = intent.getComponent(); 6172 if (comp == null) { 6173 if (intent.getSelector() != null) { 6174 intent = intent.getSelector(); 6175 comp = intent.getComponent(); 6176 } 6177 } 6178 6179 if (comp != null) { 6180 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6181 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6182 if (ai != null) { 6183 // When specifying an explicit component, we prevent the activity from being 6184 // used when either 1) the calling package is normal and the activity is within 6185 // an ephemeral application or 2) the calling package is ephemeral and the 6186 // activity is not visible to ephemeral applications. 6187 final boolean matchInstantApp = 6188 (flags & PackageManager.MATCH_INSTANT) != 0; 6189 final boolean matchVisibleToInstantAppOnly = 6190 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6191 final boolean isCallerInstantApp = 6192 instantAppPkgName != null; 6193 final boolean isTargetSameInstantApp = 6194 comp.getPackageName().equals(instantAppPkgName); 6195 final boolean isTargetInstantApp = 6196 (ai.applicationInfo.privateFlags 6197 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6198 final boolean isTargetHiddenFromInstantApp = 6199 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6200 final boolean blockResolution = 6201 !isTargetSameInstantApp 6202 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6203 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6204 && isTargetHiddenFromInstantApp)); 6205 if (!blockResolution) { 6206 final ResolveInfo ri = new ResolveInfo(); 6207 ri.activityInfo = ai; 6208 list.add(ri); 6209 } 6210 } 6211 return applyPostResolutionFilter(list, instantAppPkgName); 6212 } 6213 6214 // reader 6215 boolean sortResult = false; 6216 boolean addEphemeral = false; 6217 List<ResolveInfo> result; 6218 final String pkgName = intent.getPackage(); 6219 final boolean ephemeralDisabled = isEphemeralDisabled(); 6220 synchronized (mPackages) { 6221 if (pkgName == null) { 6222 List<CrossProfileIntentFilter> matchingFilters = 6223 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6224 // Check for results that need to skip the current profile. 6225 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6226 resolvedType, flags, userId); 6227 if (xpResolveInfo != null) { 6228 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6229 xpResult.add(xpResolveInfo); 6230 return applyPostResolutionFilter( 6231 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6232 } 6233 6234 // Check for results in the current profile. 6235 result = filterIfNotSystemUser(mActivities.queryIntent( 6236 intent, resolvedType, flags, userId), userId); 6237 addEphemeral = !ephemeralDisabled 6238 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6239 6240 // Check for cross profile results. 6241 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6242 xpResolveInfo = queryCrossProfileIntents( 6243 matchingFilters, intent, resolvedType, flags, userId, 6244 hasNonNegativePriorityResult); 6245 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6246 boolean isVisibleToUser = filterIfNotSystemUser( 6247 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6248 if (isVisibleToUser) { 6249 result.add(xpResolveInfo); 6250 sortResult = true; 6251 } 6252 } 6253 if (hasWebURI(intent)) { 6254 CrossProfileDomainInfo xpDomainInfo = null; 6255 final UserInfo parent = getProfileParent(userId); 6256 if (parent != null) { 6257 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6258 flags, userId, parent.id); 6259 } 6260 if (xpDomainInfo != null) { 6261 if (xpResolveInfo != null) { 6262 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6263 // in the result. 6264 result.remove(xpResolveInfo); 6265 } 6266 if (result.size() == 0 && !addEphemeral) { 6267 // No result in current profile, but found candidate in parent user. 6268 // And we are not going to add emphemeral app, so we can return the 6269 // result straight away. 6270 result.add(xpDomainInfo.resolveInfo); 6271 return applyPostResolutionFilter(result, instantAppPkgName); 6272 } 6273 } else if (result.size() <= 1 && !addEphemeral) { 6274 // No result in parent user and <= 1 result in current profile, and we 6275 // are not going to add emphemeral app, so we can return the result without 6276 // further processing. 6277 return applyPostResolutionFilter(result, instantAppPkgName); 6278 } 6279 // We have more than one candidate (combining results from current and parent 6280 // profile), so we need filtering and sorting. 6281 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6282 intent, flags, result, xpDomainInfo, userId); 6283 sortResult = true; 6284 } 6285 } else { 6286 final PackageParser.Package pkg = mPackages.get(pkgName); 6287 if (pkg != null) { 6288 result = applyPostResolutionFilter(filterIfNotSystemUser( 6289 mActivities.queryIntentForPackage( 6290 intent, resolvedType, flags, pkg.activities, userId), 6291 userId), instantAppPkgName); 6292 } else { 6293 // the caller wants to resolve for a particular package; however, there 6294 // were no installed results, so, try to find an ephemeral result 6295 addEphemeral = !ephemeralDisabled 6296 && isEphemeralAllowed( 6297 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6298 result = new ArrayList<ResolveInfo>(); 6299 } 6300 } 6301 } 6302 if (addEphemeral) { 6303 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6304 final InstantAppRequest requestObject = new InstantAppRequest( 6305 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6306 null /*callingPackage*/, userId); 6307 final AuxiliaryResolveInfo auxiliaryResponse = 6308 InstantAppResolver.doInstantAppResolutionPhaseOne( 6309 mContext, mInstantAppResolverConnection, requestObject); 6310 if (auxiliaryResponse != null) { 6311 if (DEBUG_EPHEMERAL) { 6312 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6313 } 6314 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6315 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6316 // make sure this resolver is the default 6317 ephemeralInstaller.isDefault = true; 6318 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6319 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6320 // add a non-generic filter 6321 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6322 ephemeralInstaller.filter.addDataPath( 6323 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6324 ephemeralInstaller.instantAppAvailable = true; 6325 result.add(ephemeralInstaller); 6326 } 6327 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6328 } 6329 if (sortResult) { 6330 Collections.sort(result, mResolvePrioritySorter); 6331 } 6332 return applyPostResolutionFilter(result, instantAppPkgName); 6333 } 6334 6335 private static class CrossProfileDomainInfo { 6336 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6337 ResolveInfo resolveInfo; 6338 /* Best domain verification status of the activities found in the other profile */ 6339 int bestDomainVerificationStatus; 6340 } 6341 6342 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6343 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6344 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6345 sourceUserId)) { 6346 return null; 6347 } 6348 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6349 resolvedType, flags, parentUserId); 6350 6351 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6352 return null; 6353 } 6354 CrossProfileDomainInfo result = null; 6355 int size = resultTargetUser.size(); 6356 for (int i = 0; i < size; i++) { 6357 ResolveInfo riTargetUser = resultTargetUser.get(i); 6358 // Intent filter verification is only for filters that specify a host. So don't return 6359 // those that handle all web uris. 6360 if (riTargetUser.handleAllWebDataURI) { 6361 continue; 6362 } 6363 String packageName = riTargetUser.activityInfo.packageName; 6364 PackageSetting ps = mSettings.mPackages.get(packageName); 6365 if (ps == null) { 6366 continue; 6367 } 6368 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6369 int status = (int)(verificationState >> 32); 6370 if (result == null) { 6371 result = new CrossProfileDomainInfo(); 6372 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6373 sourceUserId, parentUserId); 6374 result.bestDomainVerificationStatus = status; 6375 } else { 6376 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6377 result.bestDomainVerificationStatus); 6378 } 6379 } 6380 // Don't consider matches with status NEVER across profiles. 6381 if (result != null && result.bestDomainVerificationStatus 6382 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6383 return null; 6384 } 6385 return result; 6386 } 6387 6388 /** 6389 * Verification statuses are ordered from the worse to the best, except for 6390 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6391 */ 6392 private int bestDomainVerificationStatus(int status1, int status2) { 6393 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6394 return status2; 6395 } 6396 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6397 return status1; 6398 } 6399 return (int) MathUtils.max(status1, status2); 6400 } 6401 6402 private boolean isUserEnabled(int userId) { 6403 long callingId = Binder.clearCallingIdentity(); 6404 try { 6405 UserInfo userInfo = sUserManager.getUserInfo(userId); 6406 return userInfo != null && userInfo.isEnabled(); 6407 } finally { 6408 Binder.restoreCallingIdentity(callingId); 6409 } 6410 } 6411 6412 /** 6413 * Filter out activities with systemUserOnly flag set, when current user is not System. 6414 * 6415 * @return filtered list 6416 */ 6417 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6418 if (userId == UserHandle.USER_SYSTEM) { 6419 return resolveInfos; 6420 } 6421 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6422 ResolveInfo info = resolveInfos.get(i); 6423 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6424 resolveInfos.remove(i); 6425 } 6426 } 6427 return resolveInfos; 6428 } 6429 6430 /** 6431 * Filters out ephemeral activities. 6432 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6433 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6434 * 6435 * @param resolveInfos The pre-filtered list of resolved activities 6436 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6437 * is performed. 6438 * @return A filtered list of resolved activities. 6439 */ 6440 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6441 String ephemeralPkgName) { 6442 // TODO: When adding on-demand split support for non-instant apps, remove this check 6443 // and always apply post filtering 6444 if (ephemeralPkgName == null) { 6445 return resolveInfos; 6446 } 6447 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6448 final ResolveInfo info = resolveInfos.get(i); 6449 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6450 // allow activities that are defined in the provided package 6451 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6452 if (info.activityInfo.splitName != null 6453 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6454 info.activityInfo.splitName)) { 6455 // requested activity is defined in a split that hasn't been installed yet. 6456 // add the installer to the resolve list 6457 if (DEBUG_EPHEMERAL) { 6458 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6459 } 6460 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6461 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6462 info.activityInfo.packageName, info.activityInfo.splitName, 6463 info.activityInfo.applicationInfo.versionCode); 6464 // make sure this resolver is the default 6465 installerInfo.isDefault = true; 6466 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6467 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6468 // add a non-generic filter 6469 installerInfo.filter = new IntentFilter(); 6470 // load resources from the correct package 6471 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6472 resolveInfos.set(i, installerInfo); 6473 } 6474 continue; 6475 } 6476 // allow activities that have been explicitly exposed to ephemeral apps 6477 if (!isEphemeralApp 6478 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6479 continue; 6480 } 6481 resolveInfos.remove(i); 6482 } 6483 return resolveInfos; 6484 } 6485 6486 /** 6487 * @param resolveInfos list of resolve infos in descending priority order 6488 * @return if the list contains a resolve info with non-negative priority 6489 */ 6490 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6491 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6492 } 6493 6494 private static boolean hasWebURI(Intent intent) { 6495 if (intent.getData() == null) { 6496 return false; 6497 } 6498 final String scheme = intent.getScheme(); 6499 if (TextUtils.isEmpty(scheme)) { 6500 return false; 6501 } 6502 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6503 } 6504 6505 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6506 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6507 int userId) { 6508 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6509 6510 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6511 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6512 candidates.size()); 6513 } 6514 6515 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6516 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6517 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6518 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6519 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6520 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6521 6522 synchronized (mPackages) { 6523 final int count = candidates.size(); 6524 // First, try to use linked apps. Partition the candidates into four lists: 6525 // one for the final results, one for the "do not use ever", one for "undefined status" 6526 // and finally one for "browser app type". 6527 for (int n=0; n<count; n++) { 6528 ResolveInfo info = candidates.get(n); 6529 String packageName = info.activityInfo.packageName; 6530 PackageSetting ps = mSettings.mPackages.get(packageName); 6531 if (ps != null) { 6532 // Add to the special match all list (Browser use case) 6533 if (info.handleAllWebDataURI) { 6534 matchAllList.add(info); 6535 continue; 6536 } 6537 // Try to get the status from User settings first 6538 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6539 int status = (int)(packedStatus >> 32); 6540 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6541 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6542 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6543 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6544 + " : linkgen=" + linkGeneration); 6545 } 6546 // Use link-enabled generation as preferredOrder, i.e. 6547 // prefer newly-enabled over earlier-enabled. 6548 info.preferredOrder = linkGeneration; 6549 alwaysList.add(info); 6550 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6551 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6552 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6553 } 6554 neverList.add(info); 6555 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6556 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6557 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6558 } 6559 alwaysAskList.add(info); 6560 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6561 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6562 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6563 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6564 } 6565 undefinedList.add(info); 6566 } 6567 } 6568 } 6569 6570 // We'll want to include browser possibilities in a few cases 6571 boolean includeBrowser = false; 6572 6573 // First try to add the "always" resolution(s) for the current user, if any 6574 if (alwaysList.size() > 0) { 6575 result.addAll(alwaysList); 6576 } else { 6577 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6578 result.addAll(undefinedList); 6579 // Maybe add one for the other profile. 6580 if (xpDomainInfo != null && ( 6581 xpDomainInfo.bestDomainVerificationStatus 6582 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6583 result.add(xpDomainInfo.resolveInfo); 6584 } 6585 includeBrowser = true; 6586 } 6587 6588 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6589 // If there were 'always' entries their preferred order has been set, so we also 6590 // back that off to make the alternatives equivalent 6591 if (alwaysAskList.size() > 0) { 6592 for (ResolveInfo i : result) { 6593 i.preferredOrder = 0; 6594 } 6595 result.addAll(alwaysAskList); 6596 includeBrowser = true; 6597 } 6598 6599 if (includeBrowser) { 6600 // Also add browsers (all of them or only the default one) 6601 if (DEBUG_DOMAIN_VERIFICATION) { 6602 Slog.v(TAG, " ...including browsers in candidate set"); 6603 } 6604 if ((matchFlags & MATCH_ALL) != 0) { 6605 result.addAll(matchAllList); 6606 } else { 6607 // Browser/generic handling case. If there's a default browser, go straight 6608 // to that (but only if there is no other higher-priority match). 6609 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6610 int maxMatchPrio = 0; 6611 ResolveInfo defaultBrowserMatch = null; 6612 final int numCandidates = matchAllList.size(); 6613 for (int n = 0; n < numCandidates; n++) { 6614 ResolveInfo info = matchAllList.get(n); 6615 // track the highest overall match priority... 6616 if (info.priority > maxMatchPrio) { 6617 maxMatchPrio = info.priority; 6618 } 6619 // ...and the highest-priority default browser match 6620 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6621 if (defaultBrowserMatch == null 6622 || (defaultBrowserMatch.priority < info.priority)) { 6623 if (debug) { 6624 Slog.v(TAG, "Considering default browser match " + info); 6625 } 6626 defaultBrowserMatch = info; 6627 } 6628 } 6629 } 6630 if (defaultBrowserMatch != null 6631 && defaultBrowserMatch.priority >= maxMatchPrio 6632 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6633 { 6634 if (debug) { 6635 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6636 } 6637 result.add(defaultBrowserMatch); 6638 } else { 6639 result.addAll(matchAllList); 6640 } 6641 } 6642 6643 // If there is nothing selected, add all candidates and remove the ones that the user 6644 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6645 if (result.size() == 0) { 6646 result.addAll(candidates); 6647 result.removeAll(neverList); 6648 } 6649 } 6650 } 6651 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6652 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6653 result.size()); 6654 for (ResolveInfo info : result) { 6655 Slog.v(TAG, " + " + info.activityInfo); 6656 } 6657 } 6658 return result; 6659 } 6660 6661 // Returns a packed value as a long: 6662 // 6663 // high 'int'-sized word: link status: undefined/ask/never/always. 6664 // low 'int'-sized word: relative priority among 'always' results. 6665 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6666 long result = ps.getDomainVerificationStatusForUser(userId); 6667 // if none available, get the master status 6668 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6669 if (ps.getIntentFilterVerificationInfo() != null) { 6670 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6671 } 6672 } 6673 return result; 6674 } 6675 6676 private ResolveInfo querySkipCurrentProfileIntents( 6677 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6678 int flags, int sourceUserId) { 6679 if (matchingFilters != null) { 6680 int size = matchingFilters.size(); 6681 for (int i = 0; i < size; i ++) { 6682 CrossProfileIntentFilter filter = matchingFilters.get(i); 6683 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6684 // Checking if there are activities in the target user that can handle the 6685 // intent. 6686 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6687 resolvedType, flags, sourceUserId); 6688 if (resolveInfo != null) { 6689 return resolveInfo; 6690 } 6691 } 6692 } 6693 } 6694 return null; 6695 } 6696 6697 // Return matching ResolveInfo in target user if any. 6698 private ResolveInfo queryCrossProfileIntents( 6699 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6700 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6701 if (matchingFilters != null) { 6702 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6703 // match the same intent. For performance reasons, it is better not to 6704 // run queryIntent twice for the same userId 6705 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6706 int size = matchingFilters.size(); 6707 for (int i = 0; i < size; i++) { 6708 CrossProfileIntentFilter filter = matchingFilters.get(i); 6709 int targetUserId = filter.getTargetUserId(); 6710 boolean skipCurrentProfile = 6711 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6712 boolean skipCurrentProfileIfNoMatchFound = 6713 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6714 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6715 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6716 // Checking if there are activities in the target user that can handle the 6717 // intent. 6718 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6719 resolvedType, flags, sourceUserId); 6720 if (resolveInfo != null) return resolveInfo; 6721 alreadyTriedUserIds.put(targetUserId, true); 6722 } 6723 } 6724 } 6725 return null; 6726 } 6727 6728 /** 6729 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6730 * will forward the intent to the filter's target user. 6731 * Otherwise, returns null. 6732 */ 6733 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6734 String resolvedType, int flags, int sourceUserId) { 6735 int targetUserId = filter.getTargetUserId(); 6736 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6737 resolvedType, flags, targetUserId); 6738 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6739 // If all the matches in the target profile are suspended, return null. 6740 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6741 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6742 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6743 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6744 targetUserId); 6745 } 6746 } 6747 } 6748 return null; 6749 } 6750 6751 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6752 int sourceUserId, int targetUserId) { 6753 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6754 long ident = Binder.clearCallingIdentity(); 6755 boolean targetIsProfile; 6756 try { 6757 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6758 } finally { 6759 Binder.restoreCallingIdentity(ident); 6760 } 6761 String className; 6762 if (targetIsProfile) { 6763 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6764 } else { 6765 className = FORWARD_INTENT_TO_PARENT; 6766 } 6767 ComponentName forwardingActivityComponentName = new ComponentName( 6768 mAndroidApplication.packageName, className); 6769 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6770 sourceUserId); 6771 if (!targetIsProfile) { 6772 forwardingActivityInfo.showUserIcon = targetUserId; 6773 forwardingResolveInfo.noResourceId = true; 6774 } 6775 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6776 forwardingResolveInfo.priority = 0; 6777 forwardingResolveInfo.preferredOrder = 0; 6778 forwardingResolveInfo.match = 0; 6779 forwardingResolveInfo.isDefault = true; 6780 forwardingResolveInfo.filter = filter; 6781 forwardingResolveInfo.targetUserId = targetUserId; 6782 return forwardingResolveInfo; 6783 } 6784 6785 @Override 6786 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6787 Intent[] specifics, String[] specificTypes, Intent intent, 6788 String resolvedType, int flags, int userId) { 6789 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6790 specificTypes, intent, resolvedType, flags, userId)); 6791 } 6792 6793 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6794 Intent[] specifics, String[] specificTypes, Intent intent, 6795 String resolvedType, int flags, int userId) { 6796 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6797 flags = updateFlagsForResolve(flags, userId, intent, false); 6798 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6799 false /* requireFullPermission */, false /* checkShell */, 6800 "query intent activity options"); 6801 final String resultsAction = intent.getAction(); 6802 6803 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6804 | PackageManager.GET_RESOLVED_FILTER, userId); 6805 6806 if (DEBUG_INTENT_MATCHING) { 6807 Log.v(TAG, "Query " + intent + ": " + results); 6808 } 6809 6810 int specificsPos = 0; 6811 int N; 6812 6813 // todo: note that the algorithm used here is O(N^2). This 6814 // isn't a problem in our current environment, but if we start running 6815 // into situations where we have more than 5 or 10 matches then this 6816 // should probably be changed to something smarter... 6817 6818 // First we go through and resolve each of the specific items 6819 // that were supplied, taking care of removing any corresponding 6820 // duplicate items in the generic resolve list. 6821 if (specifics != null) { 6822 for (int i=0; i<specifics.length; i++) { 6823 final Intent sintent = specifics[i]; 6824 if (sintent == null) { 6825 continue; 6826 } 6827 6828 if (DEBUG_INTENT_MATCHING) { 6829 Log.v(TAG, "Specific #" + i + ": " + sintent); 6830 } 6831 6832 String action = sintent.getAction(); 6833 if (resultsAction != null && resultsAction.equals(action)) { 6834 // If this action was explicitly requested, then don't 6835 // remove things that have it. 6836 action = null; 6837 } 6838 6839 ResolveInfo ri = null; 6840 ActivityInfo ai = null; 6841 6842 ComponentName comp = sintent.getComponent(); 6843 if (comp == null) { 6844 ri = resolveIntent( 6845 sintent, 6846 specificTypes != null ? specificTypes[i] : null, 6847 flags, userId); 6848 if (ri == null) { 6849 continue; 6850 } 6851 if (ri == mResolveInfo) { 6852 // ACK! Must do something better with this. 6853 } 6854 ai = ri.activityInfo; 6855 comp = new ComponentName(ai.applicationInfo.packageName, 6856 ai.name); 6857 } else { 6858 ai = getActivityInfo(comp, flags, userId); 6859 if (ai == null) { 6860 continue; 6861 } 6862 } 6863 6864 // Look for any generic query activities that are duplicates 6865 // of this specific one, and remove them from the results. 6866 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6867 N = results.size(); 6868 int j; 6869 for (j=specificsPos; j<N; j++) { 6870 ResolveInfo sri = results.get(j); 6871 if ((sri.activityInfo.name.equals(comp.getClassName()) 6872 && sri.activityInfo.applicationInfo.packageName.equals( 6873 comp.getPackageName())) 6874 || (action != null && sri.filter.matchAction(action))) { 6875 results.remove(j); 6876 if (DEBUG_INTENT_MATCHING) Log.v( 6877 TAG, "Removing duplicate item from " + j 6878 + " due to specific " + specificsPos); 6879 if (ri == null) { 6880 ri = sri; 6881 } 6882 j--; 6883 N--; 6884 } 6885 } 6886 6887 // Add this specific item to its proper place. 6888 if (ri == null) { 6889 ri = new ResolveInfo(); 6890 ri.activityInfo = ai; 6891 } 6892 results.add(specificsPos, ri); 6893 ri.specificIndex = i; 6894 specificsPos++; 6895 } 6896 } 6897 6898 // Now we go through the remaining generic results and remove any 6899 // duplicate actions that are found here. 6900 N = results.size(); 6901 for (int i=specificsPos; i<N-1; i++) { 6902 final ResolveInfo rii = results.get(i); 6903 if (rii.filter == null) { 6904 continue; 6905 } 6906 6907 // Iterate over all of the actions of this result's intent 6908 // filter... typically this should be just one. 6909 final Iterator<String> it = rii.filter.actionsIterator(); 6910 if (it == null) { 6911 continue; 6912 } 6913 while (it.hasNext()) { 6914 final String action = it.next(); 6915 if (resultsAction != null && resultsAction.equals(action)) { 6916 // If this action was explicitly requested, then don't 6917 // remove things that have it. 6918 continue; 6919 } 6920 for (int j=i+1; j<N; j++) { 6921 final ResolveInfo rij = results.get(j); 6922 if (rij.filter != null && rij.filter.hasAction(action)) { 6923 results.remove(j); 6924 if (DEBUG_INTENT_MATCHING) Log.v( 6925 TAG, "Removing duplicate item from " + j 6926 + " due to action " + action + " at " + i); 6927 j--; 6928 N--; 6929 } 6930 } 6931 } 6932 6933 // If the caller didn't request filter information, drop it now 6934 // so we don't have to marshall/unmarshall it. 6935 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6936 rii.filter = null; 6937 } 6938 } 6939 6940 // Filter out the caller activity if so requested. 6941 if (caller != null) { 6942 N = results.size(); 6943 for (int i=0; i<N; i++) { 6944 ActivityInfo ainfo = results.get(i).activityInfo; 6945 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6946 && caller.getClassName().equals(ainfo.name)) { 6947 results.remove(i); 6948 break; 6949 } 6950 } 6951 } 6952 6953 // If the caller didn't request filter information, 6954 // drop them now so we don't have to 6955 // marshall/unmarshall it. 6956 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6957 N = results.size(); 6958 for (int i=0; i<N; i++) { 6959 results.get(i).filter = null; 6960 } 6961 } 6962 6963 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6964 return results; 6965 } 6966 6967 @Override 6968 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6969 String resolvedType, int flags, int userId) { 6970 return new ParceledListSlice<>( 6971 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6972 } 6973 6974 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6975 String resolvedType, int flags, int userId) { 6976 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6977 flags = updateFlagsForResolve(flags, userId, intent, false); 6978 ComponentName comp = intent.getComponent(); 6979 if (comp == null) { 6980 if (intent.getSelector() != null) { 6981 intent = intent.getSelector(); 6982 comp = intent.getComponent(); 6983 } 6984 } 6985 if (comp != null) { 6986 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6987 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6988 if (ai != null) { 6989 ResolveInfo ri = new ResolveInfo(); 6990 ri.activityInfo = ai; 6991 list.add(ri); 6992 } 6993 return list; 6994 } 6995 6996 // reader 6997 synchronized (mPackages) { 6998 String pkgName = intent.getPackage(); 6999 if (pkgName == null) { 7000 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7001 } 7002 final PackageParser.Package pkg = mPackages.get(pkgName); 7003 if (pkg != null) { 7004 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7005 userId); 7006 } 7007 return Collections.emptyList(); 7008 } 7009 } 7010 7011 @Override 7012 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7013 if (!sUserManager.exists(userId)) return null; 7014 flags = updateFlagsForResolve(flags, userId, intent, false); 7015 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 7016 if (query != null) { 7017 if (query.size() >= 1) { 7018 // If there is more than one service with the same priority, 7019 // just arbitrarily pick the first one. 7020 return query.get(0); 7021 } 7022 } 7023 return null; 7024 } 7025 7026 @Override 7027 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7028 String resolvedType, int flags, int userId) { 7029 return new ParceledListSlice<>( 7030 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 7031 } 7032 7033 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7034 String resolvedType, int flags, int userId) { 7035 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7036 flags = updateFlagsForResolve(flags, userId, intent, false); 7037 ComponentName comp = intent.getComponent(); 7038 if (comp == null) { 7039 if (intent.getSelector() != null) { 7040 intent = intent.getSelector(); 7041 comp = intent.getComponent(); 7042 } 7043 } 7044 if (comp != null) { 7045 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7046 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7047 if (si != null) { 7048 final ResolveInfo ri = new ResolveInfo(); 7049 ri.serviceInfo = si; 7050 list.add(ri); 7051 } 7052 return list; 7053 } 7054 7055 // reader 7056 synchronized (mPackages) { 7057 String pkgName = intent.getPackage(); 7058 if (pkgName == null) { 7059 return mServices.queryIntent(intent, resolvedType, flags, userId); 7060 } 7061 final PackageParser.Package pkg = mPackages.get(pkgName); 7062 if (pkg != null) { 7063 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7064 userId); 7065 } 7066 return Collections.emptyList(); 7067 } 7068 } 7069 7070 @Override 7071 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7072 String resolvedType, int flags, int userId) { 7073 return new ParceledListSlice<>( 7074 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7075 } 7076 7077 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7078 Intent intent, String resolvedType, int flags, int userId) { 7079 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7080 flags = updateFlagsForResolve(flags, userId, intent, false); 7081 ComponentName comp = intent.getComponent(); 7082 if (comp == null) { 7083 if (intent.getSelector() != null) { 7084 intent = intent.getSelector(); 7085 comp = intent.getComponent(); 7086 } 7087 } 7088 if (comp != null) { 7089 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7090 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7091 if (pi != null) { 7092 final ResolveInfo ri = new ResolveInfo(); 7093 ri.providerInfo = pi; 7094 list.add(ri); 7095 } 7096 return list; 7097 } 7098 7099 // reader 7100 synchronized (mPackages) { 7101 String pkgName = intent.getPackage(); 7102 if (pkgName == null) { 7103 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7104 } 7105 final PackageParser.Package pkg = mPackages.get(pkgName); 7106 if (pkg != null) { 7107 return mProviders.queryIntentForPackage( 7108 intent, resolvedType, flags, pkg.providers, userId); 7109 } 7110 return Collections.emptyList(); 7111 } 7112 } 7113 7114 @Override 7115 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7116 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7117 flags = updateFlagsForPackage(flags, userId, null); 7118 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7119 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7120 true /* requireFullPermission */, false /* checkShell */, 7121 "get installed packages"); 7122 7123 // writer 7124 synchronized (mPackages) { 7125 ArrayList<PackageInfo> list; 7126 if (listUninstalled) { 7127 list = new ArrayList<>(mSettings.mPackages.size()); 7128 for (PackageSetting ps : mSettings.mPackages.values()) { 7129 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7130 continue; 7131 } 7132 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7133 if (pi != null) { 7134 list.add(pi); 7135 } 7136 } 7137 } else { 7138 list = new ArrayList<>(mPackages.size()); 7139 for (PackageParser.Package p : mPackages.values()) { 7140 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7141 Binder.getCallingUid(), userId)) { 7142 continue; 7143 } 7144 final PackageInfo pi = generatePackageInfo((PackageSetting) 7145 p.mExtras, flags, userId); 7146 if (pi != null) { 7147 list.add(pi); 7148 } 7149 } 7150 } 7151 7152 return new ParceledListSlice<>(list); 7153 } 7154 } 7155 7156 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7157 String[] permissions, boolean[] tmp, int flags, int userId) { 7158 int numMatch = 0; 7159 final PermissionsState permissionsState = ps.getPermissionsState(); 7160 for (int i=0; i<permissions.length; i++) { 7161 final String permission = permissions[i]; 7162 if (permissionsState.hasPermission(permission, userId)) { 7163 tmp[i] = true; 7164 numMatch++; 7165 } else { 7166 tmp[i] = false; 7167 } 7168 } 7169 if (numMatch == 0) { 7170 return; 7171 } 7172 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7173 7174 // The above might return null in cases of uninstalled apps or install-state 7175 // skew across users/profiles. 7176 if (pi != null) { 7177 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7178 if (numMatch == permissions.length) { 7179 pi.requestedPermissions = permissions; 7180 } else { 7181 pi.requestedPermissions = new String[numMatch]; 7182 numMatch = 0; 7183 for (int i=0; i<permissions.length; i++) { 7184 if (tmp[i]) { 7185 pi.requestedPermissions[numMatch] = permissions[i]; 7186 numMatch++; 7187 } 7188 } 7189 } 7190 } 7191 list.add(pi); 7192 } 7193 } 7194 7195 @Override 7196 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7197 String[] permissions, int flags, int userId) { 7198 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7199 flags = updateFlagsForPackage(flags, userId, permissions); 7200 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7201 true /* requireFullPermission */, false /* checkShell */, 7202 "get packages holding permissions"); 7203 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7204 7205 // writer 7206 synchronized (mPackages) { 7207 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7208 boolean[] tmpBools = new boolean[permissions.length]; 7209 if (listUninstalled) { 7210 for (PackageSetting ps : mSettings.mPackages.values()) { 7211 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7212 userId); 7213 } 7214 } else { 7215 for (PackageParser.Package pkg : mPackages.values()) { 7216 PackageSetting ps = (PackageSetting)pkg.mExtras; 7217 if (ps != null) { 7218 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7219 userId); 7220 } 7221 } 7222 } 7223 7224 return new ParceledListSlice<PackageInfo>(list); 7225 } 7226 } 7227 7228 @Override 7229 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7230 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7231 flags = updateFlagsForApplication(flags, userId, null); 7232 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7233 7234 // writer 7235 synchronized (mPackages) { 7236 ArrayList<ApplicationInfo> list; 7237 if (listUninstalled) { 7238 list = new ArrayList<>(mSettings.mPackages.size()); 7239 for (PackageSetting ps : mSettings.mPackages.values()) { 7240 ApplicationInfo ai; 7241 int effectiveFlags = flags; 7242 if (ps.isSystem()) { 7243 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7244 } 7245 if (ps.pkg != null) { 7246 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7247 continue; 7248 } 7249 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7250 ps.readUserState(userId), userId); 7251 if (ai != null) { 7252 rebaseEnabledOverlays(ai, userId); 7253 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7254 } 7255 } else { 7256 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7257 // and already converts to externally visible package name 7258 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7259 Binder.getCallingUid(), effectiveFlags, userId); 7260 } 7261 if (ai != null) { 7262 list.add(ai); 7263 } 7264 } 7265 } else { 7266 list = new ArrayList<>(mPackages.size()); 7267 for (PackageParser.Package p : mPackages.values()) { 7268 if (p.mExtras != null) { 7269 PackageSetting ps = (PackageSetting) p.mExtras; 7270 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7271 continue; 7272 } 7273 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7274 ps.readUserState(userId), userId); 7275 if (ai != null) { 7276 rebaseEnabledOverlays(ai, userId); 7277 ai.packageName = resolveExternalPackageNameLPr(p); 7278 list.add(ai); 7279 } 7280 } 7281 } 7282 } 7283 7284 return new ParceledListSlice<>(list); 7285 } 7286 } 7287 7288 @Override 7289 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7290 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7291 return null; 7292 } 7293 7294 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7295 "getEphemeralApplications"); 7296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7297 true /* requireFullPermission */, false /* checkShell */, 7298 "getEphemeralApplications"); 7299 synchronized (mPackages) { 7300 List<InstantAppInfo> instantApps = mInstantAppRegistry 7301 .getInstantAppsLPr(userId); 7302 if (instantApps != null) { 7303 return new ParceledListSlice<>(instantApps); 7304 } 7305 } 7306 return null; 7307 } 7308 7309 @Override 7310 public boolean isInstantApp(String packageName, int userId) { 7311 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7312 true /* requireFullPermission */, false /* checkShell */, 7313 "isInstantApp"); 7314 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7315 return false; 7316 } 7317 7318 synchronized (mPackages) { 7319 final PackageSetting ps = mSettings.mPackages.get(packageName); 7320 final boolean returnAllowed = 7321 ps != null 7322 && (isCallerSameApp(packageName) 7323 || mContext.checkCallingOrSelfPermission( 7324 android.Manifest.permission.ACCESS_INSTANT_APPS) 7325 == PERMISSION_GRANTED 7326 || mInstantAppRegistry.isInstantAccessGranted( 7327 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7328 if (returnAllowed) { 7329 return ps.getInstantApp(userId); 7330 } 7331 } 7332 return false; 7333 } 7334 7335 @Override 7336 public byte[] getInstantAppCookie(String packageName, int userId) { 7337 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7338 return null; 7339 } 7340 7341 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7342 true /* requireFullPermission */, false /* checkShell */, 7343 "getInstantAppCookie"); 7344 if (!isCallerSameApp(packageName)) { 7345 return null; 7346 } 7347 synchronized (mPackages) { 7348 return mInstantAppRegistry.getInstantAppCookieLPw( 7349 packageName, userId); 7350 } 7351 } 7352 7353 @Override 7354 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7355 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7356 return true; 7357 } 7358 7359 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7360 true /* requireFullPermission */, true /* checkShell */, 7361 "setInstantAppCookie"); 7362 if (!isCallerSameApp(packageName)) { 7363 return false; 7364 } 7365 synchronized (mPackages) { 7366 return mInstantAppRegistry.setInstantAppCookieLPw( 7367 packageName, cookie, userId); 7368 } 7369 } 7370 7371 @Override 7372 public Bitmap getInstantAppIcon(String packageName, int userId) { 7373 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7374 return null; 7375 } 7376 7377 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7378 "getInstantAppIcon"); 7379 7380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7381 true /* requireFullPermission */, false /* checkShell */, 7382 "getInstantAppIcon"); 7383 7384 synchronized (mPackages) { 7385 return mInstantAppRegistry.getInstantAppIconLPw( 7386 packageName, userId); 7387 } 7388 } 7389 7390 private boolean isCallerSameApp(String packageName) { 7391 PackageParser.Package pkg = mPackages.get(packageName); 7392 return pkg != null 7393 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7394 } 7395 7396 @Override 7397 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7398 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7399 } 7400 7401 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7402 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7403 7404 // reader 7405 synchronized (mPackages) { 7406 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7407 final int userId = UserHandle.getCallingUserId(); 7408 while (i.hasNext()) { 7409 final PackageParser.Package p = i.next(); 7410 if (p.applicationInfo == null) continue; 7411 7412 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7413 && !p.applicationInfo.isDirectBootAware(); 7414 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7415 && p.applicationInfo.isDirectBootAware(); 7416 7417 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7418 && (!mSafeMode || isSystemApp(p)) 7419 && (matchesUnaware || matchesAware)) { 7420 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7421 if (ps != null) { 7422 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7423 ps.readUserState(userId), userId); 7424 if (ai != null) { 7425 rebaseEnabledOverlays(ai, userId); 7426 finalList.add(ai); 7427 } 7428 } 7429 } 7430 } 7431 } 7432 7433 return finalList; 7434 } 7435 7436 @Override 7437 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7438 if (!sUserManager.exists(userId)) return null; 7439 flags = updateFlagsForComponent(flags, userId, name); 7440 // reader 7441 synchronized (mPackages) { 7442 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7443 PackageSetting ps = provider != null 7444 ? mSettings.mPackages.get(provider.owner.packageName) 7445 : null; 7446 return ps != null 7447 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7448 ? PackageParser.generateProviderInfo(provider, flags, 7449 ps.readUserState(userId), userId) 7450 : null; 7451 } 7452 } 7453 7454 /** 7455 * @deprecated 7456 */ 7457 @Deprecated 7458 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7459 // reader 7460 synchronized (mPackages) { 7461 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7462 .entrySet().iterator(); 7463 final int userId = UserHandle.getCallingUserId(); 7464 while (i.hasNext()) { 7465 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7466 PackageParser.Provider p = entry.getValue(); 7467 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7468 7469 if (ps != null && p.syncable 7470 && (!mSafeMode || (p.info.applicationInfo.flags 7471 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7472 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7473 ps.readUserState(userId), userId); 7474 if (info != null) { 7475 outNames.add(entry.getKey()); 7476 outInfo.add(info); 7477 } 7478 } 7479 } 7480 } 7481 } 7482 7483 @Override 7484 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7485 int uid, int flags, String metaDataKey) { 7486 final int userId = processName != null ? UserHandle.getUserId(uid) 7487 : UserHandle.getCallingUserId(); 7488 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7489 flags = updateFlagsForComponent(flags, userId, processName); 7490 7491 ArrayList<ProviderInfo> finalList = null; 7492 // reader 7493 synchronized (mPackages) { 7494 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7495 while (i.hasNext()) { 7496 final PackageParser.Provider p = i.next(); 7497 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7498 if (ps != null && p.info.authority != null 7499 && (processName == null 7500 || (p.info.processName.equals(processName) 7501 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7502 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7503 7504 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7505 // parameter. 7506 if (metaDataKey != null 7507 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7508 continue; 7509 } 7510 7511 if (finalList == null) { 7512 finalList = new ArrayList<ProviderInfo>(3); 7513 } 7514 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7515 ps.readUserState(userId), userId); 7516 if (info != null) { 7517 finalList.add(info); 7518 } 7519 } 7520 } 7521 } 7522 7523 if (finalList != null) { 7524 Collections.sort(finalList, mProviderInitOrderSorter); 7525 return new ParceledListSlice<ProviderInfo>(finalList); 7526 } 7527 7528 return ParceledListSlice.emptyList(); 7529 } 7530 7531 @Override 7532 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7533 // reader 7534 synchronized (mPackages) { 7535 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7536 return PackageParser.generateInstrumentationInfo(i, flags); 7537 } 7538 } 7539 7540 @Override 7541 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7542 String targetPackage, int flags) { 7543 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7544 } 7545 7546 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7547 int flags) { 7548 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7549 7550 // reader 7551 synchronized (mPackages) { 7552 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7553 while (i.hasNext()) { 7554 final PackageParser.Instrumentation p = i.next(); 7555 if (targetPackage == null 7556 || targetPackage.equals(p.info.targetPackage)) { 7557 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7558 flags); 7559 if (ii != null) { 7560 finalList.add(ii); 7561 } 7562 } 7563 } 7564 } 7565 7566 return finalList; 7567 } 7568 7569 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7571 try { 7572 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7573 } finally { 7574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7575 } 7576 } 7577 7578 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7579 final File[] files = dir.listFiles(); 7580 if (ArrayUtils.isEmpty(files)) { 7581 Log.d(TAG, "No files in app dir " + dir); 7582 return; 7583 } 7584 7585 if (DEBUG_PACKAGE_SCANNING) { 7586 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7587 + " flags=0x" + Integer.toHexString(parseFlags)); 7588 } 7589 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7590 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7591 7592 // Submit files for parsing in parallel 7593 int fileCount = 0; 7594 for (File file : files) { 7595 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7596 && !PackageInstallerService.isStageName(file.getName()); 7597 if (!isPackage) { 7598 // Ignore entries which are not packages 7599 continue; 7600 } 7601 parallelPackageParser.submit(file, parseFlags); 7602 fileCount++; 7603 } 7604 7605 // Process results one by one 7606 for (; fileCount > 0; fileCount--) { 7607 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7608 Throwable throwable = parseResult.throwable; 7609 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7610 7611 if (throwable == null) { 7612 // Static shared libraries have synthetic package names 7613 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7614 renameStaticSharedLibraryPackage(parseResult.pkg); 7615 } 7616 try { 7617 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7618 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7619 currentTime, null); 7620 } 7621 } catch (PackageManagerException e) { 7622 errorCode = e.error; 7623 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7624 } 7625 } else if (throwable instanceof PackageParser.PackageParserException) { 7626 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7627 throwable; 7628 errorCode = e.error; 7629 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7630 } else { 7631 throw new IllegalStateException("Unexpected exception occurred while parsing " 7632 + parseResult.scanFile, throwable); 7633 } 7634 7635 // Delete invalid userdata apps 7636 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7637 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7638 logCriticalInfo(Log.WARN, 7639 "Deleting invalid package at " + parseResult.scanFile); 7640 removeCodePathLI(parseResult.scanFile); 7641 } 7642 } 7643 parallelPackageParser.close(); 7644 } 7645 7646 private static File getSettingsProblemFile() { 7647 File dataDir = Environment.getDataDirectory(); 7648 File systemDir = new File(dataDir, "system"); 7649 File fname = new File(systemDir, "uiderrors.txt"); 7650 return fname; 7651 } 7652 7653 static void reportSettingsProblem(int priority, String msg) { 7654 logCriticalInfo(priority, msg); 7655 } 7656 7657 public static void logCriticalInfo(int priority, String msg) { 7658 Slog.println(priority, TAG, msg); 7659 EventLogTags.writePmCriticalInfo(msg); 7660 try { 7661 File fname = getSettingsProblemFile(); 7662 FileOutputStream out = new FileOutputStream(fname, true); 7663 PrintWriter pw = new FastPrintWriter(out); 7664 SimpleDateFormat formatter = new SimpleDateFormat(); 7665 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7666 pw.println(dateString + ": " + msg); 7667 pw.close(); 7668 FileUtils.setPermissions( 7669 fname.toString(), 7670 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7671 -1, -1); 7672 } catch (java.io.IOException e) { 7673 } 7674 } 7675 7676 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7677 if (srcFile.isDirectory()) { 7678 final File baseFile = new File(pkg.baseCodePath); 7679 long maxModifiedTime = baseFile.lastModified(); 7680 if (pkg.splitCodePaths != null) { 7681 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7682 final File splitFile = new File(pkg.splitCodePaths[i]); 7683 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7684 } 7685 } 7686 return maxModifiedTime; 7687 } 7688 return srcFile.lastModified(); 7689 } 7690 7691 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7692 final int policyFlags) throws PackageManagerException { 7693 // When upgrading from pre-N MR1, verify the package time stamp using the package 7694 // directory and not the APK file. 7695 final long lastModifiedTime = mIsPreNMR1Upgrade 7696 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7697 if (ps != null 7698 && ps.codePath.equals(srcFile) 7699 && ps.timeStamp == lastModifiedTime 7700 && !isCompatSignatureUpdateNeeded(pkg) 7701 && !isRecoverSignatureUpdateNeeded(pkg)) { 7702 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7703 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7704 ArraySet<PublicKey> signingKs; 7705 synchronized (mPackages) { 7706 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7707 } 7708 if (ps.signatures.mSignatures != null 7709 && ps.signatures.mSignatures.length != 0 7710 && signingKs != null) { 7711 // Optimization: reuse the existing cached certificates 7712 // if the package appears to be unchanged. 7713 pkg.mSignatures = ps.signatures.mSignatures; 7714 pkg.mSigningKeys = signingKs; 7715 return; 7716 } 7717 7718 Slog.w(TAG, "PackageSetting for " + ps.name 7719 + " is missing signatures. Collecting certs again to recover them."); 7720 } else { 7721 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7722 } 7723 7724 try { 7725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7726 PackageParser.collectCertificates(pkg, policyFlags); 7727 } catch (PackageParserException e) { 7728 throw PackageManagerException.from(e); 7729 } finally { 7730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7731 } 7732 } 7733 7734 /** 7735 * Traces a package scan. 7736 * @see #scanPackageLI(File, int, int, long, UserHandle) 7737 */ 7738 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7739 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7740 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7741 try { 7742 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7743 } finally { 7744 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7745 } 7746 } 7747 7748 /** 7749 * Scans a package and returns the newly parsed package. 7750 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7751 */ 7752 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7753 long currentTime, UserHandle user) throws PackageManagerException { 7754 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7755 PackageParser pp = new PackageParser(); 7756 pp.setSeparateProcesses(mSeparateProcesses); 7757 pp.setOnlyCoreApps(mOnlyCore); 7758 pp.setDisplayMetrics(mMetrics); 7759 pp.setCallback(mPackageParserCallback); 7760 7761 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7762 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7763 } 7764 7765 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7766 final PackageParser.Package pkg; 7767 try { 7768 pkg = pp.parsePackage(scanFile, parseFlags); 7769 } catch (PackageParserException e) { 7770 throw PackageManagerException.from(e); 7771 } finally { 7772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7773 } 7774 7775 // Static shared libraries have synthetic package names 7776 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7777 renameStaticSharedLibraryPackage(pkg); 7778 } 7779 7780 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7781 } 7782 7783 /** 7784 * Scans a package and returns the newly parsed package. 7785 * @throws PackageManagerException on a parse error. 7786 */ 7787 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7788 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7789 throws PackageManagerException { 7790 // If the package has children and this is the first dive in the function 7791 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7792 // packages (parent and children) would be successfully scanned before the 7793 // actual scan since scanning mutates internal state and we want to atomically 7794 // install the package and its children. 7795 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7796 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7797 scanFlags |= SCAN_CHECK_ONLY; 7798 } 7799 } else { 7800 scanFlags &= ~SCAN_CHECK_ONLY; 7801 } 7802 7803 // Scan the parent 7804 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7805 scanFlags, currentTime, user); 7806 7807 // Scan the children 7808 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7809 for (int i = 0; i < childCount; i++) { 7810 PackageParser.Package childPackage = pkg.childPackages.get(i); 7811 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7812 currentTime, user); 7813 } 7814 7815 7816 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7817 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7818 } 7819 7820 return scannedPkg; 7821 } 7822 7823 /** 7824 * Scans a package and returns the newly parsed package. 7825 * @throws PackageManagerException on a parse error. 7826 */ 7827 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7828 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7829 throws PackageManagerException { 7830 PackageSetting ps = null; 7831 PackageSetting updatedPkg; 7832 // reader 7833 synchronized (mPackages) { 7834 // Look to see if we already know about this package. 7835 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7836 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7837 // This package has been renamed to its original name. Let's 7838 // use that. 7839 ps = mSettings.getPackageLPr(oldName); 7840 } 7841 // If there was no original package, see one for the real package name. 7842 if (ps == null) { 7843 ps = mSettings.getPackageLPr(pkg.packageName); 7844 } 7845 // Check to see if this package could be hiding/updating a system 7846 // package. Must look for it either under the original or real 7847 // package name depending on our state. 7848 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7849 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7850 7851 // If this is a package we don't know about on the system partition, we 7852 // may need to remove disabled child packages on the system partition 7853 // or may need to not add child packages if the parent apk is updated 7854 // on the data partition and no longer defines this child package. 7855 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7856 // If this is a parent package for an updated system app and this system 7857 // app got an OTA update which no longer defines some of the child packages 7858 // we have to prune them from the disabled system packages. 7859 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7860 if (disabledPs != null) { 7861 final int scannedChildCount = (pkg.childPackages != null) 7862 ? pkg.childPackages.size() : 0; 7863 final int disabledChildCount = disabledPs.childPackageNames != null 7864 ? disabledPs.childPackageNames.size() : 0; 7865 for (int i = 0; i < disabledChildCount; i++) { 7866 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7867 boolean disabledPackageAvailable = false; 7868 for (int j = 0; j < scannedChildCount; j++) { 7869 PackageParser.Package childPkg = pkg.childPackages.get(j); 7870 if (childPkg.packageName.equals(disabledChildPackageName)) { 7871 disabledPackageAvailable = true; 7872 break; 7873 } 7874 } 7875 if (!disabledPackageAvailable) { 7876 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7877 } 7878 } 7879 } 7880 } 7881 } 7882 7883 boolean updatedPkgBetter = false; 7884 // First check if this is a system package that may involve an update 7885 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7886 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7887 // it needs to drop FLAG_PRIVILEGED. 7888 if (locationIsPrivileged(scanFile)) { 7889 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7890 } else { 7891 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7892 } 7893 7894 if (ps != null && !ps.codePath.equals(scanFile)) { 7895 // The path has changed from what was last scanned... check the 7896 // version of the new path against what we have stored to determine 7897 // what to do. 7898 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7899 if (pkg.mVersionCode <= ps.versionCode) { 7900 // The system package has been updated and the code path does not match 7901 // Ignore entry. Skip it. 7902 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7903 + " ignored: updated version " + ps.versionCode 7904 + " better than this " + pkg.mVersionCode); 7905 if (!updatedPkg.codePath.equals(scanFile)) { 7906 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7907 + ps.name + " changing from " + updatedPkg.codePathString 7908 + " to " + scanFile); 7909 updatedPkg.codePath = scanFile; 7910 updatedPkg.codePathString = scanFile.toString(); 7911 updatedPkg.resourcePath = scanFile; 7912 updatedPkg.resourcePathString = scanFile.toString(); 7913 } 7914 updatedPkg.pkg = pkg; 7915 updatedPkg.versionCode = pkg.mVersionCode; 7916 7917 // Update the disabled system child packages to point to the package too. 7918 final int childCount = updatedPkg.childPackageNames != null 7919 ? updatedPkg.childPackageNames.size() : 0; 7920 for (int i = 0; i < childCount; i++) { 7921 String childPackageName = updatedPkg.childPackageNames.get(i); 7922 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7923 childPackageName); 7924 if (updatedChildPkg != null) { 7925 updatedChildPkg.pkg = pkg; 7926 updatedChildPkg.versionCode = pkg.mVersionCode; 7927 } 7928 } 7929 7930 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7931 + scanFile + " ignored: updated version " + ps.versionCode 7932 + " better than this " + pkg.mVersionCode); 7933 } else { 7934 // The current app on the system partition is better than 7935 // what we have updated to on the data partition; switch 7936 // back to the system partition version. 7937 // At this point, its safely assumed that package installation for 7938 // apps in system partition will go through. If not there won't be a working 7939 // version of the app 7940 // writer 7941 synchronized (mPackages) { 7942 // Just remove the loaded entries from package lists. 7943 mPackages.remove(ps.name); 7944 } 7945 7946 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7947 + " reverting from " + ps.codePathString 7948 + ": new version " + pkg.mVersionCode 7949 + " better than installed " + ps.versionCode); 7950 7951 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7952 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7953 synchronized (mInstallLock) { 7954 args.cleanUpResourcesLI(); 7955 } 7956 synchronized (mPackages) { 7957 mSettings.enableSystemPackageLPw(ps.name); 7958 } 7959 updatedPkgBetter = true; 7960 } 7961 } 7962 } 7963 7964 if (updatedPkg != null) { 7965 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7966 // initially 7967 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7968 7969 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7970 // flag set initially 7971 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7972 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7973 } 7974 } 7975 7976 // Verify certificates against what was last scanned 7977 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7978 7979 /* 7980 * A new system app appeared, but we already had a non-system one of the 7981 * same name installed earlier. 7982 */ 7983 boolean shouldHideSystemApp = false; 7984 if (updatedPkg == null && ps != null 7985 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7986 /* 7987 * Check to make sure the signatures match first. If they don't, 7988 * wipe the installed application and its data. 7989 */ 7990 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7991 != PackageManager.SIGNATURE_MATCH) { 7992 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7993 + " signatures don't match existing userdata copy; removing"); 7994 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7995 "scanPackageInternalLI")) { 7996 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7997 } 7998 ps = null; 7999 } else { 8000 /* 8001 * If the newly-added system app is an older version than the 8002 * already installed version, hide it. It will be scanned later 8003 * and re-added like an update. 8004 */ 8005 if (pkg.mVersionCode <= ps.versionCode) { 8006 shouldHideSystemApp = true; 8007 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8008 + " but new version " + pkg.mVersionCode + " better than installed " 8009 + ps.versionCode + "; hiding system"); 8010 } else { 8011 /* 8012 * The newly found system app is a newer version that the 8013 * one previously installed. Simply remove the 8014 * already-installed application and replace it with our own 8015 * while keeping the application data. 8016 */ 8017 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8018 + " reverting from " + ps.codePathString + ": new version " 8019 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8020 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8021 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8022 synchronized (mInstallLock) { 8023 args.cleanUpResourcesLI(); 8024 } 8025 } 8026 } 8027 } 8028 8029 // The apk is forward locked (not public) if its code and resources 8030 // are kept in different files. (except for app in either system or 8031 // vendor path). 8032 // TODO grab this value from PackageSettings 8033 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8034 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8035 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8036 } 8037 } 8038 8039 // TODO: extend to support forward-locked splits 8040 String resourcePath = null; 8041 String baseResourcePath = null; 8042 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8043 if (ps != null && ps.resourcePathString != null) { 8044 resourcePath = ps.resourcePathString; 8045 baseResourcePath = ps.resourcePathString; 8046 } else { 8047 // Should not happen at all. Just log an error. 8048 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8049 } 8050 } else { 8051 resourcePath = pkg.codePath; 8052 baseResourcePath = pkg.baseCodePath; 8053 } 8054 8055 // Set application objects path explicitly. 8056 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8057 pkg.setApplicationInfoCodePath(pkg.codePath); 8058 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8059 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8060 pkg.setApplicationInfoResourcePath(resourcePath); 8061 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8062 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8063 8064 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8065 if (ps != null && ps.getInstantApp(userId)) { 8066 scanFlags |= SCAN_AS_INSTANT_APP; 8067 } 8068 8069 // Note that we invoke the following method only if we are about to unpack an application 8070 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8071 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8072 8073 /* 8074 * If the system app should be overridden by a previously installed 8075 * data, hide the system app now and let the /data/app scan pick it up 8076 * again. 8077 */ 8078 if (shouldHideSystemApp) { 8079 synchronized (mPackages) { 8080 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8081 } 8082 } 8083 8084 return scannedPkg; 8085 } 8086 8087 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8088 // Derive the new package synthetic package name 8089 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8090 + pkg.staticSharedLibVersion); 8091 } 8092 8093 private static String fixProcessName(String defProcessName, 8094 String processName) { 8095 if (processName == null) { 8096 return defProcessName; 8097 } 8098 return processName; 8099 } 8100 8101 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8102 throws PackageManagerException { 8103 if (pkgSetting.signatures.mSignatures != null) { 8104 // Already existing package. Make sure signatures match 8105 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8106 == PackageManager.SIGNATURE_MATCH; 8107 if (!match) { 8108 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8109 == PackageManager.SIGNATURE_MATCH; 8110 } 8111 if (!match) { 8112 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8113 == PackageManager.SIGNATURE_MATCH; 8114 } 8115 if (!match) { 8116 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8117 + pkg.packageName + " signatures do not match the " 8118 + "previously installed version; ignoring!"); 8119 } 8120 } 8121 8122 // Check for shared user signatures 8123 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8124 // Already existing package. Make sure signatures match 8125 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8126 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8127 if (!match) { 8128 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8129 == PackageManager.SIGNATURE_MATCH; 8130 } 8131 if (!match) { 8132 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8133 == PackageManager.SIGNATURE_MATCH; 8134 } 8135 if (!match) { 8136 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8137 "Package " + pkg.packageName 8138 + " has no signatures that match those in shared user " 8139 + pkgSetting.sharedUser.name + "; ignoring!"); 8140 } 8141 } 8142 } 8143 8144 /** 8145 * Enforces that only the system UID or root's UID can call a method exposed 8146 * via Binder. 8147 * 8148 * @param message used as message if SecurityException is thrown 8149 * @throws SecurityException if the caller is not system or root 8150 */ 8151 private static final void enforceSystemOrRoot(String message) { 8152 final int uid = Binder.getCallingUid(); 8153 if (uid != Process.SYSTEM_UID && uid != 0) { 8154 throw new SecurityException(message); 8155 } 8156 } 8157 8158 @Override 8159 public void performFstrimIfNeeded() { 8160 enforceSystemOrRoot("Only the system can request fstrim"); 8161 8162 // Before everything else, see whether we need to fstrim. 8163 try { 8164 IStorageManager sm = PackageHelper.getStorageManager(); 8165 if (sm != null) { 8166 boolean doTrim = false; 8167 final long interval = android.provider.Settings.Global.getLong( 8168 mContext.getContentResolver(), 8169 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8170 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8171 if (interval > 0) { 8172 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8173 if (timeSinceLast > interval) { 8174 doTrim = true; 8175 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8176 + "; running immediately"); 8177 } 8178 } 8179 if (doTrim) { 8180 final boolean dexOptDialogShown; 8181 synchronized (mPackages) { 8182 dexOptDialogShown = mDexOptDialogShown; 8183 } 8184 if (!isFirstBoot() && dexOptDialogShown) { 8185 try { 8186 ActivityManager.getService().showBootMessage( 8187 mContext.getResources().getString( 8188 R.string.android_upgrading_fstrim), true); 8189 } catch (RemoteException e) { 8190 } 8191 } 8192 sm.runMaintenance(); 8193 } 8194 } else { 8195 Slog.e(TAG, "storageManager service unavailable!"); 8196 } 8197 } catch (RemoteException e) { 8198 // Can't happen; StorageManagerService is local 8199 } 8200 } 8201 8202 @Override 8203 public void updatePackagesIfNeeded() { 8204 enforceSystemOrRoot("Only the system can request package update"); 8205 8206 // We need to re-extract after an OTA. 8207 boolean causeUpgrade = isUpgrade(); 8208 8209 // First boot or factory reset. 8210 // Note: we also handle devices that are upgrading to N right now as if it is their 8211 // first boot, as they do not have profile data. 8212 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8213 8214 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8215 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8216 8217 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8218 return; 8219 } 8220 8221 List<PackageParser.Package> pkgs; 8222 synchronized (mPackages) { 8223 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8224 } 8225 8226 final long startTime = System.nanoTime(); 8227 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8228 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8229 8230 final int elapsedTimeSeconds = 8231 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8232 8233 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8234 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8235 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8236 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8237 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8238 } 8239 8240 /** 8241 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8242 * containing statistics about the invocation. The array consists of three elements, 8243 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8244 * and {@code numberOfPackagesFailed}. 8245 */ 8246 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8247 String compilerFilter) { 8248 8249 int numberOfPackagesVisited = 0; 8250 int numberOfPackagesOptimized = 0; 8251 int numberOfPackagesSkipped = 0; 8252 int numberOfPackagesFailed = 0; 8253 final int numberOfPackagesToDexopt = pkgs.size(); 8254 8255 for (PackageParser.Package pkg : pkgs) { 8256 numberOfPackagesVisited++; 8257 8258 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8259 if (DEBUG_DEXOPT) { 8260 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8261 } 8262 numberOfPackagesSkipped++; 8263 continue; 8264 } 8265 8266 if (DEBUG_DEXOPT) { 8267 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8268 numberOfPackagesToDexopt + ": " + pkg.packageName); 8269 } 8270 8271 if (showDialog) { 8272 try { 8273 ActivityManager.getService().showBootMessage( 8274 mContext.getResources().getString(R.string.android_upgrading_apk, 8275 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8276 } catch (RemoteException e) { 8277 } 8278 synchronized (mPackages) { 8279 mDexOptDialogShown = true; 8280 } 8281 } 8282 8283 // If the OTA updates a system app which was previously preopted to a non-preopted state 8284 // the app might end up being verified at runtime. That's because by default the apps 8285 // are verify-profile but for preopted apps there's no profile. 8286 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8287 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8288 // filter (by default interpret-only). 8289 // Note that at this stage unused apps are already filtered. 8290 if (isSystemApp(pkg) && 8291 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8292 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8293 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8294 } 8295 8296 // checkProfiles is false to avoid merging profiles during boot which 8297 // might interfere with background compilation (b/28612421). 8298 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8299 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8300 // trade-off worth doing to save boot time work. 8301 int dexOptStatus = performDexOptTraced(pkg.packageName, 8302 false /* checkProfiles */, 8303 compilerFilter, 8304 false /* force */); 8305 switch (dexOptStatus) { 8306 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8307 numberOfPackagesOptimized++; 8308 break; 8309 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8310 numberOfPackagesSkipped++; 8311 break; 8312 case PackageDexOptimizer.DEX_OPT_FAILED: 8313 numberOfPackagesFailed++; 8314 break; 8315 default: 8316 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8317 break; 8318 } 8319 } 8320 8321 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8322 numberOfPackagesFailed }; 8323 } 8324 8325 @Override 8326 public void notifyPackageUse(String packageName, int reason) { 8327 synchronized (mPackages) { 8328 PackageParser.Package p = mPackages.get(packageName); 8329 if (p == null) { 8330 return; 8331 } 8332 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8333 } 8334 } 8335 8336 @Override 8337 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8338 int userId = UserHandle.getCallingUserId(); 8339 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8340 if (ai == null) { 8341 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8342 + loadingPackageName + ", user=" + userId); 8343 return; 8344 } 8345 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8346 } 8347 8348 // TODO: this is not used nor needed. Delete it. 8349 @Override 8350 public boolean performDexOptIfNeeded(String packageName) { 8351 int dexOptStatus = performDexOptTraced(packageName, 8352 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8353 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8354 } 8355 8356 @Override 8357 public boolean performDexOpt(String packageName, 8358 boolean checkProfiles, int compileReason, boolean force) { 8359 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8360 getCompilerFilterForReason(compileReason), force); 8361 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8362 } 8363 8364 @Override 8365 public boolean performDexOptMode(String packageName, 8366 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8367 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8368 targetCompilerFilter, force); 8369 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8370 } 8371 8372 private int performDexOptTraced(String packageName, 8373 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8375 try { 8376 return performDexOptInternal(packageName, checkProfiles, 8377 targetCompilerFilter, force); 8378 } finally { 8379 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8380 } 8381 } 8382 8383 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8384 // if the package can now be considered up to date for the given filter. 8385 private int performDexOptInternal(String packageName, 8386 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8387 PackageParser.Package p; 8388 synchronized (mPackages) { 8389 p = mPackages.get(packageName); 8390 if (p == null) { 8391 // Package could not be found. Report failure. 8392 return PackageDexOptimizer.DEX_OPT_FAILED; 8393 } 8394 mPackageUsage.maybeWriteAsync(mPackages); 8395 mCompilerStats.maybeWriteAsync(); 8396 } 8397 long callingId = Binder.clearCallingIdentity(); 8398 try { 8399 synchronized (mInstallLock) { 8400 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8401 targetCompilerFilter, force); 8402 } 8403 } finally { 8404 Binder.restoreCallingIdentity(callingId); 8405 } 8406 } 8407 8408 public ArraySet<String> getOptimizablePackages() { 8409 ArraySet<String> pkgs = new ArraySet<String>(); 8410 synchronized (mPackages) { 8411 for (PackageParser.Package p : mPackages.values()) { 8412 if (PackageDexOptimizer.canOptimizePackage(p)) { 8413 pkgs.add(p.packageName); 8414 } 8415 } 8416 } 8417 return pkgs; 8418 } 8419 8420 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8421 boolean checkProfiles, String targetCompilerFilter, 8422 boolean force) { 8423 // Select the dex optimizer based on the force parameter. 8424 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8425 // allocate an object here. 8426 PackageDexOptimizer pdo = force 8427 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8428 : mPackageDexOptimizer; 8429 8430 // Optimize all dependencies first. Note: we ignore the return value and march on 8431 // on errors. 8432 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8433 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8434 if (!deps.isEmpty()) { 8435 for (PackageParser.Package depPackage : deps) { 8436 // TODO: Analyze and investigate if we (should) profile libraries. 8437 // Currently this will do a full compilation of the library by default. 8438 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8439 false /* checkProfiles */, 8440 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8441 getOrCreateCompilerPackageStats(depPackage), 8442 mDexManager.isUsedByOtherApps(p.packageName)); 8443 } 8444 } 8445 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8446 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8447 mDexManager.isUsedByOtherApps(p.packageName)); 8448 } 8449 8450 // Performs dexopt on the used secondary dex files belonging to the given package. 8451 // Returns true if all dex files were process successfully (which could mean either dexopt or 8452 // skip). Returns false if any of the files caused errors. 8453 @Override 8454 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8455 boolean force) { 8456 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8457 } 8458 8459 public boolean performDexOptSecondary(String packageName, int compileReason, 8460 boolean force) { 8461 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8462 } 8463 8464 /** 8465 * Reconcile the information we have about the secondary dex files belonging to 8466 * {@code packagName} and the actual dex files. For all dex files that were 8467 * deleted, update the internal records and delete the generated oat files. 8468 */ 8469 @Override 8470 public void reconcileSecondaryDexFiles(String packageName) { 8471 mDexManager.reconcileSecondaryDexFiles(packageName); 8472 } 8473 8474 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8475 // a reference there. 8476 /*package*/ DexManager getDexManager() { 8477 return mDexManager; 8478 } 8479 8480 /** 8481 * Execute the background dexopt job immediately. 8482 */ 8483 @Override 8484 public boolean runBackgroundDexoptJob() { 8485 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8486 } 8487 8488 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8489 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8490 || p.usesStaticLibraries != null) { 8491 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8492 Set<String> collectedNames = new HashSet<>(); 8493 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8494 8495 retValue.remove(p); 8496 8497 return retValue; 8498 } else { 8499 return Collections.emptyList(); 8500 } 8501 } 8502 8503 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8504 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8505 if (!collectedNames.contains(p.packageName)) { 8506 collectedNames.add(p.packageName); 8507 collected.add(p); 8508 8509 if (p.usesLibraries != null) { 8510 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8511 null, collected, collectedNames); 8512 } 8513 if (p.usesOptionalLibraries != null) { 8514 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8515 null, collected, collectedNames); 8516 } 8517 if (p.usesStaticLibraries != null) { 8518 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8519 p.usesStaticLibrariesVersions, collected, collectedNames); 8520 } 8521 } 8522 } 8523 8524 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8525 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8526 final int libNameCount = libs.size(); 8527 for (int i = 0; i < libNameCount; i++) { 8528 String libName = libs.get(i); 8529 int version = (versions != null && versions.length == libNameCount) 8530 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8531 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8532 if (libPkg != null) { 8533 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8534 } 8535 } 8536 } 8537 8538 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8539 synchronized (mPackages) { 8540 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8541 if (libEntry != null) { 8542 return mPackages.get(libEntry.apk); 8543 } 8544 return null; 8545 } 8546 } 8547 8548 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8549 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8550 if (versionedLib == null) { 8551 return null; 8552 } 8553 return versionedLib.get(version); 8554 } 8555 8556 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8557 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8558 pkg.staticSharedLibName); 8559 if (versionedLib == null) { 8560 return null; 8561 } 8562 int previousLibVersion = -1; 8563 final int versionCount = versionedLib.size(); 8564 for (int i = 0; i < versionCount; i++) { 8565 final int libVersion = versionedLib.keyAt(i); 8566 if (libVersion < pkg.staticSharedLibVersion) { 8567 previousLibVersion = Math.max(previousLibVersion, libVersion); 8568 } 8569 } 8570 if (previousLibVersion >= 0) { 8571 return versionedLib.get(previousLibVersion); 8572 } 8573 return null; 8574 } 8575 8576 public void shutdown() { 8577 mPackageUsage.writeNow(mPackages); 8578 mCompilerStats.writeNow(); 8579 } 8580 8581 @Override 8582 public void dumpProfiles(String packageName) { 8583 PackageParser.Package pkg; 8584 synchronized (mPackages) { 8585 pkg = mPackages.get(packageName); 8586 if (pkg == null) { 8587 throw new IllegalArgumentException("Unknown package: " + packageName); 8588 } 8589 } 8590 /* Only the shell, root, or the app user should be able to dump profiles. */ 8591 int callingUid = Binder.getCallingUid(); 8592 if (callingUid != Process.SHELL_UID && 8593 callingUid != Process.ROOT_UID && 8594 callingUid != pkg.applicationInfo.uid) { 8595 throw new SecurityException("dumpProfiles"); 8596 } 8597 8598 synchronized (mInstallLock) { 8599 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8600 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8601 try { 8602 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8603 String codePaths = TextUtils.join(";", allCodePaths); 8604 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8605 } catch (InstallerException e) { 8606 Slog.w(TAG, "Failed to dump profiles", e); 8607 } 8608 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8609 } 8610 } 8611 8612 @Override 8613 public void forceDexOpt(String packageName) { 8614 enforceSystemOrRoot("forceDexOpt"); 8615 8616 PackageParser.Package pkg; 8617 synchronized (mPackages) { 8618 pkg = mPackages.get(packageName); 8619 if (pkg == null) { 8620 throw new IllegalArgumentException("Unknown package: " + packageName); 8621 } 8622 } 8623 8624 synchronized (mInstallLock) { 8625 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8626 8627 // Whoever is calling forceDexOpt wants a fully compiled package. 8628 // Don't use profiles since that may cause compilation to be skipped. 8629 final int res = performDexOptInternalWithDependenciesLI(pkg, 8630 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8631 true /* force */); 8632 8633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8634 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8635 throw new IllegalStateException("Failed to dexopt: " + res); 8636 } 8637 } 8638 } 8639 8640 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8641 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8642 Slog.w(TAG, "Unable to update from " + oldPkg.name 8643 + " to " + newPkg.packageName 8644 + ": old package not in system partition"); 8645 return false; 8646 } else if (mPackages.get(oldPkg.name) != null) { 8647 Slog.w(TAG, "Unable to update from " + oldPkg.name 8648 + " to " + newPkg.packageName 8649 + ": old package still exists"); 8650 return false; 8651 } 8652 return true; 8653 } 8654 8655 void removeCodePathLI(File codePath) { 8656 if (codePath.isDirectory()) { 8657 try { 8658 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8659 } catch (InstallerException e) { 8660 Slog.w(TAG, "Failed to remove code path", e); 8661 } 8662 } else { 8663 codePath.delete(); 8664 } 8665 } 8666 8667 private int[] resolveUserIds(int userId) { 8668 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8669 } 8670 8671 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8672 if (pkg == null) { 8673 Slog.wtf(TAG, "Package was null!", new Throwable()); 8674 return; 8675 } 8676 clearAppDataLeafLIF(pkg, userId, flags); 8677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8678 for (int i = 0; i < childCount; i++) { 8679 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8680 } 8681 } 8682 8683 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8684 final PackageSetting ps; 8685 synchronized (mPackages) { 8686 ps = mSettings.mPackages.get(pkg.packageName); 8687 } 8688 for (int realUserId : resolveUserIds(userId)) { 8689 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8690 try { 8691 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8692 ceDataInode); 8693 } catch (InstallerException e) { 8694 Slog.w(TAG, String.valueOf(e)); 8695 } 8696 } 8697 } 8698 8699 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8700 if (pkg == null) { 8701 Slog.wtf(TAG, "Package was null!", new Throwable()); 8702 return; 8703 } 8704 destroyAppDataLeafLIF(pkg, userId, flags); 8705 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8706 for (int i = 0; i < childCount; i++) { 8707 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8708 } 8709 } 8710 8711 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8712 final PackageSetting ps; 8713 synchronized (mPackages) { 8714 ps = mSettings.mPackages.get(pkg.packageName); 8715 } 8716 for (int realUserId : resolveUserIds(userId)) { 8717 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8718 try { 8719 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8720 ceDataInode); 8721 } catch (InstallerException e) { 8722 Slog.w(TAG, String.valueOf(e)); 8723 } 8724 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8725 } 8726 } 8727 8728 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8729 if (pkg == null) { 8730 Slog.wtf(TAG, "Package was null!", new Throwable()); 8731 return; 8732 } 8733 destroyAppProfilesLeafLIF(pkg); 8734 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8735 for (int i = 0; i < childCount; i++) { 8736 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8737 } 8738 } 8739 8740 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8741 try { 8742 mInstaller.destroyAppProfiles(pkg.packageName); 8743 } catch (InstallerException e) { 8744 Slog.w(TAG, String.valueOf(e)); 8745 } 8746 } 8747 8748 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8749 if (pkg == null) { 8750 Slog.wtf(TAG, "Package was null!", new Throwable()); 8751 return; 8752 } 8753 clearAppProfilesLeafLIF(pkg); 8754 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8755 for (int i = 0; i < childCount; i++) { 8756 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8757 } 8758 } 8759 8760 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8761 try { 8762 mInstaller.clearAppProfiles(pkg.packageName); 8763 } catch (InstallerException e) { 8764 Slog.w(TAG, String.valueOf(e)); 8765 } 8766 } 8767 8768 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8769 long lastUpdateTime) { 8770 // Set parent install/update time 8771 PackageSetting ps = (PackageSetting) pkg.mExtras; 8772 if (ps != null) { 8773 ps.firstInstallTime = firstInstallTime; 8774 ps.lastUpdateTime = lastUpdateTime; 8775 } 8776 // Set children install/update time 8777 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8778 for (int i = 0; i < childCount; i++) { 8779 PackageParser.Package childPkg = pkg.childPackages.get(i); 8780 ps = (PackageSetting) childPkg.mExtras; 8781 if (ps != null) { 8782 ps.firstInstallTime = firstInstallTime; 8783 ps.lastUpdateTime = lastUpdateTime; 8784 } 8785 } 8786 } 8787 8788 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8789 PackageParser.Package changingLib) { 8790 if (file.path != null) { 8791 usesLibraryFiles.add(file.path); 8792 return; 8793 } 8794 PackageParser.Package p = mPackages.get(file.apk); 8795 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8796 // If we are doing this while in the middle of updating a library apk, 8797 // then we need to make sure to use that new apk for determining the 8798 // dependencies here. (We haven't yet finished committing the new apk 8799 // to the package manager state.) 8800 if (p == null || p.packageName.equals(changingLib.packageName)) { 8801 p = changingLib; 8802 } 8803 } 8804 if (p != null) { 8805 usesLibraryFiles.addAll(p.getAllCodePaths()); 8806 } 8807 } 8808 8809 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8810 PackageParser.Package changingLib) throws PackageManagerException { 8811 if (pkg == null) { 8812 return; 8813 } 8814 ArraySet<String> usesLibraryFiles = null; 8815 if (pkg.usesLibraries != null) { 8816 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8817 null, null, pkg.packageName, changingLib, true, null); 8818 } 8819 if (pkg.usesStaticLibraries != null) { 8820 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8821 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8822 pkg.packageName, changingLib, true, usesLibraryFiles); 8823 } 8824 if (pkg.usesOptionalLibraries != null) { 8825 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8826 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8827 } 8828 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8829 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8830 } else { 8831 pkg.usesLibraryFiles = null; 8832 } 8833 } 8834 8835 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8836 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8837 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8838 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8839 throws PackageManagerException { 8840 final int libCount = requestedLibraries.size(); 8841 for (int i = 0; i < libCount; i++) { 8842 final String libName = requestedLibraries.get(i); 8843 final int libVersion = requiredVersions != null ? requiredVersions[i] 8844 : SharedLibraryInfo.VERSION_UNDEFINED; 8845 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8846 if (libEntry == null) { 8847 if (required) { 8848 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8849 "Package " + packageName + " requires unavailable shared library " 8850 + libName + "; failing!"); 8851 } else { 8852 Slog.w(TAG, "Package " + packageName 8853 + " desires unavailable shared library " 8854 + libName + "; ignoring!"); 8855 } 8856 } else { 8857 if (requiredVersions != null && requiredCertDigests != null) { 8858 if (libEntry.info.getVersion() != requiredVersions[i]) { 8859 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8860 "Package " + packageName + " requires unavailable static shared" 8861 + " library " + libName + " version " 8862 + libEntry.info.getVersion() + "; failing!"); 8863 } 8864 8865 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8866 if (libPkg == null) { 8867 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8868 "Package " + packageName + " requires unavailable static shared" 8869 + " library; failing!"); 8870 } 8871 8872 String expectedCertDigest = requiredCertDigests[i]; 8873 String libCertDigest = PackageUtils.computeCertSha256Digest( 8874 libPkg.mSignatures[0]); 8875 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8876 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8877 "Package " + packageName + " requires differently signed" + 8878 " static shared library; failing!"); 8879 } 8880 } 8881 8882 if (outUsedLibraries == null) { 8883 outUsedLibraries = new ArraySet<>(); 8884 } 8885 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8886 } 8887 } 8888 return outUsedLibraries; 8889 } 8890 8891 private static boolean hasString(List<String> list, List<String> which) { 8892 if (list == null) { 8893 return false; 8894 } 8895 for (int i=list.size()-1; i>=0; i--) { 8896 for (int j=which.size()-1; j>=0; j--) { 8897 if (which.get(j).equals(list.get(i))) { 8898 return true; 8899 } 8900 } 8901 } 8902 return false; 8903 } 8904 8905 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8906 PackageParser.Package changingPkg) { 8907 ArrayList<PackageParser.Package> res = null; 8908 for (PackageParser.Package pkg : mPackages.values()) { 8909 if (changingPkg != null 8910 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8911 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8912 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8913 changingPkg.staticSharedLibName)) { 8914 return null; 8915 } 8916 if (res == null) { 8917 res = new ArrayList<>(); 8918 } 8919 res.add(pkg); 8920 try { 8921 updateSharedLibrariesLPr(pkg, changingPkg); 8922 } catch (PackageManagerException e) { 8923 // If a system app update or an app and a required lib missing we 8924 // delete the package and for updated system apps keep the data as 8925 // it is better for the user to reinstall than to be in an limbo 8926 // state. Also libs disappearing under an app should never happen 8927 // - just in case. 8928 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8929 final int flags = pkg.isUpdatedSystemApp() 8930 ? PackageManager.DELETE_KEEP_DATA : 0; 8931 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8932 flags , null, true, null); 8933 } 8934 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8935 } 8936 } 8937 return res; 8938 } 8939 8940 /** 8941 * Derive the value of the {@code cpuAbiOverride} based on the provided 8942 * value and an optional stored value from the package settings. 8943 */ 8944 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8945 String cpuAbiOverride = null; 8946 8947 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8948 cpuAbiOverride = null; 8949 } else if (abiOverride != null) { 8950 cpuAbiOverride = abiOverride; 8951 } else if (settings != null) { 8952 cpuAbiOverride = settings.cpuAbiOverrideString; 8953 } 8954 8955 return cpuAbiOverride; 8956 } 8957 8958 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8959 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8960 throws PackageManagerException { 8961 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8962 // If the package has children and this is the first dive in the function 8963 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8964 // whether all packages (parent and children) would be successfully scanned 8965 // before the actual scan since scanning mutates internal state and we want 8966 // to atomically install the package and its children. 8967 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8968 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8969 scanFlags |= SCAN_CHECK_ONLY; 8970 } 8971 } else { 8972 scanFlags &= ~SCAN_CHECK_ONLY; 8973 } 8974 8975 final PackageParser.Package scannedPkg; 8976 try { 8977 // Scan the parent 8978 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8979 // Scan the children 8980 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8981 for (int i = 0; i < childCount; i++) { 8982 PackageParser.Package childPkg = pkg.childPackages.get(i); 8983 scanPackageLI(childPkg, policyFlags, 8984 scanFlags, currentTime, user); 8985 } 8986 } finally { 8987 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8988 } 8989 8990 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8991 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8992 } 8993 8994 return scannedPkg; 8995 } 8996 8997 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8998 int scanFlags, long currentTime, @Nullable UserHandle user) 8999 throws PackageManagerException { 9000 boolean success = false; 9001 try { 9002 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9003 currentTime, user); 9004 success = true; 9005 return res; 9006 } finally { 9007 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9008 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9009 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9010 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9011 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9012 } 9013 } 9014 } 9015 9016 /** 9017 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9018 */ 9019 private static boolean apkHasCode(String fileName) { 9020 StrictJarFile jarFile = null; 9021 try { 9022 jarFile = new StrictJarFile(fileName, 9023 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9024 return jarFile.findEntry("classes.dex") != null; 9025 } catch (IOException ignore) { 9026 } finally { 9027 try { 9028 if (jarFile != null) { 9029 jarFile.close(); 9030 } 9031 } catch (IOException ignore) {} 9032 } 9033 return false; 9034 } 9035 9036 /** 9037 * Enforces code policy for the package. This ensures that if an APK has 9038 * declared hasCode="true" in its manifest that the APK actually contains 9039 * code. 9040 * 9041 * @throws PackageManagerException If bytecode could not be found when it should exist 9042 */ 9043 private static void assertCodePolicy(PackageParser.Package pkg) 9044 throws PackageManagerException { 9045 final boolean shouldHaveCode = 9046 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9047 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9048 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9049 "Package " + pkg.baseCodePath + " code is missing"); 9050 } 9051 9052 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9053 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9054 final boolean splitShouldHaveCode = 9055 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9056 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9057 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9058 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9059 } 9060 } 9061 } 9062 } 9063 9064 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9065 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9066 throws PackageManagerException { 9067 if (DEBUG_PACKAGE_SCANNING) { 9068 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9069 Log.d(TAG, "Scanning package " + pkg.packageName); 9070 } 9071 9072 applyPolicy(pkg, policyFlags); 9073 9074 assertPackageIsValid(pkg, policyFlags, scanFlags); 9075 9076 // Initialize package source and resource directories 9077 final File scanFile = new File(pkg.codePath); 9078 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9079 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9080 9081 SharedUserSetting suid = null; 9082 PackageSetting pkgSetting = null; 9083 9084 // Getting the package setting may have a side-effect, so if we 9085 // are only checking if scan would succeed, stash a copy of the 9086 // old setting to restore at the end. 9087 PackageSetting nonMutatedPs = null; 9088 9089 // We keep references to the derived CPU Abis from settings in oder to reuse 9090 // them in the case where we're not upgrading or booting for the first time. 9091 String primaryCpuAbiFromSettings = null; 9092 String secondaryCpuAbiFromSettings = null; 9093 9094 // writer 9095 synchronized (mPackages) { 9096 if (pkg.mSharedUserId != null) { 9097 // SIDE EFFECTS; may potentially allocate a new shared user 9098 suid = mSettings.getSharedUserLPw( 9099 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9100 if (DEBUG_PACKAGE_SCANNING) { 9101 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9102 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9103 + "): packages=" + suid.packages); 9104 } 9105 } 9106 9107 // Check if we are renaming from an original package name. 9108 PackageSetting origPackage = null; 9109 String realName = null; 9110 if (pkg.mOriginalPackages != null) { 9111 // This package may need to be renamed to a previously 9112 // installed name. Let's check on that... 9113 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9114 if (pkg.mOriginalPackages.contains(renamed)) { 9115 // This package had originally been installed as the 9116 // original name, and we have already taken care of 9117 // transitioning to the new one. Just update the new 9118 // one to continue using the old name. 9119 realName = pkg.mRealPackage; 9120 if (!pkg.packageName.equals(renamed)) { 9121 // Callers into this function may have already taken 9122 // care of renaming the package; only do it here if 9123 // it is not already done. 9124 pkg.setPackageName(renamed); 9125 } 9126 } else { 9127 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9128 if ((origPackage = mSettings.getPackageLPr( 9129 pkg.mOriginalPackages.get(i))) != null) { 9130 // We do have the package already installed under its 9131 // original name... should we use it? 9132 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9133 // New package is not compatible with original. 9134 origPackage = null; 9135 continue; 9136 } else if (origPackage.sharedUser != null) { 9137 // Make sure uid is compatible between packages. 9138 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9139 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9140 + " to " + pkg.packageName + ": old uid " 9141 + origPackage.sharedUser.name 9142 + " differs from " + pkg.mSharedUserId); 9143 origPackage = null; 9144 continue; 9145 } 9146 // TODO: Add case when shared user id is added [b/28144775] 9147 } else { 9148 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9149 + pkg.packageName + " to old name " + origPackage.name); 9150 } 9151 break; 9152 } 9153 } 9154 } 9155 } 9156 9157 if (mTransferedPackages.contains(pkg.packageName)) { 9158 Slog.w(TAG, "Package " + pkg.packageName 9159 + " was transferred to another, but its .apk remains"); 9160 } 9161 9162 // See comments in nonMutatedPs declaration 9163 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9164 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9165 if (foundPs != null) { 9166 nonMutatedPs = new PackageSetting(foundPs); 9167 } 9168 } 9169 9170 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9171 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9172 if (foundPs != null) { 9173 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9174 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9175 } 9176 } 9177 9178 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9179 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9180 PackageManagerService.reportSettingsProblem(Log.WARN, 9181 "Package " + pkg.packageName + " shared user changed from " 9182 + (pkgSetting.sharedUser != null 9183 ? pkgSetting.sharedUser.name : "<nothing>") 9184 + " to " 9185 + (suid != null ? suid.name : "<nothing>") 9186 + "; replacing with new"); 9187 pkgSetting = null; 9188 } 9189 final PackageSetting oldPkgSetting = 9190 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9191 final PackageSetting disabledPkgSetting = 9192 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9193 9194 String[] usesStaticLibraries = null; 9195 if (pkg.usesStaticLibraries != null) { 9196 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9197 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9198 } 9199 9200 if (pkgSetting == null) { 9201 final String parentPackageName = (pkg.parentPackage != null) 9202 ? pkg.parentPackage.packageName : null; 9203 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9204 // REMOVE SharedUserSetting from method; update in a separate call 9205 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9206 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9207 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9208 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9209 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9210 true /*allowInstall*/, instantApp, parentPackageName, 9211 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9212 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9213 // SIDE EFFECTS; updates system state; move elsewhere 9214 if (origPackage != null) { 9215 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9216 } 9217 mSettings.addUserToSettingLPw(pkgSetting); 9218 } else { 9219 // REMOVE SharedUserSetting from method; update in a separate call. 9220 // 9221 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9222 // secondaryCpuAbi are not known at this point so we always update them 9223 // to null here, only to reset them at a later point. 9224 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9225 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9226 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9227 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9228 UserManagerService.getInstance(), usesStaticLibraries, 9229 pkg.usesStaticLibrariesVersions); 9230 } 9231 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9232 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9233 9234 // SIDE EFFECTS; modifies system state; move elsewhere 9235 if (pkgSetting.origPackage != null) { 9236 // If we are first transitioning from an original package, 9237 // fix up the new package's name now. We need to do this after 9238 // looking up the package under its new name, so getPackageLP 9239 // can take care of fiddling things correctly. 9240 pkg.setPackageName(origPackage.name); 9241 9242 // File a report about this. 9243 String msg = "New package " + pkgSetting.realName 9244 + " renamed to replace old package " + pkgSetting.name; 9245 reportSettingsProblem(Log.WARN, msg); 9246 9247 // Make a note of it. 9248 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9249 mTransferedPackages.add(origPackage.name); 9250 } 9251 9252 // No longer need to retain this. 9253 pkgSetting.origPackage = null; 9254 } 9255 9256 // SIDE EFFECTS; modifies system state; move elsewhere 9257 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9258 // Make a note of it. 9259 mTransferedPackages.add(pkg.packageName); 9260 } 9261 9262 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9263 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9264 } 9265 9266 if ((scanFlags & SCAN_BOOTING) == 0 9267 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9268 // Check all shared libraries and map to their actual file path. 9269 // We only do this here for apps not on a system dir, because those 9270 // are the only ones that can fail an install due to this. We 9271 // will take care of the system apps by updating all of their 9272 // library paths after the scan is done. Also during the initial 9273 // scan don't update any libs as we do this wholesale after all 9274 // apps are scanned to avoid dependency based scanning. 9275 updateSharedLibrariesLPr(pkg, null); 9276 } 9277 9278 if (mFoundPolicyFile) { 9279 SELinuxMMAC.assignSeInfoValue(pkg); 9280 } 9281 pkg.applicationInfo.uid = pkgSetting.appId; 9282 pkg.mExtras = pkgSetting; 9283 9284 9285 // Static shared libs have same package with different versions where 9286 // we internally use a synthetic package name to allow multiple versions 9287 // of the same package, therefore we need to compare signatures against 9288 // the package setting for the latest library version. 9289 PackageSetting signatureCheckPs = pkgSetting; 9290 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9291 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9292 if (libraryEntry != null) { 9293 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9294 } 9295 } 9296 9297 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9298 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9299 // We just determined the app is signed correctly, so bring 9300 // over the latest parsed certs. 9301 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9302 } else { 9303 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9304 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9305 "Package " + pkg.packageName + " upgrade keys do not match the " 9306 + "previously installed version"); 9307 } else { 9308 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9309 String msg = "System package " + pkg.packageName 9310 + " signature changed; retaining data."; 9311 reportSettingsProblem(Log.WARN, msg); 9312 } 9313 } 9314 } else { 9315 try { 9316 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9317 verifySignaturesLP(signatureCheckPs, pkg); 9318 // We just determined the app is signed correctly, so bring 9319 // over the latest parsed certs. 9320 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9321 } catch (PackageManagerException e) { 9322 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9323 throw e; 9324 } 9325 // The signature has changed, but this package is in the system 9326 // image... let's recover! 9327 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9328 // However... if this package is part of a shared user, but it 9329 // doesn't match the signature of the shared user, let's fail. 9330 // What this means is that you can't change the signatures 9331 // associated with an overall shared user, which doesn't seem all 9332 // that unreasonable. 9333 if (signatureCheckPs.sharedUser != null) { 9334 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9335 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9336 throw new PackageManagerException( 9337 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9338 "Signature mismatch for shared user: " 9339 + pkgSetting.sharedUser); 9340 } 9341 } 9342 // File a report about this. 9343 String msg = "System package " + pkg.packageName 9344 + " signature changed; retaining data."; 9345 reportSettingsProblem(Log.WARN, msg); 9346 } 9347 } 9348 9349 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9350 // This package wants to adopt ownership of permissions from 9351 // another package. 9352 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9353 final String origName = pkg.mAdoptPermissions.get(i); 9354 final PackageSetting orig = mSettings.getPackageLPr(origName); 9355 if (orig != null) { 9356 if (verifyPackageUpdateLPr(orig, pkg)) { 9357 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9358 + pkg.packageName); 9359 // SIDE EFFECTS; updates permissions system state; move elsewhere 9360 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9361 } 9362 } 9363 } 9364 } 9365 } 9366 9367 pkg.applicationInfo.processName = fixProcessName( 9368 pkg.applicationInfo.packageName, 9369 pkg.applicationInfo.processName); 9370 9371 if (pkg != mPlatformPackage) { 9372 // Get all of our default paths setup 9373 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9374 } 9375 9376 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9377 9378 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9379 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9381 derivePackageAbi( 9382 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9383 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9384 9385 // Some system apps still use directory structure for native libraries 9386 // in which case we might end up not detecting abi solely based on apk 9387 // structure. Try to detect abi based on directory structure. 9388 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9389 pkg.applicationInfo.primaryCpuAbi == null) { 9390 setBundledAppAbisAndRoots(pkg, pkgSetting); 9391 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9392 } 9393 } else { 9394 // This is not a first boot or an upgrade, don't bother deriving the 9395 // ABI during the scan. Instead, trust the value that was stored in the 9396 // package setting. 9397 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9398 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9399 9400 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9401 9402 if (DEBUG_ABI_SELECTION) { 9403 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9404 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9405 pkg.applicationInfo.secondaryCpuAbi); 9406 } 9407 } 9408 } else { 9409 if ((scanFlags & SCAN_MOVE) != 0) { 9410 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9411 // but we already have this packages package info in the PackageSetting. We just 9412 // use that and derive the native library path based on the new codepath. 9413 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9414 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9415 } 9416 9417 // Set native library paths again. For moves, the path will be updated based on the 9418 // ABIs we've determined above. For non-moves, the path will be updated based on the 9419 // ABIs we determined during compilation, but the path will depend on the final 9420 // package path (after the rename away from the stage path). 9421 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9422 } 9423 9424 // This is a special case for the "system" package, where the ABI is 9425 // dictated by the zygote configuration (and init.rc). We should keep track 9426 // of this ABI so that we can deal with "normal" applications that run under 9427 // the same UID correctly. 9428 if (mPlatformPackage == pkg) { 9429 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9430 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9431 } 9432 9433 // If there's a mismatch between the abi-override in the package setting 9434 // and the abiOverride specified for the install. Warn about this because we 9435 // would've already compiled the app without taking the package setting into 9436 // account. 9437 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9438 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9439 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9440 " for package " + pkg.packageName); 9441 } 9442 } 9443 9444 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9445 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9446 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9447 9448 // Copy the derived override back to the parsed package, so that we can 9449 // update the package settings accordingly. 9450 pkg.cpuAbiOverride = cpuAbiOverride; 9451 9452 if (DEBUG_ABI_SELECTION) { 9453 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9454 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9455 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9456 } 9457 9458 // Push the derived path down into PackageSettings so we know what to 9459 // clean up at uninstall time. 9460 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9461 9462 if (DEBUG_ABI_SELECTION) { 9463 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9464 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9465 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9466 } 9467 9468 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9469 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9470 // We don't do this here during boot because we can do it all 9471 // at once after scanning all existing packages. 9472 // 9473 // We also do this *before* we perform dexopt on this package, so that 9474 // we can avoid redundant dexopts, and also to make sure we've got the 9475 // code and package path correct. 9476 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9477 } 9478 9479 if (mFactoryTest && pkg.requestedPermissions.contains( 9480 android.Manifest.permission.FACTORY_TEST)) { 9481 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9482 } 9483 9484 if (isSystemApp(pkg)) { 9485 pkgSetting.isOrphaned = true; 9486 } 9487 9488 // Take care of first install / last update times. 9489 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9490 if (currentTime != 0) { 9491 if (pkgSetting.firstInstallTime == 0) { 9492 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9493 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9494 pkgSetting.lastUpdateTime = currentTime; 9495 } 9496 } else if (pkgSetting.firstInstallTime == 0) { 9497 // We need *something*. Take time time stamp of the file. 9498 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9499 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9500 if (scanFileTime != pkgSetting.timeStamp) { 9501 // A package on the system image has changed; consider this 9502 // to be an update. 9503 pkgSetting.lastUpdateTime = scanFileTime; 9504 } 9505 } 9506 pkgSetting.setTimeStamp(scanFileTime); 9507 9508 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9509 if (nonMutatedPs != null) { 9510 synchronized (mPackages) { 9511 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9512 } 9513 } 9514 } else { 9515 final int userId = user == null ? 0 : user.getIdentifier(); 9516 // Modify state for the given package setting 9517 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9518 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9519 if (pkgSetting.getInstantApp(userId)) { 9520 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9521 } 9522 } 9523 return pkg; 9524 } 9525 9526 /** 9527 * Applies policy to the parsed package based upon the given policy flags. 9528 * Ensures the package is in a good state. 9529 * <p> 9530 * Implementation detail: This method must NOT have any side effect. It would 9531 * ideally be static, but, it requires locks to read system state. 9532 */ 9533 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9534 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9535 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9536 if (pkg.applicationInfo.isDirectBootAware()) { 9537 // we're direct boot aware; set for all components 9538 for (PackageParser.Service s : pkg.services) { 9539 s.info.encryptionAware = s.info.directBootAware = true; 9540 } 9541 for (PackageParser.Provider p : pkg.providers) { 9542 p.info.encryptionAware = p.info.directBootAware = true; 9543 } 9544 for (PackageParser.Activity a : pkg.activities) { 9545 a.info.encryptionAware = a.info.directBootAware = true; 9546 } 9547 for (PackageParser.Activity r : pkg.receivers) { 9548 r.info.encryptionAware = r.info.directBootAware = true; 9549 } 9550 } 9551 } else { 9552 // Only allow system apps to be flagged as core apps. 9553 pkg.coreApp = false; 9554 // clear flags not applicable to regular apps 9555 pkg.applicationInfo.privateFlags &= 9556 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9557 pkg.applicationInfo.privateFlags &= 9558 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9559 } 9560 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9561 9562 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9563 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9564 } 9565 9566 if (!isSystemApp(pkg)) { 9567 // Only system apps can use these features. 9568 pkg.mOriginalPackages = null; 9569 pkg.mRealPackage = null; 9570 pkg.mAdoptPermissions = null; 9571 } 9572 } 9573 9574 /** 9575 * Asserts the parsed package is valid according to the given policy. If the 9576 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9577 * <p> 9578 * Implementation detail: This method must NOT have any side effects. It would 9579 * ideally be static, but, it requires locks to read system state. 9580 * 9581 * @throws PackageManagerException If the package fails any of the validation checks 9582 */ 9583 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9584 throws PackageManagerException { 9585 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9586 assertCodePolicy(pkg); 9587 } 9588 9589 if (pkg.applicationInfo.getCodePath() == null || 9590 pkg.applicationInfo.getResourcePath() == null) { 9591 // Bail out. The resource and code paths haven't been set. 9592 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9593 "Code and resource paths haven't been set correctly"); 9594 } 9595 9596 // Make sure we're not adding any bogus keyset info 9597 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9598 ksms.assertScannedPackageValid(pkg); 9599 9600 synchronized (mPackages) { 9601 // The special "android" package can only be defined once 9602 if (pkg.packageName.equals("android")) { 9603 if (mAndroidApplication != null) { 9604 Slog.w(TAG, "*************************************************"); 9605 Slog.w(TAG, "Core android package being redefined. Skipping."); 9606 Slog.w(TAG, " codePath=" + pkg.codePath); 9607 Slog.w(TAG, "*************************************************"); 9608 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9609 "Core android package being redefined. Skipping."); 9610 } 9611 } 9612 9613 // A package name must be unique; don't allow duplicates 9614 if (mPackages.containsKey(pkg.packageName)) { 9615 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9616 "Application package " + pkg.packageName 9617 + " already installed. Skipping duplicate."); 9618 } 9619 9620 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9621 // Static libs have a synthetic package name containing the version 9622 // but we still want the base name to be unique. 9623 if (mPackages.containsKey(pkg.manifestPackageName)) { 9624 throw new PackageManagerException( 9625 "Duplicate static shared lib provider package"); 9626 } 9627 9628 // Static shared libraries should have at least O target SDK 9629 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9630 throw new PackageManagerException( 9631 "Packages declaring static-shared libs must target O SDK or higher"); 9632 } 9633 9634 // Package declaring static a shared lib cannot be instant apps 9635 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9636 throw new PackageManagerException( 9637 "Packages declaring static-shared libs cannot be instant apps"); 9638 } 9639 9640 // Package declaring static a shared lib cannot be renamed since the package 9641 // name is synthetic and apps can't code around package manager internals. 9642 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9643 throw new PackageManagerException( 9644 "Packages declaring static-shared libs cannot be renamed"); 9645 } 9646 9647 // Package declaring static a shared lib cannot declare child packages 9648 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9649 throw new PackageManagerException( 9650 "Packages declaring static-shared libs cannot have child packages"); 9651 } 9652 9653 // Package declaring static a shared lib cannot declare dynamic libs 9654 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9655 throw new PackageManagerException( 9656 "Packages declaring static-shared libs cannot declare dynamic libs"); 9657 } 9658 9659 // Package declaring static a shared lib cannot declare shared users 9660 if (pkg.mSharedUserId != null) { 9661 throw new PackageManagerException( 9662 "Packages declaring static-shared libs cannot declare shared users"); 9663 } 9664 9665 // Static shared libs cannot declare activities 9666 if (!pkg.activities.isEmpty()) { 9667 throw new PackageManagerException( 9668 "Static shared libs cannot declare activities"); 9669 } 9670 9671 // Static shared libs cannot declare services 9672 if (!pkg.services.isEmpty()) { 9673 throw new PackageManagerException( 9674 "Static shared libs cannot declare services"); 9675 } 9676 9677 // Static shared libs cannot declare providers 9678 if (!pkg.providers.isEmpty()) { 9679 throw new PackageManagerException( 9680 "Static shared libs cannot declare content providers"); 9681 } 9682 9683 // Static shared libs cannot declare receivers 9684 if (!pkg.receivers.isEmpty()) { 9685 throw new PackageManagerException( 9686 "Static shared libs cannot declare broadcast receivers"); 9687 } 9688 9689 // Static shared libs cannot declare permission groups 9690 if (!pkg.permissionGroups.isEmpty()) { 9691 throw new PackageManagerException( 9692 "Static shared libs cannot declare permission groups"); 9693 } 9694 9695 // Static shared libs cannot declare permissions 9696 if (!pkg.permissions.isEmpty()) { 9697 throw new PackageManagerException( 9698 "Static shared libs cannot declare permissions"); 9699 } 9700 9701 // Static shared libs cannot declare protected broadcasts 9702 if (pkg.protectedBroadcasts != null) { 9703 throw new PackageManagerException( 9704 "Static shared libs cannot declare protected broadcasts"); 9705 } 9706 9707 // Static shared libs cannot be overlay targets 9708 if (pkg.mOverlayTarget != null) { 9709 throw new PackageManagerException( 9710 "Static shared libs cannot be overlay targets"); 9711 } 9712 9713 // The version codes must be ordered as lib versions 9714 int minVersionCode = Integer.MIN_VALUE; 9715 int maxVersionCode = Integer.MAX_VALUE; 9716 9717 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9718 pkg.staticSharedLibName); 9719 if (versionedLib != null) { 9720 final int versionCount = versionedLib.size(); 9721 for (int i = 0; i < versionCount; i++) { 9722 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9723 // TODO: We will change version code to long, so in the new API it is long 9724 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9725 .getVersionCode(); 9726 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9727 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9728 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9729 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9730 } else { 9731 minVersionCode = maxVersionCode = libVersionCode; 9732 break; 9733 } 9734 } 9735 } 9736 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9737 throw new PackageManagerException("Static shared" 9738 + " lib version codes must be ordered as lib versions"); 9739 } 9740 } 9741 9742 // Only privileged apps and updated privileged apps can add child packages. 9743 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9744 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9745 throw new PackageManagerException("Only privileged apps can add child " 9746 + "packages. Ignoring package " + pkg.packageName); 9747 } 9748 final int childCount = pkg.childPackages.size(); 9749 for (int i = 0; i < childCount; i++) { 9750 PackageParser.Package childPkg = pkg.childPackages.get(i); 9751 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9752 childPkg.packageName)) { 9753 throw new PackageManagerException("Can't override child of " 9754 + "another disabled app. Ignoring package " + pkg.packageName); 9755 } 9756 } 9757 } 9758 9759 // If we're only installing presumed-existing packages, require that the 9760 // scanned APK is both already known and at the path previously established 9761 // for it. Previously unknown packages we pick up normally, but if we have an 9762 // a priori expectation about this package's install presence, enforce it. 9763 // With a singular exception for new system packages. When an OTA contains 9764 // a new system package, we allow the codepath to change from a system location 9765 // to the user-installed location. If we don't allow this change, any newer, 9766 // user-installed version of the application will be ignored. 9767 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9768 if (mExpectingBetter.containsKey(pkg.packageName)) { 9769 logCriticalInfo(Log.WARN, 9770 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9771 } else { 9772 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9773 if (known != null) { 9774 if (DEBUG_PACKAGE_SCANNING) { 9775 Log.d(TAG, "Examining " + pkg.codePath 9776 + " and requiring known paths " + known.codePathString 9777 + " & " + known.resourcePathString); 9778 } 9779 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9780 || !pkg.applicationInfo.getResourcePath().equals( 9781 known.resourcePathString)) { 9782 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9783 "Application package " + pkg.packageName 9784 + " found at " + pkg.applicationInfo.getCodePath() 9785 + " but expected at " + known.codePathString 9786 + "; ignoring."); 9787 } 9788 } 9789 } 9790 } 9791 9792 // Verify that this new package doesn't have any content providers 9793 // that conflict with existing packages. Only do this if the 9794 // package isn't already installed, since we don't want to break 9795 // things that are installed. 9796 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9797 final int N = pkg.providers.size(); 9798 int i; 9799 for (i=0; i<N; i++) { 9800 PackageParser.Provider p = pkg.providers.get(i); 9801 if (p.info.authority != null) { 9802 String names[] = p.info.authority.split(";"); 9803 for (int j = 0; j < names.length; j++) { 9804 if (mProvidersByAuthority.containsKey(names[j])) { 9805 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9806 final String otherPackageName = 9807 ((other != null && other.getComponentName() != null) ? 9808 other.getComponentName().getPackageName() : "?"); 9809 throw new PackageManagerException( 9810 INSTALL_FAILED_CONFLICTING_PROVIDER, 9811 "Can't install because provider name " + names[j] 9812 + " (in package " + pkg.applicationInfo.packageName 9813 + ") is already used by " + otherPackageName); 9814 } 9815 } 9816 } 9817 } 9818 } 9819 } 9820 } 9821 9822 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9823 int type, String declaringPackageName, int declaringVersionCode) { 9824 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9825 if (versionedLib == null) { 9826 versionedLib = new SparseArray<>(); 9827 mSharedLibraries.put(name, versionedLib); 9828 if (type == SharedLibraryInfo.TYPE_STATIC) { 9829 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9830 } 9831 } else if (versionedLib.indexOfKey(version) >= 0) { 9832 return false; 9833 } 9834 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9835 version, type, declaringPackageName, declaringVersionCode); 9836 versionedLib.put(version, libEntry); 9837 return true; 9838 } 9839 9840 private boolean removeSharedLibraryLPw(String name, int version) { 9841 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9842 if (versionedLib == null) { 9843 return false; 9844 } 9845 final int libIdx = versionedLib.indexOfKey(version); 9846 if (libIdx < 0) { 9847 return false; 9848 } 9849 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9850 versionedLib.remove(version); 9851 if (versionedLib.size() <= 0) { 9852 mSharedLibraries.remove(name); 9853 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9854 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9855 .getPackageName()); 9856 } 9857 } 9858 return true; 9859 } 9860 9861 /** 9862 * Adds a scanned package to the system. When this method is finished, the package will 9863 * be available for query, resolution, etc... 9864 */ 9865 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9866 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9867 final String pkgName = pkg.packageName; 9868 if (mCustomResolverComponentName != null && 9869 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9870 setUpCustomResolverActivity(pkg); 9871 } 9872 9873 if (pkg.packageName.equals("android")) { 9874 synchronized (mPackages) { 9875 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9876 // Set up information for our fall-back user intent resolution activity. 9877 mPlatformPackage = pkg; 9878 pkg.mVersionCode = mSdkVersion; 9879 mAndroidApplication = pkg.applicationInfo; 9880 if (!mResolverReplaced) { 9881 mResolveActivity.applicationInfo = mAndroidApplication; 9882 mResolveActivity.name = ResolverActivity.class.getName(); 9883 mResolveActivity.packageName = mAndroidApplication.packageName; 9884 mResolveActivity.processName = "system:ui"; 9885 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9886 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9887 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9888 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9889 mResolveActivity.exported = true; 9890 mResolveActivity.enabled = true; 9891 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9892 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9893 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9894 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9895 | ActivityInfo.CONFIG_ORIENTATION 9896 | ActivityInfo.CONFIG_KEYBOARD 9897 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9898 mResolveInfo.activityInfo = mResolveActivity; 9899 mResolveInfo.priority = 0; 9900 mResolveInfo.preferredOrder = 0; 9901 mResolveInfo.match = 0; 9902 mResolveComponentName = new ComponentName( 9903 mAndroidApplication.packageName, mResolveActivity.name); 9904 } 9905 } 9906 } 9907 } 9908 9909 ArrayList<PackageParser.Package> clientLibPkgs = null; 9910 // writer 9911 synchronized (mPackages) { 9912 boolean hasStaticSharedLibs = false; 9913 9914 // Any app can add new static shared libraries 9915 if (pkg.staticSharedLibName != null) { 9916 // Static shared libs don't allow renaming as they have synthetic package 9917 // names to allow install of multiple versions, so use name from manifest. 9918 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9919 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9920 pkg.manifestPackageName, pkg.mVersionCode)) { 9921 hasStaticSharedLibs = true; 9922 } else { 9923 Slog.w(TAG, "Package " + pkg.packageName + " library " 9924 + pkg.staticSharedLibName + " already exists; skipping"); 9925 } 9926 // Static shared libs cannot be updated once installed since they 9927 // use synthetic package name which includes the version code, so 9928 // not need to update other packages's shared lib dependencies. 9929 } 9930 9931 if (!hasStaticSharedLibs 9932 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9933 // Only system apps can add new dynamic shared libraries. 9934 if (pkg.libraryNames != null) { 9935 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9936 String name = pkg.libraryNames.get(i); 9937 boolean allowed = false; 9938 if (pkg.isUpdatedSystemApp()) { 9939 // New library entries can only be added through the 9940 // system image. This is important to get rid of a lot 9941 // of nasty edge cases: for example if we allowed a non- 9942 // system update of the app to add a library, then uninstalling 9943 // the update would make the library go away, and assumptions 9944 // we made such as through app install filtering would now 9945 // have allowed apps on the device which aren't compatible 9946 // with it. Better to just have the restriction here, be 9947 // conservative, and create many fewer cases that can negatively 9948 // impact the user experience. 9949 final PackageSetting sysPs = mSettings 9950 .getDisabledSystemPkgLPr(pkg.packageName); 9951 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9952 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9953 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9954 allowed = true; 9955 break; 9956 } 9957 } 9958 } 9959 } else { 9960 allowed = true; 9961 } 9962 if (allowed) { 9963 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9964 SharedLibraryInfo.VERSION_UNDEFINED, 9965 SharedLibraryInfo.TYPE_DYNAMIC, 9966 pkg.packageName, pkg.mVersionCode)) { 9967 Slog.w(TAG, "Package " + pkg.packageName + " library " 9968 + name + " already exists; skipping"); 9969 } 9970 } else { 9971 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9972 + name + " that is not declared on system image; skipping"); 9973 } 9974 } 9975 9976 if ((scanFlags & SCAN_BOOTING) == 0) { 9977 // If we are not booting, we need to update any applications 9978 // that are clients of our shared library. If we are booting, 9979 // this will all be done once the scan is complete. 9980 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9981 } 9982 } 9983 } 9984 } 9985 9986 if ((scanFlags & SCAN_BOOTING) != 0) { 9987 // No apps can run during boot scan, so they don't need to be frozen 9988 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9989 // Caller asked to not kill app, so it's probably not frozen 9990 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9991 // Caller asked us to ignore frozen check for some reason; they 9992 // probably didn't know the package name 9993 } else { 9994 // We're doing major surgery on this package, so it better be frozen 9995 // right now to keep it from launching 9996 checkPackageFrozen(pkgName); 9997 } 9998 9999 // Also need to kill any apps that are dependent on the library. 10000 if (clientLibPkgs != null) { 10001 for (int i=0; i<clientLibPkgs.size(); i++) { 10002 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10003 killApplication(clientPkg.applicationInfo.packageName, 10004 clientPkg.applicationInfo.uid, "update lib"); 10005 } 10006 } 10007 10008 // writer 10009 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10010 10011 synchronized (mPackages) { 10012 // We don't expect installation to fail beyond this point 10013 10014 // Add the new setting to mSettings 10015 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10016 // Add the new setting to mPackages 10017 mPackages.put(pkg.applicationInfo.packageName, pkg); 10018 // Make sure we don't accidentally delete its data. 10019 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10020 while (iter.hasNext()) { 10021 PackageCleanItem item = iter.next(); 10022 if (pkgName.equals(item.packageName)) { 10023 iter.remove(); 10024 } 10025 } 10026 10027 // Add the package's KeySets to the global KeySetManagerService 10028 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10029 ksms.addScannedPackageLPw(pkg); 10030 10031 int N = pkg.providers.size(); 10032 StringBuilder r = null; 10033 int i; 10034 for (i=0; i<N; i++) { 10035 PackageParser.Provider p = pkg.providers.get(i); 10036 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10037 p.info.processName); 10038 mProviders.addProvider(p); 10039 p.syncable = p.info.isSyncable; 10040 if (p.info.authority != null) { 10041 String names[] = p.info.authority.split(";"); 10042 p.info.authority = null; 10043 for (int j = 0; j < names.length; j++) { 10044 if (j == 1 && p.syncable) { 10045 // We only want the first authority for a provider to possibly be 10046 // syncable, so if we already added this provider using a different 10047 // authority clear the syncable flag. We copy the provider before 10048 // changing it because the mProviders object contains a reference 10049 // to a provider that we don't want to change. 10050 // Only do this for the second authority since the resulting provider 10051 // object can be the same for all future authorities for this provider. 10052 p = new PackageParser.Provider(p); 10053 p.syncable = false; 10054 } 10055 if (!mProvidersByAuthority.containsKey(names[j])) { 10056 mProvidersByAuthority.put(names[j], p); 10057 if (p.info.authority == null) { 10058 p.info.authority = names[j]; 10059 } else { 10060 p.info.authority = p.info.authority + ";" + names[j]; 10061 } 10062 if (DEBUG_PACKAGE_SCANNING) { 10063 if (chatty) 10064 Log.d(TAG, "Registered content provider: " + names[j] 10065 + ", className = " + p.info.name + ", isSyncable = " 10066 + p.info.isSyncable); 10067 } 10068 } else { 10069 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10070 Slog.w(TAG, "Skipping provider name " + names[j] + 10071 " (in package " + pkg.applicationInfo.packageName + 10072 "): name already used by " 10073 + ((other != null && other.getComponentName() != null) 10074 ? other.getComponentName().getPackageName() : "?")); 10075 } 10076 } 10077 } 10078 if (chatty) { 10079 if (r == null) { 10080 r = new StringBuilder(256); 10081 } else { 10082 r.append(' '); 10083 } 10084 r.append(p.info.name); 10085 } 10086 } 10087 if (r != null) { 10088 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10089 } 10090 10091 N = pkg.services.size(); 10092 r = null; 10093 for (i=0; i<N; i++) { 10094 PackageParser.Service s = pkg.services.get(i); 10095 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10096 s.info.processName); 10097 mServices.addService(s); 10098 if (chatty) { 10099 if (r == null) { 10100 r = new StringBuilder(256); 10101 } else { 10102 r.append(' '); 10103 } 10104 r.append(s.info.name); 10105 } 10106 } 10107 if (r != null) { 10108 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10109 } 10110 10111 N = pkg.receivers.size(); 10112 r = null; 10113 for (i=0; i<N; i++) { 10114 PackageParser.Activity a = pkg.receivers.get(i); 10115 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10116 a.info.processName); 10117 mReceivers.addActivity(a, "receiver"); 10118 if (chatty) { 10119 if (r == null) { 10120 r = new StringBuilder(256); 10121 } else { 10122 r.append(' '); 10123 } 10124 r.append(a.info.name); 10125 } 10126 } 10127 if (r != null) { 10128 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10129 } 10130 10131 N = pkg.activities.size(); 10132 r = null; 10133 for (i=0; i<N; i++) { 10134 PackageParser.Activity a = pkg.activities.get(i); 10135 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10136 a.info.processName); 10137 mActivities.addActivity(a, "activity"); 10138 if (chatty) { 10139 if (r == null) { 10140 r = new StringBuilder(256); 10141 } else { 10142 r.append(' '); 10143 } 10144 r.append(a.info.name); 10145 } 10146 } 10147 if (r != null) { 10148 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10149 } 10150 10151 N = pkg.permissionGroups.size(); 10152 r = null; 10153 for (i=0; i<N; i++) { 10154 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10155 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10156 final String curPackageName = cur == null ? null : cur.info.packageName; 10157 // Dont allow ephemeral apps to define new permission groups. 10158 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10159 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10160 + pg.info.packageName 10161 + " ignored: instant apps cannot define new permission groups."); 10162 continue; 10163 } 10164 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10165 if (cur == null || isPackageUpdate) { 10166 mPermissionGroups.put(pg.info.name, pg); 10167 if (chatty) { 10168 if (r == null) { 10169 r = new StringBuilder(256); 10170 } else { 10171 r.append(' '); 10172 } 10173 if (isPackageUpdate) { 10174 r.append("UPD:"); 10175 } 10176 r.append(pg.info.name); 10177 } 10178 } else { 10179 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10180 + pg.info.packageName + " ignored: original from " 10181 + cur.info.packageName); 10182 if (chatty) { 10183 if (r == null) { 10184 r = new StringBuilder(256); 10185 } else { 10186 r.append(' '); 10187 } 10188 r.append("DUP:"); 10189 r.append(pg.info.name); 10190 } 10191 } 10192 } 10193 if (r != null) { 10194 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10195 } 10196 10197 N = pkg.permissions.size(); 10198 r = null; 10199 for (i=0; i<N; i++) { 10200 PackageParser.Permission p = pkg.permissions.get(i); 10201 10202 // Dont allow ephemeral apps to define new permissions. 10203 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10204 Slog.w(TAG, "Permission " + p.info.name + " from package " 10205 + p.info.packageName 10206 + " ignored: instant apps cannot define new permissions."); 10207 continue; 10208 } 10209 10210 // Assume by default that we did not install this permission into the system. 10211 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10212 10213 // Now that permission groups have a special meaning, we ignore permission 10214 // groups for legacy apps to prevent unexpected behavior. In particular, 10215 // permissions for one app being granted to someone just becase they happen 10216 // to be in a group defined by another app (before this had no implications). 10217 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10218 p.group = mPermissionGroups.get(p.info.group); 10219 // Warn for a permission in an unknown group. 10220 if (p.info.group != null && p.group == null) { 10221 Slog.w(TAG, "Permission " + p.info.name + " from package " 10222 + p.info.packageName + " in an unknown group " + p.info.group); 10223 } 10224 } 10225 10226 ArrayMap<String, BasePermission> permissionMap = 10227 p.tree ? mSettings.mPermissionTrees 10228 : mSettings.mPermissions; 10229 BasePermission bp = permissionMap.get(p.info.name); 10230 10231 // Allow system apps to redefine non-system permissions 10232 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10233 final boolean currentOwnerIsSystem = (bp.perm != null 10234 && isSystemApp(bp.perm.owner)); 10235 if (isSystemApp(p.owner)) { 10236 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10237 // It's a built-in permission and no owner, take ownership now 10238 bp.packageSetting = pkgSetting; 10239 bp.perm = p; 10240 bp.uid = pkg.applicationInfo.uid; 10241 bp.sourcePackage = p.info.packageName; 10242 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10243 } else if (!currentOwnerIsSystem) { 10244 String msg = "New decl " + p.owner + " of permission " 10245 + p.info.name + " is system; overriding " + bp.sourcePackage; 10246 reportSettingsProblem(Log.WARN, msg); 10247 bp = null; 10248 } 10249 } 10250 } 10251 10252 if (bp == null) { 10253 bp = new BasePermission(p.info.name, p.info.packageName, 10254 BasePermission.TYPE_NORMAL); 10255 permissionMap.put(p.info.name, bp); 10256 } 10257 10258 if (bp.perm == null) { 10259 if (bp.sourcePackage == null 10260 || bp.sourcePackage.equals(p.info.packageName)) { 10261 BasePermission tree = findPermissionTreeLP(p.info.name); 10262 if (tree == null 10263 || tree.sourcePackage.equals(p.info.packageName)) { 10264 bp.packageSetting = pkgSetting; 10265 bp.perm = p; 10266 bp.uid = pkg.applicationInfo.uid; 10267 bp.sourcePackage = p.info.packageName; 10268 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10269 if (chatty) { 10270 if (r == null) { 10271 r = new StringBuilder(256); 10272 } else { 10273 r.append(' '); 10274 } 10275 r.append(p.info.name); 10276 } 10277 } else { 10278 Slog.w(TAG, "Permission " + p.info.name + " from package " 10279 + p.info.packageName + " ignored: base tree " 10280 + tree.name + " is from package " 10281 + tree.sourcePackage); 10282 } 10283 } else { 10284 Slog.w(TAG, "Permission " + p.info.name + " from package " 10285 + p.info.packageName + " ignored: original from " 10286 + bp.sourcePackage); 10287 } 10288 } else if (chatty) { 10289 if (r == null) { 10290 r = new StringBuilder(256); 10291 } else { 10292 r.append(' '); 10293 } 10294 r.append("DUP:"); 10295 r.append(p.info.name); 10296 } 10297 if (bp.perm == p) { 10298 bp.protectionLevel = p.info.protectionLevel; 10299 } 10300 } 10301 10302 if (r != null) { 10303 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10304 } 10305 10306 N = pkg.instrumentation.size(); 10307 r = null; 10308 for (i=0; i<N; i++) { 10309 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10310 a.info.packageName = pkg.applicationInfo.packageName; 10311 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10312 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10313 a.info.splitNames = pkg.splitNames; 10314 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10315 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10316 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10317 a.info.dataDir = pkg.applicationInfo.dataDir; 10318 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10319 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10320 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10321 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10322 mInstrumentation.put(a.getComponentName(), a); 10323 if (chatty) { 10324 if (r == null) { 10325 r = new StringBuilder(256); 10326 } else { 10327 r.append(' '); 10328 } 10329 r.append(a.info.name); 10330 } 10331 } 10332 if (r != null) { 10333 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10334 } 10335 10336 if (pkg.protectedBroadcasts != null) { 10337 N = pkg.protectedBroadcasts.size(); 10338 for (i=0; i<N; i++) { 10339 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10340 } 10341 } 10342 } 10343 10344 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10345 } 10346 10347 /** 10348 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10349 * is derived purely on the basis of the contents of {@code scanFile} and 10350 * {@code cpuAbiOverride}. 10351 * 10352 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10353 */ 10354 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10355 String cpuAbiOverride, boolean extractLibs, 10356 File appLib32InstallDir) 10357 throws PackageManagerException { 10358 // Give ourselves some initial paths; we'll come back for another 10359 // pass once we've determined ABI below. 10360 setNativeLibraryPaths(pkg, appLib32InstallDir); 10361 10362 // We would never need to extract libs for forward-locked and external packages, 10363 // since the container service will do it for us. We shouldn't attempt to 10364 // extract libs from system app when it was not updated. 10365 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10366 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10367 extractLibs = false; 10368 } 10369 10370 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10371 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10372 10373 NativeLibraryHelper.Handle handle = null; 10374 try { 10375 handle = NativeLibraryHelper.Handle.create(pkg); 10376 // TODO(multiArch): This can be null for apps that didn't go through the 10377 // usual installation process. We can calculate it again, like we 10378 // do during install time. 10379 // 10380 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10381 // unnecessary. 10382 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10383 10384 // Null out the abis so that they can be recalculated. 10385 pkg.applicationInfo.primaryCpuAbi = null; 10386 pkg.applicationInfo.secondaryCpuAbi = null; 10387 if (isMultiArch(pkg.applicationInfo)) { 10388 // Warn if we've set an abiOverride for multi-lib packages.. 10389 // By definition, we need to copy both 32 and 64 bit libraries for 10390 // such packages. 10391 if (pkg.cpuAbiOverride != null 10392 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10393 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10394 } 10395 10396 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10397 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10398 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10399 if (extractLibs) { 10400 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10401 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10402 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10403 useIsaSpecificSubdirs); 10404 } else { 10405 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10406 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10407 } 10408 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10409 } 10410 10411 maybeThrowExceptionForMultiArchCopy( 10412 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10413 10414 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10415 if (extractLibs) { 10416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10417 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10418 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10419 useIsaSpecificSubdirs); 10420 } else { 10421 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10422 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10423 } 10424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10425 } 10426 10427 maybeThrowExceptionForMultiArchCopy( 10428 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10429 10430 if (abi64 >= 0) { 10431 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10432 } 10433 10434 if (abi32 >= 0) { 10435 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10436 if (abi64 >= 0) { 10437 if (pkg.use32bitAbi) { 10438 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10439 pkg.applicationInfo.primaryCpuAbi = abi; 10440 } else { 10441 pkg.applicationInfo.secondaryCpuAbi = abi; 10442 } 10443 } else { 10444 pkg.applicationInfo.primaryCpuAbi = abi; 10445 } 10446 } 10447 10448 } else { 10449 String[] abiList = (cpuAbiOverride != null) ? 10450 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10451 10452 // Enable gross and lame hacks for apps that are built with old 10453 // SDK tools. We must scan their APKs for renderscript bitcode and 10454 // not launch them if it's present. Don't bother checking on devices 10455 // that don't have 64 bit support. 10456 boolean needsRenderScriptOverride = false; 10457 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10458 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10459 abiList = Build.SUPPORTED_32_BIT_ABIS; 10460 needsRenderScriptOverride = true; 10461 } 10462 10463 final int copyRet; 10464 if (extractLibs) { 10465 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10466 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10467 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10468 } else { 10469 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10470 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10471 } 10472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10473 10474 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10475 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10476 "Error unpackaging native libs for app, errorCode=" + copyRet); 10477 } 10478 10479 if (copyRet >= 0) { 10480 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10481 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10482 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10483 } else if (needsRenderScriptOverride) { 10484 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10485 } 10486 } 10487 } catch (IOException ioe) { 10488 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10489 } finally { 10490 IoUtils.closeQuietly(handle); 10491 } 10492 10493 // Now that we've calculated the ABIs and determined if it's an internal app, 10494 // we will go ahead and populate the nativeLibraryPath. 10495 setNativeLibraryPaths(pkg, appLib32InstallDir); 10496 } 10497 10498 /** 10499 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10500 * i.e, so that all packages can be run inside a single process if required. 10501 * 10502 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10503 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10504 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10505 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10506 * updating a package that belongs to a shared user. 10507 * 10508 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10509 * adds unnecessary complexity. 10510 */ 10511 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10512 PackageParser.Package scannedPackage) { 10513 String requiredInstructionSet = null; 10514 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10515 requiredInstructionSet = VMRuntime.getInstructionSet( 10516 scannedPackage.applicationInfo.primaryCpuAbi); 10517 } 10518 10519 PackageSetting requirer = null; 10520 for (PackageSetting ps : packagesForUser) { 10521 // If packagesForUser contains scannedPackage, we skip it. This will happen 10522 // when scannedPackage is an update of an existing package. Without this check, 10523 // we will never be able to change the ABI of any package belonging to a shared 10524 // user, even if it's compatible with other packages. 10525 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10526 if (ps.primaryCpuAbiString == null) { 10527 continue; 10528 } 10529 10530 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10531 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10532 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10533 // this but there's not much we can do. 10534 String errorMessage = "Instruction set mismatch, " 10535 + ((requirer == null) ? "[caller]" : requirer) 10536 + " requires " + requiredInstructionSet + " whereas " + ps 10537 + " requires " + instructionSet; 10538 Slog.w(TAG, errorMessage); 10539 } 10540 10541 if (requiredInstructionSet == null) { 10542 requiredInstructionSet = instructionSet; 10543 requirer = ps; 10544 } 10545 } 10546 } 10547 10548 if (requiredInstructionSet != null) { 10549 String adjustedAbi; 10550 if (requirer != null) { 10551 // requirer != null implies that either scannedPackage was null or that scannedPackage 10552 // did not require an ABI, in which case we have to adjust scannedPackage to match 10553 // the ABI of the set (which is the same as requirer's ABI) 10554 adjustedAbi = requirer.primaryCpuAbiString; 10555 if (scannedPackage != null) { 10556 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10557 } 10558 } else { 10559 // requirer == null implies that we're updating all ABIs in the set to 10560 // match scannedPackage. 10561 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10562 } 10563 10564 for (PackageSetting ps : packagesForUser) { 10565 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10566 if (ps.primaryCpuAbiString != null) { 10567 continue; 10568 } 10569 10570 ps.primaryCpuAbiString = adjustedAbi; 10571 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10572 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10573 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10574 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10575 + " (requirer=" 10576 + (requirer != null ? requirer.pkg : "null") 10577 + ", scannedPackage=" 10578 + (scannedPackage != null ? scannedPackage : "null") 10579 + ")"); 10580 try { 10581 mInstaller.rmdex(ps.codePathString, 10582 getDexCodeInstructionSet(getPreferredInstructionSet())); 10583 } catch (InstallerException ignored) { 10584 } 10585 } 10586 } 10587 } 10588 } 10589 } 10590 10591 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10592 synchronized (mPackages) { 10593 mResolverReplaced = true; 10594 // Set up information for custom user intent resolution activity. 10595 mResolveActivity.applicationInfo = pkg.applicationInfo; 10596 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10597 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10598 mResolveActivity.processName = pkg.applicationInfo.packageName; 10599 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10600 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10601 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10602 mResolveActivity.theme = 0; 10603 mResolveActivity.exported = true; 10604 mResolveActivity.enabled = true; 10605 mResolveInfo.activityInfo = mResolveActivity; 10606 mResolveInfo.priority = 0; 10607 mResolveInfo.preferredOrder = 0; 10608 mResolveInfo.match = 0; 10609 mResolveComponentName = mCustomResolverComponentName; 10610 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10611 mResolveComponentName); 10612 } 10613 } 10614 10615 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10616 if (installerComponent == null) { 10617 if (DEBUG_EPHEMERAL) { 10618 Slog.d(TAG, "Clear ephemeral installer activity"); 10619 } 10620 mInstantAppInstallerActivity.applicationInfo = null; 10621 return; 10622 } 10623 10624 if (DEBUG_EPHEMERAL) { 10625 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10626 } 10627 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10628 // Set up information for ephemeral installer activity 10629 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10630 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10631 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10632 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10633 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10634 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10635 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10636 mInstantAppInstallerActivity.theme = 0; 10637 mInstantAppInstallerActivity.exported = true; 10638 mInstantAppInstallerActivity.enabled = true; 10639 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10640 mInstantAppInstallerInfo.priority = 0; 10641 mInstantAppInstallerInfo.preferredOrder = 1; 10642 mInstantAppInstallerInfo.isDefault = true; 10643 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10644 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10645 } 10646 10647 private static String calculateBundledApkRoot(final String codePathString) { 10648 final File codePath = new File(codePathString); 10649 final File codeRoot; 10650 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10651 codeRoot = Environment.getRootDirectory(); 10652 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10653 codeRoot = Environment.getOemDirectory(); 10654 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10655 codeRoot = Environment.getVendorDirectory(); 10656 } else { 10657 // Unrecognized code path; take its top real segment as the apk root: 10658 // e.g. /something/app/blah.apk => /something 10659 try { 10660 File f = codePath.getCanonicalFile(); 10661 File parent = f.getParentFile(); // non-null because codePath is a file 10662 File tmp; 10663 while ((tmp = parent.getParentFile()) != null) { 10664 f = parent; 10665 parent = tmp; 10666 } 10667 codeRoot = f; 10668 Slog.w(TAG, "Unrecognized code path " 10669 + codePath + " - using " + codeRoot); 10670 } catch (IOException e) { 10671 // Can't canonicalize the code path -- shenanigans? 10672 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10673 return Environment.getRootDirectory().getPath(); 10674 } 10675 } 10676 return codeRoot.getPath(); 10677 } 10678 10679 /** 10680 * Derive and set the location of native libraries for the given package, 10681 * which varies depending on where and how the package was installed. 10682 */ 10683 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10684 final ApplicationInfo info = pkg.applicationInfo; 10685 final String codePath = pkg.codePath; 10686 final File codeFile = new File(codePath); 10687 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10688 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10689 10690 info.nativeLibraryRootDir = null; 10691 info.nativeLibraryRootRequiresIsa = false; 10692 info.nativeLibraryDir = null; 10693 info.secondaryNativeLibraryDir = null; 10694 10695 if (isApkFile(codeFile)) { 10696 // Monolithic install 10697 if (bundledApp) { 10698 // If "/system/lib64/apkname" exists, assume that is the per-package 10699 // native library directory to use; otherwise use "/system/lib/apkname". 10700 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10701 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10702 getPrimaryInstructionSet(info)); 10703 10704 // This is a bundled system app so choose the path based on the ABI. 10705 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10706 // is just the default path. 10707 final String apkName = deriveCodePathName(codePath); 10708 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10709 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10710 apkName).getAbsolutePath(); 10711 10712 if (info.secondaryCpuAbi != null) { 10713 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10714 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10715 secondaryLibDir, apkName).getAbsolutePath(); 10716 } 10717 } else if (asecApp) { 10718 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10719 .getAbsolutePath(); 10720 } else { 10721 final String apkName = deriveCodePathName(codePath); 10722 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10723 .getAbsolutePath(); 10724 } 10725 10726 info.nativeLibraryRootRequiresIsa = false; 10727 info.nativeLibraryDir = info.nativeLibraryRootDir; 10728 } else { 10729 // Cluster install 10730 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10731 info.nativeLibraryRootRequiresIsa = true; 10732 10733 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10734 getPrimaryInstructionSet(info)).getAbsolutePath(); 10735 10736 if (info.secondaryCpuAbi != null) { 10737 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10738 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10739 } 10740 } 10741 } 10742 10743 /** 10744 * Calculate the abis and roots for a bundled app. These can uniquely 10745 * be determined from the contents of the system partition, i.e whether 10746 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10747 * of this information, and instead assume that the system was built 10748 * sensibly. 10749 */ 10750 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10751 PackageSetting pkgSetting) { 10752 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10753 10754 // If "/system/lib64/apkname" exists, assume that is the per-package 10755 // native library directory to use; otherwise use "/system/lib/apkname". 10756 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10757 setBundledAppAbi(pkg, apkRoot, apkName); 10758 // pkgSetting might be null during rescan following uninstall of updates 10759 // to a bundled app, so accommodate that possibility. The settings in 10760 // that case will be established later from the parsed package. 10761 // 10762 // If the settings aren't null, sync them up with what we've just derived. 10763 // note that apkRoot isn't stored in the package settings. 10764 if (pkgSetting != null) { 10765 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10766 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10767 } 10768 } 10769 10770 /** 10771 * Deduces the ABI of a bundled app and sets the relevant fields on the 10772 * parsed pkg object. 10773 * 10774 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10775 * under which system libraries are installed. 10776 * @param apkName the name of the installed package. 10777 */ 10778 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10779 final File codeFile = new File(pkg.codePath); 10780 10781 final boolean has64BitLibs; 10782 final boolean has32BitLibs; 10783 if (isApkFile(codeFile)) { 10784 // Monolithic install 10785 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10786 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10787 } else { 10788 // Cluster install 10789 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10790 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10791 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10792 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10793 has64BitLibs = (new File(rootDir, isa)).exists(); 10794 } else { 10795 has64BitLibs = false; 10796 } 10797 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10798 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10799 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10800 has32BitLibs = (new File(rootDir, isa)).exists(); 10801 } else { 10802 has32BitLibs = false; 10803 } 10804 } 10805 10806 if (has64BitLibs && !has32BitLibs) { 10807 // The package has 64 bit libs, but not 32 bit libs. Its primary 10808 // ABI should be 64 bit. We can safely assume here that the bundled 10809 // native libraries correspond to the most preferred ABI in the list. 10810 10811 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10812 pkg.applicationInfo.secondaryCpuAbi = null; 10813 } else if (has32BitLibs && !has64BitLibs) { 10814 // The package has 32 bit libs but not 64 bit libs. Its primary 10815 // ABI should be 32 bit. 10816 10817 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10818 pkg.applicationInfo.secondaryCpuAbi = null; 10819 } else if (has32BitLibs && has64BitLibs) { 10820 // The application has both 64 and 32 bit bundled libraries. We check 10821 // here that the app declares multiArch support, and warn if it doesn't. 10822 // 10823 // We will be lenient here and record both ABIs. The primary will be the 10824 // ABI that's higher on the list, i.e, a device that's configured to prefer 10825 // 64 bit apps will see a 64 bit primary ABI, 10826 10827 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10828 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10829 } 10830 10831 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10832 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10833 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10834 } else { 10835 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10836 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10837 } 10838 } else { 10839 pkg.applicationInfo.primaryCpuAbi = null; 10840 pkg.applicationInfo.secondaryCpuAbi = null; 10841 } 10842 } 10843 10844 private void killApplication(String pkgName, int appId, String reason) { 10845 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10846 } 10847 10848 private void killApplication(String pkgName, int appId, int userId, String reason) { 10849 // Request the ActivityManager to kill the process(only for existing packages) 10850 // so that we do not end up in a confused state while the user is still using the older 10851 // version of the application while the new one gets installed. 10852 final long token = Binder.clearCallingIdentity(); 10853 try { 10854 IActivityManager am = ActivityManager.getService(); 10855 if (am != null) { 10856 try { 10857 am.killApplication(pkgName, appId, userId, reason); 10858 } catch (RemoteException e) { 10859 } 10860 } 10861 } finally { 10862 Binder.restoreCallingIdentity(token); 10863 } 10864 } 10865 10866 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10867 // Remove the parent package setting 10868 PackageSetting ps = (PackageSetting) pkg.mExtras; 10869 if (ps != null) { 10870 removePackageLI(ps, chatty); 10871 } 10872 // Remove the child package setting 10873 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10874 for (int i = 0; i < childCount; i++) { 10875 PackageParser.Package childPkg = pkg.childPackages.get(i); 10876 ps = (PackageSetting) childPkg.mExtras; 10877 if (ps != null) { 10878 removePackageLI(ps, chatty); 10879 } 10880 } 10881 } 10882 10883 void removePackageLI(PackageSetting ps, boolean chatty) { 10884 if (DEBUG_INSTALL) { 10885 if (chatty) 10886 Log.d(TAG, "Removing package " + ps.name); 10887 } 10888 10889 // writer 10890 synchronized (mPackages) { 10891 mPackages.remove(ps.name); 10892 final PackageParser.Package pkg = ps.pkg; 10893 if (pkg != null) { 10894 cleanPackageDataStructuresLILPw(pkg, chatty); 10895 } 10896 } 10897 } 10898 10899 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10900 if (DEBUG_INSTALL) { 10901 if (chatty) 10902 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10903 } 10904 10905 // writer 10906 synchronized (mPackages) { 10907 // Remove the parent package 10908 mPackages.remove(pkg.applicationInfo.packageName); 10909 cleanPackageDataStructuresLILPw(pkg, chatty); 10910 10911 // Remove the child packages 10912 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10913 for (int i = 0; i < childCount; i++) { 10914 PackageParser.Package childPkg = pkg.childPackages.get(i); 10915 mPackages.remove(childPkg.applicationInfo.packageName); 10916 cleanPackageDataStructuresLILPw(childPkg, chatty); 10917 } 10918 } 10919 } 10920 10921 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10922 int N = pkg.providers.size(); 10923 StringBuilder r = null; 10924 int i; 10925 for (i=0; i<N; i++) { 10926 PackageParser.Provider p = pkg.providers.get(i); 10927 mProviders.removeProvider(p); 10928 if (p.info.authority == null) { 10929 10930 /* There was another ContentProvider with this authority when 10931 * this app was installed so this authority is null, 10932 * Ignore it as we don't have to unregister the provider. 10933 */ 10934 continue; 10935 } 10936 String names[] = p.info.authority.split(";"); 10937 for (int j = 0; j < names.length; j++) { 10938 if (mProvidersByAuthority.get(names[j]) == p) { 10939 mProvidersByAuthority.remove(names[j]); 10940 if (DEBUG_REMOVE) { 10941 if (chatty) 10942 Log.d(TAG, "Unregistered content provider: " + names[j] 10943 + ", className = " + p.info.name + ", isSyncable = " 10944 + p.info.isSyncable); 10945 } 10946 } 10947 } 10948 if (DEBUG_REMOVE && chatty) { 10949 if (r == null) { 10950 r = new StringBuilder(256); 10951 } else { 10952 r.append(' '); 10953 } 10954 r.append(p.info.name); 10955 } 10956 } 10957 if (r != null) { 10958 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10959 } 10960 10961 N = pkg.services.size(); 10962 r = null; 10963 for (i=0; i<N; i++) { 10964 PackageParser.Service s = pkg.services.get(i); 10965 mServices.removeService(s); 10966 if (chatty) { 10967 if (r == null) { 10968 r = new StringBuilder(256); 10969 } else { 10970 r.append(' '); 10971 } 10972 r.append(s.info.name); 10973 } 10974 } 10975 if (r != null) { 10976 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10977 } 10978 10979 N = pkg.receivers.size(); 10980 r = null; 10981 for (i=0; i<N; i++) { 10982 PackageParser.Activity a = pkg.receivers.get(i); 10983 mReceivers.removeActivity(a, "receiver"); 10984 if (DEBUG_REMOVE && chatty) { 10985 if (r == null) { 10986 r = new StringBuilder(256); 10987 } else { 10988 r.append(' '); 10989 } 10990 r.append(a.info.name); 10991 } 10992 } 10993 if (r != null) { 10994 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10995 } 10996 10997 N = pkg.activities.size(); 10998 r = null; 10999 for (i=0; i<N; i++) { 11000 PackageParser.Activity a = pkg.activities.get(i); 11001 mActivities.removeActivity(a, "activity"); 11002 if (DEBUG_REMOVE && chatty) { 11003 if (r == null) { 11004 r = new StringBuilder(256); 11005 } else { 11006 r.append(' '); 11007 } 11008 r.append(a.info.name); 11009 } 11010 } 11011 if (r != null) { 11012 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11013 } 11014 11015 N = pkg.permissions.size(); 11016 r = null; 11017 for (i=0; i<N; i++) { 11018 PackageParser.Permission p = pkg.permissions.get(i); 11019 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11020 if (bp == null) { 11021 bp = mSettings.mPermissionTrees.get(p.info.name); 11022 } 11023 if (bp != null && bp.perm == p) { 11024 bp.perm = null; 11025 if (DEBUG_REMOVE && chatty) { 11026 if (r == null) { 11027 r = new StringBuilder(256); 11028 } else { 11029 r.append(' '); 11030 } 11031 r.append(p.info.name); 11032 } 11033 } 11034 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11035 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11036 if (appOpPkgs != null) { 11037 appOpPkgs.remove(pkg.packageName); 11038 } 11039 } 11040 } 11041 if (r != null) { 11042 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11043 } 11044 11045 N = pkg.requestedPermissions.size(); 11046 r = null; 11047 for (i=0; i<N; i++) { 11048 String perm = pkg.requestedPermissions.get(i); 11049 BasePermission bp = mSettings.mPermissions.get(perm); 11050 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11051 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11052 if (appOpPkgs != null) { 11053 appOpPkgs.remove(pkg.packageName); 11054 if (appOpPkgs.isEmpty()) { 11055 mAppOpPermissionPackages.remove(perm); 11056 } 11057 } 11058 } 11059 } 11060 if (r != null) { 11061 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11062 } 11063 11064 N = pkg.instrumentation.size(); 11065 r = null; 11066 for (i=0; i<N; i++) { 11067 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11068 mInstrumentation.remove(a.getComponentName()); 11069 if (DEBUG_REMOVE && chatty) { 11070 if (r == null) { 11071 r = new StringBuilder(256); 11072 } else { 11073 r.append(' '); 11074 } 11075 r.append(a.info.name); 11076 } 11077 } 11078 if (r != null) { 11079 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11080 } 11081 11082 r = null; 11083 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11084 // Only system apps can hold shared libraries. 11085 if (pkg.libraryNames != null) { 11086 for (i = 0; i < pkg.libraryNames.size(); i++) { 11087 String name = pkg.libraryNames.get(i); 11088 if (removeSharedLibraryLPw(name, 0)) { 11089 if (DEBUG_REMOVE && chatty) { 11090 if (r == null) { 11091 r = new StringBuilder(256); 11092 } else { 11093 r.append(' '); 11094 } 11095 r.append(name); 11096 } 11097 } 11098 } 11099 } 11100 } 11101 11102 r = null; 11103 11104 // Any package can hold static shared libraries. 11105 if (pkg.staticSharedLibName != null) { 11106 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11107 if (DEBUG_REMOVE && chatty) { 11108 if (r == null) { 11109 r = new StringBuilder(256); 11110 } else { 11111 r.append(' '); 11112 } 11113 r.append(pkg.staticSharedLibName); 11114 } 11115 } 11116 } 11117 11118 if (r != null) { 11119 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11120 } 11121 } 11122 11123 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11124 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11125 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11126 return true; 11127 } 11128 } 11129 return false; 11130 } 11131 11132 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11133 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11134 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11135 11136 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11137 // Update the parent permissions 11138 updatePermissionsLPw(pkg.packageName, pkg, flags); 11139 // Update the child permissions 11140 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11141 for (int i = 0; i < childCount; i++) { 11142 PackageParser.Package childPkg = pkg.childPackages.get(i); 11143 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11144 } 11145 } 11146 11147 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11148 int flags) { 11149 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11150 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11151 } 11152 11153 private void updatePermissionsLPw(String changingPkg, 11154 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11155 // Make sure there are no dangling permission trees. 11156 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11157 while (it.hasNext()) { 11158 final BasePermission bp = it.next(); 11159 if (bp.packageSetting == null) { 11160 // We may not yet have parsed the package, so just see if 11161 // we still know about its settings. 11162 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11163 } 11164 if (bp.packageSetting == null) { 11165 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11166 + " from package " + bp.sourcePackage); 11167 it.remove(); 11168 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11169 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11170 Slog.i(TAG, "Removing old permission tree: " + bp.name 11171 + " from package " + bp.sourcePackage); 11172 flags |= UPDATE_PERMISSIONS_ALL; 11173 it.remove(); 11174 } 11175 } 11176 } 11177 11178 // Make sure all dynamic permissions have been assigned to a package, 11179 // and make sure there are no dangling permissions. 11180 it = mSettings.mPermissions.values().iterator(); 11181 while (it.hasNext()) { 11182 final BasePermission bp = it.next(); 11183 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11184 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11185 + bp.name + " pkg=" + bp.sourcePackage 11186 + " info=" + bp.pendingInfo); 11187 if (bp.packageSetting == null && bp.pendingInfo != null) { 11188 final BasePermission tree = findPermissionTreeLP(bp.name); 11189 if (tree != null && tree.perm != null) { 11190 bp.packageSetting = tree.packageSetting; 11191 bp.perm = new PackageParser.Permission(tree.perm.owner, 11192 new PermissionInfo(bp.pendingInfo)); 11193 bp.perm.info.packageName = tree.perm.info.packageName; 11194 bp.perm.info.name = bp.name; 11195 bp.uid = tree.uid; 11196 } 11197 } 11198 } 11199 if (bp.packageSetting == null) { 11200 // We may not yet have parsed the package, so just see if 11201 // we still know about its settings. 11202 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11203 } 11204 if (bp.packageSetting == null) { 11205 Slog.w(TAG, "Removing dangling permission: " + bp.name 11206 + " from package " + bp.sourcePackage); 11207 it.remove(); 11208 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11209 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11210 Slog.i(TAG, "Removing old permission: " + bp.name 11211 + " from package " + bp.sourcePackage); 11212 flags |= UPDATE_PERMISSIONS_ALL; 11213 it.remove(); 11214 } 11215 } 11216 } 11217 11218 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11219 // Now update the permissions for all packages, in particular 11220 // replace the granted permissions of the system packages. 11221 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11222 for (PackageParser.Package pkg : mPackages.values()) { 11223 if (pkg != pkgInfo) { 11224 // Only replace for packages on requested volume 11225 final String volumeUuid = getVolumeUuidForPackage(pkg); 11226 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11227 && Objects.equals(replaceVolumeUuid, volumeUuid); 11228 grantPermissionsLPw(pkg, replace, changingPkg); 11229 } 11230 } 11231 } 11232 11233 if (pkgInfo != null) { 11234 // Only replace for packages on requested volume 11235 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11236 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11237 && Objects.equals(replaceVolumeUuid, volumeUuid); 11238 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11239 } 11240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11241 } 11242 11243 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11244 String packageOfInterest) { 11245 // IMPORTANT: There are two types of permissions: install and runtime. 11246 // Install time permissions are granted when the app is installed to 11247 // all device users and users added in the future. Runtime permissions 11248 // are granted at runtime explicitly to specific users. Normal and signature 11249 // protected permissions are install time permissions. Dangerous permissions 11250 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11251 // otherwise they are runtime permissions. This function does not manage 11252 // runtime permissions except for the case an app targeting Lollipop MR1 11253 // being upgraded to target a newer SDK, in which case dangerous permissions 11254 // are transformed from install time to runtime ones. 11255 11256 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11257 if (ps == null) { 11258 return; 11259 } 11260 11261 PermissionsState permissionsState = ps.getPermissionsState(); 11262 PermissionsState origPermissions = permissionsState; 11263 11264 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11265 11266 boolean runtimePermissionsRevoked = false; 11267 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11268 11269 boolean changedInstallPermission = false; 11270 11271 if (replace) { 11272 ps.installPermissionsFixed = false; 11273 if (!ps.isSharedUser()) { 11274 origPermissions = new PermissionsState(permissionsState); 11275 permissionsState.reset(); 11276 } else { 11277 // We need to know only about runtime permission changes since the 11278 // calling code always writes the install permissions state but 11279 // the runtime ones are written only if changed. The only cases of 11280 // changed runtime permissions here are promotion of an install to 11281 // runtime and revocation of a runtime from a shared user. 11282 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11283 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11284 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11285 runtimePermissionsRevoked = true; 11286 } 11287 } 11288 } 11289 11290 permissionsState.setGlobalGids(mGlobalGids); 11291 11292 final int N = pkg.requestedPermissions.size(); 11293 for (int i=0; i<N; i++) { 11294 final String name = pkg.requestedPermissions.get(i); 11295 final BasePermission bp = mSettings.mPermissions.get(name); 11296 11297 if (DEBUG_INSTALL) { 11298 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11299 } 11300 11301 if (bp == null || bp.packageSetting == null) { 11302 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11303 Slog.w(TAG, "Unknown permission " + name 11304 + " in package " + pkg.packageName); 11305 } 11306 continue; 11307 } 11308 11309 11310 // Limit ephemeral apps to ephemeral allowed permissions. 11311 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11312 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11313 + pkg.packageName); 11314 continue; 11315 } 11316 11317 final String perm = bp.name; 11318 boolean allowedSig = false; 11319 int grant = GRANT_DENIED; 11320 11321 // Keep track of app op permissions. 11322 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11323 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11324 if (pkgs == null) { 11325 pkgs = new ArraySet<>(); 11326 mAppOpPermissionPackages.put(bp.name, pkgs); 11327 } 11328 pkgs.add(pkg.packageName); 11329 } 11330 11331 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11332 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11333 >= Build.VERSION_CODES.M; 11334 switch (level) { 11335 case PermissionInfo.PROTECTION_NORMAL: { 11336 // For all apps normal permissions are install time ones. 11337 grant = GRANT_INSTALL; 11338 } break; 11339 11340 case PermissionInfo.PROTECTION_DANGEROUS: { 11341 // If a permission review is required for legacy apps we represent 11342 // their permissions as always granted runtime ones since we need 11343 // to keep the review required permission flag per user while an 11344 // install permission's state is shared across all users. 11345 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11346 // For legacy apps dangerous permissions are install time ones. 11347 grant = GRANT_INSTALL; 11348 } else if (origPermissions.hasInstallPermission(bp.name)) { 11349 // For legacy apps that became modern, install becomes runtime. 11350 grant = GRANT_UPGRADE; 11351 } else if (mPromoteSystemApps 11352 && isSystemApp(ps) 11353 && mExistingSystemPackages.contains(ps.name)) { 11354 // For legacy system apps, install becomes runtime. 11355 // We cannot check hasInstallPermission() for system apps since those 11356 // permissions were granted implicitly and not persisted pre-M. 11357 grant = GRANT_UPGRADE; 11358 } else { 11359 // For modern apps keep runtime permissions unchanged. 11360 grant = GRANT_RUNTIME; 11361 } 11362 } break; 11363 11364 case PermissionInfo.PROTECTION_SIGNATURE: { 11365 // For all apps signature permissions are install time ones. 11366 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11367 if (allowedSig) { 11368 grant = GRANT_INSTALL; 11369 } 11370 } break; 11371 } 11372 11373 if (DEBUG_INSTALL) { 11374 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11375 } 11376 11377 if (grant != GRANT_DENIED) { 11378 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11379 // If this is an existing, non-system package, then 11380 // we can't add any new permissions to it. 11381 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11382 // Except... if this is a permission that was added 11383 // to the platform (note: need to only do this when 11384 // updating the platform). 11385 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11386 grant = GRANT_DENIED; 11387 } 11388 } 11389 } 11390 11391 switch (grant) { 11392 case GRANT_INSTALL: { 11393 // Revoke this as runtime permission to handle the case of 11394 // a runtime permission being downgraded to an install one. 11395 // Also in permission review mode we keep dangerous permissions 11396 // for legacy apps 11397 for (int userId : UserManagerService.getInstance().getUserIds()) { 11398 if (origPermissions.getRuntimePermissionState( 11399 bp.name, userId) != null) { 11400 // Revoke the runtime permission and clear the flags. 11401 origPermissions.revokeRuntimePermission(bp, userId); 11402 origPermissions.updatePermissionFlags(bp, userId, 11403 PackageManager.MASK_PERMISSION_FLAGS, 0); 11404 // If we revoked a permission permission, we have to write. 11405 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11406 changedRuntimePermissionUserIds, userId); 11407 } 11408 } 11409 // Grant an install permission. 11410 if (permissionsState.grantInstallPermission(bp) != 11411 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11412 changedInstallPermission = true; 11413 } 11414 } break; 11415 11416 case GRANT_RUNTIME: { 11417 // Grant previously granted runtime permissions. 11418 for (int userId : UserManagerService.getInstance().getUserIds()) { 11419 PermissionState permissionState = origPermissions 11420 .getRuntimePermissionState(bp.name, userId); 11421 int flags = permissionState != null 11422 ? permissionState.getFlags() : 0; 11423 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11424 // Don't propagate the permission in a permission review mode if 11425 // the former was revoked, i.e. marked to not propagate on upgrade. 11426 // Note that in a permission review mode install permissions are 11427 // represented as constantly granted runtime ones since we need to 11428 // keep a per user state associated with the permission. Also the 11429 // revoke on upgrade flag is no longer applicable and is reset. 11430 final boolean revokeOnUpgrade = (flags & PackageManager 11431 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11432 if (revokeOnUpgrade) { 11433 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11434 // Since we changed the flags, we have to write. 11435 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11436 changedRuntimePermissionUserIds, userId); 11437 } 11438 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11439 if (permissionsState.grantRuntimePermission(bp, userId) == 11440 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11441 // If we cannot put the permission as it was, 11442 // we have to write. 11443 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11444 changedRuntimePermissionUserIds, userId); 11445 } 11446 } 11447 11448 // If the app supports runtime permissions no need for a review. 11449 if (mPermissionReviewRequired 11450 && appSupportsRuntimePermissions 11451 && (flags & PackageManager 11452 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11453 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11454 // Since we changed the flags, we have to write. 11455 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11456 changedRuntimePermissionUserIds, userId); 11457 } 11458 } else if (mPermissionReviewRequired 11459 && !appSupportsRuntimePermissions) { 11460 // For legacy apps that need a permission review, every new 11461 // runtime permission is granted but it is pending a review. 11462 // We also need to review only platform defined runtime 11463 // permissions as these are the only ones the platform knows 11464 // how to disable the API to simulate revocation as legacy 11465 // apps don't expect to run with revoked permissions. 11466 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11467 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11468 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11469 // We changed the flags, hence have to write. 11470 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11471 changedRuntimePermissionUserIds, userId); 11472 } 11473 } 11474 if (permissionsState.grantRuntimePermission(bp, userId) 11475 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11476 // We changed the permission, hence have to write. 11477 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11478 changedRuntimePermissionUserIds, userId); 11479 } 11480 } 11481 // Propagate the permission flags. 11482 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11483 } 11484 } break; 11485 11486 case GRANT_UPGRADE: { 11487 // Grant runtime permissions for a previously held install permission. 11488 PermissionState permissionState = origPermissions 11489 .getInstallPermissionState(bp.name); 11490 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11491 11492 if (origPermissions.revokeInstallPermission(bp) 11493 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11494 // We will be transferring the permission flags, so clear them. 11495 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11496 PackageManager.MASK_PERMISSION_FLAGS, 0); 11497 changedInstallPermission = true; 11498 } 11499 11500 // If the permission is not to be promoted to runtime we ignore it and 11501 // also its other flags as they are not applicable to install permissions. 11502 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11503 for (int userId : currentUserIds) { 11504 if (permissionsState.grantRuntimePermission(bp, userId) != 11505 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11506 // Transfer the permission flags. 11507 permissionsState.updatePermissionFlags(bp, userId, 11508 flags, flags); 11509 // If we granted the permission, we have to write. 11510 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11511 changedRuntimePermissionUserIds, userId); 11512 } 11513 } 11514 } 11515 } break; 11516 11517 default: { 11518 if (packageOfInterest == null 11519 || packageOfInterest.equals(pkg.packageName)) { 11520 Slog.w(TAG, "Not granting permission " + perm 11521 + " to package " + pkg.packageName 11522 + " because it was previously installed without"); 11523 } 11524 } break; 11525 } 11526 } else { 11527 if (permissionsState.revokeInstallPermission(bp) != 11528 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11529 // Also drop the permission flags. 11530 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11531 PackageManager.MASK_PERMISSION_FLAGS, 0); 11532 changedInstallPermission = true; 11533 Slog.i(TAG, "Un-granting permission " + perm 11534 + " from package " + pkg.packageName 11535 + " (protectionLevel=" + bp.protectionLevel 11536 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11537 + ")"); 11538 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11539 // Don't print warning for app op permissions, since it is fine for them 11540 // not to be granted, there is a UI for the user to decide. 11541 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11542 Slog.w(TAG, "Not granting permission " + perm 11543 + " to package " + pkg.packageName 11544 + " (protectionLevel=" + bp.protectionLevel 11545 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11546 + ")"); 11547 } 11548 } 11549 } 11550 } 11551 11552 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11553 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11554 // This is the first that we have heard about this package, so the 11555 // permissions we have now selected are fixed until explicitly 11556 // changed. 11557 ps.installPermissionsFixed = true; 11558 } 11559 11560 // Persist the runtime permissions state for users with changes. If permissions 11561 // were revoked because no app in the shared user declares them we have to 11562 // write synchronously to avoid losing runtime permissions state. 11563 for (int userId : changedRuntimePermissionUserIds) { 11564 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11565 } 11566 } 11567 11568 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11569 boolean allowed = false; 11570 final int NP = PackageParser.NEW_PERMISSIONS.length; 11571 for (int ip=0; ip<NP; ip++) { 11572 final PackageParser.NewPermissionInfo npi 11573 = PackageParser.NEW_PERMISSIONS[ip]; 11574 if (npi.name.equals(perm) 11575 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11576 allowed = true; 11577 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11578 + pkg.packageName); 11579 break; 11580 } 11581 } 11582 return allowed; 11583 } 11584 11585 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11586 BasePermission bp, PermissionsState origPermissions) { 11587 boolean privilegedPermission = (bp.protectionLevel 11588 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11589 boolean privappPermissionsDisable = 11590 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11591 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11592 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11593 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11594 && !platformPackage && platformPermission) { 11595 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11596 .getPrivAppPermissions(pkg.packageName); 11597 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11598 if (!whitelisted) { 11599 Slog.w(TAG, "Privileged permission " + perm + " for package " 11600 + pkg.packageName + " - not in privapp-permissions whitelist"); 11601 // Only report violations for apps on system image 11602 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11603 if (mPrivappPermissionsViolations == null) { 11604 mPrivappPermissionsViolations = new ArraySet<>(); 11605 } 11606 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11607 } 11608 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11609 return false; 11610 } 11611 } 11612 } 11613 boolean allowed = (compareSignatures( 11614 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11615 == PackageManager.SIGNATURE_MATCH) 11616 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11617 == PackageManager.SIGNATURE_MATCH); 11618 if (!allowed && privilegedPermission) { 11619 if (isSystemApp(pkg)) { 11620 // For updated system applications, a system permission 11621 // is granted only if it had been defined by the original application. 11622 if (pkg.isUpdatedSystemApp()) { 11623 final PackageSetting sysPs = mSettings 11624 .getDisabledSystemPkgLPr(pkg.packageName); 11625 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11626 // If the original was granted this permission, we take 11627 // that grant decision as read and propagate it to the 11628 // update. 11629 if (sysPs.isPrivileged()) { 11630 allowed = true; 11631 } 11632 } else { 11633 // The system apk may have been updated with an older 11634 // version of the one on the data partition, but which 11635 // granted a new system permission that it didn't have 11636 // before. In this case we do want to allow the app to 11637 // now get the new permission if the ancestral apk is 11638 // privileged to get it. 11639 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11640 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11641 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11642 allowed = true; 11643 break; 11644 } 11645 } 11646 } 11647 // Also if a privileged parent package on the system image or any of 11648 // its children requested a privileged permission, the updated child 11649 // packages can also get the permission. 11650 if (pkg.parentPackage != null) { 11651 final PackageSetting disabledSysParentPs = mSettings 11652 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11653 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11654 && disabledSysParentPs.isPrivileged()) { 11655 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11656 allowed = true; 11657 } else if (disabledSysParentPs.pkg.childPackages != null) { 11658 final int count = disabledSysParentPs.pkg.childPackages.size(); 11659 for (int i = 0; i < count; i++) { 11660 PackageParser.Package disabledSysChildPkg = 11661 disabledSysParentPs.pkg.childPackages.get(i); 11662 if (isPackageRequestingPermission(disabledSysChildPkg, 11663 perm)) { 11664 allowed = true; 11665 break; 11666 } 11667 } 11668 } 11669 } 11670 } 11671 } 11672 } else { 11673 allowed = isPrivilegedApp(pkg); 11674 } 11675 } 11676 } 11677 if (!allowed) { 11678 if (!allowed && (bp.protectionLevel 11679 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11680 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11681 // If this was a previously normal/dangerous permission that got moved 11682 // to a system permission as part of the runtime permission redesign, then 11683 // we still want to blindly grant it to old apps. 11684 allowed = true; 11685 } 11686 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11687 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11688 // If this permission is to be granted to the system installer and 11689 // this app is an installer, then it gets the permission. 11690 allowed = true; 11691 } 11692 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11693 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11694 // If this permission is to be granted to the system verifier and 11695 // this app is a verifier, then it gets the permission. 11696 allowed = true; 11697 } 11698 if (!allowed && (bp.protectionLevel 11699 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11700 && isSystemApp(pkg)) { 11701 // Any pre-installed system app is allowed to get this permission. 11702 allowed = true; 11703 } 11704 if (!allowed && (bp.protectionLevel 11705 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11706 // For development permissions, a development permission 11707 // is granted only if it was already granted. 11708 allowed = origPermissions.hasInstallPermission(perm); 11709 } 11710 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11711 && pkg.packageName.equals(mSetupWizardPackage)) { 11712 // If this permission is to be granted to the system setup wizard and 11713 // this app is a setup wizard, then it gets the permission. 11714 allowed = true; 11715 } 11716 } 11717 return allowed; 11718 } 11719 11720 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11721 final int permCount = pkg.requestedPermissions.size(); 11722 for (int j = 0; j < permCount; j++) { 11723 String requestedPermission = pkg.requestedPermissions.get(j); 11724 if (permission.equals(requestedPermission)) { 11725 return true; 11726 } 11727 } 11728 return false; 11729 } 11730 11731 final class ActivityIntentResolver 11732 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11733 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11734 boolean defaultOnly, int userId) { 11735 if (!sUserManager.exists(userId)) return null; 11736 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11737 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11738 } 11739 11740 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11741 int userId) { 11742 if (!sUserManager.exists(userId)) return null; 11743 mFlags = flags; 11744 return super.queryIntent(intent, resolvedType, 11745 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11746 userId); 11747 } 11748 11749 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11750 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11751 if (!sUserManager.exists(userId)) return null; 11752 if (packageActivities == null) { 11753 return null; 11754 } 11755 mFlags = flags; 11756 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11757 final int N = packageActivities.size(); 11758 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11759 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11760 11761 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11762 for (int i = 0; i < N; ++i) { 11763 intentFilters = packageActivities.get(i).intents; 11764 if (intentFilters != null && intentFilters.size() > 0) { 11765 PackageParser.ActivityIntentInfo[] array = 11766 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11767 intentFilters.toArray(array); 11768 listCut.add(array); 11769 } 11770 } 11771 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11772 } 11773 11774 /** 11775 * Finds a privileged activity that matches the specified activity names. 11776 */ 11777 private PackageParser.Activity findMatchingActivity( 11778 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11779 for (PackageParser.Activity sysActivity : activityList) { 11780 if (sysActivity.info.name.equals(activityInfo.name)) { 11781 return sysActivity; 11782 } 11783 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11784 return sysActivity; 11785 } 11786 if (sysActivity.info.targetActivity != null) { 11787 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11788 return sysActivity; 11789 } 11790 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11791 return sysActivity; 11792 } 11793 } 11794 } 11795 return null; 11796 } 11797 11798 public class IterGenerator<E> { 11799 public Iterator<E> generate(ActivityIntentInfo info) { 11800 return null; 11801 } 11802 } 11803 11804 public class ActionIterGenerator extends IterGenerator<String> { 11805 @Override 11806 public Iterator<String> generate(ActivityIntentInfo info) { 11807 return info.actionsIterator(); 11808 } 11809 } 11810 11811 public class CategoriesIterGenerator extends IterGenerator<String> { 11812 @Override 11813 public Iterator<String> generate(ActivityIntentInfo info) { 11814 return info.categoriesIterator(); 11815 } 11816 } 11817 11818 public class SchemesIterGenerator extends IterGenerator<String> { 11819 @Override 11820 public Iterator<String> generate(ActivityIntentInfo info) { 11821 return info.schemesIterator(); 11822 } 11823 } 11824 11825 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11826 @Override 11827 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11828 return info.authoritiesIterator(); 11829 } 11830 } 11831 11832 /** 11833 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11834 * MODIFIED. Do not pass in a list that should not be changed. 11835 */ 11836 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11837 IterGenerator<T> generator, Iterator<T> searchIterator) { 11838 // loop through the set of actions; every one must be found in the intent filter 11839 while (searchIterator.hasNext()) { 11840 // we must have at least one filter in the list to consider a match 11841 if (intentList.size() == 0) { 11842 break; 11843 } 11844 11845 final T searchAction = searchIterator.next(); 11846 11847 // loop through the set of intent filters 11848 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11849 while (intentIter.hasNext()) { 11850 final ActivityIntentInfo intentInfo = intentIter.next(); 11851 boolean selectionFound = false; 11852 11853 // loop through the intent filter's selection criteria; at least one 11854 // of them must match the searched criteria 11855 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11856 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11857 final T intentSelection = intentSelectionIter.next(); 11858 if (intentSelection != null && intentSelection.equals(searchAction)) { 11859 selectionFound = true; 11860 break; 11861 } 11862 } 11863 11864 // the selection criteria wasn't found in this filter's set; this filter 11865 // is not a potential match 11866 if (!selectionFound) { 11867 intentIter.remove(); 11868 } 11869 } 11870 } 11871 } 11872 11873 private boolean isProtectedAction(ActivityIntentInfo filter) { 11874 final Iterator<String> actionsIter = filter.actionsIterator(); 11875 while (actionsIter != null && actionsIter.hasNext()) { 11876 final String filterAction = actionsIter.next(); 11877 if (PROTECTED_ACTIONS.contains(filterAction)) { 11878 return true; 11879 } 11880 } 11881 return false; 11882 } 11883 11884 /** 11885 * Adjusts the priority of the given intent filter according to policy. 11886 * <p> 11887 * <ul> 11888 * <li>The priority for non privileged applications is capped to '0'</li> 11889 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11890 * <li>The priority for unbundled updates to privileged applications is capped to the 11891 * priority defined on the system partition</li> 11892 * </ul> 11893 * <p> 11894 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11895 * allowed to obtain any priority on any action. 11896 */ 11897 private void adjustPriority( 11898 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11899 // nothing to do; priority is fine as-is 11900 if (intent.getPriority() <= 0) { 11901 return; 11902 } 11903 11904 final ActivityInfo activityInfo = intent.activity.info; 11905 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11906 11907 final boolean privilegedApp = 11908 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11909 if (!privilegedApp) { 11910 // non-privileged applications can never define a priority >0 11911 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11912 + " package: " + applicationInfo.packageName 11913 + " activity: " + intent.activity.className 11914 + " origPrio: " + intent.getPriority()); 11915 intent.setPriority(0); 11916 return; 11917 } 11918 11919 if (systemActivities == null) { 11920 // the system package is not disabled; we're parsing the system partition 11921 if (isProtectedAction(intent)) { 11922 if (mDeferProtectedFilters) { 11923 // We can't deal with these just yet. No component should ever obtain a 11924 // >0 priority for a protected actions, with ONE exception -- the setup 11925 // wizard. The setup wizard, however, cannot be known until we're able to 11926 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11927 // until all intent filters have been processed. Chicken, meet egg. 11928 // Let the filter temporarily have a high priority and rectify the 11929 // priorities after all system packages have been scanned. 11930 mProtectedFilters.add(intent); 11931 if (DEBUG_FILTERS) { 11932 Slog.i(TAG, "Protected action; save for later;" 11933 + " package: " + applicationInfo.packageName 11934 + " activity: " + intent.activity.className 11935 + " origPrio: " + intent.getPriority()); 11936 } 11937 return; 11938 } else { 11939 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11940 Slog.i(TAG, "No setup wizard;" 11941 + " All protected intents capped to priority 0"); 11942 } 11943 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11944 if (DEBUG_FILTERS) { 11945 Slog.i(TAG, "Found setup wizard;" 11946 + " allow priority " + intent.getPriority() + ";" 11947 + " package: " + intent.activity.info.packageName 11948 + " activity: " + intent.activity.className 11949 + " priority: " + intent.getPriority()); 11950 } 11951 // setup wizard gets whatever it wants 11952 return; 11953 } 11954 Slog.w(TAG, "Protected action; cap priority to 0;" 11955 + " package: " + intent.activity.info.packageName 11956 + " activity: " + intent.activity.className 11957 + " origPrio: " + intent.getPriority()); 11958 intent.setPriority(0); 11959 return; 11960 } 11961 } 11962 // privileged apps on the system image get whatever priority they request 11963 return; 11964 } 11965 11966 // privileged app unbundled update ... try to find the same activity 11967 final PackageParser.Activity foundActivity = 11968 findMatchingActivity(systemActivities, activityInfo); 11969 if (foundActivity == null) { 11970 // this is a new activity; it cannot obtain >0 priority 11971 if (DEBUG_FILTERS) { 11972 Slog.i(TAG, "New activity; cap priority to 0;" 11973 + " package: " + applicationInfo.packageName 11974 + " activity: " + intent.activity.className 11975 + " origPrio: " + intent.getPriority()); 11976 } 11977 intent.setPriority(0); 11978 return; 11979 } 11980 11981 // found activity, now check for filter equivalence 11982 11983 // a shallow copy is enough; we modify the list, not its contents 11984 final List<ActivityIntentInfo> intentListCopy = 11985 new ArrayList<>(foundActivity.intents); 11986 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11987 11988 // find matching action subsets 11989 final Iterator<String> actionsIterator = intent.actionsIterator(); 11990 if (actionsIterator != null) { 11991 getIntentListSubset( 11992 intentListCopy, new ActionIterGenerator(), actionsIterator); 11993 if (intentListCopy.size() == 0) { 11994 // no more intents to match; we're not equivalent 11995 if (DEBUG_FILTERS) { 11996 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11997 + " package: " + applicationInfo.packageName 11998 + " activity: " + intent.activity.className 11999 + " origPrio: " + intent.getPriority()); 12000 } 12001 intent.setPriority(0); 12002 return; 12003 } 12004 } 12005 12006 // find matching category subsets 12007 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12008 if (categoriesIterator != null) { 12009 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12010 categoriesIterator); 12011 if (intentListCopy.size() == 0) { 12012 // no more intents to match; we're not equivalent 12013 if (DEBUG_FILTERS) { 12014 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12015 + " package: " + applicationInfo.packageName 12016 + " activity: " + intent.activity.className 12017 + " origPrio: " + intent.getPriority()); 12018 } 12019 intent.setPriority(0); 12020 return; 12021 } 12022 } 12023 12024 // find matching schemes subsets 12025 final Iterator<String> schemesIterator = intent.schemesIterator(); 12026 if (schemesIterator != null) { 12027 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12028 schemesIterator); 12029 if (intentListCopy.size() == 0) { 12030 // no more intents to match; we're not equivalent 12031 if (DEBUG_FILTERS) { 12032 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12033 + " package: " + applicationInfo.packageName 12034 + " activity: " + intent.activity.className 12035 + " origPrio: " + intent.getPriority()); 12036 } 12037 intent.setPriority(0); 12038 return; 12039 } 12040 } 12041 12042 // find matching authorities subsets 12043 final Iterator<IntentFilter.AuthorityEntry> 12044 authoritiesIterator = intent.authoritiesIterator(); 12045 if (authoritiesIterator != null) { 12046 getIntentListSubset(intentListCopy, 12047 new AuthoritiesIterGenerator(), 12048 authoritiesIterator); 12049 if (intentListCopy.size() == 0) { 12050 // no more intents to match; we're not equivalent 12051 if (DEBUG_FILTERS) { 12052 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12053 + " package: " + applicationInfo.packageName 12054 + " activity: " + intent.activity.className 12055 + " origPrio: " + intent.getPriority()); 12056 } 12057 intent.setPriority(0); 12058 return; 12059 } 12060 } 12061 12062 // we found matching filter(s); app gets the max priority of all intents 12063 int cappedPriority = 0; 12064 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12065 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12066 } 12067 if (intent.getPriority() > cappedPriority) { 12068 if (DEBUG_FILTERS) { 12069 Slog.i(TAG, "Found matching filter(s);" 12070 + " cap priority to " + cappedPriority + ";" 12071 + " package: " + applicationInfo.packageName 12072 + " activity: " + intent.activity.className 12073 + " origPrio: " + intent.getPriority()); 12074 } 12075 intent.setPriority(cappedPriority); 12076 return; 12077 } 12078 // all this for nothing; the requested priority was <= what was on the system 12079 } 12080 12081 public final void addActivity(PackageParser.Activity a, String type) { 12082 mActivities.put(a.getComponentName(), a); 12083 if (DEBUG_SHOW_INFO) 12084 Log.v( 12085 TAG, " " + type + " " + 12086 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12087 if (DEBUG_SHOW_INFO) 12088 Log.v(TAG, " Class=" + a.info.name); 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 ("activity".equals(type)) { 12093 final PackageSetting ps = 12094 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12095 final List<PackageParser.Activity> systemActivities = 12096 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12097 adjustPriority(systemActivities, intent); 12098 } 12099 if (DEBUG_SHOW_INFO) { 12100 Log.v(TAG, " IntentFilter:"); 12101 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12102 } 12103 if (!intent.debugCheck()) { 12104 Log.w(TAG, "==> For Activity " + a.info.name); 12105 } 12106 addFilter(intent); 12107 } 12108 } 12109 12110 public final void removeActivity(PackageParser.Activity a, String type) { 12111 mActivities.remove(a.getComponentName()); 12112 if (DEBUG_SHOW_INFO) { 12113 Log.v(TAG, " " + type + " " 12114 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12115 : a.info.name) + ":"); 12116 Log.v(TAG, " Class=" + a.info.name); 12117 } 12118 final int NI = a.intents.size(); 12119 for (int j=0; j<NI; j++) { 12120 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12121 if (DEBUG_SHOW_INFO) { 12122 Log.v(TAG, " IntentFilter:"); 12123 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12124 } 12125 removeFilter(intent); 12126 } 12127 } 12128 12129 @Override 12130 protected boolean allowFilterResult( 12131 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12132 ActivityInfo filterAi = filter.activity.info; 12133 for (int i=dest.size()-1; i>=0; i--) { 12134 ActivityInfo destAi = dest.get(i).activityInfo; 12135 if (destAi.name == filterAi.name 12136 && destAi.packageName == filterAi.packageName) { 12137 return false; 12138 } 12139 } 12140 return true; 12141 } 12142 12143 @Override 12144 protected ActivityIntentInfo[] newArray(int size) { 12145 return new ActivityIntentInfo[size]; 12146 } 12147 12148 @Override 12149 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12150 if (!sUserManager.exists(userId)) return true; 12151 PackageParser.Package p = filter.activity.owner; 12152 if (p != null) { 12153 PackageSetting ps = (PackageSetting)p.mExtras; 12154 if (ps != null) { 12155 // System apps are never considered stopped for purposes of 12156 // filtering, because there may be no way for the user to 12157 // actually re-launch them. 12158 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12159 && ps.getStopped(userId); 12160 } 12161 } 12162 return false; 12163 } 12164 12165 @Override 12166 protected boolean isPackageForFilter(String packageName, 12167 PackageParser.ActivityIntentInfo info) { 12168 return packageName.equals(info.activity.owner.packageName); 12169 } 12170 12171 @Override 12172 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12173 int match, int userId) { 12174 if (!sUserManager.exists(userId)) return null; 12175 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12176 return null; 12177 } 12178 final PackageParser.Activity activity = info.activity; 12179 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12180 if (ps == null) { 12181 return null; 12182 } 12183 final PackageUserState userState = ps.readUserState(userId); 12184 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12185 userState, userId); 12186 if (ai == null) { 12187 return null; 12188 } 12189 final boolean matchVisibleToInstantApp = 12190 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12191 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12192 // throw out filters that aren't visible to ephemeral apps 12193 if (matchVisibleToInstantApp 12194 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12195 return null; 12196 } 12197 // throw out ephemeral filters if we're not explicitly requesting them 12198 if (!isInstantApp && userState.instantApp) { 12199 return null; 12200 } 12201 // throw out instant app filters if updates are available; will trigger 12202 // instant app resolution 12203 if (userState.instantApp && ps.isUpdateAvailable()) { 12204 return null; 12205 } 12206 final ResolveInfo res = new ResolveInfo(); 12207 res.activityInfo = ai; 12208 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12209 res.filter = info; 12210 } 12211 if (info != null) { 12212 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12213 } 12214 res.priority = info.getPriority(); 12215 res.preferredOrder = activity.owner.mPreferredOrder; 12216 //System.out.println("Result: " + res.activityInfo.className + 12217 // " = " + res.priority); 12218 res.match = match; 12219 res.isDefault = info.hasDefault; 12220 res.labelRes = info.labelRes; 12221 res.nonLocalizedLabel = info.nonLocalizedLabel; 12222 if (userNeedsBadging(userId)) { 12223 res.noResourceId = true; 12224 } else { 12225 res.icon = info.icon; 12226 } 12227 res.iconResourceId = info.icon; 12228 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12229 res.instantAppAvailable = userState.instantApp; 12230 return res; 12231 } 12232 12233 @Override 12234 protected void sortResults(List<ResolveInfo> results) { 12235 Collections.sort(results, mResolvePrioritySorter); 12236 } 12237 12238 @Override 12239 protected void dumpFilter(PrintWriter out, String prefix, 12240 PackageParser.ActivityIntentInfo filter) { 12241 out.print(prefix); out.print( 12242 Integer.toHexString(System.identityHashCode(filter.activity))); 12243 out.print(' '); 12244 filter.activity.printComponentShortName(out); 12245 out.print(" filter "); 12246 out.println(Integer.toHexString(System.identityHashCode(filter))); 12247 } 12248 12249 @Override 12250 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12251 return filter.activity; 12252 } 12253 12254 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12255 PackageParser.Activity activity = (PackageParser.Activity)label; 12256 out.print(prefix); out.print( 12257 Integer.toHexString(System.identityHashCode(activity))); 12258 out.print(' '); 12259 activity.printComponentShortName(out); 12260 if (count > 1) { 12261 out.print(" ("); out.print(count); out.print(" filters)"); 12262 } 12263 out.println(); 12264 } 12265 12266 // Keys are String (activity class name), values are Activity. 12267 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12268 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12269 private int mFlags; 12270 } 12271 12272 private final class ServiceIntentResolver 12273 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12274 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12275 boolean defaultOnly, int userId) { 12276 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12277 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12278 } 12279 12280 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12281 int userId) { 12282 if (!sUserManager.exists(userId)) return null; 12283 mFlags = flags; 12284 return super.queryIntent(intent, resolvedType, 12285 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12286 userId); 12287 } 12288 12289 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12290 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12291 if (!sUserManager.exists(userId)) return null; 12292 if (packageServices == null) { 12293 return null; 12294 } 12295 mFlags = flags; 12296 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12297 final int N = packageServices.size(); 12298 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12299 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12300 12301 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12302 for (int i = 0; i < N; ++i) { 12303 intentFilters = packageServices.get(i).intents; 12304 if (intentFilters != null && intentFilters.size() > 0) { 12305 PackageParser.ServiceIntentInfo[] array = 12306 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12307 intentFilters.toArray(array); 12308 listCut.add(array); 12309 } 12310 } 12311 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12312 } 12313 12314 public final void addService(PackageParser.Service s) { 12315 mServices.put(s.getComponentName(), s); 12316 if (DEBUG_SHOW_INFO) { 12317 Log.v(TAG, " " 12318 + (s.info.nonLocalizedLabel != null 12319 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12320 Log.v(TAG, " Class=" + s.info.name); 12321 } 12322 final int NI = s.intents.size(); 12323 int j; 12324 for (j=0; j<NI; j++) { 12325 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12326 if (DEBUG_SHOW_INFO) { 12327 Log.v(TAG, " IntentFilter:"); 12328 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12329 } 12330 if (!intent.debugCheck()) { 12331 Log.w(TAG, "==> For Service " + s.info.name); 12332 } 12333 addFilter(intent); 12334 } 12335 } 12336 12337 public final void removeService(PackageParser.Service s) { 12338 mServices.remove(s.getComponentName()); 12339 if (DEBUG_SHOW_INFO) { 12340 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12341 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12342 Log.v(TAG, " Class=" + s.info.name); 12343 } 12344 final int NI = s.intents.size(); 12345 int j; 12346 for (j=0; j<NI; j++) { 12347 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12348 if (DEBUG_SHOW_INFO) { 12349 Log.v(TAG, " IntentFilter:"); 12350 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12351 } 12352 removeFilter(intent); 12353 } 12354 } 12355 12356 @Override 12357 protected boolean allowFilterResult( 12358 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12359 ServiceInfo filterSi = filter.service.info; 12360 for (int i=dest.size()-1; i>=0; i--) { 12361 ServiceInfo destAi = dest.get(i).serviceInfo; 12362 if (destAi.name == filterSi.name 12363 && destAi.packageName == filterSi.packageName) { 12364 return false; 12365 } 12366 } 12367 return true; 12368 } 12369 12370 @Override 12371 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12372 return new PackageParser.ServiceIntentInfo[size]; 12373 } 12374 12375 @Override 12376 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12377 if (!sUserManager.exists(userId)) return true; 12378 PackageParser.Package p = filter.service.owner; 12379 if (p != null) { 12380 PackageSetting ps = (PackageSetting)p.mExtras; 12381 if (ps != null) { 12382 // System apps are never considered stopped for purposes of 12383 // filtering, because there may be no way for the user to 12384 // actually re-launch them. 12385 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12386 && ps.getStopped(userId); 12387 } 12388 } 12389 return false; 12390 } 12391 12392 @Override 12393 protected boolean isPackageForFilter(String packageName, 12394 PackageParser.ServiceIntentInfo info) { 12395 return packageName.equals(info.service.owner.packageName); 12396 } 12397 12398 @Override 12399 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12400 int match, int userId) { 12401 if (!sUserManager.exists(userId)) return null; 12402 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12403 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12404 return null; 12405 } 12406 final PackageParser.Service service = info.service; 12407 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12408 if (ps == null) { 12409 return null; 12410 } 12411 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12412 ps.readUserState(userId), userId); 12413 if (si == null) { 12414 return null; 12415 } 12416 final ResolveInfo res = new ResolveInfo(); 12417 res.serviceInfo = si; 12418 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12419 res.filter = filter; 12420 } 12421 res.priority = info.getPriority(); 12422 res.preferredOrder = service.owner.mPreferredOrder; 12423 res.match = match; 12424 res.isDefault = info.hasDefault; 12425 res.labelRes = info.labelRes; 12426 res.nonLocalizedLabel = info.nonLocalizedLabel; 12427 res.icon = info.icon; 12428 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12429 return res; 12430 } 12431 12432 @Override 12433 protected void sortResults(List<ResolveInfo> results) { 12434 Collections.sort(results, mResolvePrioritySorter); 12435 } 12436 12437 @Override 12438 protected void dumpFilter(PrintWriter out, String prefix, 12439 PackageParser.ServiceIntentInfo filter) { 12440 out.print(prefix); out.print( 12441 Integer.toHexString(System.identityHashCode(filter.service))); 12442 out.print(' '); 12443 filter.service.printComponentShortName(out); 12444 out.print(" filter "); 12445 out.println(Integer.toHexString(System.identityHashCode(filter))); 12446 } 12447 12448 @Override 12449 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12450 return filter.service; 12451 } 12452 12453 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12454 PackageParser.Service service = (PackageParser.Service)label; 12455 out.print(prefix); out.print( 12456 Integer.toHexString(System.identityHashCode(service))); 12457 out.print(' '); 12458 service.printComponentShortName(out); 12459 if (count > 1) { 12460 out.print(" ("); out.print(count); out.print(" filters)"); 12461 } 12462 out.println(); 12463 } 12464 12465// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12466// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12467// final List<ResolveInfo> retList = Lists.newArrayList(); 12468// while (i.hasNext()) { 12469// final ResolveInfo resolveInfo = (ResolveInfo) i; 12470// if (isEnabledLP(resolveInfo.serviceInfo)) { 12471// retList.add(resolveInfo); 12472// } 12473// } 12474// return retList; 12475// } 12476 12477 // Keys are String (activity class name), values are Activity. 12478 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12479 = new ArrayMap<ComponentName, PackageParser.Service>(); 12480 private int mFlags; 12481 } 12482 12483 private final class ProviderIntentResolver 12484 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12485 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12486 boolean defaultOnly, int userId) { 12487 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12488 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12489 } 12490 12491 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12492 int userId) { 12493 if (!sUserManager.exists(userId)) 12494 return null; 12495 mFlags = flags; 12496 return super.queryIntent(intent, resolvedType, 12497 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12498 userId); 12499 } 12500 12501 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12502 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12503 if (!sUserManager.exists(userId)) 12504 return null; 12505 if (packageProviders == null) { 12506 return null; 12507 } 12508 mFlags = flags; 12509 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12510 final int N = packageProviders.size(); 12511 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12512 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12513 12514 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12515 for (int i = 0; i < N; ++i) { 12516 intentFilters = packageProviders.get(i).intents; 12517 if (intentFilters != null && intentFilters.size() > 0) { 12518 PackageParser.ProviderIntentInfo[] array = 12519 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12520 intentFilters.toArray(array); 12521 listCut.add(array); 12522 } 12523 } 12524 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12525 } 12526 12527 public final void addProvider(PackageParser.Provider p) { 12528 if (mProviders.containsKey(p.getComponentName())) { 12529 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12530 return; 12531 } 12532 12533 mProviders.put(p.getComponentName(), p); 12534 if (DEBUG_SHOW_INFO) { 12535 Log.v(TAG, " " 12536 + (p.info.nonLocalizedLabel != null 12537 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12538 Log.v(TAG, " Class=" + p.info.name); 12539 } 12540 final int NI = p.intents.size(); 12541 int j; 12542 for (j = 0; j < NI; j++) { 12543 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12544 if (DEBUG_SHOW_INFO) { 12545 Log.v(TAG, " IntentFilter:"); 12546 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12547 } 12548 if (!intent.debugCheck()) { 12549 Log.w(TAG, "==> For Provider " + p.info.name); 12550 } 12551 addFilter(intent); 12552 } 12553 } 12554 12555 public final void removeProvider(PackageParser.Provider p) { 12556 mProviders.remove(p.getComponentName()); 12557 if (DEBUG_SHOW_INFO) { 12558 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12559 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12560 Log.v(TAG, " Class=" + p.info.name); 12561 } 12562 final int NI = p.intents.size(); 12563 int j; 12564 for (j = 0; j < NI; j++) { 12565 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12566 if (DEBUG_SHOW_INFO) { 12567 Log.v(TAG, " IntentFilter:"); 12568 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12569 } 12570 removeFilter(intent); 12571 } 12572 } 12573 12574 @Override 12575 protected boolean allowFilterResult( 12576 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12577 ProviderInfo filterPi = filter.provider.info; 12578 for (int i = dest.size() - 1; i >= 0; i--) { 12579 ProviderInfo destPi = dest.get(i).providerInfo; 12580 if (destPi.name == filterPi.name 12581 && destPi.packageName == filterPi.packageName) { 12582 return false; 12583 } 12584 } 12585 return true; 12586 } 12587 12588 @Override 12589 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12590 return new PackageParser.ProviderIntentInfo[size]; 12591 } 12592 12593 @Override 12594 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12595 if (!sUserManager.exists(userId)) 12596 return true; 12597 PackageParser.Package p = filter.provider.owner; 12598 if (p != null) { 12599 PackageSetting ps = (PackageSetting) p.mExtras; 12600 if (ps != null) { 12601 // System apps are never considered stopped for purposes of 12602 // filtering, because there may be no way for the user to 12603 // actually re-launch them. 12604 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12605 && ps.getStopped(userId); 12606 } 12607 } 12608 return false; 12609 } 12610 12611 @Override 12612 protected boolean isPackageForFilter(String packageName, 12613 PackageParser.ProviderIntentInfo info) { 12614 return packageName.equals(info.provider.owner.packageName); 12615 } 12616 12617 @Override 12618 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12619 int match, int userId) { 12620 if (!sUserManager.exists(userId)) 12621 return null; 12622 final PackageParser.ProviderIntentInfo info = filter; 12623 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12624 return null; 12625 } 12626 final PackageParser.Provider provider = info.provider; 12627 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12628 if (ps == null) { 12629 return null; 12630 } 12631 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12632 ps.readUserState(userId), userId); 12633 if (pi == null) { 12634 return null; 12635 } 12636 final ResolveInfo res = new ResolveInfo(); 12637 res.providerInfo = pi; 12638 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12639 res.filter = filter; 12640 } 12641 res.priority = info.getPriority(); 12642 res.preferredOrder = provider.owner.mPreferredOrder; 12643 res.match = match; 12644 res.isDefault = info.hasDefault; 12645 res.labelRes = info.labelRes; 12646 res.nonLocalizedLabel = info.nonLocalizedLabel; 12647 res.icon = info.icon; 12648 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12649 return res; 12650 } 12651 12652 @Override 12653 protected void sortResults(List<ResolveInfo> results) { 12654 Collections.sort(results, mResolvePrioritySorter); 12655 } 12656 12657 @Override 12658 protected void dumpFilter(PrintWriter out, String prefix, 12659 PackageParser.ProviderIntentInfo filter) { 12660 out.print(prefix); 12661 out.print( 12662 Integer.toHexString(System.identityHashCode(filter.provider))); 12663 out.print(' '); 12664 filter.provider.printComponentShortName(out); 12665 out.print(" filter "); 12666 out.println(Integer.toHexString(System.identityHashCode(filter))); 12667 } 12668 12669 @Override 12670 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12671 return filter.provider; 12672 } 12673 12674 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12675 PackageParser.Provider provider = (PackageParser.Provider)label; 12676 out.print(prefix); out.print( 12677 Integer.toHexString(System.identityHashCode(provider))); 12678 out.print(' '); 12679 provider.printComponentShortName(out); 12680 if (count > 1) { 12681 out.print(" ("); out.print(count); out.print(" filters)"); 12682 } 12683 out.println(); 12684 } 12685 12686 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12687 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12688 private int mFlags; 12689 } 12690 12691 static final class EphemeralIntentResolver 12692 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12693 /** 12694 * The result that has the highest defined order. Ordering applies on a 12695 * per-package basis. Mapping is from package name to Pair of order and 12696 * EphemeralResolveInfo. 12697 * <p> 12698 * NOTE: This is implemented as a field variable for convenience and efficiency. 12699 * By having a field variable, we're able to track filter ordering as soon as 12700 * a non-zero order is defined. Otherwise, multiple loops across the result set 12701 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12702 * this needs to be contained entirely within {@link #filterResults}. 12703 */ 12704 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12705 12706 @Override 12707 protected AuxiliaryResolveInfo[] newArray(int size) { 12708 return new AuxiliaryResolveInfo[size]; 12709 } 12710 12711 @Override 12712 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12713 return true; 12714 } 12715 12716 @Override 12717 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12718 int userId) { 12719 if (!sUserManager.exists(userId)) { 12720 return null; 12721 } 12722 final String packageName = responseObj.resolveInfo.getPackageName(); 12723 final Integer order = responseObj.getOrder(); 12724 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12725 mOrderResult.get(packageName); 12726 // ordering is enabled and this item's order isn't high enough 12727 if (lastOrderResult != null && lastOrderResult.first >= order) { 12728 return null; 12729 } 12730 final InstantAppResolveInfo res = responseObj.resolveInfo; 12731 if (order > 0) { 12732 // non-zero order, enable ordering 12733 mOrderResult.put(packageName, new Pair<>(order, res)); 12734 } 12735 return responseObj; 12736 } 12737 12738 @Override 12739 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12740 // only do work if ordering is enabled [most of the time it won't be] 12741 if (mOrderResult.size() == 0) { 12742 return; 12743 } 12744 int resultSize = results.size(); 12745 for (int i = 0; i < resultSize; i++) { 12746 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12747 final String packageName = info.getPackageName(); 12748 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12749 if (savedInfo == null) { 12750 // package doesn't having ordering 12751 continue; 12752 } 12753 if (savedInfo.second == info) { 12754 // circled back to the highest ordered item; remove from order list 12755 mOrderResult.remove(savedInfo); 12756 if (mOrderResult.size() == 0) { 12757 // no more ordered items 12758 break; 12759 } 12760 continue; 12761 } 12762 // item has a worse order, remove it from the result list 12763 results.remove(i); 12764 resultSize--; 12765 i--; 12766 } 12767 } 12768 } 12769 12770 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12771 new Comparator<ResolveInfo>() { 12772 public int compare(ResolveInfo r1, ResolveInfo r2) { 12773 int v1 = r1.priority; 12774 int v2 = r2.priority; 12775 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12776 if (v1 != v2) { 12777 return (v1 > v2) ? -1 : 1; 12778 } 12779 v1 = r1.preferredOrder; 12780 v2 = r2.preferredOrder; 12781 if (v1 != v2) { 12782 return (v1 > v2) ? -1 : 1; 12783 } 12784 if (r1.isDefault != r2.isDefault) { 12785 return r1.isDefault ? -1 : 1; 12786 } 12787 v1 = r1.match; 12788 v2 = r2.match; 12789 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12790 if (v1 != v2) { 12791 return (v1 > v2) ? -1 : 1; 12792 } 12793 if (r1.system != r2.system) { 12794 return r1.system ? -1 : 1; 12795 } 12796 if (r1.activityInfo != null) { 12797 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12798 } 12799 if (r1.serviceInfo != null) { 12800 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12801 } 12802 if (r1.providerInfo != null) { 12803 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12804 } 12805 return 0; 12806 } 12807 }; 12808 12809 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12810 new Comparator<ProviderInfo>() { 12811 public int compare(ProviderInfo p1, ProviderInfo p2) { 12812 final int v1 = p1.initOrder; 12813 final int v2 = p2.initOrder; 12814 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12815 } 12816 }; 12817 12818 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12819 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12820 final int[] userIds) { 12821 mHandler.post(new Runnable() { 12822 @Override 12823 public void run() { 12824 try { 12825 final IActivityManager am = ActivityManager.getService(); 12826 if (am == null) return; 12827 final int[] resolvedUserIds; 12828 if (userIds == null) { 12829 resolvedUserIds = am.getRunningUserIds(); 12830 } else { 12831 resolvedUserIds = userIds; 12832 } 12833 for (int id : resolvedUserIds) { 12834 final Intent intent = new Intent(action, 12835 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12836 if (extras != null) { 12837 intent.putExtras(extras); 12838 } 12839 if (targetPkg != null) { 12840 intent.setPackage(targetPkg); 12841 } 12842 // Modify the UID when posting to other users 12843 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12844 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12845 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12846 intent.putExtra(Intent.EXTRA_UID, uid); 12847 } 12848 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12849 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12850 if (DEBUG_BROADCASTS) { 12851 RuntimeException here = new RuntimeException("here"); 12852 here.fillInStackTrace(); 12853 Slog.d(TAG, "Sending to user " + id + ": " 12854 + intent.toShortString(false, true, false, false) 12855 + " " + intent.getExtras(), here); 12856 } 12857 am.broadcastIntent(null, intent, null, finishedReceiver, 12858 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12859 null, finishedReceiver != null, false, id); 12860 } 12861 } catch (RemoteException ex) { 12862 } 12863 } 12864 }); 12865 } 12866 12867 /** 12868 * Check if the external storage media is available. This is true if there 12869 * is a mounted external storage medium or if the external storage is 12870 * emulated. 12871 */ 12872 private boolean isExternalMediaAvailable() { 12873 return mMediaMounted || Environment.isExternalStorageEmulated(); 12874 } 12875 12876 @Override 12877 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12878 // writer 12879 synchronized (mPackages) { 12880 if (!isExternalMediaAvailable()) { 12881 // If the external storage is no longer mounted at this point, 12882 // the caller may not have been able to delete all of this 12883 // packages files and can not delete any more. Bail. 12884 return null; 12885 } 12886 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12887 if (lastPackage != null) { 12888 pkgs.remove(lastPackage); 12889 } 12890 if (pkgs.size() > 0) { 12891 return pkgs.get(0); 12892 } 12893 } 12894 return null; 12895 } 12896 12897 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12898 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12899 userId, andCode ? 1 : 0, packageName); 12900 if (mSystemReady) { 12901 msg.sendToTarget(); 12902 } else { 12903 if (mPostSystemReadyMessages == null) { 12904 mPostSystemReadyMessages = new ArrayList<>(); 12905 } 12906 mPostSystemReadyMessages.add(msg); 12907 } 12908 } 12909 12910 void startCleaningPackages() { 12911 // reader 12912 if (!isExternalMediaAvailable()) { 12913 return; 12914 } 12915 synchronized (mPackages) { 12916 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12917 return; 12918 } 12919 } 12920 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12921 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12922 IActivityManager am = ActivityManager.getService(); 12923 if (am != null) { 12924 try { 12925 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12926 UserHandle.USER_SYSTEM); 12927 } catch (RemoteException e) { 12928 } 12929 } 12930 } 12931 12932 @Override 12933 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12934 int installFlags, String installerPackageName, int userId) { 12935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12936 12937 final int callingUid = Binder.getCallingUid(); 12938 enforceCrossUserPermission(callingUid, userId, 12939 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12940 12941 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12942 try { 12943 if (observer != null) { 12944 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12945 } 12946 } catch (RemoteException re) { 12947 } 12948 return; 12949 } 12950 12951 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12952 installFlags |= PackageManager.INSTALL_FROM_ADB; 12953 12954 } else { 12955 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12956 // about installerPackageName. 12957 12958 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12959 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12960 } 12961 12962 UserHandle user; 12963 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12964 user = UserHandle.ALL; 12965 } else { 12966 user = new UserHandle(userId); 12967 } 12968 12969 // Only system components can circumvent runtime permissions when installing. 12970 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12971 && mContext.checkCallingOrSelfPermission(Manifest.permission 12972 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12973 throw new SecurityException("You need the " 12974 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12975 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12976 } 12977 12978 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 12979 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12980 throw new IllegalArgumentException( 12981 "New installs into ASEC containers no longer supported"); 12982 } 12983 12984 final File originFile = new File(originPath); 12985 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12986 12987 final Message msg = mHandler.obtainMessage(INIT_COPY); 12988 final VerificationInfo verificationInfo = new VerificationInfo( 12989 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12990 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12991 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12992 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12993 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12994 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12995 msg.obj = params; 12996 12997 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12998 System.identityHashCode(msg.obj)); 12999 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13000 System.identityHashCode(msg.obj)); 13001 13002 mHandler.sendMessage(msg); 13003 } 13004 13005 13006 /** 13007 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13008 * it is acting on behalf on an enterprise or the user). 13009 * 13010 * Note that the ordering of the conditionals in this method is important. The checks we perform 13011 * are as follows, in this order: 13012 * 13013 * 1) If the install is being performed by a system app, we can trust the app to have set the 13014 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13015 * what it is. 13016 * 2) If the install is being performed by a device or profile owner app, the install reason 13017 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13018 * set the install reason correctly. If the app targets an older SDK version where install 13019 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13020 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13021 * 3) In all other cases, the install is being performed by a regular app that is neither part 13022 * of the system nor a device or profile owner. We have no reason to believe that this app is 13023 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13024 * set to enterprise policy and if so, change it to unknown instead. 13025 */ 13026 private int fixUpInstallReason(String installerPackageName, int installerUid, 13027 int installReason) { 13028 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13029 == PERMISSION_GRANTED) { 13030 // If the install is being performed by a system app, we trust that app to have set the 13031 // install reason correctly. 13032 return installReason; 13033 } 13034 13035 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13036 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13037 if (dpm != null) { 13038 ComponentName owner = null; 13039 try { 13040 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13041 if (owner == null) { 13042 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13043 } 13044 } catch (RemoteException e) { 13045 } 13046 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13047 // If the install is being performed by a device or profile owner, the install 13048 // reason should be enterprise policy. 13049 return PackageManager.INSTALL_REASON_POLICY; 13050 } 13051 } 13052 13053 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13054 // If the install is being performed by a regular app (i.e. neither system app nor 13055 // device or profile owner), we have no reason to believe that the app is acting on 13056 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13057 // change it to unknown instead. 13058 return PackageManager.INSTALL_REASON_UNKNOWN; 13059 } 13060 13061 // If the install is being performed by a regular app and the install reason was set to any 13062 // value but enterprise policy, leave the install reason unchanged. 13063 return installReason; 13064 } 13065 13066 void installStage(String packageName, File stagedDir, String stagedCid, 13067 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13068 String installerPackageName, int installerUid, UserHandle user, 13069 Certificate[][] certificates) { 13070 if (DEBUG_EPHEMERAL) { 13071 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13072 Slog.d(TAG, "Ephemeral install of " + packageName); 13073 } 13074 } 13075 final VerificationInfo verificationInfo = new VerificationInfo( 13076 sessionParams.originatingUri, sessionParams.referrerUri, 13077 sessionParams.originatingUid, installerUid); 13078 13079 final OriginInfo origin; 13080 if (stagedDir != null) { 13081 origin = OriginInfo.fromStagedFile(stagedDir); 13082 } else { 13083 origin = OriginInfo.fromStagedContainer(stagedCid); 13084 } 13085 13086 final Message msg = mHandler.obtainMessage(INIT_COPY); 13087 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13088 sessionParams.installReason); 13089 final InstallParams params = new InstallParams(origin, null, observer, 13090 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13091 verificationInfo, user, sessionParams.abiOverride, 13092 sessionParams.grantedRuntimePermissions, certificates, installReason); 13093 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13094 msg.obj = params; 13095 13096 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13097 System.identityHashCode(msg.obj)); 13098 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13099 System.identityHashCode(msg.obj)); 13100 13101 mHandler.sendMessage(msg); 13102 } 13103 13104 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13105 int userId) { 13106 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13107 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13108 } 13109 13110 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13111 int appId, int... userIds) { 13112 if (ArrayUtils.isEmpty(userIds)) { 13113 return; 13114 } 13115 Bundle extras = new Bundle(1); 13116 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13117 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13118 13119 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13120 packageName, extras, 0, null, null, userIds); 13121 if (isSystem) { 13122 mHandler.post(() -> { 13123 for (int userId : userIds) { 13124 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13125 } 13126 } 13127 ); 13128 } 13129 } 13130 13131 /** 13132 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13133 * automatically without needing an explicit launch. 13134 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13135 */ 13136 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13137 // If user is not running, the app didn't miss any broadcast 13138 if (!mUserManagerInternal.isUserRunning(userId)) { 13139 return; 13140 } 13141 final IActivityManager am = ActivityManager.getService(); 13142 try { 13143 // Deliver LOCKED_BOOT_COMPLETED first 13144 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13145 .setPackage(packageName); 13146 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13147 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13148 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13149 13150 // Deliver BOOT_COMPLETED only if user is unlocked 13151 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13152 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13153 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13154 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13155 } 13156 } catch (RemoteException e) { 13157 throw e.rethrowFromSystemServer(); 13158 } 13159 } 13160 13161 @Override 13162 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13163 int userId) { 13164 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13165 PackageSetting pkgSetting; 13166 final int uid = Binder.getCallingUid(); 13167 enforceCrossUserPermission(uid, userId, 13168 true /* requireFullPermission */, true /* checkShell */, 13169 "setApplicationHiddenSetting for user " + userId); 13170 13171 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13172 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13173 return false; 13174 } 13175 13176 long callingId = Binder.clearCallingIdentity(); 13177 try { 13178 boolean sendAdded = false; 13179 boolean sendRemoved = false; 13180 // writer 13181 synchronized (mPackages) { 13182 pkgSetting = mSettings.mPackages.get(packageName); 13183 if (pkgSetting == null) { 13184 return false; 13185 } 13186 // Do not allow "android" is being disabled 13187 if ("android".equals(packageName)) { 13188 Slog.w(TAG, "Cannot hide package: android"); 13189 return false; 13190 } 13191 // Cannot hide static shared libs as they are considered 13192 // a part of the using app (emulating static linking). Also 13193 // static libs are installed always on internal storage. 13194 PackageParser.Package pkg = mPackages.get(packageName); 13195 if (pkg != null && pkg.staticSharedLibName != null) { 13196 Slog.w(TAG, "Cannot hide package: " + packageName 13197 + " providing static shared library: " 13198 + pkg.staticSharedLibName); 13199 return false; 13200 } 13201 // Only allow protected packages to hide themselves. 13202 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13203 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13204 Slog.w(TAG, "Not hiding protected package: " + packageName); 13205 return false; 13206 } 13207 13208 if (pkgSetting.getHidden(userId) != hidden) { 13209 pkgSetting.setHidden(hidden, userId); 13210 mSettings.writePackageRestrictionsLPr(userId); 13211 if (hidden) { 13212 sendRemoved = true; 13213 } else { 13214 sendAdded = true; 13215 } 13216 } 13217 } 13218 if (sendAdded) { 13219 sendPackageAddedForUser(packageName, pkgSetting, userId); 13220 return true; 13221 } 13222 if (sendRemoved) { 13223 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13224 "hiding pkg"); 13225 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13226 return true; 13227 } 13228 } finally { 13229 Binder.restoreCallingIdentity(callingId); 13230 } 13231 return false; 13232 } 13233 13234 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13235 int userId) { 13236 final PackageRemovedInfo info = new PackageRemovedInfo(); 13237 info.removedPackage = packageName; 13238 info.removedUsers = new int[] {userId}; 13239 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13240 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13241 } 13242 13243 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13244 if (pkgList.length > 0) { 13245 Bundle extras = new Bundle(1); 13246 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13247 13248 sendPackageBroadcast( 13249 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13250 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13251 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13252 new int[] {userId}); 13253 } 13254 } 13255 13256 /** 13257 * Returns true if application is not found or there was an error. Otherwise it returns 13258 * the hidden state of the package for the given user. 13259 */ 13260 @Override 13261 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13262 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13264 true /* requireFullPermission */, false /* checkShell */, 13265 "getApplicationHidden for user " + userId); 13266 PackageSetting pkgSetting; 13267 long callingId = Binder.clearCallingIdentity(); 13268 try { 13269 // writer 13270 synchronized (mPackages) { 13271 pkgSetting = mSettings.mPackages.get(packageName); 13272 if (pkgSetting == null) { 13273 return true; 13274 } 13275 return pkgSetting.getHidden(userId); 13276 } 13277 } finally { 13278 Binder.restoreCallingIdentity(callingId); 13279 } 13280 } 13281 13282 /** 13283 * @hide 13284 */ 13285 @Override 13286 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13287 int installReason) { 13288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13289 null); 13290 PackageSetting pkgSetting; 13291 final int uid = Binder.getCallingUid(); 13292 enforceCrossUserPermission(uid, userId, 13293 true /* requireFullPermission */, true /* checkShell */, 13294 "installExistingPackage for user " + userId); 13295 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13296 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13297 } 13298 13299 long callingId = Binder.clearCallingIdentity(); 13300 try { 13301 boolean installed = false; 13302 final boolean instantApp = 13303 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13304 final boolean fullApp = 13305 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13306 13307 // writer 13308 synchronized (mPackages) { 13309 pkgSetting = mSettings.mPackages.get(packageName); 13310 if (pkgSetting == null) { 13311 return PackageManager.INSTALL_FAILED_INVALID_URI; 13312 } 13313 if (!pkgSetting.getInstalled(userId)) { 13314 pkgSetting.setInstalled(true, userId); 13315 pkgSetting.setHidden(false, userId); 13316 pkgSetting.setInstallReason(installReason, userId); 13317 mSettings.writePackageRestrictionsLPr(userId); 13318 mSettings.writeKernelMappingLPr(pkgSetting); 13319 installed = true; 13320 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13321 // upgrade app from instant to full; we don't allow app downgrade 13322 installed = true; 13323 } 13324 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13325 } 13326 13327 if (installed) { 13328 if (pkgSetting.pkg != null) { 13329 synchronized (mInstallLock) { 13330 // We don't need to freeze for a brand new install 13331 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13332 } 13333 } 13334 sendPackageAddedForUser(packageName, pkgSetting, userId); 13335 synchronized (mPackages) { 13336 updateSequenceNumberLP(packageName, new int[]{ userId }); 13337 } 13338 } 13339 } finally { 13340 Binder.restoreCallingIdentity(callingId); 13341 } 13342 13343 return PackageManager.INSTALL_SUCCEEDED; 13344 } 13345 13346 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13347 boolean instantApp, boolean fullApp) { 13348 // no state specified; do nothing 13349 if (!instantApp && !fullApp) { 13350 return; 13351 } 13352 if (userId != UserHandle.USER_ALL) { 13353 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13354 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13355 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13356 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13357 } 13358 } else { 13359 for (int currentUserId : sUserManager.getUserIds()) { 13360 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13361 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13362 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13363 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13364 } 13365 } 13366 } 13367 } 13368 13369 boolean isUserRestricted(int userId, String restrictionKey) { 13370 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13371 if (restrictions.getBoolean(restrictionKey, false)) { 13372 Log.w(TAG, "User is restricted: " + restrictionKey); 13373 return true; 13374 } 13375 return false; 13376 } 13377 13378 @Override 13379 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13380 int userId) { 13381 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13383 true /* requireFullPermission */, true /* checkShell */, 13384 "setPackagesSuspended for user " + userId); 13385 13386 if (ArrayUtils.isEmpty(packageNames)) { 13387 return packageNames; 13388 } 13389 13390 // List of package names for whom the suspended state has changed. 13391 List<String> changedPackages = new ArrayList<>(packageNames.length); 13392 // List of package names for whom the suspended state is not set as requested in this 13393 // method. 13394 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13395 long callingId = Binder.clearCallingIdentity(); 13396 try { 13397 for (int i = 0; i < packageNames.length; i++) { 13398 String packageName = packageNames[i]; 13399 boolean changed = false; 13400 final int appId; 13401 synchronized (mPackages) { 13402 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13403 if (pkgSetting == null) { 13404 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13405 + "\". Skipping suspending/un-suspending."); 13406 unactionedPackages.add(packageName); 13407 continue; 13408 } 13409 appId = pkgSetting.appId; 13410 if (pkgSetting.getSuspended(userId) != suspended) { 13411 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13412 unactionedPackages.add(packageName); 13413 continue; 13414 } 13415 pkgSetting.setSuspended(suspended, userId); 13416 mSettings.writePackageRestrictionsLPr(userId); 13417 changed = true; 13418 changedPackages.add(packageName); 13419 } 13420 } 13421 13422 if (changed && suspended) { 13423 killApplication(packageName, UserHandle.getUid(userId, appId), 13424 "suspending package"); 13425 } 13426 } 13427 } finally { 13428 Binder.restoreCallingIdentity(callingId); 13429 } 13430 13431 if (!changedPackages.isEmpty()) { 13432 sendPackagesSuspendedForUser(changedPackages.toArray( 13433 new String[changedPackages.size()]), userId, suspended); 13434 } 13435 13436 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13437 } 13438 13439 @Override 13440 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13441 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13442 true /* requireFullPermission */, false /* checkShell */, 13443 "isPackageSuspendedForUser for user " + userId); 13444 synchronized (mPackages) { 13445 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13446 if (pkgSetting == null) { 13447 throw new IllegalArgumentException("Unknown target package: " + packageName); 13448 } 13449 return pkgSetting.getSuspended(userId); 13450 } 13451 } 13452 13453 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13454 if (isPackageDeviceAdmin(packageName, userId)) { 13455 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13456 + "\": has an active device admin"); 13457 return false; 13458 } 13459 13460 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13461 if (packageName.equals(activeLauncherPackageName)) { 13462 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13463 + "\": contains the active launcher"); 13464 return false; 13465 } 13466 13467 if (packageName.equals(mRequiredInstallerPackage)) { 13468 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13469 + "\": required for package installation"); 13470 return false; 13471 } 13472 13473 if (packageName.equals(mRequiredUninstallerPackage)) { 13474 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13475 + "\": required for package uninstallation"); 13476 return false; 13477 } 13478 13479 if (packageName.equals(mRequiredVerifierPackage)) { 13480 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13481 + "\": required for package verification"); 13482 return false; 13483 } 13484 13485 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13486 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13487 + "\": is the default dialer"); 13488 return false; 13489 } 13490 13491 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13492 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13493 + "\": protected package"); 13494 return false; 13495 } 13496 13497 // Cannot suspend static shared libs as they are considered 13498 // a part of the using app (emulating static linking). Also 13499 // static libs are installed always on internal storage. 13500 PackageParser.Package pkg = mPackages.get(packageName); 13501 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13502 Slog.w(TAG, "Cannot suspend package: " + packageName 13503 + " providing static shared library: " 13504 + pkg.staticSharedLibName); 13505 return false; 13506 } 13507 13508 return true; 13509 } 13510 13511 private String getActiveLauncherPackageName(int userId) { 13512 Intent intent = new Intent(Intent.ACTION_MAIN); 13513 intent.addCategory(Intent.CATEGORY_HOME); 13514 ResolveInfo resolveInfo = resolveIntent( 13515 intent, 13516 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13517 PackageManager.MATCH_DEFAULT_ONLY, 13518 userId); 13519 13520 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13521 } 13522 13523 private String getDefaultDialerPackageName(int userId) { 13524 synchronized (mPackages) { 13525 return mSettings.getDefaultDialerPackageNameLPw(userId); 13526 } 13527 } 13528 13529 @Override 13530 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13531 mContext.enforceCallingOrSelfPermission( 13532 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13533 "Only package verification agents can verify applications"); 13534 13535 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13536 final PackageVerificationResponse response = new PackageVerificationResponse( 13537 verificationCode, Binder.getCallingUid()); 13538 msg.arg1 = id; 13539 msg.obj = response; 13540 mHandler.sendMessage(msg); 13541 } 13542 13543 @Override 13544 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13545 long millisecondsToDelay) { 13546 mContext.enforceCallingOrSelfPermission( 13547 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13548 "Only package verification agents can extend verification timeouts"); 13549 13550 final PackageVerificationState state = mPendingVerification.get(id); 13551 final PackageVerificationResponse response = new PackageVerificationResponse( 13552 verificationCodeAtTimeout, Binder.getCallingUid()); 13553 13554 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13555 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13556 } 13557 if (millisecondsToDelay < 0) { 13558 millisecondsToDelay = 0; 13559 } 13560 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13561 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13562 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13563 } 13564 13565 if ((state != null) && !state.timeoutExtended()) { 13566 state.extendTimeout(); 13567 13568 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13569 msg.arg1 = id; 13570 msg.obj = response; 13571 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13572 } 13573 } 13574 13575 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13576 int verificationCode, UserHandle user) { 13577 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13578 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13579 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13580 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13581 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13582 13583 mContext.sendBroadcastAsUser(intent, user, 13584 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13585 } 13586 13587 private ComponentName matchComponentForVerifier(String packageName, 13588 List<ResolveInfo> receivers) { 13589 ActivityInfo targetReceiver = null; 13590 13591 final int NR = receivers.size(); 13592 for (int i = 0; i < NR; i++) { 13593 final ResolveInfo info = receivers.get(i); 13594 if (info.activityInfo == null) { 13595 continue; 13596 } 13597 13598 if (packageName.equals(info.activityInfo.packageName)) { 13599 targetReceiver = info.activityInfo; 13600 break; 13601 } 13602 } 13603 13604 if (targetReceiver == null) { 13605 return null; 13606 } 13607 13608 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13609 } 13610 13611 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13612 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13613 if (pkgInfo.verifiers.length == 0) { 13614 return null; 13615 } 13616 13617 final int N = pkgInfo.verifiers.length; 13618 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13619 for (int i = 0; i < N; i++) { 13620 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13621 13622 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13623 receivers); 13624 if (comp == null) { 13625 continue; 13626 } 13627 13628 final int verifierUid = getUidForVerifier(verifierInfo); 13629 if (verifierUid == -1) { 13630 continue; 13631 } 13632 13633 if (DEBUG_VERIFY) { 13634 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13635 + " with the correct signature"); 13636 } 13637 sufficientVerifiers.add(comp); 13638 verificationState.addSufficientVerifier(verifierUid); 13639 } 13640 13641 return sufficientVerifiers; 13642 } 13643 13644 private int getUidForVerifier(VerifierInfo verifierInfo) { 13645 synchronized (mPackages) { 13646 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13647 if (pkg == null) { 13648 return -1; 13649 } else if (pkg.mSignatures.length != 1) { 13650 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13651 + " has more than one signature; ignoring"); 13652 return -1; 13653 } 13654 13655 /* 13656 * If the public key of the package's signature does not match 13657 * our expected public key, then this is a different package and 13658 * we should skip. 13659 */ 13660 13661 final byte[] expectedPublicKey; 13662 try { 13663 final Signature verifierSig = pkg.mSignatures[0]; 13664 final PublicKey publicKey = verifierSig.getPublicKey(); 13665 expectedPublicKey = publicKey.getEncoded(); 13666 } catch (CertificateException e) { 13667 return -1; 13668 } 13669 13670 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13671 13672 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13673 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13674 + " does not have the expected public key; ignoring"); 13675 return -1; 13676 } 13677 13678 return pkg.applicationInfo.uid; 13679 } 13680 } 13681 13682 @Override 13683 public void finishPackageInstall(int token, boolean didLaunch) { 13684 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13685 13686 if (DEBUG_INSTALL) { 13687 Slog.v(TAG, "BM finishing package install for " + token); 13688 } 13689 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13690 13691 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13692 mHandler.sendMessage(msg); 13693 } 13694 13695 /** 13696 * Get the verification agent timeout. 13697 * 13698 * @return verification timeout in milliseconds 13699 */ 13700 private long getVerificationTimeout() { 13701 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13702 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13703 DEFAULT_VERIFICATION_TIMEOUT); 13704 } 13705 13706 /** 13707 * Get the default verification agent response code. 13708 * 13709 * @return default verification response code 13710 */ 13711 private int getDefaultVerificationResponse() { 13712 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13713 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13714 DEFAULT_VERIFICATION_RESPONSE); 13715 } 13716 13717 /** 13718 * Check whether or not package verification has been enabled. 13719 * 13720 * @return true if verification should be performed 13721 */ 13722 private boolean isVerificationEnabled(int userId, int installFlags) { 13723 if (!DEFAULT_VERIFY_ENABLE) { 13724 return false; 13725 } 13726 13727 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13728 13729 // Check if installing from ADB 13730 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13731 // Do not run verification in a test harness environment 13732 if (ActivityManager.isRunningInTestHarness()) { 13733 return false; 13734 } 13735 if (ensureVerifyAppsEnabled) { 13736 return true; 13737 } 13738 // Check if the developer does not want package verification for ADB installs 13739 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13740 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13741 return false; 13742 } 13743 } 13744 13745 if (ensureVerifyAppsEnabled) { 13746 return true; 13747 } 13748 13749 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13750 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13751 } 13752 13753 @Override 13754 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13755 throws RemoteException { 13756 mContext.enforceCallingOrSelfPermission( 13757 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13758 "Only intentfilter verification agents can verify applications"); 13759 13760 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13761 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13762 Binder.getCallingUid(), verificationCode, failedDomains); 13763 msg.arg1 = id; 13764 msg.obj = response; 13765 mHandler.sendMessage(msg); 13766 } 13767 13768 @Override 13769 public int getIntentVerificationStatus(String packageName, int userId) { 13770 synchronized (mPackages) { 13771 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13772 } 13773 } 13774 13775 @Override 13776 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13777 mContext.enforceCallingOrSelfPermission( 13778 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13779 13780 boolean result = false; 13781 synchronized (mPackages) { 13782 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13783 } 13784 if (result) { 13785 scheduleWritePackageRestrictionsLocked(userId); 13786 } 13787 return result; 13788 } 13789 13790 @Override 13791 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13792 String packageName) { 13793 synchronized (mPackages) { 13794 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13795 } 13796 } 13797 13798 @Override 13799 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13800 if (TextUtils.isEmpty(packageName)) { 13801 return ParceledListSlice.emptyList(); 13802 } 13803 synchronized (mPackages) { 13804 PackageParser.Package pkg = mPackages.get(packageName); 13805 if (pkg == null || pkg.activities == null) { 13806 return ParceledListSlice.emptyList(); 13807 } 13808 final int count = pkg.activities.size(); 13809 ArrayList<IntentFilter> result = new ArrayList<>(); 13810 for (int n=0; n<count; n++) { 13811 PackageParser.Activity activity = pkg.activities.get(n); 13812 if (activity.intents != null && activity.intents.size() > 0) { 13813 result.addAll(activity.intents); 13814 } 13815 } 13816 return new ParceledListSlice<>(result); 13817 } 13818 } 13819 13820 @Override 13821 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13822 mContext.enforceCallingOrSelfPermission( 13823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13824 13825 synchronized (mPackages) { 13826 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13827 if (packageName != null) { 13828 result |= updateIntentVerificationStatus(packageName, 13829 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13830 userId); 13831 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13832 packageName, userId); 13833 } 13834 return result; 13835 } 13836 } 13837 13838 @Override 13839 public String getDefaultBrowserPackageName(int userId) { 13840 synchronized (mPackages) { 13841 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13842 } 13843 } 13844 13845 /** 13846 * Get the "allow unknown sources" setting. 13847 * 13848 * @return the current "allow unknown sources" setting 13849 */ 13850 private int getUnknownSourcesSettings() { 13851 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13852 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13853 -1); 13854 } 13855 13856 @Override 13857 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13858 final int uid = Binder.getCallingUid(); 13859 // writer 13860 synchronized (mPackages) { 13861 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13862 if (targetPackageSetting == null) { 13863 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13864 } 13865 13866 PackageSetting installerPackageSetting; 13867 if (installerPackageName != null) { 13868 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13869 if (installerPackageSetting == null) { 13870 throw new IllegalArgumentException("Unknown installer package: " 13871 + installerPackageName); 13872 } 13873 } else { 13874 installerPackageSetting = null; 13875 } 13876 13877 Signature[] callerSignature; 13878 Object obj = mSettings.getUserIdLPr(uid); 13879 if (obj != null) { 13880 if (obj instanceof SharedUserSetting) { 13881 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13882 } else if (obj instanceof PackageSetting) { 13883 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13884 } else { 13885 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13886 } 13887 } else { 13888 throw new SecurityException("Unknown calling UID: " + uid); 13889 } 13890 13891 // Verify: can't set installerPackageName to a package that is 13892 // not signed with the same cert as the caller. 13893 if (installerPackageSetting != null) { 13894 if (compareSignatures(callerSignature, 13895 installerPackageSetting.signatures.mSignatures) 13896 != PackageManager.SIGNATURE_MATCH) { 13897 throw new SecurityException( 13898 "Caller does not have same cert as new installer package " 13899 + installerPackageName); 13900 } 13901 } 13902 13903 // Verify: if target already has an installer package, it must 13904 // be signed with the same cert as the caller. 13905 if (targetPackageSetting.installerPackageName != null) { 13906 PackageSetting setting = mSettings.mPackages.get( 13907 targetPackageSetting.installerPackageName); 13908 // If the currently set package isn't valid, then it's always 13909 // okay to change it. 13910 if (setting != null) { 13911 if (compareSignatures(callerSignature, 13912 setting.signatures.mSignatures) 13913 != PackageManager.SIGNATURE_MATCH) { 13914 throw new SecurityException( 13915 "Caller does not have same cert as old installer package " 13916 + targetPackageSetting.installerPackageName); 13917 } 13918 } 13919 } 13920 13921 // Okay! 13922 targetPackageSetting.installerPackageName = installerPackageName; 13923 if (installerPackageName != null) { 13924 mSettings.mInstallerPackages.add(installerPackageName); 13925 } 13926 scheduleWriteSettingsLocked(); 13927 } 13928 } 13929 13930 @Override 13931 public void setApplicationCategoryHint(String packageName, int categoryHint, 13932 String callerPackageName) { 13933 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13934 callerPackageName); 13935 synchronized (mPackages) { 13936 PackageSetting ps = mSettings.mPackages.get(packageName); 13937 if (ps == null) { 13938 throw new IllegalArgumentException("Unknown target package " + packageName); 13939 } 13940 13941 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13942 throw new IllegalArgumentException("Calling package " + callerPackageName 13943 + " is not installer for " + packageName); 13944 } 13945 13946 if (ps.categoryHint != categoryHint) { 13947 ps.categoryHint = categoryHint; 13948 scheduleWriteSettingsLocked(); 13949 } 13950 } 13951 } 13952 13953 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13954 // Queue up an async operation since the package installation may take a little while. 13955 mHandler.post(new Runnable() { 13956 public void run() { 13957 mHandler.removeCallbacks(this); 13958 // Result object to be returned 13959 PackageInstalledInfo res = new PackageInstalledInfo(); 13960 res.setReturnCode(currentStatus); 13961 res.uid = -1; 13962 res.pkg = null; 13963 res.removedInfo = null; 13964 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13965 args.doPreInstall(res.returnCode); 13966 synchronized (mInstallLock) { 13967 installPackageTracedLI(args, res); 13968 } 13969 args.doPostInstall(res.returnCode, res.uid); 13970 } 13971 13972 // A restore should be performed at this point if (a) the install 13973 // succeeded, (b) the operation is not an update, and (c) the new 13974 // package has not opted out of backup participation. 13975 final boolean update = res.removedInfo != null 13976 && res.removedInfo.removedPackage != null; 13977 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13978 boolean doRestore = !update 13979 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13980 13981 // Set up the post-install work request bookkeeping. This will be used 13982 // and cleaned up by the post-install event handling regardless of whether 13983 // there's a restore pass performed. Token values are >= 1. 13984 int token; 13985 if (mNextInstallToken < 0) mNextInstallToken = 1; 13986 token = mNextInstallToken++; 13987 13988 PostInstallData data = new PostInstallData(args, res); 13989 mRunningInstalls.put(token, data); 13990 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13991 13992 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13993 // Pass responsibility to the Backup Manager. It will perform a 13994 // restore if appropriate, then pass responsibility back to the 13995 // Package Manager to run the post-install observer callbacks 13996 // and broadcasts. 13997 IBackupManager bm = IBackupManager.Stub.asInterface( 13998 ServiceManager.getService(Context.BACKUP_SERVICE)); 13999 if (bm != null) { 14000 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14001 + " to BM for possible restore"); 14002 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14003 try { 14004 // TODO: http://b/22388012 14005 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14006 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14007 } else { 14008 doRestore = false; 14009 } 14010 } catch (RemoteException e) { 14011 // can't happen; the backup manager is local 14012 } catch (Exception e) { 14013 Slog.e(TAG, "Exception trying to enqueue restore", e); 14014 doRestore = false; 14015 } 14016 } else { 14017 Slog.e(TAG, "Backup Manager not found!"); 14018 doRestore = false; 14019 } 14020 } 14021 14022 if (!doRestore) { 14023 // No restore possible, or the Backup Manager was mysteriously not 14024 // available -- just fire the post-install work request directly. 14025 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14026 14027 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14028 14029 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14030 mHandler.sendMessage(msg); 14031 } 14032 } 14033 }); 14034 } 14035 14036 /** 14037 * Callback from PackageSettings whenever an app is first transitioned out of the 14038 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14039 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14040 * here whether the app is the target of an ongoing install, and only send the 14041 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14042 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14043 * handling. 14044 */ 14045 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14046 // Serialize this with the rest of the install-process message chain. In the 14047 // restore-at-install case, this Runnable will necessarily run before the 14048 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14049 // are coherent. In the non-restore case, the app has already completed install 14050 // and been launched through some other means, so it is not in a problematic 14051 // state for observers to see the FIRST_LAUNCH signal. 14052 mHandler.post(new Runnable() { 14053 @Override 14054 public void run() { 14055 for (int i = 0; i < mRunningInstalls.size(); i++) { 14056 final PostInstallData data = mRunningInstalls.valueAt(i); 14057 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14058 continue; 14059 } 14060 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14061 // right package; but is it for the right user? 14062 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14063 if (userId == data.res.newUsers[uIndex]) { 14064 if (DEBUG_BACKUP) { 14065 Slog.i(TAG, "Package " + pkgName 14066 + " being restored so deferring FIRST_LAUNCH"); 14067 } 14068 return; 14069 } 14070 } 14071 } 14072 } 14073 // didn't find it, so not being restored 14074 if (DEBUG_BACKUP) { 14075 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14076 } 14077 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14078 } 14079 }); 14080 } 14081 14082 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14083 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14084 installerPkg, null, userIds); 14085 } 14086 14087 private abstract class HandlerParams { 14088 private static final int MAX_RETRIES = 4; 14089 14090 /** 14091 * Number of times startCopy() has been attempted and had a non-fatal 14092 * error. 14093 */ 14094 private int mRetries = 0; 14095 14096 /** User handle for the user requesting the information or installation. */ 14097 private final UserHandle mUser; 14098 String traceMethod; 14099 int traceCookie; 14100 14101 HandlerParams(UserHandle user) { 14102 mUser = user; 14103 } 14104 14105 UserHandle getUser() { 14106 return mUser; 14107 } 14108 14109 HandlerParams setTraceMethod(String traceMethod) { 14110 this.traceMethod = traceMethod; 14111 return this; 14112 } 14113 14114 HandlerParams setTraceCookie(int traceCookie) { 14115 this.traceCookie = traceCookie; 14116 return this; 14117 } 14118 14119 final boolean startCopy() { 14120 boolean res; 14121 try { 14122 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14123 14124 if (++mRetries > MAX_RETRIES) { 14125 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14126 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14127 handleServiceError(); 14128 return false; 14129 } else { 14130 handleStartCopy(); 14131 res = true; 14132 } 14133 } catch (RemoteException e) { 14134 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14135 mHandler.sendEmptyMessage(MCS_RECONNECT); 14136 res = false; 14137 } 14138 handleReturnCode(); 14139 return res; 14140 } 14141 14142 final void serviceError() { 14143 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14144 handleServiceError(); 14145 handleReturnCode(); 14146 } 14147 14148 abstract void handleStartCopy() throws RemoteException; 14149 abstract void handleServiceError(); 14150 abstract void handleReturnCode(); 14151 } 14152 14153 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14154 for (File path : paths) { 14155 try { 14156 mcs.clearDirectory(path.getAbsolutePath()); 14157 } catch (RemoteException e) { 14158 } 14159 } 14160 } 14161 14162 static class OriginInfo { 14163 /** 14164 * Location where install is coming from, before it has been 14165 * copied/renamed into place. This could be a single monolithic APK 14166 * file, or a cluster directory. This location may be untrusted. 14167 */ 14168 final File file; 14169 final String cid; 14170 14171 /** 14172 * Flag indicating that {@link #file} or {@link #cid} has already been 14173 * staged, meaning downstream users don't need to defensively copy the 14174 * contents. 14175 */ 14176 final boolean staged; 14177 14178 /** 14179 * Flag indicating that {@link #file} or {@link #cid} is an already 14180 * installed app that is being moved. 14181 */ 14182 final boolean existing; 14183 14184 final String resolvedPath; 14185 final File resolvedFile; 14186 14187 static OriginInfo fromNothing() { 14188 return new OriginInfo(null, null, false, false); 14189 } 14190 14191 static OriginInfo fromUntrustedFile(File file) { 14192 return new OriginInfo(file, null, false, false); 14193 } 14194 14195 static OriginInfo fromExistingFile(File file) { 14196 return new OriginInfo(file, null, false, true); 14197 } 14198 14199 static OriginInfo fromStagedFile(File file) { 14200 return new OriginInfo(file, null, true, false); 14201 } 14202 14203 static OriginInfo fromStagedContainer(String cid) { 14204 return new OriginInfo(null, cid, true, false); 14205 } 14206 14207 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14208 this.file = file; 14209 this.cid = cid; 14210 this.staged = staged; 14211 this.existing = existing; 14212 14213 if (cid != null) { 14214 resolvedPath = PackageHelper.getSdDir(cid); 14215 resolvedFile = new File(resolvedPath); 14216 } else if (file != null) { 14217 resolvedPath = file.getAbsolutePath(); 14218 resolvedFile = file; 14219 } else { 14220 resolvedPath = null; 14221 resolvedFile = null; 14222 } 14223 } 14224 } 14225 14226 static class MoveInfo { 14227 final int moveId; 14228 final String fromUuid; 14229 final String toUuid; 14230 final String packageName; 14231 final String dataAppName; 14232 final int appId; 14233 final String seinfo; 14234 final int targetSdkVersion; 14235 14236 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14237 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14238 this.moveId = moveId; 14239 this.fromUuid = fromUuid; 14240 this.toUuid = toUuid; 14241 this.packageName = packageName; 14242 this.dataAppName = dataAppName; 14243 this.appId = appId; 14244 this.seinfo = seinfo; 14245 this.targetSdkVersion = targetSdkVersion; 14246 } 14247 } 14248 14249 static class VerificationInfo { 14250 /** A constant used to indicate that a uid value is not present. */ 14251 public static final int NO_UID = -1; 14252 14253 /** URI referencing where the package was downloaded from. */ 14254 final Uri originatingUri; 14255 14256 /** HTTP referrer URI associated with the originatingURI. */ 14257 final Uri referrer; 14258 14259 /** UID of the application that the install request originated from. */ 14260 final int originatingUid; 14261 14262 /** UID of application requesting the install */ 14263 final int installerUid; 14264 14265 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14266 this.originatingUri = originatingUri; 14267 this.referrer = referrer; 14268 this.originatingUid = originatingUid; 14269 this.installerUid = installerUid; 14270 } 14271 } 14272 14273 class InstallParams extends HandlerParams { 14274 final OriginInfo origin; 14275 final MoveInfo move; 14276 final IPackageInstallObserver2 observer; 14277 int installFlags; 14278 final String installerPackageName; 14279 final String volumeUuid; 14280 private InstallArgs mArgs; 14281 private int mRet; 14282 final String packageAbiOverride; 14283 final String[] grantedRuntimePermissions; 14284 final VerificationInfo verificationInfo; 14285 final Certificate[][] certificates; 14286 final int installReason; 14287 14288 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14289 int installFlags, String installerPackageName, String volumeUuid, 14290 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14291 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14292 super(user); 14293 this.origin = origin; 14294 this.move = move; 14295 this.observer = observer; 14296 this.installFlags = installFlags; 14297 this.installerPackageName = installerPackageName; 14298 this.volumeUuid = volumeUuid; 14299 this.verificationInfo = verificationInfo; 14300 this.packageAbiOverride = packageAbiOverride; 14301 this.grantedRuntimePermissions = grantedPermissions; 14302 this.certificates = certificates; 14303 this.installReason = installReason; 14304 } 14305 14306 @Override 14307 public String toString() { 14308 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14309 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14310 } 14311 14312 private int installLocationPolicy(PackageInfoLite pkgLite) { 14313 String packageName = pkgLite.packageName; 14314 int installLocation = pkgLite.installLocation; 14315 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14316 // reader 14317 synchronized (mPackages) { 14318 // Currently installed package which the new package is attempting to replace or 14319 // null if no such package is installed. 14320 PackageParser.Package installedPkg = mPackages.get(packageName); 14321 // Package which currently owns the data which the new package will own if installed. 14322 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14323 // will be null whereas dataOwnerPkg will contain information about the package 14324 // which was uninstalled while keeping its data. 14325 PackageParser.Package dataOwnerPkg = installedPkg; 14326 if (dataOwnerPkg == null) { 14327 PackageSetting ps = mSettings.mPackages.get(packageName); 14328 if (ps != null) { 14329 dataOwnerPkg = ps.pkg; 14330 } 14331 } 14332 14333 if (dataOwnerPkg != null) { 14334 // If installed, the package will get access to data left on the device by its 14335 // predecessor. As a security measure, this is permited only if this is not a 14336 // version downgrade or if the predecessor package is marked as debuggable and 14337 // a downgrade is explicitly requested. 14338 // 14339 // On debuggable platform builds, downgrades are permitted even for 14340 // non-debuggable packages to make testing easier. Debuggable platform builds do 14341 // not offer security guarantees and thus it's OK to disable some security 14342 // mechanisms to make debugging/testing easier on those builds. However, even on 14343 // debuggable builds downgrades of packages are permitted only if requested via 14344 // installFlags. This is because we aim to keep the behavior of debuggable 14345 // platform builds as close as possible to the behavior of non-debuggable 14346 // platform builds. 14347 final boolean downgradeRequested = 14348 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14349 final boolean packageDebuggable = 14350 (dataOwnerPkg.applicationInfo.flags 14351 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14352 final boolean downgradePermitted = 14353 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14354 if (!downgradePermitted) { 14355 try { 14356 checkDowngrade(dataOwnerPkg, pkgLite); 14357 } catch (PackageManagerException e) { 14358 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14359 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14360 } 14361 } 14362 } 14363 14364 if (installedPkg != null) { 14365 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14366 // Check for updated system application. 14367 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14368 if (onSd) { 14369 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14370 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14371 } 14372 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14373 } else { 14374 if (onSd) { 14375 // Install flag overrides everything. 14376 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14377 } 14378 // If current upgrade specifies particular preference 14379 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14380 // Application explicitly specified internal. 14381 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14382 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14383 // App explictly prefers external. Let policy decide 14384 } else { 14385 // Prefer previous location 14386 if (isExternal(installedPkg)) { 14387 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14388 } 14389 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14390 } 14391 } 14392 } else { 14393 // Invalid install. Return error code 14394 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14395 } 14396 } 14397 } 14398 // All the special cases have been taken care of. 14399 // Return result based on recommended install location. 14400 if (onSd) { 14401 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14402 } 14403 return pkgLite.recommendedInstallLocation; 14404 } 14405 14406 /* 14407 * Invoke remote method to get package information and install 14408 * location values. Override install location based on default 14409 * policy if needed and then create install arguments based 14410 * on the install location. 14411 */ 14412 public void handleStartCopy() throws RemoteException { 14413 int ret = PackageManager.INSTALL_SUCCEEDED; 14414 14415 // If we're already staged, we've firmly committed to an install location 14416 if (origin.staged) { 14417 if (origin.file != null) { 14418 installFlags |= PackageManager.INSTALL_INTERNAL; 14419 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14420 } else if (origin.cid != null) { 14421 installFlags |= PackageManager.INSTALL_EXTERNAL; 14422 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14423 } else { 14424 throw new IllegalStateException("Invalid stage location"); 14425 } 14426 } 14427 14428 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14429 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14430 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14431 PackageInfoLite pkgLite = null; 14432 14433 if (onInt && onSd) { 14434 // Check if both bits are set. 14435 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14436 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14437 } else if (onSd && ephemeral) { 14438 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14439 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14440 } else { 14441 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14442 packageAbiOverride); 14443 14444 if (DEBUG_EPHEMERAL && ephemeral) { 14445 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14446 } 14447 14448 /* 14449 * If we have too little free space, try to free cache 14450 * before giving up. 14451 */ 14452 if (!origin.staged && pkgLite.recommendedInstallLocation 14453 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14454 // TODO: focus freeing disk space on the target device 14455 final StorageManager storage = StorageManager.from(mContext); 14456 final long lowThreshold = storage.getStorageLowBytes( 14457 Environment.getDataDirectory()); 14458 14459 final long sizeBytes = mContainerService.calculateInstalledSize( 14460 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14461 14462 try { 14463 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14464 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14465 installFlags, packageAbiOverride); 14466 } catch (InstallerException e) { 14467 Slog.w(TAG, "Failed to free cache", e); 14468 } 14469 14470 /* 14471 * The cache free must have deleted the file we 14472 * downloaded to install. 14473 * 14474 * TODO: fix the "freeCache" call to not delete 14475 * the file we care about. 14476 */ 14477 if (pkgLite.recommendedInstallLocation 14478 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14479 pkgLite.recommendedInstallLocation 14480 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14481 } 14482 } 14483 } 14484 14485 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14486 int loc = pkgLite.recommendedInstallLocation; 14487 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14488 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14489 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14490 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14491 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14492 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14493 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14494 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14495 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14496 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14497 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14498 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14499 } else { 14500 // Override with defaults if needed. 14501 loc = installLocationPolicy(pkgLite); 14502 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14503 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14504 } else if (!onSd && !onInt) { 14505 // Override install location with flags 14506 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14507 // Set the flag to install on external media. 14508 installFlags |= PackageManager.INSTALL_EXTERNAL; 14509 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14510 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14511 if (DEBUG_EPHEMERAL) { 14512 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14513 } 14514 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14515 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14516 |PackageManager.INSTALL_INTERNAL); 14517 } else { 14518 // Make sure the flag for installing on external 14519 // media is unset 14520 installFlags |= PackageManager.INSTALL_INTERNAL; 14521 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14522 } 14523 } 14524 } 14525 } 14526 14527 final InstallArgs args = createInstallArgs(this); 14528 mArgs = args; 14529 14530 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14531 // TODO: http://b/22976637 14532 // Apps installed for "all" users use the device owner to verify the app 14533 UserHandle verifierUser = getUser(); 14534 if (verifierUser == UserHandle.ALL) { 14535 verifierUser = UserHandle.SYSTEM; 14536 } 14537 14538 /* 14539 * Determine if we have any installed package verifiers. If we 14540 * do, then we'll defer to them to verify the packages. 14541 */ 14542 final int requiredUid = mRequiredVerifierPackage == null ? -1 14543 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14544 verifierUser.getIdentifier()); 14545 if (!origin.existing && requiredUid != -1 14546 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14547 final Intent verification = new Intent( 14548 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14549 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14550 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14551 PACKAGE_MIME_TYPE); 14552 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14553 14554 // Query all live verifiers based on current user state 14555 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14556 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14557 14558 if (DEBUG_VERIFY) { 14559 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14560 + verification.toString() + " with " + pkgLite.verifiers.length 14561 + " optional verifiers"); 14562 } 14563 14564 final int verificationId = mPendingVerificationToken++; 14565 14566 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14567 14568 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14569 installerPackageName); 14570 14571 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14572 installFlags); 14573 14574 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14575 pkgLite.packageName); 14576 14577 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14578 pkgLite.versionCode); 14579 14580 if (verificationInfo != null) { 14581 if (verificationInfo.originatingUri != null) { 14582 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14583 verificationInfo.originatingUri); 14584 } 14585 if (verificationInfo.referrer != null) { 14586 verification.putExtra(Intent.EXTRA_REFERRER, 14587 verificationInfo.referrer); 14588 } 14589 if (verificationInfo.originatingUid >= 0) { 14590 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14591 verificationInfo.originatingUid); 14592 } 14593 if (verificationInfo.installerUid >= 0) { 14594 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14595 verificationInfo.installerUid); 14596 } 14597 } 14598 14599 final PackageVerificationState verificationState = new PackageVerificationState( 14600 requiredUid, args); 14601 14602 mPendingVerification.append(verificationId, verificationState); 14603 14604 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14605 receivers, verificationState); 14606 14607 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14608 final long idleDuration = getVerificationTimeout(); 14609 14610 /* 14611 * If any sufficient verifiers were listed in the package 14612 * manifest, attempt to ask them. 14613 */ 14614 if (sufficientVerifiers != null) { 14615 final int N = sufficientVerifiers.size(); 14616 if (N == 0) { 14617 Slog.i(TAG, "Additional verifiers required, but none installed."); 14618 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14619 } else { 14620 for (int i = 0; i < N; i++) { 14621 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14622 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14623 verifierComponent.getPackageName(), idleDuration, 14624 verifierUser.getIdentifier(), false, "package verifier"); 14625 14626 final Intent sufficientIntent = new Intent(verification); 14627 sufficientIntent.setComponent(verifierComponent); 14628 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14629 } 14630 } 14631 } 14632 14633 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14634 mRequiredVerifierPackage, receivers); 14635 if (ret == PackageManager.INSTALL_SUCCEEDED 14636 && mRequiredVerifierPackage != null) { 14637 Trace.asyncTraceBegin( 14638 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14639 /* 14640 * Send the intent to the required verification agent, 14641 * but only start the verification timeout after the 14642 * target BroadcastReceivers have run. 14643 */ 14644 verification.setComponent(requiredVerifierComponent); 14645 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14646 mRequiredVerifierPackage, idleDuration, 14647 verifierUser.getIdentifier(), false, "package verifier"); 14648 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14649 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14650 new BroadcastReceiver() { 14651 @Override 14652 public void onReceive(Context context, Intent intent) { 14653 final Message msg = mHandler 14654 .obtainMessage(CHECK_PENDING_VERIFICATION); 14655 msg.arg1 = verificationId; 14656 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14657 } 14658 }, null, 0, null, null); 14659 14660 /* 14661 * We don't want the copy to proceed until verification 14662 * succeeds, so null out this field. 14663 */ 14664 mArgs = null; 14665 } 14666 } else { 14667 /* 14668 * No package verification is enabled, so immediately start 14669 * the remote call to initiate copy using temporary file. 14670 */ 14671 ret = args.copyApk(mContainerService, true); 14672 } 14673 } 14674 14675 mRet = ret; 14676 } 14677 14678 @Override 14679 void handleReturnCode() { 14680 // If mArgs is null, then MCS couldn't be reached. When it 14681 // reconnects, it will try again to install. At that point, this 14682 // will succeed. 14683 if (mArgs != null) { 14684 processPendingInstall(mArgs, mRet); 14685 } 14686 } 14687 14688 @Override 14689 void handleServiceError() { 14690 mArgs = createInstallArgs(this); 14691 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14692 } 14693 14694 public boolean isForwardLocked() { 14695 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14696 } 14697 } 14698 14699 /** 14700 * Used during creation of InstallArgs 14701 * 14702 * @param installFlags package installation flags 14703 * @return true if should be installed on external storage 14704 */ 14705 private static boolean installOnExternalAsec(int installFlags) { 14706 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14707 return false; 14708 } 14709 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14710 return true; 14711 } 14712 return false; 14713 } 14714 14715 /** 14716 * Used during creation of InstallArgs 14717 * 14718 * @param installFlags package installation flags 14719 * @return true if should be installed as forward locked 14720 */ 14721 private static boolean installForwardLocked(int installFlags) { 14722 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14723 } 14724 14725 private InstallArgs createInstallArgs(InstallParams params) { 14726 if (params.move != null) { 14727 return new MoveInstallArgs(params); 14728 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14729 return new AsecInstallArgs(params); 14730 } else { 14731 return new FileInstallArgs(params); 14732 } 14733 } 14734 14735 /** 14736 * Create args that describe an existing installed package. Typically used 14737 * when cleaning up old installs, or used as a move source. 14738 */ 14739 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14740 String resourcePath, String[] instructionSets) { 14741 final boolean isInAsec; 14742 if (installOnExternalAsec(installFlags)) { 14743 /* Apps on SD card are always in ASEC containers. */ 14744 isInAsec = true; 14745 } else if (installForwardLocked(installFlags) 14746 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14747 /* 14748 * Forward-locked apps are only in ASEC containers if they're the 14749 * new style 14750 */ 14751 isInAsec = true; 14752 } else { 14753 isInAsec = false; 14754 } 14755 14756 if (isInAsec) { 14757 return new AsecInstallArgs(codePath, instructionSets, 14758 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14759 } else { 14760 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14761 } 14762 } 14763 14764 static abstract class InstallArgs { 14765 /** @see InstallParams#origin */ 14766 final OriginInfo origin; 14767 /** @see InstallParams#move */ 14768 final MoveInfo move; 14769 14770 final IPackageInstallObserver2 observer; 14771 // Always refers to PackageManager flags only 14772 final int installFlags; 14773 final String installerPackageName; 14774 final String volumeUuid; 14775 final UserHandle user; 14776 final String abiOverride; 14777 final String[] installGrantPermissions; 14778 /** If non-null, drop an async trace when the install completes */ 14779 final String traceMethod; 14780 final int traceCookie; 14781 final Certificate[][] certificates; 14782 final int installReason; 14783 14784 // The list of instruction sets supported by this app. This is currently 14785 // only used during the rmdex() phase to clean up resources. We can get rid of this 14786 // if we move dex files under the common app path. 14787 /* nullable */ String[] instructionSets; 14788 14789 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14790 int installFlags, String installerPackageName, String volumeUuid, 14791 UserHandle user, String[] instructionSets, 14792 String abiOverride, String[] installGrantPermissions, 14793 String traceMethod, int traceCookie, Certificate[][] certificates, 14794 int installReason) { 14795 this.origin = origin; 14796 this.move = move; 14797 this.installFlags = installFlags; 14798 this.observer = observer; 14799 this.installerPackageName = installerPackageName; 14800 this.volumeUuid = volumeUuid; 14801 this.user = user; 14802 this.instructionSets = instructionSets; 14803 this.abiOverride = abiOverride; 14804 this.installGrantPermissions = installGrantPermissions; 14805 this.traceMethod = traceMethod; 14806 this.traceCookie = traceCookie; 14807 this.certificates = certificates; 14808 this.installReason = installReason; 14809 } 14810 14811 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14812 abstract int doPreInstall(int status); 14813 14814 /** 14815 * Rename package into final resting place. All paths on the given 14816 * scanned package should be updated to reflect the rename. 14817 */ 14818 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14819 abstract int doPostInstall(int status, int uid); 14820 14821 /** @see PackageSettingBase#codePathString */ 14822 abstract String getCodePath(); 14823 /** @see PackageSettingBase#resourcePathString */ 14824 abstract String getResourcePath(); 14825 14826 // Need installer lock especially for dex file removal. 14827 abstract void cleanUpResourcesLI(); 14828 abstract boolean doPostDeleteLI(boolean delete); 14829 14830 /** 14831 * Called before the source arguments are copied. This is used mostly 14832 * for MoveParams when it needs to read the source file to put it in the 14833 * destination. 14834 */ 14835 int doPreCopy() { 14836 return PackageManager.INSTALL_SUCCEEDED; 14837 } 14838 14839 /** 14840 * Called after the source arguments are copied. This is used mostly for 14841 * MoveParams when it needs to read the source file to put it in the 14842 * destination. 14843 */ 14844 int doPostCopy(int uid) { 14845 return PackageManager.INSTALL_SUCCEEDED; 14846 } 14847 14848 protected boolean isFwdLocked() { 14849 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14850 } 14851 14852 protected boolean isExternalAsec() { 14853 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14854 } 14855 14856 protected boolean isEphemeral() { 14857 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14858 } 14859 14860 UserHandle getUser() { 14861 return user; 14862 } 14863 } 14864 14865 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14866 if (!allCodePaths.isEmpty()) { 14867 if (instructionSets == null) { 14868 throw new IllegalStateException("instructionSet == null"); 14869 } 14870 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14871 for (String codePath : allCodePaths) { 14872 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14873 try { 14874 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14875 } catch (InstallerException ignored) { 14876 } 14877 } 14878 } 14879 } 14880 } 14881 14882 /** 14883 * Logic to handle installation of non-ASEC applications, including copying 14884 * and renaming logic. 14885 */ 14886 class FileInstallArgs extends InstallArgs { 14887 private File codeFile; 14888 private File resourceFile; 14889 14890 // Example topology: 14891 // /data/app/com.example/base.apk 14892 // /data/app/com.example/split_foo.apk 14893 // /data/app/com.example/lib/arm/libfoo.so 14894 // /data/app/com.example/lib/arm64/libfoo.so 14895 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14896 14897 /** New install */ 14898 FileInstallArgs(InstallParams params) { 14899 super(params.origin, params.move, params.observer, params.installFlags, 14900 params.installerPackageName, params.volumeUuid, 14901 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14902 params.grantedRuntimePermissions, 14903 params.traceMethod, params.traceCookie, params.certificates, 14904 params.installReason); 14905 if (isFwdLocked()) { 14906 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14907 } 14908 } 14909 14910 /** Existing install */ 14911 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14912 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14913 null, null, null, 0, null /*certificates*/, 14914 PackageManager.INSTALL_REASON_UNKNOWN); 14915 this.codeFile = (codePath != null) ? new File(codePath) : null; 14916 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14917 } 14918 14919 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14921 try { 14922 return doCopyApk(imcs, temp); 14923 } finally { 14924 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14925 } 14926 } 14927 14928 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14929 if (origin.staged) { 14930 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14931 codeFile = origin.file; 14932 resourceFile = origin.file; 14933 return PackageManager.INSTALL_SUCCEEDED; 14934 } 14935 14936 try { 14937 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14938 final File tempDir = 14939 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14940 codeFile = tempDir; 14941 resourceFile = tempDir; 14942 } catch (IOException e) { 14943 Slog.w(TAG, "Failed to create copy file: " + e); 14944 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14945 } 14946 14947 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14948 @Override 14949 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14950 if (!FileUtils.isValidExtFilename(name)) { 14951 throw new IllegalArgumentException("Invalid filename: " + name); 14952 } 14953 try { 14954 final File file = new File(codeFile, name); 14955 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14956 O_RDWR | O_CREAT, 0644); 14957 Os.chmod(file.getAbsolutePath(), 0644); 14958 return new ParcelFileDescriptor(fd); 14959 } catch (ErrnoException e) { 14960 throw new RemoteException("Failed to open: " + e.getMessage()); 14961 } 14962 } 14963 }; 14964 14965 int ret = PackageManager.INSTALL_SUCCEEDED; 14966 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14967 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14968 Slog.e(TAG, "Failed to copy package"); 14969 return ret; 14970 } 14971 14972 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14973 NativeLibraryHelper.Handle handle = null; 14974 try { 14975 handle = NativeLibraryHelper.Handle.create(codeFile); 14976 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14977 abiOverride); 14978 } catch (IOException e) { 14979 Slog.e(TAG, "Copying native libraries failed", e); 14980 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14981 } finally { 14982 IoUtils.closeQuietly(handle); 14983 } 14984 14985 return ret; 14986 } 14987 14988 int doPreInstall(int status) { 14989 if (status != PackageManager.INSTALL_SUCCEEDED) { 14990 cleanUp(); 14991 } 14992 return status; 14993 } 14994 14995 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14996 if (status != PackageManager.INSTALL_SUCCEEDED) { 14997 cleanUp(); 14998 return false; 14999 } 15000 15001 final File targetDir = codeFile.getParentFile(); 15002 final File beforeCodeFile = codeFile; 15003 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15004 15005 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15006 try { 15007 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15008 } catch (ErrnoException e) { 15009 Slog.w(TAG, "Failed to rename", e); 15010 return false; 15011 } 15012 15013 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15014 Slog.w(TAG, "Failed to restorecon"); 15015 return false; 15016 } 15017 15018 // Reflect the rename internally 15019 codeFile = afterCodeFile; 15020 resourceFile = afterCodeFile; 15021 15022 // Reflect the rename in scanned details 15023 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15024 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15025 afterCodeFile, pkg.baseCodePath)); 15026 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15027 afterCodeFile, pkg.splitCodePaths)); 15028 15029 // Reflect the rename in app info 15030 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15031 pkg.setApplicationInfoCodePath(pkg.codePath); 15032 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15033 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15034 pkg.setApplicationInfoResourcePath(pkg.codePath); 15035 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15036 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15037 15038 return true; 15039 } 15040 15041 int doPostInstall(int status, int uid) { 15042 if (status != PackageManager.INSTALL_SUCCEEDED) { 15043 cleanUp(); 15044 } 15045 return status; 15046 } 15047 15048 @Override 15049 String getCodePath() { 15050 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15051 } 15052 15053 @Override 15054 String getResourcePath() { 15055 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15056 } 15057 15058 private boolean cleanUp() { 15059 if (codeFile == null || !codeFile.exists()) { 15060 return false; 15061 } 15062 15063 removeCodePathLI(codeFile); 15064 15065 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15066 resourceFile.delete(); 15067 } 15068 15069 return true; 15070 } 15071 15072 void cleanUpResourcesLI() { 15073 // Try enumerating all code paths before deleting 15074 List<String> allCodePaths = Collections.EMPTY_LIST; 15075 if (codeFile != null && codeFile.exists()) { 15076 try { 15077 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15078 allCodePaths = pkg.getAllCodePaths(); 15079 } catch (PackageParserException e) { 15080 // Ignored; we tried our best 15081 } 15082 } 15083 15084 cleanUp(); 15085 removeDexFiles(allCodePaths, instructionSets); 15086 } 15087 15088 boolean doPostDeleteLI(boolean delete) { 15089 // XXX err, shouldn't we respect the delete flag? 15090 cleanUpResourcesLI(); 15091 return true; 15092 } 15093 } 15094 15095 private boolean isAsecExternal(String cid) { 15096 final String asecPath = PackageHelper.getSdFilesystem(cid); 15097 return !asecPath.startsWith(mAsecInternalPath); 15098 } 15099 15100 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15101 PackageManagerException { 15102 if (copyRet < 0) { 15103 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15104 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15105 throw new PackageManagerException(copyRet, message); 15106 } 15107 } 15108 } 15109 15110 /** 15111 * Extract the StorageManagerService "container ID" from the full code path of an 15112 * .apk. 15113 */ 15114 static String cidFromCodePath(String fullCodePath) { 15115 int eidx = fullCodePath.lastIndexOf("/"); 15116 String subStr1 = fullCodePath.substring(0, eidx); 15117 int sidx = subStr1.lastIndexOf("/"); 15118 return subStr1.substring(sidx+1, eidx); 15119 } 15120 15121 /** 15122 * Logic to handle installation of ASEC applications, including copying and 15123 * renaming logic. 15124 */ 15125 class AsecInstallArgs extends InstallArgs { 15126 static final String RES_FILE_NAME = "pkg.apk"; 15127 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15128 15129 String cid; 15130 String packagePath; 15131 String resourcePath; 15132 15133 /** New install */ 15134 AsecInstallArgs(InstallParams params) { 15135 super(params.origin, params.move, params.observer, params.installFlags, 15136 params.installerPackageName, params.volumeUuid, 15137 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15138 params.grantedRuntimePermissions, 15139 params.traceMethod, params.traceCookie, params.certificates, 15140 params.installReason); 15141 } 15142 15143 /** Existing install */ 15144 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15145 boolean isExternal, boolean isForwardLocked) { 15146 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15147 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15148 instructionSets, null, null, null, 0, null /*certificates*/, 15149 PackageManager.INSTALL_REASON_UNKNOWN); 15150 // Hackily pretend we're still looking at a full code path 15151 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15152 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15153 } 15154 15155 // Extract cid from fullCodePath 15156 int eidx = fullCodePath.lastIndexOf("/"); 15157 String subStr1 = fullCodePath.substring(0, eidx); 15158 int sidx = subStr1.lastIndexOf("/"); 15159 cid = subStr1.substring(sidx+1, eidx); 15160 setMountPath(subStr1); 15161 } 15162 15163 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15164 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15165 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15166 instructionSets, null, null, null, 0, null /*certificates*/, 15167 PackageManager.INSTALL_REASON_UNKNOWN); 15168 this.cid = cid; 15169 setMountPath(PackageHelper.getSdDir(cid)); 15170 } 15171 15172 void createCopyFile() { 15173 cid = mInstallerService.allocateExternalStageCidLegacy(); 15174 } 15175 15176 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15177 if (origin.staged && origin.cid != null) { 15178 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15179 cid = origin.cid; 15180 setMountPath(PackageHelper.getSdDir(cid)); 15181 return PackageManager.INSTALL_SUCCEEDED; 15182 } 15183 15184 if (temp) { 15185 createCopyFile(); 15186 } else { 15187 /* 15188 * Pre-emptively destroy the container since it's destroyed if 15189 * copying fails due to it existing anyway. 15190 */ 15191 PackageHelper.destroySdDir(cid); 15192 } 15193 15194 final String newMountPath = imcs.copyPackageToContainer( 15195 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15196 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15197 15198 if (newMountPath != null) { 15199 setMountPath(newMountPath); 15200 return PackageManager.INSTALL_SUCCEEDED; 15201 } else { 15202 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15203 } 15204 } 15205 15206 @Override 15207 String getCodePath() { 15208 return packagePath; 15209 } 15210 15211 @Override 15212 String getResourcePath() { 15213 return resourcePath; 15214 } 15215 15216 int doPreInstall(int status) { 15217 if (status != PackageManager.INSTALL_SUCCEEDED) { 15218 // Destroy container 15219 PackageHelper.destroySdDir(cid); 15220 } else { 15221 boolean mounted = PackageHelper.isContainerMounted(cid); 15222 if (!mounted) { 15223 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15224 Process.SYSTEM_UID); 15225 if (newMountPath != null) { 15226 setMountPath(newMountPath); 15227 } else { 15228 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15229 } 15230 } 15231 } 15232 return status; 15233 } 15234 15235 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15236 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15237 String newMountPath = null; 15238 if (PackageHelper.isContainerMounted(cid)) { 15239 // Unmount the container 15240 if (!PackageHelper.unMountSdDir(cid)) { 15241 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15242 return false; 15243 } 15244 } 15245 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15246 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15247 " which might be stale. Will try to clean up."); 15248 // Clean up the stale container and proceed to recreate. 15249 if (!PackageHelper.destroySdDir(newCacheId)) { 15250 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15251 return false; 15252 } 15253 // Successfully cleaned up stale container. Try to rename again. 15254 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15255 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15256 + " inspite of cleaning it up."); 15257 return false; 15258 } 15259 } 15260 if (!PackageHelper.isContainerMounted(newCacheId)) { 15261 Slog.w(TAG, "Mounting container " + newCacheId); 15262 newMountPath = PackageHelper.mountSdDir(newCacheId, 15263 getEncryptKey(), Process.SYSTEM_UID); 15264 } else { 15265 newMountPath = PackageHelper.getSdDir(newCacheId); 15266 } 15267 if (newMountPath == null) { 15268 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15269 return false; 15270 } 15271 Log.i(TAG, "Succesfully renamed " + cid + 15272 " to " + newCacheId + 15273 " at new path: " + newMountPath); 15274 cid = newCacheId; 15275 15276 final File beforeCodeFile = new File(packagePath); 15277 setMountPath(newMountPath); 15278 final File afterCodeFile = new File(packagePath); 15279 15280 // Reflect the rename in scanned details 15281 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15282 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15283 afterCodeFile, pkg.baseCodePath)); 15284 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15285 afterCodeFile, pkg.splitCodePaths)); 15286 15287 // Reflect the rename in app info 15288 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15289 pkg.setApplicationInfoCodePath(pkg.codePath); 15290 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15291 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15292 pkg.setApplicationInfoResourcePath(pkg.codePath); 15293 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15294 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15295 15296 return true; 15297 } 15298 15299 private void setMountPath(String mountPath) { 15300 final File mountFile = new File(mountPath); 15301 15302 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15303 if (monolithicFile.exists()) { 15304 packagePath = monolithicFile.getAbsolutePath(); 15305 if (isFwdLocked()) { 15306 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15307 } else { 15308 resourcePath = packagePath; 15309 } 15310 } else { 15311 packagePath = mountFile.getAbsolutePath(); 15312 resourcePath = packagePath; 15313 } 15314 } 15315 15316 int doPostInstall(int status, int uid) { 15317 if (status != PackageManager.INSTALL_SUCCEEDED) { 15318 cleanUp(); 15319 } else { 15320 final int groupOwner; 15321 final String protectedFile; 15322 if (isFwdLocked()) { 15323 groupOwner = UserHandle.getSharedAppGid(uid); 15324 protectedFile = RES_FILE_NAME; 15325 } else { 15326 groupOwner = -1; 15327 protectedFile = null; 15328 } 15329 15330 if (uid < Process.FIRST_APPLICATION_UID 15331 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15332 Slog.e(TAG, "Failed to finalize " + cid); 15333 PackageHelper.destroySdDir(cid); 15334 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15335 } 15336 15337 boolean mounted = PackageHelper.isContainerMounted(cid); 15338 if (!mounted) { 15339 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15340 } 15341 } 15342 return status; 15343 } 15344 15345 private void cleanUp() { 15346 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15347 15348 // Destroy secure container 15349 PackageHelper.destroySdDir(cid); 15350 } 15351 15352 private List<String> getAllCodePaths() { 15353 final File codeFile = new File(getCodePath()); 15354 if (codeFile != null && codeFile.exists()) { 15355 try { 15356 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15357 return pkg.getAllCodePaths(); 15358 } catch (PackageParserException e) { 15359 // Ignored; we tried our best 15360 } 15361 } 15362 return Collections.EMPTY_LIST; 15363 } 15364 15365 void cleanUpResourcesLI() { 15366 // Enumerate all code paths before deleting 15367 cleanUpResourcesLI(getAllCodePaths()); 15368 } 15369 15370 private void cleanUpResourcesLI(List<String> allCodePaths) { 15371 cleanUp(); 15372 removeDexFiles(allCodePaths, instructionSets); 15373 } 15374 15375 String getPackageName() { 15376 return getAsecPackageName(cid); 15377 } 15378 15379 boolean doPostDeleteLI(boolean delete) { 15380 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15381 final List<String> allCodePaths = getAllCodePaths(); 15382 boolean mounted = PackageHelper.isContainerMounted(cid); 15383 if (mounted) { 15384 // Unmount first 15385 if (PackageHelper.unMountSdDir(cid)) { 15386 mounted = false; 15387 } 15388 } 15389 if (!mounted && delete) { 15390 cleanUpResourcesLI(allCodePaths); 15391 } 15392 return !mounted; 15393 } 15394 15395 @Override 15396 int doPreCopy() { 15397 if (isFwdLocked()) { 15398 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15399 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15400 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15401 } 15402 } 15403 15404 return PackageManager.INSTALL_SUCCEEDED; 15405 } 15406 15407 @Override 15408 int doPostCopy(int uid) { 15409 if (isFwdLocked()) { 15410 if (uid < Process.FIRST_APPLICATION_UID 15411 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15412 RES_FILE_NAME)) { 15413 Slog.e(TAG, "Failed to finalize " + cid); 15414 PackageHelper.destroySdDir(cid); 15415 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15416 } 15417 } 15418 15419 return PackageManager.INSTALL_SUCCEEDED; 15420 } 15421 } 15422 15423 /** 15424 * Logic to handle movement of existing installed applications. 15425 */ 15426 class MoveInstallArgs extends InstallArgs { 15427 private File codeFile; 15428 private File resourceFile; 15429 15430 /** New install */ 15431 MoveInstallArgs(InstallParams params) { 15432 super(params.origin, params.move, params.observer, params.installFlags, 15433 params.installerPackageName, params.volumeUuid, 15434 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15435 params.grantedRuntimePermissions, 15436 params.traceMethod, params.traceCookie, params.certificates, 15437 params.installReason); 15438 } 15439 15440 int copyApk(IMediaContainerService imcs, boolean temp) { 15441 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15442 + move.fromUuid + " to " + move.toUuid); 15443 synchronized (mInstaller) { 15444 try { 15445 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15446 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15447 } catch (InstallerException e) { 15448 Slog.w(TAG, "Failed to move app", e); 15449 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15450 } 15451 } 15452 15453 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15454 resourceFile = codeFile; 15455 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15456 15457 return PackageManager.INSTALL_SUCCEEDED; 15458 } 15459 15460 int doPreInstall(int status) { 15461 if (status != PackageManager.INSTALL_SUCCEEDED) { 15462 cleanUp(move.toUuid); 15463 } 15464 return status; 15465 } 15466 15467 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15468 if (status != PackageManager.INSTALL_SUCCEEDED) { 15469 cleanUp(move.toUuid); 15470 return false; 15471 } 15472 15473 // Reflect the move in app info 15474 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15475 pkg.setApplicationInfoCodePath(pkg.codePath); 15476 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15477 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15478 pkg.setApplicationInfoResourcePath(pkg.codePath); 15479 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15480 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15481 15482 return true; 15483 } 15484 15485 int doPostInstall(int status, int uid) { 15486 if (status == PackageManager.INSTALL_SUCCEEDED) { 15487 cleanUp(move.fromUuid); 15488 } else { 15489 cleanUp(move.toUuid); 15490 } 15491 return status; 15492 } 15493 15494 @Override 15495 String getCodePath() { 15496 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15497 } 15498 15499 @Override 15500 String getResourcePath() { 15501 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15502 } 15503 15504 private boolean cleanUp(String volumeUuid) { 15505 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15506 move.dataAppName); 15507 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15508 final int[] userIds = sUserManager.getUserIds(); 15509 synchronized (mInstallLock) { 15510 // Clean up both app data and code 15511 // All package moves are frozen until finished 15512 for (int userId : userIds) { 15513 try { 15514 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15515 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15516 } catch (InstallerException e) { 15517 Slog.w(TAG, String.valueOf(e)); 15518 } 15519 } 15520 removeCodePathLI(codeFile); 15521 } 15522 return true; 15523 } 15524 15525 void cleanUpResourcesLI() { 15526 throw new UnsupportedOperationException(); 15527 } 15528 15529 boolean doPostDeleteLI(boolean delete) { 15530 throw new UnsupportedOperationException(); 15531 } 15532 } 15533 15534 static String getAsecPackageName(String packageCid) { 15535 int idx = packageCid.lastIndexOf("-"); 15536 if (idx == -1) { 15537 return packageCid; 15538 } 15539 return packageCid.substring(0, idx); 15540 } 15541 15542 // Utility method used to create code paths based on package name and available index. 15543 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15544 String idxStr = ""; 15545 int idx = 1; 15546 // Fall back to default value of idx=1 if prefix is not 15547 // part of oldCodePath 15548 if (oldCodePath != null) { 15549 String subStr = oldCodePath; 15550 // Drop the suffix right away 15551 if (suffix != null && subStr.endsWith(suffix)) { 15552 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15553 } 15554 // If oldCodePath already contains prefix find out the 15555 // ending index to either increment or decrement. 15556 int sidx = subStr.lastIndexOf(prefix); 15557 if (sidx != -1) { 15558 subStr = subStr.substring(sidx + prefix.length()); 15559 if (subStr != null) { 15560 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15561 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15562 } 15563 try { 15564 idx = Integer.parseInt(subStr); 15565 if (idx <= 1) { 15566 idx++; 15567 } else { 15568 idx--; 15569 } 15570 } catch(NumberFormatException e) { 15571 } 15572 } 15573 } 15574 } 15575 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15576 return prefix + idxStr; 15577 } 15578 15579 private File getNextCodePath(File targetDir, String packageName) { 15580 File result; 15581 SecureRandom random = new SecureRandom(); 15582 byte[] bytes = new byte[16]; 15583 do { 15584 random.nextBytes(bytes); 15585 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15586 result = new File(targetDir, packageName + "-" + suffix); 15587 } while (result.exists()); 15588 return result; 15589 } 15590 15591 // Utility method that returns the relative package path with respect 15592 // to the installation directory. Like say for /data/data/com.test-1.apk 15593 // string com.test-1 is returned. 15594 static String deriveCodePathName(String codePath) { 15595 if (codePath == null) { 15596 return null; 15597 } 15598 final File codeFile = new File(codePath); 15599 final String name = codeFile.getName(); 15600 if (codeFile.isDirectory()) { 15601 return name; 15602 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15603 final int lastDot = name.lastIndexOf('.'); 15604 return name.substring(0, lastDot); 15605 } else { 15606 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15607 return null; 15608 } 15609 } 15610 15611 static class PackageInstalledInfo { 15612 String name; 15613 int uid; 15614 // The set of users that originally had this package installed. 15615 int[] origUsers; 15616 // The set of users that now have this package installed. 15617 int[] newUsers; 15618 PackageParser.Package pkg; 15619 int returnCode; 15620 String returnMsg; 15621 PackageRemovedInfo removedInfo; 15622 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15623 15624 public void setError(int code, String msg) { 15625 setReturnCode(code); 15626 setReturnMessage(msg); 15627 Slog.w(TAG, msg); 15628 } 15629 15630 public void setError(String msg, PackageParserException e) { 15631 setReturnCode(e.error); 15632 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15633 Slog.w(TAG, msg, e); 15634 } 15635 15636 public void setError(String msg, PackageManagerException e) { 15637 returnCode = e.error; 15638 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15639 Slog.w(TAG, msg, e); 15640 } 15641 15642 public void setReturnCode(int returnCode) { 15643 this.returnCode = returnCode; 15644 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15645 for (int i = 0; i < childCount; i++) { 15646 addedChildPackages.valueAt(i).returnCode = returnCode; 15647 } 15648 } 15649 15650 private void setReturnMessage(String returnMsg) { 15651 this.returnMsg = returnMsg; 15652 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15653 for (int i = 0; i < childCount; i++) { 15654 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15655 } 15656 } 15657 15658 // In some error cases we want to convey more info back to the observer 15659 String origPackage; 15660 String origPermission; 15661 } 15662 15663 /* 15664 * Install a non-existing package. 15665 */ 15666 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15667 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15668 PackageInstalledInfo res, int installReason) { 15669 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15670 15671 // Remember this for later, in case we need to rollback this install 15672 String pkgName = pkg.packageName; 15673 15674 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15675 15676 synchronized(mPackages) { 15677 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15678 if (renamedPackage != null) { 15679 // A package with the same name is already installed, though 15680 // it has been renamed to an older name. The package we 15681 // are trying to install should be installed as an update to 15682 // the existing one, but that has not been requested, so bail. 15683 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15684 + " without first uninstalling package running as " 15685 + renamedPackage); 15686 return; 15687 } 15688 if (mPackages.containsKey(pkgName)) { 15689 // Don't allow installation over an existing package with the same name. 15690 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15691 + " without first uninstalling."); 15692 return; 15693 } 15694 } 15695 15696 try { 15697 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15698 System.currentTimeMillis(), user); 15699 15700 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15701 15702 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15703 prepareAppDataAfterInstallLIF(newPackage); 15704 15705 } else { 15706 // Remove package from internal structures, but keep around any 15707 // data that might have already existed 15708 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15709 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15710 } 15711 } catch (PackageManagerException e) { 15712 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15713 } 15714 15715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15716 } 15717 15718 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15719 // Can't rotate keys during boot or if sharedUser. 15720 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15721 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15722 return false; 15723 } 15724 // app is using upgradeKeySets; make sure all are valid 15725 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15726 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15727 for (int i = 0; i < upgradeKeySets.length; i++) { 15728 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15729 Slog.wtf(TAG, "Package " 15730 + (oldPs.name != null ? oldPs.name : "<null>") 15731 + " contains upgrade-key-set reference to unknown key-set: " 15732 + upgradeKeySets[i] 15733 + " reverting to signatures check."); 15734 return false; 15735 } 15736 } 15737 return true; 15738 } 15739 15740 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15741 // Upgrade keysets are being used. Determine if new package has a superset of the 15742 // required keys. 15743 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15744 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15745 for (int i = 0; i < upgradeKeySets.length; i++) { 15746 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15747 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15748 return true; 15749 } 15750 } 15751 return false; 15752 } 15753 15754 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15755 try (DigestInputStream digestStream = 15756 new DigestInputStream(new FileInputStream(file), digest)) { 15757 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15758 } 15759 } 15760 15761 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15762 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15763 int installReason) { 15764 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15765 15766 final PackageParser.Package oldPackage; 15767 final String pkgName = pkg.packageName; 15768 final int[] allUsers; 15769 final int[] installedUsers; 15770 15771 synchronized(mPackages) { 15772 oldPackage = mPackages.get(pkgName); 15773 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15774 15775 // don't allow upgrade to target a release SDK from a pre-release SDK 15776 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15777 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15778 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15779 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15780 if (oldTargetsPreRelease 15781 && !newTargetsPreRelease 15782 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15783 Slog.w(TAG, "Can't install package targeting released sdk"); 15784 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15785 return; 15786 } 15787 15788 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15789 15790 // verify signatures are valid 15791 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15792 if (!checkUpgradeKeySetLP(ps, pkg)) { 15793 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15794 "New package not signed by keys specified by upgrade-keysets: " 15795 + pkgName); 15796 return; 15797 } 15798 } else { 15799 // default to original signature matching 15800 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15801 != PackageManager.SIGNATURE_MATCH) { 15802 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15803 "New package has a different signature: " + pkgName); 15804 return; 15805 } 15806 } 15807 15808 // don't allow a system upgrade unless the upgrade hash matches 15809 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15810 byte[] digestBytes = null; 15811 try { 15812 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15813 updateDigest(digest, new File(pkg.baseCodePath)); 15814 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15815 for (String path : pkg.splitCodePaths) { 15816 updateDigest(digest, new File(path)); 15817 } 15818 } 15819 digestBytes = digest.digest(); 15820 } catch (NoSuchAlgorithmException | IOException e) { 15821 res.setError(INSTALL_FAILED_INVALID_APK, 15822 "Could not compute hash: " + pkgName); 15823 return; 15824 } 15825 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15826 res.setError(INSTALL_FAILED_INVALID_APK, 15827 "New package fails restrict-update check: " + pkgName); 15828 return; 15829 } 15830 // retain upgrade restriction 15831 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15832 } 15833 15834 // Check for shared user id changes 15835 String invalidPackageName = 15836 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15837 if (invalidPackageName != null) { 15838 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15839 "Package " + invalidPackageName + " tried to change user " 15840 + oldPackage.mSharedUserId); 15841 return; 15842 } 15843 15844 // In case of rollback, remember per-user/profile install state 15845 allUsers = sUserManager.getUserIds(); 15846 installedUsers = ps.queryInstalledUsers(allUsers, true); 15847 15848 // don't allow an upgrade from full to ephemeral 15849 if (isInstantApp) { 15850 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15851 for (int currentUser : allUsers) { 15852 if (!ps.getInstantApp(currentUser)) { 15853 // can't downgrade from full to instant 15854 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15855 + " for user: " + currentUser); 15856 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15857 return; 15858 } 15859 } 15860 } else if (!ps.getInstantApp(user.getIdentifier())) { 15861 // can't downgrade from full to instant 15862 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15863 + " for user: " + user.getIdentifier()); 15864 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15865 return; 15866 } 15867 } 15868 } 15869 15870 // Update what is removed 15871 res.removedInfo = new PackageRemovedInfo(); 15872 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15873 res.removedInfo.removedPackage = oldPackage.packageName; 15874 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15875 res.removedInfo.isUpdate = true; 15876 res.removedInfo.origUsers = installedUsers; 15877 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15878 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15879 for (int i = 0; i < installedUsers.length; i++) { 15880 final int userId = installedUsers[i]; 15881 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15882 } 15883 15884 final int childCount = (oldPackage.childPackages != null) 15885 ? oldPackage.childPackages.size() : 0; 15886 for (int i = 0; i < childCount; i++) { 15887 boolean childPackageUpdated = false; 15888 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15889 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15890 if (res.addedChildPackages != null) { 15891 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15892 if (childRes != null) { 15893 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15894 childRes.removedInfo.removedPackage = childPkg.packageName; 15895 childRes.removedInfo.isUpdate = true; 15896 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15897 childPackageUpdated = true; 15898 } 15899 } 15900 if (!childPackageUpdated) { 15901 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15902 childRemovedRes.removedPackage = childPkg.packageName; 15903 childRemovedRes.isUpdate = false; 15904 childRemovedRes.dataRemoved = true; 15905 synchronized (mPackages) { 15906 if (childPs != null) { 15907 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15908 } 15909 } 15910 if (res.removedInfo.removedChildPackages == null) { 15911 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15912 } 15913 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15914 } 15915 } 15916 15917 boolean sysPkg = (isSystemApp(oldPackage)); 15918 if (sysPkg) { 15919 // Set the system/privileged flags as needed 15920 final boolean privileged = 15921 (oldPackage.applicationInfo.privateFlags 15922 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15923 final int systemPolicyFlags = policyFlags 15924 | PackageParser.PARSE_IS_SYSTEM 15925 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15926 15927 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15928 user, allUsers, installerPackageName, res, installReason); 15929 } else { 15930 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15931 user, allUsers, installerPackageName, res, installReason); 15932 } 15933 } 15934 15935 public List<String> getPreviousCodePaths(String packageName) { 15936 final PackageSetting ps = mSettings.mPackages.get(packageName); 15937 final List<String> result = new ArrayList<String>(); 15938 if (ps != null && ps.oldCodePaths != null) { 15939 result.addAll(ps.oldCodePaths); 15940 } 15941 return result; 15942 } 15943 15944 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15945 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15946 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15947 int installReason) { 15948 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15949 + deletedPackage); 15950 15951 String pkgName = deletedPackage.packageName; 15952 boolean deletedPkg = true; 15953 boolean addedPkg = false; 15954 boolean updatedSettings = false; 15955 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15956 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15957 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15958 15959 final long origUpdateTime = (pkg.mExtras != null) 15960 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15961 15962 // First delete the existing package while retaining the data directory 15963 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15964 res.removedInfo, true, pkg)) { 15965 // If the existing package wasn't successfully deleted 15966 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15967 deletedPkg = false; 15968 } else { 15969 // Successfully deleted the old package; proceed with replace. 15970 15971 // If deleted package lived in a container, give users a chance to 15972 // relinquish resources before killing. 15973 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15974 if (DEBUG_INSTALL) { 15975 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15976 } 15977 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15978 final ArrayList<String> pkgList = new ArrayList<String>(1); 15979 pkgList.add(deletedPackage.applicationInfo.packageName); 15980 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15981 } 15982 15983 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15984 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15985 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15986 15987 try { 15988 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15989 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15990 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15991 installReason); 15992 15993 // Update the in-memory copy of the previous code paths. 15994 PackageSetting ps = mSettings.mPackages.get(pkgName); 15995 if (!killApp) { 15996 if (ps.oldCodePaths == null) { 15997 ps.oldCodePaths = new ArraySet<>(); 15998 } 15999 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16000 if (deletedPackage.splitCodePaths != null) { 16001 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16002 } 16003 } else { 16004 ps.oldCodePaths = null; 16005 } 16006 if (ps.childPackageNames != null) { 16007 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16008 final String childPkgName = ps.childPackageNames.get(i); 16009 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16010 childPs.oldCodePaths = ps.oldCodePaths; 16011 } 16012 } 16013 // set instant app status, but, only if it's explicitly specified 16014 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16015 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16016 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16017 prepareAppDataAfterInstallLIF(newPackage); 16018 addedPkg = true; 16019 mDexManager.notifyPackageUpdated(newPackage.packageName, 16020 newPackage.baseCodePath, newPackage.splitCodePaths); 16021 } catch (PackageManagerException e) { 16022 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16023 } 16024 } 16025 16026 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16027 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16028 16029 // Revert all internal state mutations and added folders for the failed install 16030 if (addedPkg) { 16031 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16032 res.removedInfo, true, null); 16033 } 16034 16035 // Restore the old package 16036 if (deletedPkg) { 16037 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16038 File restoreFile = new File(deletedPackage.codePath); 16039 // Parse old package 16040 boolean oldExternal = isExternal(deletedPackage); 16041 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16042 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16043 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16044 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16045 try { 16046 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16047 null); 16048 } catch (PackageManagerException e) { 16049 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16050 + e.getMessage()); 16051 return; 16052 } 16053 16054 synchronized (mPackages) { 16055 // Ensure the installer package name up to date 16056 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16057 16058 // Update permissions for restored package 16059 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16060 16061 mSettings.writeLPr(); 16062 } 16063 16064 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16065 } 16066 } else { 16067 synchronized (mPackages) { 16068 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16069 if (ps != null) { 16070 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16071 if (res.removedInfo.removedChildPackages != null) { 16072 final int childCount = res.removedInfo.removedChildPackages.size(); 16073 // Iterate in reverse as we may modify the collection 16074 for (int i = childCount - 1; i >= 0; i--) { 16075 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16076 if (res.addedChildPackages.containsKey(childPackageName)) { 16077 res.removedInfo.removedChildPackages.removeAt(i); 16078 } else { 16079 PackageRemovedInfo childInfo = res.removedInfo 16080 .removedChildPackages.valueAt(i); 16081 childInfo.removedForAllUsers = mPackages.get( 16082 childInfo.removedPackage) == null; 16083 } 16084 } 16085 } 16086 } 16087 } 16088 } 16089 } 16090 16091 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16092 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16093 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16094 int installReason) { 16095 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16096 + ", old=" + deletedPackage); 16097 16098 final boolean disabledSystem; 16099 16100 // Remove existing system package 16101 removePackageLI(deletedPackage, true); 16102 16103 synchronized (mPackages) { 16104 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16105 } 16106 if (!disabledSystem) { 16107 // We didn't need to disable the .apk as a current system package, 16108 // which means we are replacing another update that is already 16109 // installed. We need to make sure to delete the older one's .apk. 16110 res.removedInfo.args = createInstallArgsForExisting(0, 16111 deletedPackage.applicationInfo.getCodePath(), 16112 deletedPackage.applicationInfo.getResourcePath(), 16113 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16114 } else { 16115 res.removedInfo.args = null; 16116 } 16117 16118 // Successfully disabled the old package. Now proceed with re-installation 16119 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16120 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16121 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16122 16123 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16124 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16125 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16126 16127 PackageParser.Package newPackage = null; 16128 try { 16129 // Add the package to the internal data structures 16130 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16131 16132 // Set the update and install times 16133 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16134 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16135 System.currentTimeMillis()); 16136 16137 // Update the package dynamic state if succeeded 16138 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16139 // Now that the install succeeded make sure we remove data 16140 // directories for any child package the update removed. 16141 final int deletedChildCount = (deletedPackage.childPackages != null) 16142 ? deletedPackage.childPackages.size() : 0; 16143 final int newChildCount = (newPackage.childPackages != null) 16144 ? newPackage.childPackages.size() : 0; 16145 for (int i = 0; i < deletedChildCount; i++) { 16146 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16147 boolean childPackageDeleted = true; 16148 for (int j = 0; j < newChildCount; j++) { 16149 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16150 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16151 childPackageDeleted = false; 16152 break; 16153 } 16154 } 16155 if (childPackageDeleted) { 16156 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16157 deletedChildPkg.packageName); 16158 if (ps != null && res.removedInfo.removedChildPackages != null) { 16159 PackageRemovedInfo removedChildRes = res.removedInfo 16160 .removedChildPackages.get(deletedChildPkg.packageName); 16161 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16162 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16163 } 16164 } 16165 } 16166 16167 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16168 installReason); 16169 prepareAppDataAfterInstallLIF(newPackage); 16170 16171 mDexManager.notifyPackageUpdated(newPackage.packageName, 16172 newPackage.baseCodePath, newPackage.splitCodePaths); 16173 } 16174 } catch (PackageManagerException e) { 16175 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16176 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16177 } 16178 16179 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16180 // Re installation failed. Restore old information 16181 // Remove new pkg information 16182 if (newPackage != null) { 16183 removeInstalledPackageLI(newPackage, true); 16184 } 16185 // Add back the old system package 16186 try { 16187 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16188 } catch (PackageManagerException e) { 16189 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16190 } 16191 16192 synchronized (mPackages) { 16193 if (disabledSystem) { 16194 enableSystemPackageLPw(deletedPackage); 16195 } 16196 16197 // Ensure the installer package name up to date 16198 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16199 16200 // Update permissions for restored package 16201 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16202 16203 mSettings.writeLPr(); 16204 } 16205 16206 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16207 + " after failed upgrade"); 16208 } 16209 } 16210 16211 /** 16212 * Checks whether the parent or any of the child packages have a change shared 16213 * user. For a package to be a valid update the shred users of the parent and 16214 * the children should match. We may later support changing child shared users. 16215 * @param oldPkg The updated package. 16216 * @param newPkg The update package. 16217 * @return The shared user that change between the versions. 16218 */ 16219 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16220 PackageParser.Package newPkg) { 16221 // Check parent shared user 16222 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16223 return newPkg.packageName; 16224 } 16225 // Check child shared users 16226 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16227 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16228 for (int i = 0; i < newChildCount; i++) { 16229 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16230 // If this child was present, did it have the same shared user? 16231 for (int j = 0; j < oldChildCount; j++) { 16232 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16233 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16234 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16235 return newChildPkg.packageName; 16236 } 16237 } 16238 } 16239 return null; 16240 } 16241 16242 private void removeNativeBinariesLI(PackageSetting ps) { 16243 // Remove the lib path for the parent package 16244 if (ps != null) { 16245 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16246 // Remove the lib path for the child packages 16247 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16248 for (int i = 0; i < childCount; i++) { 16249 PackageSetting childPs = null; 16250 synchronized (mPackages) { 16251 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16252 } 16253 if (childPs != null) { 16254 NativeLibraryHelper.removeNativeBinariesLI(childPs 16255 .legacyNativeLibraryPathString); 16256 } 16257 } 16258 } 16259 } 16260 16261 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16262 // Enable the parent package 16263 mSettings.enableSystemPackageLPw(pkg.packageName); 16264 // Enable the child packages 16265 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16266 for (int i = 0; i < childCount; i++) { 16267 PackageParser.Package childPkg = pkg.childPackages.get(i); 16268 mSettings.enableSystemPackageLPw(childPkg.packageName); 16269 } 16270 } 16271 16272 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16273 PackageParser.Package newPkg) { 16274 // Disable the parent package (parent always replaced) 16275 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16276 // Disable the child packages 16277 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16278 for (int i = 0; i < childCount; i++) { 16279 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16280 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16281 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16282 } 16283 return disabled; 16284 } 16285 16286 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16287 String installerPackageName) { 16288 // Enable the parent package 16289 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16290 // Enable the child packages 16291 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16292 for (int i = 0; i < childCount; i++) { 16293 PackageParser.Package childPkg = pkg.childPackages.get(i); 16294 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16295 } 16296 } 16297 16298 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16299 // Collect all used permissions in the UID 16300 ArraySet<String> usedPermissions = new ArraySet<>(); 16301 final int packageCount = su.packages.size(); 16302 for (int i = 0; i < packageCount; i++) { 16303 PackageSetting ps = su.packages.valueAt(i); 16304 if (ps.pkg == null) { 16305 continue; 16306 } 16307 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16308 for (int j = 0; j < requestedPermCount; j++) { 16309 String permission = ps.pkg.requestedPermissions.get(j); 16310 BasePermission bp = mSettings.mPermissions.get(permission); 16311 if (bp != null) { 16312 usedPermissions.add(permission); 16313 } 16314 } 16315 } 16316 16317 PermissionsState permissionsState = su.getPermissionsState(); 16318 // Prune install permissions 16319 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16320 final int installPermCount = installPermStates.size(); 16321 for (int i = installPermCount - 1; i >= 0; i--) { 16322 PermissionState permissionState = installPermStates.get(i); 16323 if (!usedPermissions.contains(permissionState.getName())) { 16324 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16325 if (bp != null) { 16326 permissionsState.revokeInstallPermission(bp); 16327 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16328 PackageManager.MASK_PERMISSION_FLAGS, 0); 16329 } 16330 } 16331 } 16332 16333 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16334 16335 // Prune runtime permissions 16336 for (int userId : allUserIds) { 16337 List<PermissionState> runtimePermStates = permissionsState 16338 .getRuntimePermissionStates(userId); 16339 final int runtimePermCount = runtimePermStates.size(); 16340 for (int i = runtimePermCount - 1; i >= 0; i--) { 16341 PermissionState permissionState = runtimePermStates.get(i); 16342 if (!usedPermissions.contains(permissionState.getName())) { 16343 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16344 if (bp != null) { 16345 permissionsState.revokeRuntimePermission(bp, userId); 16346 permissionsState.updatePermissionFlags(bp, userId, 16347 PackageManager.MASK_PERMISSION_FLAGS, 0); 16348 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16349 runtimePermissionChangedUserIds, userId); 16350 } 16351 } 16352 } 16353 } 16354 16355 return runtimePermissionChangedUserIds; 16356 } 16357 16358 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16359 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16360 // Update the parent package setting 16361 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16362 res, user, installReason); 16363 // Update the child packages setting 16364 final int childCount = (newPackage.childPackages != null) 16365 ? newPackage.childPackages.size() : 0; 16366 for (int i = 0; i < childCount; i++) { 16367 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16368 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16369 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16370 childRes.origUsers, childRes, user, installReason); 16371 } 16372 } 16373 16374 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16375 String installerPackageName, int[] allUsers, int[] installedForUsers, 16376 PackageInstalledInfo res, UserHandle user, int installReason) { 16377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16378 16379 String pkgName = newPackage.packageName; 16380 synchronized (mPackages) { 16381 //write settings. the installStatus will be incomplete at this stage. 16382 //note that the new package setting would have already been 16383 //added to mPackages. It hasn't been persisted yet. 16384 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16385 // TODO: Remove this write? It's also written at the end of this method 16386 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16387 mSettings.writeLPr(); 16388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16389 } 16390 16391 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16392 synchronized (mPackages) { 16393 updatePermissionsLPw(newPackage.packageName, newPackage, 16394 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16395 ? UPDATE_PERMISSIONS_ALL : 0)); 16396 // For system-bundled packages, we assume that installing an upgraded version 16397 // of the package implies that the user actually wants to run that new code, 16398 // so we enable the package. 16399 PackageSetting ps = mSettings.mPackages.get(pkgName); 16400 final int userId = user.getIdentifier(); 16401 if (ps != null) { 16402 if (isSystemApp(newPackage)) { 16403 if (DEBUG_INSTALL) { 16404 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16405 } 16406 // Enable system package for requested users 16407 if (res.origUsers != null) { 16408 for (int origUserId : res.origUsers) { 16409 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16410 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16411 origUserId, installerPackageName); 16412 } 16413 } 16414 } 16415 // Also convey the prior install/uninstall state 16416 if (allUsers != null && installedForUsers != null) { 16417 for (int currentUserId : allUsers) { 16418 final boolean installed = ArrayUtils.contains( 16419 installedForUsers, currentUserId); 16420 if (DEBUG_INSTALL) { 16421 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16422 } 16423 ps.setInstalled(installed, currentUserId); 16424 } 16425 // these install state changes will be persisted in the 16426 // upcoming call to mSettings.writeLPr(). 16427 } 16428 } 16429 // It's implied that when a user requests installation, they want the app to be 16430 // installed and enabled. 16431 if (userId != UserHandle.USER_ALL) { 16432 ps.setInstalled(true, userId); 16433 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16434 } 16435 16436 // When replacing an existing package, preserve the original install reason for all 16437 // users that had the package installed before. 16438 final Set<Integer> previousUserIds = new ArraySet<>(); 16439 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16440 final int installReasonCount = res.removedInfo.installReasons.size(); 16441 for (int i = 0; i < installReasonCount; i++) { 16442 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16443 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16444 ps.setInstallReason(previousInstallReason, previousUserId); 16445 previousUserIds.add(previousUserId); 16446 } 16447 } 16448 16449 // Set install reason for users that are having the package newly installed. 16450 if (userId == UserHandle.USER_ALL) { 16451 for (int currentUserId : sUserManager.getUserIds()) { 16452 if (!previousUserIds.contains(currentUserId)) { 16453 ps.setInstallReason(installReason, currentUserId); 16454 } 16455 } 16456 } else if (!previousUserIds.contains(userId)) { 16457 ps.setInstallReason(installReason, userId); 16458 } 16459 mSettings.writeKernelMappingLPr(ps); 16460 } 16461 res.name = pkgName; 16462 res.uid = newPackage.applicationInfo.uid; 16463 res.pkg = newPackage; 16464 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16465 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16466 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16467 //to update install status 16468 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16469 mSettings.writeLPr(); 16470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16471 } 16472 16473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16474 } 16475 16476 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16477 try { 16478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16479 installPackageLI(args, res); 16480 } finally { 16481 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16482 } 16483 } 16484 16485 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16486 final int installFlags = args.installFlags; 16487 final String installerPackageName = args.installerPackageName; 16488 final String volumeUuid = args.volumeUuid; 16489 final File tmpPackageFile = new File(args.getCodePath()); 16490 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16491 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16492 || (args.volumeUuid != null)); 16493 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16494 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16495 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16496 boolean replace = false; 16497 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16498 if (args.move != null) { 16499 // moving a complete application; perform an initial scan on the new install location 16500 scanFlags |= SCAN_INITIAL; 16501 } 16502 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16503 scanFlags |= SCAN_DONT_KILL_APP; 16504 } 16505 if (instantApp) { 16506 scanFlags |= SCAN_AS_INSTANT_APP; 16507 } 16508 if (fullApp) { 16509 scanFlags |= SCAN_AS_FULL_APP; 16510 } 16511 16512 // Result object to be returned 16513 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16514 16515 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16516 16517 // Sanity check 16518 if (instantApp && (forwardLocked || onExternal)) { 16519 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16520 + " external=" + onExternal); 16521 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16522 return; 16523 } 16524 16525 // Retrieve PackageSettings and parse package 16526 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16527 | PackageParser.PARSE_ENFORCE_CODE 16528 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16529 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16530 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16531 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16532 PackageParser pp = new PackageParser(); 16533 pp.setSeparateProcesses(mSeparateProcesses); 16534 pp.setDisplayMetrics(mMetrics); 16535 pp.setCallback(mPackageParserCallback); 16536 16537 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16538 final PackageParser.Package pkg; 16539 try { 16540 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16541 } catch (PackageParserException e) { 16542 res.setError("Failed parse during installPackageLI", e); 16543 return; 16544 } finally { 16545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16546 } 16547 16548 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16549 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16550 Slog.w(TAG, "Instant app package " + pkg.packageName 16551 + " does not target O, this will be a fatal error."); 16552 // STOPSHIP: Make this a fatal error 16553 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16554 } 16555 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16556 Slog.w(TAG, "Instant app package " + pkg.packageName 16557 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16558 // STOPSHIP: Make this a fatal error 16559 pkg.applicationInfo.targetSandboxVersion = 2; 16560 } 16561 16562 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16563 // Static shared libraries have synthetic package names 16564 renameStaticSharedLibraryPackage(pkg); 16565 16566 // No static shared libs on external storage 16567 if (onExternal) { 16568 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16569 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16570 "Packages declaring static-shared libs cannot be updated"); 16571 return; 16572 } 16573 } 16574 16575 // If we are installing a clustered package add results for the children 16576 if (pkg.childPackages != null) { 16577 synchronized (mPackages) { 16578 final int childCount = pkg.childPackages.size(); 16579 for (int i = 0; i < childCount; i++) { 16580 PackageParser.Package childPkg = pkg.childPackages.get(i); 16581 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16582 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16583 childRes.pkg = childPkg; 16584 childRes.name = childPkg.packageName; 16585 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16586 if (childPs != null) { 16587 childRes.origUsers = childPs.queryInstalledUsers( 16588 sUserManager.getUserIds(), true); 16589 } 16590 if ((mPackages.containsKey(childPkg.packageName))) { 16591 childRes.removedInfo = new PackageRemovedInfo(); 16592 childRes.removedInfo.removedPackage = childPkg.packageName; 16593 } 16594 if (res.addedChildPackages == null) { 16595 res.addedChildPackages = new ArrayMap<>(); 16596 } 16597 res.addedChildPackages.put(childPkg.packageName, childRes); 16598 } 16599 } 16600 } 16601 16602 // If package doesn't declare API override, mark that we have an install 16603 // time CPU ABI override. 16604 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16605 pkg.cpuAbiOverride = args.abiOverride; 16606 } 16607 16608 String pkgName = res.name = pkg.packageName; 16609 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16610 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16611 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16612 return; 16613 } 16614 } 16615 16616 try { 16617 // either use what we've been given or parse directly from the APK 16618 if (args.certificates != null) { 16619 try { 16620 PackageParser.populateCertificates(pkg, args.certificates); 16621 } catch (PackageParserException e) { 16622 // there was something wrong with the certificates we were given; 16623 // try to pull them from the APK 16624 PackageParser.collectCertificates(pkg, parseFlags); 16625 } 16626 } else { 16627 PackageParser.collectCertificates(pkg, parseFlags); 16628 } 16629 } catch (PackageParserException e) { 16630 res.setError("Failed collect during installPackageLI", e); 16631 return; 16632 } 16633 16634 // Get rid of all references to package scan path via parser. 16635 pp = null; 16636 String oldCodePath = null; 16637 boolean systemApp = false; 16638 synchronized (mPackages) { 16639 // Check if installing already existing package 16640 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16641 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16642 if (pkg.mOriginalPackages != null 16643 && pkg.mOriginalPackages.contains(oldName) 16644 && mPackages.containsKey(oldName)) { 16645 // This package is derived from an original package, 16646 // and this device has been updating from that original 16647 // name. We must continue using the original name, so 16648 // rename the new package here. 16649 pkg.setPackageName(oldName); 16650 pkgName = pkg.packageName; 16651 replace = true; 16652 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16653 + oldName + " pkgName=" + pkgName); 16654 } else if (mPackages.containsKey(pkgName)) { 16655 // This package, under its official name, already exists 16656 // on the device; we should replace it. 16657 replace = true; 16658 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16659 } 16660 16661 // Child packages are installed through the parent package 16662 if (pkg.parentPackage != null) { 16663 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16664 "Package " + pkg.packageName + " is child of package " 16665 + pkg.parentPackage.parentPackage + ". Child packages " 16666 + "can be updated only through the parent package."); 16667 return; 16668 } 16669 16670 if (replace) { 16671 // Prevent apps opting out from runtime permissions 16672 PackageParser.Package oldPackage = mPackages.get(pkgName); 16673 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16674 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16675 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16676 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16677 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16678 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16679 + " doesn't support runtime permissions but the old" 16680 + " target SDK " + oldTargetSdk + " does."); 16681 return; 16682 } 16683 16684 // Prevent installing of child packages 16685 if (oldPackage.parentPackage != null) { 16686 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16687 "Package " + pkg.packageName + " is child of package " 16688 + oldPackage.parentPackage + ". Child packages " 16689 + "can be updated only through the parent package."); 16690 return; 16691 } 16692 } 16693 } 16694 16695 PackageSetting ps = mSettings.mPackages.get(pkgName); 16696 if (ps != null) { 16697 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16698 16699 // Static shared libs have same package with different versions where 16700 // we internally use a synthetic package name to allow multiple versions 16701 // of the same package, therefore we need to compare signatures against 16702 // the package setting for the latest library version. 16703 PackageSetting signatureCheckPs = ps; 16704 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16705 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16706 if (libraryEntry != null) { 16707 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16708 } 16709 } 16710 16711 // Quick sanity check that we're signed correctly if updating; 16712 // we'll check this again later when scanning, but we want to 16713 // bail early here before tripping over redefined permissions. 16714 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16715 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16716 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16717 + pkg.packageName + " upgrade keys do not match the " 16718 + "previously installed version"); 16719 return; 16720 } 16721 } else { 16722 try { 16723 verifySignaturesLP(signatureCheckPs, pkg); 16724 } catch (PackageManagerException e) { 16725 res.setError(e.error, e.getMessage()); 16726 return; 16727 } 16728 } 16729 16730 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16731 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16732 systemApp = (ps.pkg.applicationInfo.flags & 16733 ApplicationInfo.FLAG_SYSTEM) != 0; 16734 } 16735 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16736 } 16737 16738 int N = pkg.permissions.size(); 16739 for (int i = N-1; i >= 0; i--) { 16740 PackageParser.Permission perm = pkg.permissions.get(i); 16741 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16742 16743 // Don't allow anyone but the platform to define ephemeral permissions. 16744 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16745 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16746 Slog.w(TAG, "Package " + pkg.packageName 16747 + " attempting to delcare ephemeral permission " 16748 + perm.info.name + "; Removing ephemeral."); 16749 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16750 } 16751 // Check whether the newly-scanned package wants to define an already-defined perm 16752 if (bp != null) { 16753 // If the defining package is signed with our cert, it's okay. This 16754 // also includes the "updating the same package" case, of course. 16755 // "updating same package" could also involve key-rotation. 16756 final boolean sigsOk; 16757 if (bp.sourcePackage.equals(pkg.packageName) 16758 && (bp.packageSetting instanceof PackageSetting) 16759 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16760 scanFlags))) { 16761 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16762 } else { 16763 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16764 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16765 } 16766 if (!sigsOk) { 16767 // If the owning package is the system itself, we log but allow 16768 // install to proceed; we fail the install on all other permission 16769 // redefinitions. 16770 if (!bp.sourcePackage.equals("android")) { 16771 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16772 + pkg.packageName + " attempting to redeclare permission " 16773 + perm.info.name + " already owned by " + bp.sourcePackage); 16774 res.origPermission = perm.info.name; 16775 res.origPackage = bp.sourcePackage; 16776 return; 16777 } else { 16778 Slog.w(TAG, "Package " + pkg.packageName 16779 + " attempting to redeclare system permission " 16780 + perm.info.name + "; ignoring new declaration"); 16781 pkg.permissions.remove(i); 16782 } 16783 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16784 // Prevent apps to change protection level to dangerous from any other 16785 // type as this would allow a privilege escalation where an app adds a 16786 // normal/signature permission in other app's group and later redefines 16787 // it as dangerous leading to the group auto-grant. 16788 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16789 == PermissionInfo.PROTECTION_DANGEROUS) { 16790 if (bp != null && !bp.isRuntime()) { 16791 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16792 + "non-runtime permission " + perm.info.name 16793 + " to runtime; keeping old protection level"); 16794 perm.info.protectionLevel = bp.protectionLevel; 16795 } 16796 } 16797 } 16798 } 16799 } 16800 } 16801 16802 if (systemApp) { 16803 if (onExternal) { 16804 // Abort update; system app can't be replaced with app on sdcard 16805 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16806 "Cannot install updates to system apps on sdcard"); 16807 return; 16808 } else if (instantApp) { 16809 // Abort update; system app can't be replaced with an instant app 16810 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16811 "Cannot update a system app with an instant app"); 16812 return; 16813 } 16814 } 16815 16816 if (args.move != null) { 16817 // We did an in-place move, so dex is ready to roll 16818 scanFlags |= SCAN_NO_DEX; 16819 scanFlags |= SCAN_MOVE; 16820 16821 synchronized (mPackages) { 16822 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16823 if (ps == null) { 16824 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16825 "Missing settings for moved package " + pkgName); 16826 } 16827 16828 // We moved the entire application as-is, so bring over the 16829 // previously derived ABI information. 16830 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16831 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16832 } 16833 16834 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16835 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16836 scanFlags |= SCAN_NO_DEX; 16837 16838 try { 16839 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16840 args.abiOverride : pkg.cpuAbiOverride); 16841 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16842 true /*extractLibs*/, mAppLib32InstallDir); 16843 } catch (PackageManagerException pme) { 16844 Slog.e(TAG, "Error deriving application ABI", pme); 16845 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16846 return; 16847 } 16848 16849 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16850 // Do not run PackageDexOptimizer through the local performDexOpt 16851 // method because `pkg` may not be in `mPackages` yet. 16852 // 16853 // Also, don't fail application installs if the dexopt step fails. 16854 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16855 null /* instructionSets */, false /* checkProfiles */, 16856 getCompilerFilterForReason(REASON_INSTALL), 16857 getOrCreateCompilerPackageStats(pkg), 16858 mDexManager.isUsedByOtherApps(pkg.packageName)); 16859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16860 16861 // Notify BackgroundDexOptService that the package has been changed. 16862 // If this is an update of a package which used to fail to compile, 16863 // BDOS will remove it from its blacklist. 16864 // TODO: Layering violation 16865 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16866 } 16867 16868 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16869 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16870 return; 16871 } 16872 16873 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16874 16875 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16876 "installPackageLI")) { 16877 if (replace) { 16878 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16879 // Static libs have a synthetic package name containing the version 16880 // and cannot be updated as an update would get a new package name, 16881 // unless this is the exact same version code which is useful for 16882 // development. 16883 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16884 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16885 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16886 + "static-shared libs cannot be updated"); 16887 return; 16888 } 16889 } 16890 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16891 installerPackageName, res, args.installReason); 16892 } else { 16893 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16894 args.user, installerPackageName, volumeUuid, res, args.installReason); 16895 } 16896 } 16897 synchronized (mPackages) { 16898 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16899 if (ps != null) { 16900 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16901 ps.setUpdateAvailable(false /*updateAvailable*/); 16902 } 16903 16904 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16905 for (int i = 0; i < childCount; i++) { 16906 PackageParser.Package childPkg = pkg.childPackages.get(i); 16907 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16908 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16909 if (childPs != null) { 16910 childRes.newUsers = childPs.queryInstalledUsers( 16911 sUserManager.getUserIds(), true); 16912 } 16913 } 16914 16915 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16916 updateSequenceNumberLP(pkgName, res.newUsers); 16917 } 16918 } 16919 } 16920 16921 private void startIntentFilterVerifications(int userId, boolean replacing, 16922 PackageParser.Package pkg) { 16923 if (mIntentFilterVerifierComponent == null) { 16924 Slog.w(TAG, "No IntentFilter verification will not be done as " 16925 + "there is no IntentFilterVerifier available!"); 16926 return; 16927 } 16928 16929 final int verifierUid = getPackageUid( 16930 mIntentFilterVerifierComponent.getPackageName(), 16931 MATCH_DEBUG_TRIAGED_MISSING, 16932 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16933 16934 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16935 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16936 mHandler.sendMessage(msg); 16937 16938 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16939 for (int i = 0; i < childCount; i++) { 16940 PackageParser.Package childPkg = pkg.childPackages.get(i); 16941 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16942 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16943 mHandler.sendMessage(msg); 16944 } 16945 } 16946 16947 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16948 PackageParser.Package pkg) { 16949 int size = pkg.activities.size(); 16950 if (size == 0) { 16951 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16952 "No activity, so no need to verify any IntentFilter!"); 16953 return; 16954 } 16955 16956 final boolean hasDomainURLs = hasDomainURLs(pkg); 16957 if (!hasDomainURLs) { 16958 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16959 "No domain URLs, so no need to verify any IntentFilter!"); 16960 return; 16961 } 16962 16963 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16964 + " if any IntentFilter from the " + size 16965 + " Activities needs verification ..."); 16966 16967 int count = 0; 16968 final String packageName = pkg.packageName; 16969 16970 synchronized (mPackages) { 16971 // If this is a new install and we see that we've already run verification for this 16972 // package, we have nothing to do: it means the state was restored from backup. 16973 if (!replacing) { 16974 IntentFilterVerificationInfo ivi = 16975 mSettings.getIntentFilterVerificationLPr(packageName); 16976 if (ivi != null) { 16977 if (DEBUG_DOMAIN_VERIFICATION) { 16978 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16979 + ivi.getStatusString()); 16980 } 16981 return; 16982 } 16983 } 16984 16985 // If any filters need to be verified, then all need to be. 16986 boolean needToVerify = false; 16987 for (PackageParser.Activity a : pkg.activities) { 16988 for (ActivityIntentInfo filter : a.intents) { 16989 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16990 if (DEBUG_DOMAIN_VERIFICATION) { 16991 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16992 } 16993 needToVerify = true; 16994 break; 16995 } 16996 } 16997 } 16998 16999 if (needToVerify) { 17000 final int verificationId = mIntentFilterVerificationToken++; 17001 for (PackageParser.Activity a : pkg.activities) { 17002 for (ActivityIntentInfo filter : a.intents) { 17003 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17004 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17005 "Verification needed for IntentFilter:" + filter.toString()); 17006 mIntentFilterVerifier.addOneIntentFilterVerification( 17007 verifierUid, userId, verificationId, filter, packageName); 17008 count++; 17009 } 17010 } 17011 } 17012 } 17013 } 17014 17015 if (count > 0) { 17016 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17017 + " IntentFilter verification" + (count > 1 ? "s" : "") 17018 + " for userId:" + userId); 17019 mIntentFilterVerifier.startVerifications(userId); 17020 } else { 17021 if (DEBUG_DOMAIN_VERIFICATION) { 17022 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17023 } 17024 } 17025 } 17026 17027 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17028 final ComponentName cn = filter.activity.getComponentName(); 17029 final String packageName = cn.getPackageName(); 17030 17031 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17032 packageName); 17033 if (ivi == null) { 17034 return true; 17035 } 17036 int status = ivi.getStatus(); 17037 switch (status) { 17038 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17039 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17040 return true; 17041 17042 default: 17043 // Nothing to do 17044 return false; 17045 } 17046 } 17047 17048 private static boolean isMultiArch(ApplicationInfo info) { 17049 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17050 } 17051 17052 private static boolean isExternal(PackageParser.Package pkg) { 17053 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17054 } 17055 17056 private static boolean isExternal(PackageSetting ps) { 17057 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17058 } 17059 17060 private static boolean isSystemApp(PackageParser.Package pkg) { 17061 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17062 } 17063 17064 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17065 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17066 } 17067 17068 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17069 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17070 } 17071 17072 private static boolean isSystemApp(PackageSetting ps) { 17073 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17074 } 17075 17076 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17077 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17078 } 17079 17080 private int packageFlagsToInstallFlags(PackageSetting ps) { 17081 int installFlags = 0; 17082 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17083 // This existing package was an external ASEC install when we have 17084 // the external flag without a UUID 17085 installFlags |= PackageManager.INSTALL_EXTERNAL; 17086 } 17087 if (ps.isForwardLocked()) { 17088 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17089 } 17090 return installFlags; 17091 } 17092 17093 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17094 if (isExternal(pkg)) { 17095 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17096 return StorageManager.UUID_PRIMARY_PHYSICAL; 17097 } else { 17098 return pkg.volumeUuid; 17099 } 17100 } else { 17101 return StorageManager.UUID_PRIVATE_INTERNAL; 17102 } 17103 } 17104 17105 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17106 if (isExternal(pkg)) { 17107 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17108 return mSettings.getExternalVersion(); 17109 } else { 17110 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17111 } 17112 } else { 17113 return mSettings.getInternalVersion(); 17114 } 17115 } 17116 17117 private void deleteTempPackageFiles() { 17118 final FilenameFilter filter = new FilenameFilter() { 17119 public boolean accept(File dir, String name) { 17120 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17121 } 17122 }; 17123 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17124 file.delete(); 17125 } 17126 } 17127 17128 @Override 17129 public void deletePackageAsUser(String packageName, int versionCode, 17130 IPackageDeleteObserver observer, int userId, int flags) { 17131 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17132 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17133 } 17134 17135 @Override 17136 public void deletePackageVersioned(VersionedPackage versionedPackage, 17137 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17138 mContext.enforceCallingOrSelfPermission( 17139 android.Manifest.permission.DELETE_PACKAGES, null); 17140 Preconditions.checkNotNull(versionedPackage); 17141 Preconditions.checkNotNull(observer); 17142 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17143 PackageManager.VERSION_CODE_HIGHEST, 17144 Integer.MAX_VALUE, "versionCode must be >= -1"); 17145 17146 final String packageName = versionedPackage.getPackageName(); 17147 // TODO: We will change version code to long, so in the new API it is long 17148 final int versionCode = (int) versionedPackage.getVersionCode(); 17149 final String internalPackageName; 17150 synchronized (mPackages) { 17151 // Normalize package name to handle renamed packages and static libs 17152 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17153 // TODO: We will change version code to long, so in the new API it is long 17154 (int) versionedPackage.getVersionCode()); 17155 } 17156 17157 final int uid = Binder.getCallingUid(); 17158 if (!isOrphaned(internalPackageName) 17159 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17160 try { 17161 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17162 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17163 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17164 observer.onUserActionRequired(intent); 17165 } catch (RemoteException re) { 17166 } 17167 return; 17168 } 17169 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17170 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17171 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17172 mContext.enforceCallingOrSelfPermission( 17173 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17174 "deletePackage for user " + userId); 17175 } 17176 17177 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17178 try { 17179 observer.onPackageDeleted(packageName, 17180 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17181 } catch (RemoteException re) { 17182 } 17183 return; 17184 } 17185 17186 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17187 try { 17188 observer.onPackageDeleted(packageName, 17189 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17190 } catch (RemoteException re) { 17191 } 17192 return; 17193 } 17194 17195 if (DEBUG_REMOVE) { 17196 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17197 + " deleteAllUsers: " + deleteAllUsers + " version=" 17198 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17199 ? "VERSION_CODE_HIGHEST" : versionCode)); 17200 } 17201 // Queue up an async operation since the package deletion may take a little while. 17202 mHandler.post(new Runnable() { 17203 public void run() { 17204 mHandler.removeCallbacks(this); 17205 int returnCode; 17206 if (!deleteAllUsers) { 17207 returnCode = deletePackageX(internalPackageName, versionCode, 17208 userId, deleteFlags); 17209 } else { 17210 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17211 internalPackageName, users); 17212 // If nobody is blocking uninstall, proceed with delete for all users 17213 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17214 returnCode = deletePackageX(internalPackageName, versionCode, 17215 userId, deleteFlags); 17216 } else { 17217 // Otherwise uninstall individually for users with blockUninstalls=false 17218 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17219 for (int userId : users) { 17220 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17221 returnCode = deletePackageX(internalPackageName, versionCode, 17222 userId, userFlags); 17223 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17224 Slog.w(TAG, "Package delete failed for user " + userId 17225 + ", returnCode " + returnCode); 17226 } 17227 } 17228 } 17229 // The app has only been marked uninstalled for certain users. 17230 // We still need to report that delete was blocked 17231 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17232 } 17233 } 17234 try { 17235 observer.onPackageDeleted(packageName, returnCode, null); 17236 } catch (RemoteException e) { 17237 Log.i(TAG, "Observer no longer exists."); 17238 } //end catch 17239 } //end run 17240 }); 17241 } 17242 17243 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17244 if (pkg.staticSharedLibName != null) { 17245 return pkg.manifestPackageName; 17246 } 17247 return pkg.packageName; 17248 } 17249 17250 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17251 // Handle renamed packages 17252 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17253 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17254 17255 // Is this a static library? 17256 SparseArray<SharedLibraryEntry> versionedLib = 17257 mStaticLibsByDeclaringPackage.get(packageName); 17258 if (versionedLib == null || versionedLib.size() <= 0) { 17259 return packageName; 17260 } 17261 17262 // Figure out which lib versions the caller can see 17263 SparseIntArray versionsCallerCanSee = null; 17264 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17265 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17266 && callingAppId != Process.ROOT_UID) { 17267 versionsCallerCanSee = new SparseIntArray(); 17268 String libName = versionedLib.valueAt(0).info.getName(); 17269 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17270 if (uidPackages != null) { 17271 for (String uidPackage : uidPackages) { 17272 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17273 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17274 if (libIdx >= 0) { 17275 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17276 versionsCallerCanSee.append(libVersion, libVersion); 17277 } 17278 } 17279 } 17280 } 17281 17282 // Caller can see nothing - done 17283 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17284 return packageName; 17285 } 17286 17287 // Find the version the caller can see and the app version code 17288 SharedLibraryEntry highestVersion = null; 17289 final int versionCount = versionedLib.size(); 17290 for (int i = 0; i < versionCount; i++) { 17291 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17292 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17293 libEntry.info.getVersion()) < 0) { 17294 continue; 17295 } 17296 // TODO: We will change version code to long, so in the new API it is long 17297 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17298 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17299 if (libVersionCode == versionCode) { 17300 return libEntry.apk; 17301 } 17302 } else if (highestVersion == null) { 17303 highestVersion = libEntry; 17304 } else if (libVersionCode > highestVersion.info 17305 .getDeclaringPackage().getVersionCode()) { 17306 highestVersion = libEntry; 17307 } 17308 } 17309 17310 if (highestVersion != null) { 17311 return highestVersion.apk; 17312 } 17313 17314 return packageName; 17315 } 17316 17317 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17318 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17319 || callingUid == Process.SYSTEM_UID) { 17320 return true; 17321 } 17322 final int callingUserId = UserHandle.getUserId(callingUid); 17323 // If the caller installed the pkgName, then allow it to silently uninstall. 17324 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17325 return true; 17326 } 17327 17328 // Allow package verifier to silently uninstall. 17329 if (mRequiredVerifierPackage != null && 17330 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17331 return true; 17332 } 17333 17334 // Allow package uninstaller to silently uninstall. 17335 if (mRequiredUninstallerPackage != null && 17336 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17337 return true; 17338 } 17339 17340 // Allow storage manager to silently uninstall. 17341 if (mStorageManagerPackage != null && 17342 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17343 return true; 17344 } 17345 return false; 17346 } 17347 17348 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17349 int[] result = EMPTY_INT_ARRAY; 17350 for (int userId : userIds) { 17351 if (getBlockUninstallForUser(packageName, userId)) { 17352 result = ArrayUtils.appendInt(result, userId); 17353 } 17354 } 17355 return result; 17356 } 17357 17358 @Override 17359 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17360 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17361 } 17362 17363 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17364 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17365 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17366 try { 17367 if (dpm != null) { 17368 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17369 /* callingUserOnly =*/ false); 17370 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17371 : deviceOwnerComponentName.getPackageName(); 17372 // Does the package contains the device owner? 17373 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17374 // this check is probably not needed, since DO should be registered as a device 17375 // admin on some user too. (Original bug for this: b/17657954) 17376 if (packageName.equals(deviceOwnerPackageName)) { 17377 return true; 17378 } 17379 // Does it contain a device admin for any user? 17380 int[] users; 17381 if (userId == UserHandle.USER_ALL) { 17382 users = sUserManager.getUserIds(); 17383 } else { 17384 users = new int[]{userId}; 17385 } 17386 for (int i = 0; i < users.length; ++i) { 17387 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17388 return true; 17389 } 17390 } 17391 } 17392 } catch (RemoteException e) { 17393 } 17394 return false; 17395 } 17396 17397 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17398 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17399 } 17400 17401 /** 17402 * This method is an internal method that could be get invoked either 17403 * to delete an installed package or to clean up a failed installation. 17404 * After deleting an installed package, a broadcast is sent to notify any 17405 * listeners that the package has been removed. For cleaning up a failed 17406 * installation, the broadcast is not necessary since the package's 17407 * installation wouldn't have sent the initial broadcast either 17408 * The key steps in deleting a package are 17409 * deleting the package information in internal structures like mPackages, 17410 * deleting the packages base directories through installd 17411 * updating mSettings to reflect current status 17412 * persisting settings for later use 17413 * sending a broadcast if necessary 17414 */ 17415 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17416 final PackageRemovedInfo info = new PackageRemovedInfo(); 17417 final boolean res; 17418 17419 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17420 ? UserHandle.USER_ALL : userId; 17421 17422 if (isPackageDeviceAdmin(packageName, removeUser)) { 17423 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17424 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17425 } 17426 17427 PackageSetting uninstalledPs = null; 17428 PackageParser.Package pkg = null; 17429 17430 // for the uninstall-updates case and restricted profiles, remember the per- 17431 // user handle installed state 17432 int[] allUsers; 17433 synchronized (mPackages) { 17434 uninstalledPs = mSettings.mPackages.get(packageName); 17435 if (uninstalledPs == null) { 17436 Slog.w(TAG, "Not removing non-existent package " + packageName); 17437 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17438 } 17439 17440 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17441 && uninstalledPs.versionCode != versionCode) { 17442 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17443 + uninstalledPs.versionCode + " != " + versionCode); 17444 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17445 } 17446 17447 // Static shared libs can be declared by any package, so let us not 17448 // allow removing a package if it provides a lib others depend on. 17449 pkg = mPackages.get(packageName); 17450 if (pkg != null && pkg.staticSharedLibName != null) { 17451 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17452 pkg.staticSharedLibVersion); 17453 if (libEntry != null) { 17454 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17455 libEntry.info, 0, userId); 17456 if (!ArrayUtils.isEmpty(libClientPackages)) { 17457 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17458 + " hosting lib " + libEntry.info.getName() + " version " 17459 + libEntry.info.getVersion() + " used by " + libClientPackages); 17460 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17461 } 17462 } 17463 } 17464 17465 allUsers = sUserManager.getUserIds(); 17466 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17467 } 17468 17469 final int freezeUser; 17470 if (isUpdatedSystemApp(uninstalledPs) 17471 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17472 // We're downgrading a system app, which will apply to all users, so 17473 // freeze them all during the downgrade 17474 freezeUser = UserHandle.USER_ALL; 17475 } else { 17476 freezeUser = removeUser; 17477 } 17478 17479 synchronized (mInstallLock) { 17480 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17481 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17482 deleteFlags, "deletePackageX")) { 17483 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17484 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17485 } 17486 synchronized (mPackages) { 17487 if (res) { 17488 if (pkg != null) { 17489 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17490 } 17491 updateSequenceNumberLP(packageName, info.removedUsers); 17492 } 17493 } 17494 } 17495 17496 if (res) { 17497 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17498 info.sendPackageRemovedBroadcasts(killApp); 17499 info.sendSystemPackageUpdatedBroadcasts(); 17500 info.sendSystemPackageAppearedBroadcasts(); 17501 } 17502 // Force a gc here. 17503 Runtime.getRuntime().gc(); 17504 // Delete the resources here after sending the broadcast to let 17505 // other processes clean up before deleting resources. 17506 if (info.args != null) { 17507 synchronized (mInstallLock) { 17508 info.args.doPostDeleteLI(true); 17509 } 17510 } 17511 17512 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17513 } 17514 17515 class PackageRemovedInfo { 17516 String removedPackage; 17517 int uid = -1; 17518 int removedAppId = -1; 17519 int[] origUsers; 17520 int[] removedUsers = null; 17521 SparseArray<Integer> installReasons; 17522 boolean isRemovedPackageSystemUpdate = false; 17523 boolean isUpdate; 17524 boolean dataRemoved; 17525 boolean removedForAllUsers; 17526 boolean isStaticSharedLib; 17527 // Clean up resources deleted packages. 17528 InstallArgs args = null; 17529 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17530 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17531 17532 void sendPackageRemovedBroadcasts(boolean killApp) { 17533 sendPackageRemovedBroadcastInternal(killApp); 17534 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17535 for (int i = 0; i < childCount; i++) { 17536 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17537 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17538 } 17539 } 17540 17541 void sendSystemPackageUpdatedBroadcasts() { 17542 if (isRemovedPackageSystemUpdate) { 17543 sendSystemPackageUpdatedBroadcastsInternal(); 17544 final int childCount = (removedChildPackages != null) 17545 ? removedChildPackages.size() : 0; 17546 for (int i = 0; i < childCount; i++) { 17547 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17548 if (childInfo.isRemovedPackageSystemUpdate) { 17549 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17550 } 17551 } 17552 } 17553 } 17554 17555 void sendSystemPackageAppearedBroadcasts() { 17556 final int packageCount = (appearedChildPackages != null) 17557 ? appearedChildPackages.size() : 0; 17558 for (int i = 0; i < packageCount; i++) { 17559 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17560 sendPackageAddedForNewUsers(installedInfo.name, true, 17561 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17562 } 17563 } 17564 17565 private void sendSystemPackageUpdatedBroadcastsInternal() { 17566 Bundle extras = new Bundle(2); 17567 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17568 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17569 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17570 extras, 0, null, null, null); 17571 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17572 extras, 0, null, null, null); 17573 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17574 null, 0, removedPackage, null, null); 17575 } 17576 17577 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17578 // Don't send static shared library removal broadcasts as these 17579 // libs are visible only the the apps that depend on them an one 17580 // cannot remove the library if it has a dependency. 17581 if (isStaticSharedLib) { 17582 return; 17583 } 17584 Bundle extras = new Bundle(2); 17585 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17586 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17587 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17588 if (isUpdate || isRemovedPackageSystemUpdate) { 17589 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17590 } 17591 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17592 if (removedPackage != null) { 17593 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17594 extras, 0, null, null, removedUsers); 17595 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17596 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17597 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17598 null, null, removedUsers); 17599 } 17600 } 17601 if (removedAppId >= 0) { 17602 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17603 removedUsers); 17604 } 17605 } 17606 } 17607 17608 /* 17609 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17610 * flag is not set, the data directory is removed as well. 17611 * make sure this flag is set for partially installed apps. If not its meaningless to 17612 * delete a partially installed application. 17613 */ 17614 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17615 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17616 String packageName = ps.name; 17617 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17618 // Retrieve object to delete permissions for shared user later on 17619 final PackageParser.Package deletedPkg; 17620 final PackageSetting deletedPs; 17621 // reader 17622 synchronized (mPackages) { 17623 deletedPkg = mPackages.get(packageName); 17624 deletedPs = mSettings.mPackages.get(packageName); 17625 if (outInfo != null) { 17626 outInfo.removedPackage = packageName; 17627 outInfo.isStaticSharedLib = deletedPkg != null 17628 && deletedPkg.staticSharedLibName != null; 17629 outInfo.removedUsers = deletedPs != null 17630 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17631 : null; 17632 } 17633 } 17634 17635 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17636 17637 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17638 final PackageParser.Package resolvedPkg; 17639 if (deletedPkg != null) { 17640 resolvedPkg = deletedPkg; 17641 } else { 17642 // We don't have a parsed package when it lives on an ejected 17643 // adopted storage device, so fake something together 17644 resolvedPkg = new PackageParser.Package(ps.name); 17645 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17646 } 17647 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17648 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17649 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17650 if (outInfo != null) { 17651 outInfo.dataRemoved = true; 17652 } 17653 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17654 } 17655 17656 int removedAppId = -1; 17657 17658 // writer 17659 synchronized (mPackages) { 17660 boolean installedStateChanged = false; 17661 if (deletedPs != null) { 17662 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17663 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17664 clearDefaultBrowserIfNeeded(packageName); 17665 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17666 removedAppId = mSettings.removePackageLPw(packageName); 17667 if (outInfo != null) { 17668 outInfo.removedAppId = removedAppId; 17669 } 17670 updatePermissionsLPw(deletedPs.name, null, 0); 17671 if (deletedPs.sharedUser != null) { 17672 // Remove permissions associated with package. Since runtime 17673 // permissions are per user we have to kill the removed package 17674 // or packages running under the shared user of the removed 17675 // package if revoking the permissions requested only by the removed 17676 // package is successful and this causes a change in gids. 17677 for (int userId : UserManagerService.getInstance().getUserIds()) { 17678 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17679 userId); 17680 if (userIdToKill == UserHandle.USER_ALL 17681 || userIdToKill >= UserHandle.USER_SYSTEM) { 17682 // If gids changed for this user, kill all affected packages. 17683 mHandler.post(new Runnable() { 17684 @Override 17685 public void run() { 17686 // This has to happen with no lock held. 17687 killApplication(deletedPs.name, deletedPs.appId, 17688 KILL_APP_REASON_GIDS_CHANGED); 17689 } 17690 }); 17691 break; 17692 } 17693 } 17694 } 17695 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17696 } 17697 // make sure to preserve per-user disabled state if this removal was just 17698 // a downgrade of a system app to the factory package 17699 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17700 if (DEBUG_REMOVE) { 17701 Slog.d(TAG, "Propagating install state across downgrade"); 17702 } 17703 for (int userId : allUserHandles) { 17704 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17705 if (DEBUG_REMOVE) { 17706 Slog.d(TAG, " user " + userId + " => " + installed); 17707 } 17708 if (installed != ps.getInstalled(userId)) { 17709 installedStateChanged = true; 17710 } 17711 ps.setInstalled(installed, userId); 17712 } 17713 } 17714 } 17715 // can downgrade to reader 17716 if (writeSettings) { 17717 // Save settings now 17718 mSettings.writeLPr(); 17719 } 17720 if (installedStateChanged) { 17721 mSettings.writeKernelMappingLPr(ps); 17722 } 17723 } 17724 if (removedAppId != -1) { 17725 // A user ID was deleted here. Go through all users and remove it 17726 // from KeyStore. 17727 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17728 } 17729 } 17730 17731 static boolean locationIsPrivileged(File path) { 17732 try { 17733 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17734 .getCanonicalPath(); 17735 return path.getCanonicalPath().startsWith(privilegedAppDir); 17736 } catch (IOException e) { 17737 Slog.e(TAG, "Unable to access code path " + path); 17738 } 17739 return false; 17740 } 17741 17742 /* 17743 * Tries to delete system package. 17744 */ 17745 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17746 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17747 boolean writeSettings) { 17748 if (deletedPs.parentPackageName != null) { 17749 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17750 return false; 17751 } 17752 17753 final boolean applyUserRestrictions 17754 = (allUserHandles != null) && (outInfo.origUsers != null); 17755 final PackageSetting disabledPs; 17756 // Confirm if the system package has been updated 17757 // An updated system app can be deleted. This will also have to restore 17758 // the system pkg from system partition 17759 // reader 17760 synchronized (mPackages) { 17761 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17762 } 17763 17764 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17765 + " disabledPs=" + disabledPs); 17766 17767 if (disabledPs == null) { 17768 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17769 return false; 17770 } else if (DEBUG_REMOVE) { 17771 Slog.d(TAG, "Deleting system pkg from data partition"); 17772 } 17773 17774 if (DEBUG_REMOVE) { 17775 if (applyUserRestrictions) { 17776 Slog.d(TAG, "Remembering install states:"); 17777 for (int userId : allUserHandles) { 17778 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17779 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17780 } 17781 } 17782 } 17783 17784 // Delete the updated package 17785 outInfo.isRemovedPackageSystemUpdate = true; 17786 if (outInfo.removedChildPackages != null) { 17787 final int childCount = (deletedPs.childPackageNames != null) 17788 ? deletedPs.childPackageNames.size() : 0; 17789 for (int i = 0; i < childCount; i++) { 17790 String childPackageName = deletedPs.childPackageNames.get(i); 17791 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17792 .contains(childPackageName)) { 17793 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17794 childPackageName); 17795 if (childInfo != null) { 17796 childInfo.isRemovedPackageSystemUpdate = true; 17797 } 17798 } 17799 } 17800 } 17801 17802 if (disabledPs.versionCode < deletedPs.versionCode) { 17803 // Delete data for downgrades 17804 flags &= ~PackageManager.DELETE_KEEP_DATA; 17805 } else { 17806 // Preserve data by setting flag 17807 flags |= PackageManager.DELETE_KEEP_DATA; 17808 } 17809 17810 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17811 outInfo, writeSettings, disabledPs.pkg); 17812 if (!ret) { 17813 return false; 17814 } 17815 17816 // writer 17817 synchronized (mPackages) { 17818 // Reinstate the old system package 17819 enableSystemPackageLPw(disabledPs.pkg); 17820 // Remove any native libraries from the upgraded package. 17821 removeNativeBinariesLI(deletedPs); 17822 } 17823 17824 // Install the system package 17825 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17826 int parseFlags = mDefParseFlags 17827 | PackageParser.PARSE_MUST_BE_APK 17828 | PackageParser.PARSE_IS_SYSTEM 17829 | PackageParser.PARSE_IS_SYSTEM_DIR; 17830 if (locationIsPrivileged(disabledPs.codePath)) { 17831 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17832 } 17833 17834 final PackageParser.Package newPkg; 17835 try { 17836 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17837 0 /* currentTime */, null); 17838 } catch (PackageManagerException e) { 17839 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17840 + e.getMessage()); 17841 return false; 17842 } 17843 17844 try { 17845 // update shared libraries for the newly re-installed system package 17846 updateSharedLibrariesLPr(newPkg, null); 17847 } catch (PackageManagerException e) { 17848 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17849 } 17850 17851 prepareAppDataAfterInstallLIF(newPkg); 17852 17853 // writer 17854 synchronized (mPackages) { 17855 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17856 17857 // Propagate the permissions state as we do not want to drop on the floor 17858 // runtime permissions. The update permissions method below will take 17859 // care of removing obsolete permissions and grant install permissions. 17860 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17861 updatePermissionsLPw(newPkg.packageName, newPkg, 17862 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17863 17864 if (applyUserRestrictions) { 17865 boolean installedStateChanged = false; 17866 if (DEBUG_REMOVE) { 17867 Slog.d(TAG, "Propagating install state across reinstall"); 17868 } 17869 for (int userId : allUserHandles) { 17870 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17871 if (DEBUG_REMOVE) { 17872 Slog.d(TAG, " user " + userId + " => " + installed); 17873 } 17874 if (installed != ps.getInstalled(userId)) { 17875 installedStateChanged = true; 17876 } 17877 ps.setInstalled(installed, userId); 17878 17879 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17880 } 17881 // Regardless of writeSettings we need to ensure that this restriction 17882 // state propagation is persisted 17883 mSettings.writeAllUsersPackageRestrictionsLPr(); 17884 if (installedStateChanged) { 17885 mSettings.writeKernelMappingLPr(ps); 17886 } 17887 } 17888 // can downgrade to reader here 17889 if (writeSettings) { 17890 mSettings.writeLPr(); 17891 } 17892 } 17893 return true; 17894 } 17895 17896 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17897 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17898 PackageRemovedInfo outInfo, boolean writeSettings, 17899 PackageParser.Package replacingPackage) { 17900 synchronized (mPackages) { 17901 if (outInfo != null) { 17902 outInfo.uid = ps.appId; 17903 } 17904 17905 if (outInfo != null && outInfo.removedChildPackages != null) { 17906 final int childCount = (ps.childPackageNames != null) 17907 ? ps.childPackageNames.size() : 0; 17908 for (int i = 0; i < childCount; i++) { 17909 String childPackageName = ps.childPackageNames.get(i); 17910 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17911 if (childPs == null) { 17912 return false; 17913 } 17914 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17915 childPackageName); 17916 if (childInfo != null) { 17917 childInfo.uid = childPs.appId; 17918 } 17919 } 17920 } 17921 } 17922 17923 // Delete package data from internal structures and also remove data if flag is set 17924 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17925 17926 // Delete the child packages data 17927 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17928 for (int i = 0; i < childCount; i++) { 17929 PackageSetting childPs; 17930 synchronized (mPackages) { 17931 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17932 } 17933 if (childPs != null) { 17934 PackageRemovedInfo childOutInfo = (outInfo != null 17935 && outInfo.removedChildPackages != null) 17936 ? outInfo.removedChildPackages.get(childPs.name) : null; 17937 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17938 && (replacingPackage != null 17939 && !replacingPackage.hasChildPackage(childPs.name)) 17940 ? flags & ~DELETE_KEEP_DATA : flags; 17941 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17942 deleteFlags, writeSettings); 17943 } 17944 } 17945 17946 // Delete application code and resources only for parent packages 17947 if (ps.parentPackageName == null) { 17948 if (deleteCodeAndResources && (outInfo != null)) { 17949 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17950 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17951 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17952 } 17953 } 17954 17955 return true; 17956 } 17957 17958 @Override 17959 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17960 int userId) { 17961 mContext.enforceCallingOrSelfPermission( 17962 android.Manifest.permission.DELETE_PACKAGES, null); 17963 synchronized (mPackages) { 17964 PackageSetting ps = mSettings.mPackages.get(packageName); 17965 if (ps == null) { 17966 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17967 return false; 17968 } 17969 // Cannot block uninstall of static shared libs as they are 17970 // considered a part of the using app (emulating static linking). 17971 // Also static libs are installed always on internal storage. 17972 PackageParser.Package pkg = mPackages.get(packageName); 17973 if (pkg != null && pkg.staticSharedLibName != null) { 17974 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17975 + " providing static shared library: " + pkg.staticSharedLibName); 17976 return false; 17977 } 17978 if (!ps.getInstalled(userId)) { 17979 // Can't block uninstall for an app that is not installed or enabled. 17980 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17981 return false; 17982 } 17983 ps.setBlockUninstall(blockUninstall, userId); 17984 mSettings.writePackageRestrictionsLPr(userId); 17985 } 17986 return true; 17987 } 17988 17989 @Override 17990 public boolean getBlockUninstallForUser(String packageName, int userId) { 17991 synchronized (mPackages) { 17992 PackageSetting ps = mSettings.mPackages.get(packageName); 17993 if (ps == null) { 17994 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 17995 return false; 17996 } 17997 return ps.getBlockUninstall(userId); 17998 } 17999 } 18000 18001 @Override 18002 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18003 int callingUid = Binder.getCallingUid(); 18004 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18005 throw new SecurityException( 18006 "setRequiredForSystemUser can only be run by the system or root"); 18007 } 18008 synchronized (mPackages) { 18009 PackageSetting ps = mSettings.mPackages.get(packageName); 18010 if (ps == null) { 18011 Log.w(TAG, "Package doesn't exist: " + packageName); 18012 return false; 18013 } 18014 if (systemUserApp) { 18015 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18016 } else { 18017 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18018 } 18019 mSettings.writeLPr(); 18020 } 18021 return true; 18022 } 18023 18024 /* 18025 * This method handles package deletion in general 18026 */ 18027 private boolean deletePackageLIF(String packageName, UserHandle user, 18028 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18029 PackageRemovedInfo outInfo, boolean writeSettings, 18030 PackageParser.Package replacingPackage) { 18031 if (packageName == null) { 18032 Slog.w(TAG, "Attempt to delete null packageName."); 18033 return false; 18034 } 18035 18036 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18037 18038 PackageSetting ps; 18039 synchronized (mPackages) { 18040 ps = mSettings.mPackages.get(packageName); 18041 if (ps == null) { 18042 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18043 return false; 18044 } 18045 18046 if (ps.parentPackageName != null && (!isSystemApp(ps) 18047 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18048 if (DEBUG_REMOVE) { 18049 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18050 + ((user == null) ? UserHandle.USER_ALL : user)); 18051 } 18052 final int removedUserId = (user != null) ? user.getIdentifier() 18053 : UserHandle.USER_ALL; 18054 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18055 return false; 18056 } 18057 markPackageUninstalledForUserLPw(ps, user); 18058 scheduleWritePackageRestrictionsLocked(user); 18059 return true; 18060 } 18061 } 18062 18063 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18064 && user.getIdentifier() != UserHandle.USER_ALL)) { 18065 // The caller is asking that the package only be deleted for a single 18066 // user. To do this, we just mark its uninstalled state and delete 18067 // its data. If this is a system app, we only allow this to happen if 18068 // they have set the special DELETE_SYSTEM_APP which requests different 18069 // semantics than normal for uninstalling system apps. 18070 markPackageUninstalledForUserLPw(ps, user); 18071 18072 if (!isSystemApp(ps)) { 18073 // Do not uninstall the APK if an app should be cached 18074 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18075 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18076 // Other user still have this package installed, so all 18077 // we need to do is clear this user's data and save that 18078 // it is uninstalled. 18079 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18080 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18081 return false; 18082 } 18083 scheduleWritePackageRestrictionsLocked(user); 18084 return true; 18085 } else { 18086 // We need to set it back to 'installed' so the uninstall 18087 // broadcasts will be sent correctly. 18088 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18089 ps.setInstalled(true, user.getIdentifier()); 18090 mSettings.writeKernelMappingLPr(ps); 18091 } 18092 } else { 18093 // This is a system app, so we assume that the 18094 // other users still have this package installed, so all 18095 // we need to do is clear this user's data and save that 18096 // it is uninstalled. 18097 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18098 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18099 return false; 18100 } 18101 scheduleWritePackageRestrictionsLocked(user); 18102 return true; 18103 } 18104 } 18105 18106 // If we are deleting a composite package for all users, keep track 18107 // of result for each child. 18108 if (ps.childPackageNames != null && outInfo != null) { 18109 synchronized (mPackages) { 18110 final int childCount = ps.childPackageNames.size(); 18111 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18112 for (int i = 0; i < childCount; i++) { 18113 String childPackageName = ps.childPackageNames.get(i); 18114 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18115 childInfo.removedPackage = childPackageName; 18116 outInfo.removedChildPackages.put(childPackageName, childInfo); 18117 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18118 if (childPs != null) { 18119 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18120 } 18121 } 18122 } 18123 } 18124 18125 boolean ret = false; 18126 if (isSystemApp(ps)) { 18127 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18128 // When an updated system application is deleted we delete the existing resources 18129 // as well and fall back to existing code in system partition 18130 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18131 } else { 18132 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18133 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18134 outInfo, writeSettings, replacingPackage); 18135 } 18136 18137 // Take a note whether we deleted the package for all users 18138 if (outInfo != null) { 18139 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18140 if (outInfo.removedChildPackages != null) { 18141 synchronized (mPackages) { 18142 final int childCount = outInfo.removedChildPackages.size(); 18143 for (int i = 0; i < childCount; i++) { 18144 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18145 if (childInfo != null) { 18146 childInfo.removedForAllUsers = mPackages.get( 18147 childInfo.removedPackage) == null; 18148 } 18149 } 18150 } 18151 } 18152 // If we uninstalled an update to a system app there may be some 18153 // child packages that appeared as they are declared in the system 18154 // app but were not declared in the update. 18155 if (isSystemApp(ps)) { 18156 synchronized (mPackages) { 18157 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18158 final int childCount = (updatedPs.childPackageNames != null) 18159 ? updatedPs.childPackageNames.size() : 0; 18160 for (int i = 0; i < childCount; i++) { 18161 String childPackageName = updatedPs.childPackageNames.get(i); 18162 if (outInfo.removedChildPackages == null 18163 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18164 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18165 if (childPs == null) { 18166 continue; 18167 } 18168 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18169 installRes.name = childPackageName; 18170 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18171 installRes.pkg = mPackages.get(childPackageName); 18172 installRes.uid = childPs.pkg.applicationInfo.uid; 18173 if (outInfo.appearedChildPackages == null) { 18174 outInfo.appearedChildPackages = new ArrayMap<>(); 18175 } 18176 outInfo.appearedChildPackages.put(childPackageName, installRes); 18177 } 18178 } 18179 } 18180 } 18181 } 18182 18183 return ret; 18184 } 18185 18186 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18187 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18188 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18189 for (int nextUserId : userIds) { 18190 if (DEBUG_REMOVE) { 18191 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18192 } 18193 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18194 false /*installed*/, 18195 true /*stopped*/, 18196 true /*notLaunched*/, 18197 false /*hidden*/, 18198 false /*suspended*/, 18199 false /*instantApp*/, 18200 null /*lastDisableAppCaller*/, 18201 null /*enabledComponents*/, 18202 null /*disabledComponents*/, 18203 false /*blockUninstall*/, 18204 ps.readUserState(nextUserId).domainVerificationStatus, 18205 0, PackageManager.INSTALL_REASON_UNKNOWN); 18206 } 18207 mSettings.writeKernelMappingLPr(ps); 18208 } 18209 18210 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18211 PackageRemovedInfo outInfo) { 18212 final PackageParser.Package pkg; 18213 synchronized (mPackages) { 18214 pkg = mPackages.get(ps.name); 18215 } 18216 18217 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18218 : new int[] {userId}; 18219 for (int nextUserId : userIds) { 18220 if (DEBUG_REMOVE) { 18221 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18222 + nextUserId); 18223 } 18224 18225 destroyAppDataLIF(pkg, userId, 18226 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18227 destroyAppProfilesLIF(pkg, userId); 18228 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18229 schedulePackageCleaning(ps.name, nextUserId, false); 18230 synchronized (mPackages) { 18231 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18232 scheduleWritePackageRestrictionsLocked(nextUserId); 18233 } 18234 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18235 } 18236 } 18237 18238 if (outInfo != null) { 18239 outInfo.removedPackage = ps.name; 18240 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18241 outInfo.removedAppId = ps.appId; 18242 outInfo.removedUsers = userIds; 18243 } 18244 18245 return true; 18246 } 18247 18248 private final class ClearStorageConnection implements ServiceConnection { 18249 IMediaContainerService mContainerService; 18250 18251 @Override 18252 public void onServiceConnected(ComponentName name, IBinder service) { 18253 synchronized (this) { 18254 mContainerService = IMediaContainerService.Stub 18255 .asInterface(Binder.allowBlocking(service)); 18256 notifyAll(); 18257 } 18258 } 18259 18260 @Override 18261 public void onServiceDisconnected(ComponentName name) { 18262 } 18263 } 18264 18265 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18266 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18267 18268 final boolean mounted; 18269 if (Environment.isExternalStorageEmulated()) { 18270 mounted = true; 18271 } else { 18272 final String status = Environment.getExternalStorageState(); 18273 18274 mounted = status.equals(Environment.MEDIA_MOUNTED) 18275 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18276 } 18277 18278 if (!mounted) { 18279 return; 18280 } 18281 18282 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18283 int[] users; 18284 if (userId == UserHandle.USER_ALL) { 18285 users = sUserManager.getUserIds(); 18286 } else { 18287 users = new int[] { userId }; 18288 } 18289 final ClearStorageConnection conn = new ClearStorageConnection(); 18290 if (mContext.bindServiceAsUser( 18291 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18292 try { 18293 for (int curUser : users) { 18294 long timeout = SystemClock.uptimeMillis() + 5000; 18295 synchronized (conn) { 18296 long now; 18297 while (conn.mContainerService == null && 18298 (now = SystemClock.uptimeMillis()) < timeout) { 18299 try { 18300 conn.wait(timeout - now); 18301 } catch (InterruptedException e) { 18302 } 18303 } 18304 } 18305 if (conn.mContainerService == null) { 18306 return; 18307 } 18308 18309 final UserEnvironment userEnv = new UserEnvironment(curUser); 18310 clearDirectory(conn.mContainerService, 18311 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18312 if (allData) { 18313 clearDirectory(conn.mContainerService, 18314 userEnv.buildExternalStorageAppDataDirs(packageName)); 18315 clearDirectory(conn.mContainerService, 18316 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18317 } 18318 } 18319 } finally { 18320 mContext.unbindService(conn); 18321 } 18322 } 18323 } 18324 18325 @Override 18326 public void clearApplicationProfileData(String packageName) { 18327 enforceSystemOrRoot("Only the system can clear all profile data"); 18328 18329 final PackageParser.Package pkg; 18330 synchronized (mPackages) { 18331 pkg = mPackages.get(packageName); 18332 } 18333 18334 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18335 synchronized (mInstallLock) { 18336 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18337 } 18338 } 18339 } 18340 18341 @Override 18342 public void clearApplicationUserData(final String packageName, 18343 final IPackageDataObserver observer, final int userId) { 18344 mContext.enforceCallingOrSelfPermission( 18345 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18346 18347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18348 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18349 18350 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18351 throw new SecurityException("Cannot clear data for a protected package: " 18352 + packageName); 18353 } 18354 // Queue up an async operation since the package deletion may take a little while. 18355 mHandler.post(new Runnable() { 18356 public void run() { 18357 mHandler.removeCallbacks(this); 18358 final boolean succeeded; 18359 try (PackageFreezer freezer = freezePackage(packageName, 18360 "clearApplicationUserData")) { 18361 synchronized (mInstallLock) { 18362 succeeded = clearApplicationUserDataLIF(packageName, userId); 18363 } 18364 clearExternalStorageDataSync(packageName, userId, true); 18365 synchronized (mPackages) { 18366 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18367 packageName, userId); 18368 } 18369 } 18370 if (succeeded) { 18371 // invoke DeviceStorageMonitor's update method to clear any notifications 18372 DeviceStorageMonitorInternal dsm = LocalServices 18373 .getService(DeviceStorageMonitorInternal.class); 18374 if (dsm != null) { 18375 dsm.checkMemory(); 18376 } 18377 } 18378 if(observer != null) { 18379 try { 18380 observer.onRemoveCompleted(packageName, succeeded); 18381 } catch (RemoteException e) { 18382 Log.i(TAG, "Observer no longer exists."); 18383 } 18384 } //end if observer 18385 } //end run 18386 }); 18387 } 18388 18389 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18390 if (packageName == null) { 18391 Slog.w(TAG, "Attempt to delete null packageName."); 18392 return false; 18393 } 18394 18395 // Try finding details about the requested package 18396 PackageParser.Package pkg; 18397 synchronized (mPackages) { 18398 pkg = mPackages.get(packageName); 18399 if (pkg == null) { 18400 final PackageSetting ps = mSettings.mPackages.get(packageName); 18401 if (ps != null) { 18402 pkg = ps.pkg; 18403 } 18404 } 18405 18406 if (pkg == null) { 18407 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18408 return false; 18409 } 18410 18411 PackageSetting ps = (PackageSetting) pkg.mExtras; 18412 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18413 } 18414 18415 clearAppDataLIF(pkg, userId, 18416 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18417 18418 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18419 removeKeystoreDataIfNeeded(userId, appId); 18420 18421 UserManagerInternal umInternal = getUserManagerInternal(); 18422 final int flags; 18423 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18424 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18425 } else if (umInternal.isUserRunning(userId)) { 18426 flags = StorageManager.FLAG_STORAGE_DE; 18427 } else { 18428 flags = 0; 18429 } 18430 prepareAppDataContentsLIF(pkg, userId, flags); 18431 18432 return true; 18433 } 18434 18435 /** 18436 * Reverts user permission state changes (permissions and flags) in 18437 * all packages for a given user. 18438 * 18439 * @param userId The device user for which to do a reset. 18440 */ 18441 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18442 final int packageCount = mPackages.size(); 18443 for (int i = 0; i < packageCount; i++) { 18444 PackageParser.Package pkg = mPackages.valueAt(i); 18445 PackageSetting ps = (PackageSetting) pkg.mExtras; 18446 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18447 } 18448 } 18449 18450 private void resetNetworkPolicies(int userId) { 18451 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18452 } 18453 18454 /** 18455 * Reverts user permission state changes (permissions and flags). 18456 * 18457 * @param ps The package for which to reset. 18458 * @param userId The device user for which to do a reset. 18459 */ 18460 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18461 final PackageSetting ps, final int userId) { 18462 if (ps.pkg == null) { 18463 return; 18464 } 18465 18466 // These are flags that can change base on user actions. 18467 final int userSettableMask = FLAG_PERMISSION_USER_SET 18468 | FLAG_PERMISSION_USER_FIXED 18469 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18470 | FLAG_PERMISSION_REVIEW_REQUIRED; 18471 18472 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18473 | FLAG_PERMISSION_POLICY_FIXED; 18474 18475 boolean writeInstallPermissions = false; 18476 boolean writeRuntimePermissions = false; 18477 18478 final int permissionCount = ps.pkg.requestedPermissions.size(); 18479 for (int i = 0; i < permissionCount; i++) { 18480 String permission = ps.pkg.requestedPermissions.get(i); 18481 18482 BasePermission bp = mSettings.mPermissions.get(permission); 18483 if (bp == null) { 18484 continue; 18485 } 18486 18487 // If shared user we just reset the state to which only this app contributed. 18488 if (ps.sharedUser != null) { 18489 boolean used = false; 18490 final int packageCount = ps.sharedUser.packages.size(); 18491 for (int j = 0; j < packageCount; j++) { 18492 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18493 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18494 && pkg.pkg.requestedPermissions.contains(permission)) { 18495 used = true; 18496 break; 18497 } 18498 } 18499 if (used) { 18500 continue; 18501 } 18502 } 18503 18504 PermissionsState permissionsState = ps.getPermissionsState(); 18505 18506 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18507 18508 // Always clear the user settable flags. 18509 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18510 bp.name) != null; 18511 // If permission review is enabled and this is a legacy app, mark the 18512 // permission as requiring a review as this is the initial state. 18513 int flags = 0; 18514 if (mPermissionReviewRequired 18515 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18516 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18517 } 18518 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18519 if (hasInstallState) { 18520 writeInstallPermissions = true; 18521 } else { 18522 writeRuntimePermissions = true; 18523 } 18524 } 18525 18526 // Below is only runtime permission handling. 18527 if (!bp.isRuntime()) { 18528 continue; 18529 } 18530 18531 // Never clobber system or policy. 18532 if ((oldFlags & policyOrSystemFlags) != 0) { 18533 continue; 18534 } 18535 18536 // If this permission was granted by default, make sure it is. 18537 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18538 if (permissionsState.grantRuntimePermission(bp, userId) 18539 != PERMISSION_OPERATION_FAILURE) { 18540 writeRuntimePermissions = true; 18541 } 18542 // If permission review is enabled the permissions for a legacy apps 18543 // are represented as constantly granted runtime ones, so don't revoke. 18544 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18545 // Otherwise, reset the permission. 18546 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18547 switch (revokeResult) { 18548 case PERMISSION_OPERATION_SUCCESS: 18549 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18550 writeRuntimePermissions = true; 18551 final int appId = ps.appId; 18552 mHandler.post(new Runnable() { 18553 @Override 18554 public void run() { 18555 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18556 } 18557 }); 18558 } break; 18559 } 18560 } 18561 } 18562 18563 // Synchronously write as we are taking permissions away. 18564 if (writeRuntimePermissions) { 18565 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18566 } 18567 18568 // Synchronously write as we are taking permissions away. 18569 if (writeInstallPermissions) { 18570 mSettings.writeLPr(); 18571 } 18572 } 18573 18574 /** 18575 * Remove entries from the keystore daemon. Will only remove it if the 18576 * {@code appId} is valid. 18577 */ 18578 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18579 if (appId < 0) { 18580 return; 18581 } 18582 18583 final KeyStore keyStore = KeyStore.getInstance(); 18584 if (keyStore != null) { 18585 if (userId == UserHandle.USER_ALL) { 18586 for (final int individual : sUserManager.getUserIds()) { 18587 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18588 } 18589 } else { 18590 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18591 } 18592 } else { 18593 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18594 } 18595 } 18596 18597 @Override 18598 public void deleteApplicationCacheFiles(final String packageName, 18599 final IPackageDataObserver observer) { 18600 final int userId = UserHandle.getCallingUserId(); 18601 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18602 } 18603 18604 @Override 18605 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18606 final IPackageDataObserver observer) { 18607 mContext.enforceCallingOrSelfPermission( 18608 android.Manifest.permission.DELETE_CACHE_FILES, null); 18609 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18610 /* requireFullPermission= */ true, /* checkShell= */ false, 18611 "delete application cache files"); 18612 18613 final PackageParser.Package pkg; 18614 synchronized (mPackages) { 18615 pkg = mPackages.get(packageName); 18616 } 18617 18618 // Queue up an async operation since the package deletion may take a little while. 18619 mHandler.post(new Runnable() { 18620 public void run() { 18621 synchronized (mInstallLock) { 18622 final int flags = StorageManager.FLAG_STORAGE_DE 18623 | StorageManager.FLAG_STORAGE_CE; 18624 // We're only clearing cache files, so we don't care if the 18625 // app is unfrozen and still able to run 18626 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18627 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18628 } 18629 clearExternalStorageDataSync(packageName, userId, false); 18630 if (observer != null) { 18631 try { 18632 observer.onRemoveCompleted(packageName, true); 18633 } catch (RemoteException e) { 18634 Log.i(TAG, "Observer no longer exists."); 18635 } 18636 } 18637 } 18638 }); 18639 } 18640 18641 @Override 18642 public void getPackageSizeInfo(final String packageName, int userHandle, 18643 final IPackageStatsObserver observer) { 18644 throw new UnsupportedOperationException( 18645 "Shame on you for calling a hidden API. Shame!"); 18646 } 18647 18648 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18649 final PackageSetting ps; 18650 synchronized (mPackages) { 18651 ps = mSettings.mPackages.get(packageName); 18652 if (ps == null) { 18653 Slog.w(TAG, "Failed to find settings for " + packageName); 18654 return false; 18655 } 18656 } 18657 18658 final String[] packageNames = { packageName }; 18659 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18660 final String[] codePaths = { ps.codePathString }; 18661 18662 try { 18663 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18664 ps.appId, ceDataInodes, codePaths, stats); 18665 18666 // For now, ignore code size of packages on system partition 18667 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18668 stats.codeSize = 0; 18669 } 18670 18671 // External clients expect these to be tracked separately 18672 stats.dataSize -= stats.cacheSize; 18673 18674 } catch (InstallerException e) { 18675 Slog.w(TAG, String.valueOf(e)); 18676 return false; 18677 } 18678 18679 return true; 18680 } 18681 18682 private int getUidTargetSdkVersionLockedLPr(int uid) { 18683 Object obj = mSettings.getUserIdLPr(uid); 18684 if (obj instanceof SharedUserSetting) { 18685 final SharedUserSetting sus = (SharedUserSetting) obj; 18686 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18687 final Iterator<PackageSetting> it = sus.packages.iterator(); 18688 while (it.hasNext()) { 18689 final PackageSetting ps = it.next(); 18690 if (ps.pkg != null) { 18691 int v = ps.pkg.applicationInfo.targetSdkVersion; 18692 if (v < vers) vers = v; 18693 } 18694 } 18695 return vers; 18696 } else if (obj instanceof PackageSetting) { 18697 final PackageSetting ps = (PackageSetting) obj; 18698 if (ps.pkg != null) { 18699 return ps.pkg.applicationInfo.targetSdkVersion; 18700 } 18701 } 18702 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18703 } 18704 18705 @Override 18706 public void addPreferredActivity(IntentFilter filter, int match, 18707 ComponentName[] set, ComponentName activity, int userId) { 18708 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18709 "Adding preferred"); 18710 } 18711 18712 private void addPreferredActivityInternal(IntentFilter filter, int match, 18713 ComponentName[] set, ComponentName activity, boolean always, int userId, 18714 String opname) { 18715 // writer 18716 int callingUid = Binder.getCallingUid(); 18717 enforceCrossUserPermission(callingUid, userId, 18718 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18719 if (filter.countActions() == 0) { 18720 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18721 return; 18722 } 18723 synchronized (mPackages) { 18724 if (mContext.checkCallingOrSelfPermission( 18725 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18726 != PackageManager.PERMISSION_GRANTED) { 18727 if (getUidTargetSdkVersionLockedLPr(callingUid) 18728 < Build.VERSION_CODES.FROYO) { 18729 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18730 + callingUid); 18731 return; 18732 } 18733 mContext.enforceCallingOrSelfPermission( 18734 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18735 } 18736 18737 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18738 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18739 + userId + ":"); 18740 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18741 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18742 scheduleWritePackageRestrictionsLocked(userId); 18743 postPreferredActivityChangedBroadcast(userId); 18744 } 18745 } 18746 18747 private void postPreferredActivityChangedBroadcast(int userId) { 18748 mHandler.post(() -> { 18749 final IActivityManager am = ActivityManager.getService(); 18750 if (am == null) { 18751 return; 18752 } 18753 18754 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18755 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18756 try { 18757 am.broadcastIntent(null, intent, null, null, 18758 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18759 null, false, false, userId); 18760 } catch (RemoteException e) { 18761 } 18762 }); 18763 } 18764 18765 @Override 18766 public void replacePreferredActivity(IntentFilter filter, int match, 18767 ComponentName[] set, ComponentName activity, int userId) { 18768 if (filter.countActions() != 1) { 18769 throw new IllegalArgumentException( 18770 "replacePreferredActivity expects filter to have only 1 action."); 18771 } 18772 if (filter.countDataAuthorities() != 0 18773 || filter.countDataPaths() != 0 18774 || filter.countDataSchemes() > 1 18775 || filter.countDataTypes() != 0) { 18776 throw new IllegalArgumentException( 18777 "replacePreferredActivity expects filter to have no data authorities, " + 18778 "paths, or types; and at most one scheme."); 18779 } 18780 18781 final int callingUid = Binder.getCallingUid(); 18782 enforceCrossUserPermission(callingUid, userId, 18783 true /* requireFullPermission */, false /* checkShell */, 18784 "replace preferred activity"); 18785 synchronized (mPackages) { 18786 if (mContext.checkCallingOrSelfPermission( 18787 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18788 != PackageManager.PERMISSION_GRANTED) { 18789 if (getUidTargetSdkVersionLockedLPr(callingUid) 18790 < Build.VERSION_CODES.FROYO) { 18791 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18792 + Binder.getCallingUid()); 18793 return; 18794 } 18795 mContext.enforceCallingOrSelfPermission( 18796 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18797 } 18798 18799 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18800 if (pir != null) { 18801 // Get all of the existing entries that exactly match this filter. 18802 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18803 if (existing != null && existing.size() == 1) { 18804 PreferredActivity cur = existing.get(0); 18805 if (DEBUG_PREFERRED) { 18806 Slog.i(TAG, "Checking replace of preferred:"); 18807 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18808 if (!cur.mPref.mAlways) { 18809 Slog.i(TAG, " -- CUR; not mAlways!"); 18810 } else { 18811 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18812 Slog.i(TAG, " -- CUR: mSet=" 18813 + Arrays.toString(cur.mPref.mSetComponents)); 18814 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18815 Slog.i(TAG, " -- NEW: mMatch=" 18816 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18817 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18818 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18819 } 18820 } 18821 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18822 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18823 && cur.mPref.sameSet(set)) { 18824 // Setting the preferred activity to what it happens to be already 18825 if (DEBUG_PREFERRED) { 18826 Slog.i(TAG, "Replacing with same preferred activity " 18827 + cur.mPref.mShortComponent + " for user " 18828 + userId + ":"); 18829 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18830 } 18831 return; 18832 } 18833 } 18834 18835 if (existing != null) { 18836 if (DEBUG_PREFERRED) { 18837 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18838 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18839 } 18840 for (int i = 0; i < existing.size(); i++) { 18841 PreferredActivity pa = existing.get(i); 18842 if (DEBUG_PREFERRED) { 18843 Slog.i(TAG, "Removing existing preferred activity " 18844 + pa.mPref.mComponent + ":"); 18845 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18846 } 18847 pir.removeFilter(pa); 18848 } 18849 } 18850 } 18851 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18852 "Replacing preferred"); 18853 } 18854 } 18855 18856 @Override 18857 public void clearPackagePreferredActivities(String packageName) { 18858 final int uid = Binder.getCallingUid(); 18859 // writer 18860 synchronized (mPackages) { 18861 PackageParser.Package pkg = mPackages.get(packageName); 18862 if (pkg == null || pkg.applicationInfo.uid != uid) { 18863 if (mContext.checkCallingOrSelfPermission( 18864 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18865 != PackageManager.PERMISSION_GRANTED) { 18866 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18867 < Build.VERSION_CODES.FROYO) { 18868 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18869 + Binder.getCallingUid()); 18870 return; 18871 } 18872 mContext.enforceCallingOrSelfPermission( 18873 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18874 } 18875 } 18876 18877 int user = UserHandle.getCallingUserId(); 18878 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18879 scheduleWritePackageRestrictionsLocked(user); 18880 } 18881 } 18882 } 18883 18884 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18885 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18886 ArrayList<PreferredActivity> removed = null; 18887 boolean changed = false; 18888 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18889 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18890 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18891 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18892 continue; 18893 } 18894 Iterator<PreferredActivity> it = pir.filterIterator(); 18895 while (it.hasNext()) { 18896 PreferredActivity pa = it.next(); 18897 // Mark entry for removal only if it matches the package name 18898 // and the entry is of type "always". 18899 if (packageName == null || 18900 (pa.mPref.mComponent.getPackageName().equals(packageName) 18901 && pa.mPref.mAlways)) { 18902 if (removed == null) { 18903 removed = new ArrayList<PreferredActivity>(); 18904 } 18905 removed.add(pa); 18906 } 18907 } 18908 if (removed != null) { 18909 for (int j=0; j<removed.size(); j++) { 18910 PreferredActivity pa = removed.get(j); 18911 pir.removeFilter(pa); 18912 } 18913 changed = true; 18914 } 18915 } 18916 if (changed) { 18917 postPreferredActivityChangedBroadcast(userId); 18918 } 18919 return changed; 18920 } 18921 18922 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18923 private void clearIntentFilterVerificationsLPw(int userId) { 18924 final int packageCount = mPackages.size(); 18925 for (int i = 0; i < packageCount; i++) { 18926 PackageParser.Package pkg = mPackages.valueAt(i); 18927 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18928 } 18929 } 18930 18931 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18932 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18933 if (userId == UserHandle.USER_ALL) { 18934 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18935 sUserManager.getUserIds())) { 18936 for (int oneUserId : sUserManager.getUserIds()) { 18937 scheduleWritePackageRestrictionsLocked(oneUserId); 18938 } 18939 } 18940 } else { 18941 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18942 scheduleWritePackageRestrictionsLocked(userId); 18943 } 18944 } 18945 } 18946 18947 void clearDefaultBrowserIfNeeded(String packageName) { 18948 for (int oneUserId : sUserManager.getUserIds()) { 18949 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18950 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18951 if (packageName.equals(defaultBrowserPackageName)) { 18952 setDefaultBrowserPackageName(null, oneUserId); 18953 } 18954 } 18955 } 18956 18957 @Override 18958 public void resetApplicationPreferences(int userId) { 18959 mContext.enforceCallingOrSelfPermission( 18960 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18961 final long identity = Binder.clearCallingIdentity(); 18962 // writer 18963 try { 18964 synchronized (mPackages) { 18965 clearPackagePreferredActivitiesLPw(null, userId); 18966 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18967 // TODO: We have to reset the default SMS and Phone. This requires 18968 // significant refactoring to keep all default apps in the package 18969 // manager (cleaner but more work) or have the services provide 18970 // callbacks to the package manager to request a default app reset. 18971 applyFactoryDefaultBrowserLPw(userId); 18972 clearIntentFilterVerificationsLPw(userId); 18973 primeDomainVerificationsLPw(userId); 18974 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18975 scheduleWritePackageRestrictionsLocked(userId); 18976 } 18977 resetNetworkPolicies(userId); 18978 } finally { 18979 Binder.restoreCallingIdentity(identity); 18980 } 18981 } 18982 18983 @Override 18984 public int getPreferredActivities(List<IntentFilter> outFilters, 18985 List<ComponentName> outActivities, String packageName) { 18986 18987 int num = 0; 18988 final int userId = UserHandle.getCallingUserId(); 18989 // reader 18990 synchronized (mPackages) { 18991 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18992 if (pir != null) { 18993 final Iterator<PreferredActivity> it = pir.filterIterator(); 18994 while (it.hasNext()) { 18995 final PreferredActivity pa = it.next(); 18996 if (packageName == null 18997 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18998 && pa.mPref.mAlways)) { 18999 if (outFilters != null) { 19000 outFilters.add(new IntentFilter(pa)); 19001 } 19002 if (outActivities != null) { 19003 outActivities.add(pa.mPref.mComponent); 19004 } 19005 } 19006 } 19007 } 19008 } 19009 19010 return num; 19011 } 19012 19013 @Override 19014 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19015 int userId) { 19016 int callingUid = Binder.getCallingUid(); 19017 if (callingUid != Process.SYSTEM_UID) { 19018 throw new SecurityException( 19019 "addPersistentPreferredActivity can only be run by the system"); 19020 } 19021 if (filter.countActions() == 0) { 19022 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19023 return; 19024 } 19025 synchronized (mPackages) { 19026 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19027 ":"); 19028 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19029 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19030 new PersistentPreferredActivity(filter, activity)); 19031 scheduleWritePackageRestrictionsLocked(userId); 19032 postPreferredActivityChangedBroadcast(userId); 19033 } 19034 } 19035 19036 @Override 19037 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19038 int callingUid = Binder.getCallingUid(); 19039 if (callingUid != Process.SYSTEM_UID) { 19040 throw new SecurityException( 19041 "clearPackagePersistentPreferredActivities can only be run by the system"); 19042 } 19043 ArrayList<PersistentPreferredActivity> removed = null; 19044 boolean changed = false; 19045 synchronized (mPackages) { 19046 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19047 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19048 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19049 .valueAt(i); 19050 if (userId != thisUserId) { 19051 continue; 19052 } 19053 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19054 while (it.hasNext()) { 19055 PersistentPreferredActivity ppa = it.next(); 19056 // Mark entry for removal only if it matches the package name. 19057 if (ppa.mComponent.getPackageName().equals(packageName)) { 19058 if (removed == null) { 19059 removed = new ArrayList<PersistentPreferredActivity>(); 19060 } 19061 removed.add(ppa); 19062 } 19063 } 19064 if (removed != null) { 19065 for (int j=0; j<removed.size(); j++) { 19066 PersistentPreferredActivity ppa = removed.get(j); 19067 ppir.removeFilter(ppa); 19068 } 19069 changed = true; 19070 } 19071 } 19072 19073 if (changed) { 19074 scheduleWritePackageRestrictionsLocked(userId); 19075 postPreferredActivityChangedBroadcast(userId); 19076 } 19077 } 19078 } 19079 19080 /** 19081 * Common machinery for picking apart a restored XML blob and passing 19082 * it to a caller-supplied functor to be applied to the running system. 19083 */ 19084 private void restoreFromXml(XmlPullParser parser, int userId, 19085 String expectedStartTag, BlobXmlRestorer functor) 19086 throws IOException, XmlPullParserException { 19087 int type; 19088 while ((type = parser.next()) != XmlPullParser.START_TAG 19089 && type != XmlPullParser.END_DOCUMENT) { 19090 } 19091 if (type != XmlPullParser.START_TAG) { 19092 // oops didn't find a start tag?! 19093 if (DEBUG_BACKUP) { 19094 Slog.e(TAG, "Didn't find start tag during restore"); 19095 } 19096 return; 19097 } 19098Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19099 // this is supposed to be TAG_PREFERRED_BACKUP 19100 if (!expectedStartTag.equals(parser.getName())) { 19101 if (DEBUG_BACKUP) { 19102 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19103 } 19104 return; 19105 } 19106 19107 // skip interfering stuff, then we're aligned with the backing implementation 19108 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19109Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19110 functor.apply(parser, userId); 19111 } 19112 19113 private interface BlobXmlRestorer { 19114 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19115 } 19116 19117 /** 19118 * Non-Binder method, support for the backup/restore mechanism: write the 19119 * full set of preferred activities in its canonical XML format. Returns the 19120 * XML output as a byte array, or null if there is none. 19121 */ 19122 @Override 19123 public byte[] getPreferredActivityBackup(int userId) { 19124 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19125 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19126 } 19127 19128 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19129 try { 19130 final XmlSerializer serializer = new FastXmlSerializer(); 19131 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19132 serializer.startDocument(null, true); 19133 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19134 19135 synchronized (mPackages) { 19136 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19137 } 19138 19139 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19140 serializer.endDocument(); 19141 serializer.flush(); 19142 } catch (Exception e) { 19143 if (DEBUG_BACKUP) { 19144 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19145 } 19146 return null; 19147 } 19148 19149 return dataStream.toByteArray(); 19150 } 19151 19152 @Override 19153 public void restorePreferredActivities(byte[] backup, int userId) { 19154 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19155 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19156 } 19157 19158 try { 19159 final XmlPullParser parser = Xml.newPullParser(); 19160 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19161 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19162 new BlobXmlRestorer() { 19163 @Override 19164 public void apply(XmlPullParser parser, int userId) 19165 throws XmlPullParserException, IOException { 19166 synchronized (mPackages) { 19167 mSettings.readPreferredActivitiesLPw(parser, userId); 19168 } 19169 } 19170 } ); 19171 } catch (Exception e) { 19172 if (DEBUG_BACKUP) { 19173 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19174 } 19175 } 19176 } 19177 19178 /** 19179 * Non-Binder method, support for the backup/restore mechanism: write the 19180 * default browser (etc) settings in its canonical XML format. Returns the default 19181 * browser XML representation as a byte array, or null if there is none. 19182 */ 19183 @Override 19184 public byte[] getDefaultAppsBackup(int userId) { 19185 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19186 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19187 } 19188 19189 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19190 try { 19191 final XmlSerializer serializer = new FastXmlSerializer(); 19192 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19193 serializer.startDocument(null, true); 19194 serializer.startTag(null, TAG_DEFAULT_APPS); 19195 19196 synchronized (mPackages) { 19197 mSettings.writeDefaultAppsLPr(serializer, userId); 19198 } 19199 19200 serializer.endTag(null, TAG_DEFAULT_APPS); 19201 serializer.endDocument(); 19202 serializer.flush(); 19203 } catch (Exception e) { 19204 if (DEBUG_BACKUP) { 19205 Slog.e(TAG, "Unable to write default apps for backup", e); 19206 } 19207 return null; 19208 } 19209 19210 return dataStream.toByteArray(); 19211 } 19212 19213 @Override 19214 public void restoreDefaultApps(byte[] backup, int userId) { 19215 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19216 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19217 } 19218 19219 try { 19220 final XmlPullParser parser = Xml.newPullParser(); 19221 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19222 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19223 new BlobXmlRestorer() { 19224 @Override 19225 public void apply(XmlPullParser parser, int userId) 19226 throws XmlPullParserException, IOException { 19227 synchronized (mPackages) { 19228 mSettings.readDefaultAppsLPw(parser, userId); 19229 } 19230 } 19231 } ); 19232 } catch (Exception e) { 19233 if (DEBUG_BACKUP) { 19234 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19235 } 19236 } 19237 } 19238 19239 @Override 19240 public byte[] getIntentFilterVerificationBackup(int userId) { 19241 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19242 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19243 } 19244 19245 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19246 try { 19247 final XmlSerializer serializer = new FastXmlSerializer(); 19248 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19249 serializer.startDocument(null, true); 19250 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19251 19252 synchronized (mPackages) { 19253 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19254 } 19255 19256 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19257 serializer.endDocument(); 19258 serializer.flush(); 19259 } catch (Exception e) { 19260 if (DEBUG_BACKUP) { 19261 Slog.e(TAG, "Unable to write default apps for backup", e); 19262 } 19263 return null; 19264 } 19265 19266 return dataStream.toByteArray(); 19267 } 19268 19269 @Override 19270 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19271 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19272 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19273 } 19274 19275 try { 19276 final XmlPullParser parser = Xml.newPullParser(); 19277 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19278 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19279 new BlobXmlRestorer() { 19280 @Override 19281 public void apply(XmlPullParser parser, int userId) 19282 throws XmlPullParserException, IOException { 19283 synchronized (mPackages) { 19284 mSettings.readAllDomainVerificationsLPr(parser, userId); 19285 mSettings.writeLPr(); 19286 } 19287 } 19288 } ); 19289 } catch (Exception e) { 19290 if (DEBUG_BACKUP) { 19291 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19292 } 19293 } 19294 } 19295 19296 @Override 19297 public byte[] getPermissionGrantBackup(int userId) { 19298 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19299 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19300 } 19301 19302 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19303 try { 19304 final XmlSerializer serializer = new FastXmlSerializer(); 19305 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19306 serializer.startDocument(null, true); 19307 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19308 19309 synchronized (mPackages) { 19310 serializeRuntimePermissionGrantsLPr(serializer, userId); 19311 } 19312 19313 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19314 serializer.endDocument(); 19315 serializer.flush(); 19316 } catch (Exception e) { 19317 if (DEBUG_BACKUP) { 19318 Slog.e(TAG, "Unable to write default apps for backup", e); 19319 } 19320 return null; 19321 } 19322 19323 return dataStream.toByteArray(); 19324 } 19325 19326 @Override 19327 public void restorePermissionGrants(byte[] backup, int userId) { 19328 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19329 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19330 } 19331 19332 try { 19333 final XmlPullParser parser = Xml.newPullParser(); 19334 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19335 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19336 new BlobXmlRestorer() { 19337 @Override 19338 public void apply(XmlPullParser parser, int userId) 19339 throws XmlPullParserException, IOException { 19340 synchronized (mPackages) { 19341 processRestoredPermissionGrantsLPr(parser, userId); 19342 } 19343 } 19344 } ); 19345 } catch (Exception e) { 19346 if (DEBUG_BACKUP) { 19347 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19348 } 19349 } 19350 } 19351 19352 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19353 throws IOException { 19354 serializer.startTag(null, TAG_ALL_GRANTS); 19355 19356 final int N = mSettings.mPackages.size(); 19357 for (int i = 0; i < N; i++) { 19358 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19359 boolean pkgGrantsKnown = false; 19360 19361 PermissionsState packagePerms = ps.getPermissionsState(); 19362 19363 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19364 final int grantFlags = state.getFlags(); 19365 // only look at grants that are not system/policy fixed 19366 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19367 final boolean isGranted = state.isGranted(); 19368 // And only back up the user-twiddled state bits 19369 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19370 final String packageName = mSettings.mPackages.keyAt(i); 19371 if (!pkgGrantsKnown) { 19372 serializer.startTag(null, TAG_GRANT); 19373 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19374 pkgGrantsKnown = true; 19375 } 19376 19377 final boolean userSet = 19378 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19379 final boolean userFixed = 19380 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19381 final boolean revoke = 19382 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19383 19384 serializer.startTag(null, TAG_PERMISSION); 19385 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19386 if (isGranted) { 19387 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19388 } 19389 if (userSet) { 19390 serializer.attribute(null, ATTR_USER_SET, "true"); 19391 } 19392 if (userFixed) { 19393 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19394 } 19395 if (revoke) { 19396 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19397 } 19398 serializer.endTag(null, TAG_PERMISSION); 19399 } 19400 } 19401 } 19402 19403 if (pkgGrantsKnown) { 19404 serializer.endTag(null, TAG_GRANT); 19405 } 19406 } 19407 19408 serializer.endTag(null, TAG_ALL_GRANTS); 19409 } 19410 19411 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19412 throws XmlPullParserException, IOException { 19413 String pkgName = null; 19414 int outerDepth = parser.getDepth(); 19415 int type; 19416 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19417 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19418 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19419 continue; 19420 } 19421 19422 final String tagName = parser.getName(); 19423 if (tagName.equals(TAG_GRANT)) { 19424 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19425 if (DEBUG_BACKUP) { 19426 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19427 } 19428 } else if (tagName.equals(TAG_PERMISSION)) { 19429 19430 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19431 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19432 19433 int newFlagSet = 0; 19434 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19435 newFlagSet |= FLAG_PERMISSION_USER_SET; 19436 } 19437 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19438 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19439 } 19440 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19441 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19442 } 19443 if (DEBUG_BACKUP) { 19444 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19445 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19446 } 19447 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19448 if (ps != null) { 19449 // Already installed so we apply the grant immediately 19450 if (DEBUG_BACKUP) { 19451 Slog.v(TAG, " + already installed; applying"); 19452 } 19453 PermissionsState perms = ps.getPermissionsState(); 19454 BasePermission bp = mSettings.mPermissions.get(permName); 19455 if (bp != null) { 19456 if (isGranted) { 19457 perms.grantRuntimePermission(bp, userId); 19458 } 19459 if (newFlagSet != 0) { 19460 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19461 } 19462 } 19463 } else { 19464 // Need to wait for post-restore install to apply the grant 19465 if (DEBUG_BACKUP) { 19466 Slog.v(TAG, " - not yet installed; saving for later"); 19467 } 19468 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19469 isGranted, newFlagSet, userId); 19470 } 19471 } else { 19472 PackageManagerService.reportSettingsProblem(Log.WARN, 19473 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19474 XmlUtils.skipCurrentTag(parser); 19475 } 19476 } 19477 19478 scheduleWriteSettingsLocked(); 19479 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19480 } 19481 19482 @Override 19483 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19484 int sourceUserId, int targetUserId, int flags) { 19485 mContext.enforceCallingOrSelfPermission( 19486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19487 int callingUid = Binder.getCallingUid(); 19488 enforceOwnerRights(ownerPackage, callingUid); 19489 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19490 if (intentFilter.countActions() == 0) { 19491 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19492 return; 19493 } 19494 synchronized (mPackages) { 19495 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19496 ownerPackage, targetUserId, flags); 19497 CrossProfileIntentResolver resolver = 19498 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19499 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19500 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19501 if (existing != null) { 19502 int size = existing.size(); 19503 for (int i = 0; i < size; i++) { 19504 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19505 return; 19506 } 19507 } 19508 } 19509 resolver.addFilter(newFilter); 19510 scheduleWritePackageRestrictionsLocked(sourceUserId); 19511 } 19512 } 19513 19514 @Override 19515 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19516 mContext.enforceCallingOrSelfPermission( 19517 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19518 int callingUid = Binder.getCallingUid(); 19519 enforceOwnerRights(ownerPackage, callingUid); 19520 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19521 synchronized (mPackages) { 19522 CrossProfileIntentResolver resolver = 19523 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19524 ArraySet<CrossProfileIntentFilter> set = 19525 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19526 for (CrossProfileIntentFilter filter : set) { 19527 if (filter.getOwnerPackage().equals(ownerPackage)) { 19528 resolver.removeFilter(filter); 19529 } 19530 } 19531 scheduleWritePackageRestrictionsLocked(sourceUserId); 19532 } 19533 } 19534 19535 // Enforcing that callingUid is owning pkg on userId 19536 private void enforceOwnerRights(String pkg, int callingUid) { 19537 // The system owns everything. 19538 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19539 return; 19540 } 19541 int callingUserId = UserHandle.getUserId(callingUid); 19542 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19543 if (pi == null) { 19544 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19545 + callingUserId); 19546 } 19547 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19548 throw new SecurityException("Calling uid " + callingUid 19549 + " does not own package " + pkg); 19550 } 19551 } 19552 19553 @Override 19554 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19555 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19556 } 19557 19558 /** 19559 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19560 * then reports the most likely home activity or null if there are more than one. 19561 */ 19562 public ComponentName getDefaultHomeActivity(int userId) { 19563 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19564 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19565 if (cn != null) { 19566 return cn; 19567 } 19568 19569 // Find the launcher with the highest priority and return that component if there are no 19570 // other home activity with the same priority. 19571 int lastPriority = Integer.MIN_VALUE; 19572 ComponentName lastComponent = null; 19573 final int size = allHomeCandidates.size(); 19574 for (int i = 0; i < size; i++) { 19575 final ResolveInfo ri = allHomeCandidates.get(i); 19576 if (ri.priority > lastPriority) { 19577 lastComponent = ri.activityInfo.getComponentName(); 19578 lastPriority = ri.priority; 19579 } else if (ri.priority == lastPriority) { 19580 // Two components found with same priority. 19581 lastComponent = null; 19582 } 19583 } 19584 return lastComponent; 19585 } 19586 19587 private Intent getHomeIntent() { 19588 Intent intent = new Intent(Intent.ACTION_MAIN); 19589 intent.addCategory(Intent.CATEGORY_HOME); 19590 intent.addCategory(Intent.CATEGORY_DEFAULT); 19591 return intent; 19592 } 19593 19594 private IntentFilter getHomeFilter() { 19595 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19596 filter.addCategory(Intent.CATEGORY_HOME); 19597 filter.addCategory(Intent.CATEGORY_DEFAULT); 19598 return filter; 19599 } 19600 19601 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19602 int userId) { 19603 Intent intent = getHomeIntent(); 19604 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19605 PackageManager.GET_META_DATA, userId); 19606 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19607 true, false, false, userId); 19608 19609 allHomeCandidates.clear(); 19610 if (list != null) { 19611 for (ResolveInfo ri : list) { 19612 allHomeCandidates.add(ri); 19613 } 19614 } 19615 return (preferred == null || preferred.activityInfo == null) 19616 ? null 19617 : new ComponentName(preferred.activityInfo.packageName, 19618 preferred.activityInfo.name); 19619 } 19620 19621 @Override 19622 public void setHomeActivity(ComponentName comp, int userId) { 19623 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19624 getHomeActivitiesAsUser(homeActivities, userId); 19625 19626 boolean found = false; 19627 19628 final int size = homeActivities.size(); 19629 final ComponentName[] set = new ComponentName[size]; 19630 for (int i = 0; i < size; i++) { 19631 final ResolveInfo candidate = homeActivities.get(i); 19632 final ActivityInfo info = candidate.activityInfo; 19633 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19634 set[i] = activityName; 19635 if (!found && activityName.equals(comp)) { 19636 found = true; 19637 } 19638 } 19639 if (!found) { 19640 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19641 + userId); 19642 } 19643 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19644 set, comp, userId); 19645 } 19646 19647 private @Nullable String getSetupWizardPackageName() { 19648 final Intent intent = new Intent(Intent.ACTION_MAIN); 19649 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19650 19651 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19652 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19653 | MATCH_DISABLED_COMPONENTS, 19654 UserHandle.myUserId()); 19655 if (matches.size() == 1) { 19656 return matches.get(0).getComponentInfo().packageName; 19657 } else { 19658 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19659 + ": matches=" + matches); 19660 return null; 19661 } 19662 } 19663 19664 private @Nullable String getStorageManagerPackageName() { 19665 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19666 19667 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19668 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19669 | MATCH_DISABLED_COMPONENTS, 19670 UserHandle.myUserId()); 19671 if (matches.size() == 1) { 19672 return matches.get(0).getComponentInfo().packageName; 19673 } else { 19674 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19675 + matches.size() + ": matches=" + matches); 19676 return null; 19677 } 19678 } 19679 19680 @Override 19681 public void setApplicationEnabledSetting(String appPackageName, 19682 int newState, int flags, int userId, String callingPackage) { 19683 if (!sUserManager.exists(userId)) return; 19684 if (callingPackage == null) { 19685 callingPackage = Integer.toString(Binder.getCallingUid()); 19686 } 19687 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19688 } 19689 19690 @Override 19691 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19692 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19693 synchronized (mPackages) { 19694 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19695 if (pkgSetting != null) { 19696 pkgSetting.setUpdateAvailable(updateAvailable); 19697 } 19698 } 19699 } 19700 19701 @Override 19702 public void setComponentEnabledSetting(ComponentName componentName, 19703 int newState, int flags, int userId) { 19704 if (!sUserManager.exists(userId)) return; 19705 setEnabledSetting(componentName.getPackageName(), 19706 componentName.getClassName(), newState, flags, userId, null); 19707 } 19708 19709 private void setEnabledSetting(final String packageName, String className, int newState, 19710 final int flags, int userId, String callingPackage) { 19711 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19712 || newState == COMPONENT_ENABLED_STATE_ENABLED 19713 || newState == COMPONENT_ENABLED_STATE_DISABLED 19714 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19715 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19716 throw new IllegalArgumentException("Invalid new component state: " 19717 + newState); 19718 } 19719 PackageSetting pkgSetting; 19720 final int uid = Binder.getCallingUid(); 19721 final int permission; 19722 if (uid == Process.SYSTEM_UID) { 19723 permission = PackageManager.PERMISSION_GRANTED; 19724 } else { 19725 permission = mContext.checkCallingOrSelfPermission( 19726 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19727 } 19728 enforceCrossUserPermission(uid, userId, 19729 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19730 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19731 boolean sendNow = false; 19732 boolean isApp = (className == null); 19733 String componentName = isApp ? packageName : className; 19734 int packageUid = -1; 19735 ArrayList<String> components; 19736 19737 // writer 19738 synchronized (mPackages) { 19739 pkgSetting = mSettings.mPackages.get(packageName); 19740 if (pkgSetting == null) { 19741 if (className == null) { 19742 throw new IllegalArgumentException("Unknown package: " + packageName); 19743 } 19744 throw new IllegalArgumentException( 19745 "Unknown component: " + packageName + "/" + className); 19746 } 19747 } 19748 19749 // Limit who can change which apps 19750 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19751 // Don't allow apps that don't have permission to modify other apps 19752 if (!allowedByPermission) { 19753 throw new SecurityException( 19754 "Permission Denial: attempt to change component state from pid=" 19755 + Binder.getCallingPid() 19756 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19757 } 19758 // Don't allow changing protected packages. 19759 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19760 throw new SecurityException("Cannot disable a protected package: " + packageName); 19761 } 19762 } 19763 19764 synchronized (mPackages) { 19765 if (uid == Process.SHELL_UID 19766 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19767 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19768 // unless it is a test package. 19769 int oldState = pkgSetting.getEnabled(userId); 19770 if (className == null 19771 && 19772 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19773 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19774 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19775 && 19776 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19777 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19778 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19779 // ok 19780 } else { 19781 throw new SecurityException( 19782 "Shell cannot change component state for " + packageName + "/" 19783 + className + " to " + newState); 19784 } 19785 } 19786 if (className == null) { 19787 // We're dealing with an application/package level state change 19788 if (pkgSetting.getEnabled(userId) == newState) { 19789 // Nothing to do 19790 return; 19791 } 19792 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19793 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19794 // Don't care about who enables an app. 19795 callingPackage = null; 19796 } 19797 pkgSetting.setEnabled(newState, userId, callingPackage); 19798 // pkgSetting.pkg.mSetEnabled = newState; 19799 } else { 19800 // We're dealing with a component level state change 19801 // First, verify that this is a valid class name. 19802 PackageParser.Package pkg = pkgSetting.pkg; 19803 if (pkg == null || !pkg.hasComponentClassName(className)) { 19804 if (pkg != null && 19805 pkg.applicationInfo.targetSdkVersion >= 19806 Build.VERSION_CODES.JELLY_BEAN) { 19807 throw new IllegalArgumentException("Component class " + className 19808 + " does not exist in " + packageName); 19809 } else { 19810 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19811 + className + " does not exist in " + packageName); 19812 } 19813 } 19814 switch (newState) { 19815 case COMPONENT_ENABLED_STATE_ENABLED: 19816 if (!pkgSetting.enableComponentLPw(className, userId)) { 19817 return; 19818 } 19819 break; 19820 case COMPONENT_ENABLED_STATE_DISABLED: 19821 if (!pkgSetting.disableComponentLPw(className, userId)) { 19822 return; 19823 } 19824 break; 19825 case COMPONENT_ENABLED_STATE_DEFAULT: 19826 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19827 return; 19828 } 19829 break; 19830 default: 19831 Slog.e(TAG, "Invalid new component state: " + newState); 19832 return; 19833 } 19834 } 19835 scheduleWritePackageRestrictionsLocked(userId); 19836 updateSequenceNumberLP(packageName, new int[] { userId }); 19837 components = mPendingBroadcasts.get(userId, packageName); 19838 final boolean newPackage = components == null; 19839 if (newPackage) { 19840 components = new ArrayList<String>(); 19841 } 19842 if (!components.contains(componentName)) { 19843 components.add(componentName); 19844 } 19845 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19846 sendNow = true; 19847 // Purge entry from pending broadcast list if another one exists already 19848 // since we are sending one right away. 19849 mPendingBroadcasts.remove(userId, packageName); 19850 } else { 19851 if (newPackage) { 19852 mPendingBroadcasts.put(userId, packageName, components); 19853 } 19854 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19855 // Schedule a message 19856 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19857 } 19858 } 19859 } 19860 19861 long callingId = Binder.clearCallingIdentity(); 19862 try { 19863 if (sendNow) { 19864 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19865 sendPackageChangedBroadcast(packageName, 19866 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19867 } 19868 } finally { 19869 Binder.restoreCallingIdentity(callingId); 19870 } 19871 } 19872 19873 @Override 19874 public void flushPackageRestrictionsAsUser(int userId) { 19875 if (!sUserManager.exists(userId)) { 19876 return; 19877 } 19878 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19879 false /* checkShell */, "flushPackageRestrictions"); 19880 synchronized (mPackages) { 19881 mSettings.writePackageRestrictionsLPr(userId); 19882 mDirtyUsers.remove(userId); 19883 if (mDirtyUsers.isEmpty()) { 19884 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19885 } 19886 } 19887 } 19888 19889 private void sendPackageChangedBroadcast(String packageName, 19890 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19891 if (DEBUG_INSTALL) 19892 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19893 + componentNames); 19894 Bundle extras = new Bundle(4); 19895 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19896 String nameList[] = new String[componentNames.size()]; 19897 componentNames.toArray(nameList); 19898 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19899 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19900 extras.putInt(Intent.EXTRA_UID, packageUid); 19901 // If this is not reporting a change of the overall package, then only send it 19902 // to registered receivers. We don't want to launch a swath of apps for every 19903 // little component state change. 19904 final int flags = !componentNames.contains(packageName) 19905 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19906 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19907 new int[] {UserHandle.getUserId(packageUid)}); 19908 } 19909 19910 @Override 19911 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19912 if (!sUserManager.exists(userId)) return; 19913 final int uid = Binder.getCallingUid(); 19914 final int permission = mContext.checkCallingOrSelfPermission( 19915 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19916 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19917 enforceCrossUserPermission(uid, userId, 19918 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19919 // writer 19920 synchronized (mPackages) { 19921 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19922 allowedByPermission, uid, userId)) { 19923 scheduleWritePackageRestrictionsLocked(userId); 19924 } 19925 } 19926 } 19927 19928 @Override 19929 public String getInstallerPackageName(String packageName) { 19930 // reader 19931 synchronized (mPackages) { 19932 return mSettings.getInstallerPackageNameLPr(packageName); 19933 } 19934 } 19935 19936 public boolean isOrphaned(String packageName) { 19937 // reader 19938 synchronized (mPackages) { 19939 return mSettings.isOrphaned(packageName); 19940 } 19941 } 19942 19943 @Override 19944 public int getApplicationEnabledSetting(String packageName, int userId) { 19945 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19946 int uid = Binder.getCallingUid(); 19947 enforceCrossUserPermission(uid, userId, 19948 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19949 // reader 19950 synchronized (mPackages) { 19951 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19952 } 19953 } 19954 19955 @Override 19956 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19957 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19958 int uid = Binder.getCallingUid(); 19959 enforceCrossUserPermission(uid, userId, 19960 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19961 // reader 19962 synchronized (mPackages) { 19963 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19964 } 19965 } 19966 19967 @Override 19968 public void enterSafeMode() { 19969 enforceSystemOrRoot("Only the system can request entering safe mode"); 19970 19971 if (!mSystemReady) { 19972 mSafeMode = true; 19973 } 19974 } 19975 19976 @Override 19977 public void systemReady() { 19978 mSystemReady = true; 19979 19980 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19981 // disabled after already being started. 19982 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19983 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19984 19985 // Read the compatibilty setting when the system is ready. 19986 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19987 mContext.getContentResolver(), 19988 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19989 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19990 if (DEBUG_SETTINGS) { 19991 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19992 } 19993 19994 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19995 19996 synchronized (mPackages) { 19997 // Verify that all of the preferred activity components actually 19998 // exist. It is possible for applications to be updated and at 19999 // that point remove a previously declared activity component that 20000 // had been set as a preferred activity. We try to clean this up 20001 // the next time we encounter that preferred activity, but it is 20002 // possible for the user flow to never be able to return to that 20003 // situation so here we do a sanity check to make sure we haven't 20004 // left any junk around. 20005 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20006 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20007 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20008 removed.clear(); 20009 for (PreferredActivity pa : pir.filterSet()) { 20010 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20011 removed.add(pa); 20012 } 20013 } 20014 if (removed.size() > 0) { 20015 for (int r=0; r<removed.size(); r++) { 20016 PreferredActivity pa = removed.get(r); 20017 Slog.w(TAG, "Removing dangling preferred activity: " 20018 + pa.mPref.mComponent); 20019 pir.removeFilter(pa); 20020 } 20021 mSettings.writePackageRestrictionsLPr( 20022 mSettings.mPreferredActivities.keyAt(i)); 20023 } 20024 } 20025 20026 for (int userId : UserManagerService.getInstance().getUserIds()) { 20027 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20028 grantPermissionsUserIds = ArrayUtils.appendInt( 20029 grantPermissionsUserIds, userId); 20030 } 20031 } 20032 } 20033 sUserManager.systemReady(); 20034 20035 // If we upgraded grant all default permissions before kicking off. 20036 for (int userId : grantPermissionsUserIds) { 20037 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20038 } 20039 20040 // If we did not grant default permissions, we preload from this the 20041 // default permission exceptions lazily to ensure we don't hit the 20042 // disk on a new user creation. 20043 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20044 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20045 } 20046 20047 // Kick off any messages waiting for system ready 20048 if (mPostSystemReadyMessages != null) { 20049 for (Message msg : mPostSystemReadyMessages) { 20050 msg.sendToTarget(); 20051 } 20052 mPostSystemReadyMessages = null; 20053 } 20054 20055 // Watch for external volumes that come and go over time 20056 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20057 storage.registerListener(mStorageListener); 20058 20059 mInstallerService.systemReady(); 20060 mPackageDexOptimizer.systemReady(); 20061 20062 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20063 StorageManagerInternal.class); 20064 StorageManagerInternal.addExternalStoragePolicy( 20065 new StorageManagerInternal.ExternalStorageMountPolicy() { 20066 @Override 20067 public int getMountMode(int uid, String packageName) { 20068 if (Process.isIsolated(uid)) { 20069 return Zygote.MOUNT_EXTERNAL_NONE; 20070 } 20071 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20072 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20073 } 20074 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20075 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20076 } 20077 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20078 return Zygote.MOUNT_EXTERNAL_READ; 20079 } 20080 return Zygote.MOUNT_EXTERNAL_WRITE; 20081 } 20082 20083 @Override 20084 public boolean hasExternalStorage(int uid, String packageName) { 20085 return true; 20086 } 20087 }); 20088 20089 // Now that we're mostly running, clean up stale users and apps 20090 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20091 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20092 20093 if (mPrivappPermissionsViolations != null) { 20094 Slog.wtf(TAG,"Signature|privileged permissions not in " 20095 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20096 mPrivappPermissionsViolations = null; 20097 } 20098 } 20099 20100 public void waitForAppDataPrepared() { 20101 if (mPrepareAppDataFuture == null) { 20102 return; 20103 } 20104 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20105 mPrepareAppDataFuture = null; 20106 } 20107 20108 @Override 20109 public boolean isSafeMode() { 20110 return mSafeMode; 20111 } 20112 20113 @Override 20114 public boolean hasSystemUidErrors() { 20115 return mHasSystemUidErrors; 20116 } 20117 20118 static String arrayToString(int[] array) { 20119 StringBuffer buf = new StringBuffer(128); 20120 buf.append('['); 20121 if (array != null) { 20122 for (int i=0; i<array.length; i++) { 20123 if (i > 0) buf.append(", "); 20124 buf.append(array[i]); 20125 } 20126 } 20127 buf.append(']'); 20128 return buf.toString(); 20129 } 20130 20131 static class DumpState { 20132 public static final int DUMP_LIBS = 1 << 0; 20133 public static final int DUMP_FEATURES = 1 << 1; 20134 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20135 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20136 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20137 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20138 public static final int DUMP_PERMISSIONS = 1 << 6; 20139 public static final int DUMP_PACKAGES = 1 << 7; 20140 public static final int DUMP_SHARED_USERS = 1 << 8; 20141 public static final int DUMP_MESSAGES = 1 << 9; 20142 public static final int DUMP_PROVIDERS = 1 << 10; 20143 public static final int DUMP_VERIFIERS = 1 << 11; 20144 public static final int DUMP_PREFERRED = 1 << 12; 20145 public static final int DUMP_PREFERRED_XML = 1 << 13; 20146 public static final int DUMP_KEYSETS = 1 << 14; 20147 public static final int DUMP_VERSION = 1 << 15; 20148 public static final int DUMP_INSTALLS = 1 << 16; 20149 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20150 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20151 public static final int DUMP_FROZEN = 1 << 19; 20152 public static final int DUMP_DEXOPT = 1 << 20; 20153 public static final int DUMP_COMPILER_STATS = 1 << 21; 20154 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20155 20156 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20157 20158 private int mTypes; 20159 20160 private int mOptions; 20161 20162 private boolean mTitlePrinted; 20163 20164 private SharedUserSetting mSharedUser; 20165 20166 public boolean isDumping(int type) { 20167 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20168 return true; 20169 } 20170 20171 return (mTypes & type) != 0; 20172 } 20173 20174 public void setDump(int type) { 20175 mTypes |= type; 20176 } 20177 20178 public boolean isOptionEnabled(int option) { 20179 return (mOptions & option) != 0; 20180 } 20181 20182 public void setOptionEnabled(int option) { 20183 mOptions |= option; 20184 } 20185 20186 public boolean onTitlePrinted() { 20187 final boolean printed = mTitlePrinted; 20188 mTitlePrinted = true; 20189 return printed; 20190 } 20191 20192 public boolean getTitlePrinted() { 20193 return mTitlePrinted; 20194 } 20195 20196 public void setTitlePrinted(boolean enabled) { 20197 mTitlePrinted = enabled; 20198 } 20199 20200 public SharedUserSetting getSharedUser() { 20201 return mSharedUser; 20202 } 20203 20204 public void setSharedUser(SharedUserSetting user) { 20205 mSharedUser = user; 20206 } 20207 } 20208 20209 @Override 20210 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20211 FileDescriptor err, String[] args, ShellCallback callback, 20212 ResultReceiver resultReceiver) { 20213 (new PackageManagerShellCommand(this)).exec( 20214 this, in, out, err, args, callback, resultReceiver); 20215 } 20216 20217 @Override 20218 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20219 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20220 != PackageManager.PERMISSION_GRANTED) { 20221 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20222 + Binder.getCallingPid() 20223 + ", uid=" + Binder.getCallingUid() 20224 + " without permission " 20225 + android.Manifest.permission.DUMP); 20226 return; 20227 } 20228 20229 DumpState dumpState = new DumpState(); 20230 boolean fullPreferred = false; 20231 boolean checkin = false; 20232 20233 String packageName = null; 20234 ArraySet<String> permissionNames = null; 20235 20236 int opti = 0; 20237 while (opti < args.length) { 20238 String opt = args[opti]; 20239 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20240 break; 20241 } 20242 opti++; 20243 20244 if ("-a".equals(opt)) { 20245 // Right now we only know how to print all. 20246 } else if ("-h".equals(opt)) { 20247 pw.println("Package manager dump options:"); 20248 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20249 pw.println(" --checkin: dump for a checkin"); 20250 pw.println(" -f: print details of intent filters"); 20251 pw.println(" -h: print this help"); 20252 pw.println(" cmd may be one of:"); 20253 pw.println(" l[ibraries]: list known shared libraries"); 20254 pw.println(" f[eatures]: list device features"); 20255 pw.println(" k[eysets]: print known keysets"); 20256 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20257 pw.println(" perm[issions]: dump permissions"); 20258 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20259 pw.println(" pref[erred]: print preferred package settings"); 20260 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20261 pw.println(" prov[iders]: dump content providers"); 20262 pw.println(" p[ackages]: dump installed packages"); 20263 pw.println(" s[hared-users]: dump shared user IDs"); 20264 pw.println(" m[essages]: print collected runtime messages"); 20265 pw.println(" v[erifiers]: print package verifier info"); 20266 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20267 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20268 pw.println(" version: print database version info"); 20269 pw.println(" write: write current settings now"); 20270 pw.println(" installs: details about install sessions"); 20271 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20272 pw.println(" dexopt: dump dexopt state"); 20273 pw.println(" compiler-stats: dump compiler statistics"); 20274 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20275 pw.println(" <package.name>: info about given package"); 20276 return; 20277 } else if ("--checkin".equals(opt)) { 20278 checkin = true; 20279 } else if ("-f".equals(opt)) { 20280 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20281 } else if ("--proto".equals(opt)) { 20282 dumpProto(fd); 20283 return; 20284 } else { 20285 pw.println("Unknown argument: " + opt + "; use -h for help"); 20286 } 20287 } 20288 20289 // Is the caller requesting to dump a particular piece of data? 20290 if (opti < args.length) { 20291 String cmd = args[opti]; 20292 opti++; 20293 // Is this a package name? 20294 if ("android".equals(cmd) || cmd.contains(".")) { 20295 packageName = cmd; 20296 // When dumping a single package, we always dump all of its 20297 // filter information since the amount of data will be reasonable. 20298 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20299 } else if ("check-permission".equals(cmd)) { 20300 if (opti >= args.length) { 20301 pw.println("Error: check-permission missing permission argument"); 20302 return; 20303 } 20304 String perm = args[opti]; 20305 opti++; 20306 if (opti >= args.length) { 20307 pw.println("Error: check-permission missing package argument"); 20308 return; 20309 } 20310 20311 String pkg = args[opti]; 20312 opti++; 20313 int user = UserHandle.getUserId(Binder.getCallingUid()); 20314 if (opti < args.length) { 20315 try { 20316 user = Integer.parseInt(args[opti]); 20317 } catch (NumberFormatException e) { 20318 pw.println("Error: check-permission user argument is not a number: " 20319 + args[opti]); 20320 return; 20321 } 20322 } 20323 20324 // Normalize package name to handle renamed packages and static libs 20325 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20326 20327 pw.println(checkPermission(perm, pkg, user)); 20328 return; 20329 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20330 dumpState.setDump(DumpState.DUMP_LIBS); 20331 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20332 dumpState.setDump(DumpState.DUMP_FEATURES); 20333 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20334 if (opti >= args.length) { 20335 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20336 | DumpState.DUMP_SERVICE_RESOLVERS 20337 | DumpState.DUMP_RECEIVER_RESOLVERS 20338 | DumpState.DUMP_CONTENT_RESOLVERS); 20339 } else { 20340 while (opti < args.length) { 20341 String name = args[opti]; 20342 if ("a".equals(name) || "activity".equals(name)) { 20343 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20344 } else if ("s".equals(name) || "service".equals(name)) { 20345 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20346 } else if ("r".equals(name) || "receiver".equals(name)) { 20347 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20348 } else if ("c".equals(name) || "content".equals(name)) { 20349 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20350 } else { 20351 pw.println("Error: unknown resolver table type: " + name); 20352 return; 20353 } 20354 opti++; 20355 } 20356 } 20357 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20358 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20359 } else if ("permission".equals(cmd)) { 20360 if (opti >= args.length) { 20361 pw.println("Error: permission requires permission name"); 20362 return; 20363 } 20364 permissionNames = new ArraySet<>(); 20365 while (opti < args.length) { 20366 permissionNames.add(args[opti]); 20367 opti++; 20368 } 20369 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20370 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20371 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20372 dumpState.setDump(DumpState.DUMP_PREFERRED); 20373 } else if ("preferred-xml".equals(cmd)) { 20374 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20375 if (opti < args.length && "--full".equals(args[opti])) { 20376 fullPreferred = true; 20377 opti++; 20378 } 20379 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20380 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20381 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20382 dumpState.setDump(DumpState.DUMP_PACKAGES); 20383 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20384 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20385 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20386 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20387 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20388 dumpState.setDump(DumpState.DUMP_MESSAGES); 20389 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20390 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20391 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20392 || "intent-filter-verifiers".equals(cmd)) { 20393 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20394 } else if ("version".equals(cmd)) { 20395 dumpState.setDump(DumpState.DUMP_VERSION); 20396 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20397 dumpState.setDump(DumpState.DUMP_KEYSETS); 20398 } else if ("installs".equals(cmd)) { 20399 dumpState.setDump(DumpState.DUMP_INSTALLS); 20400 } else if ("frozen".equals(cmd)) { 20401 dumpState.setDump(DumpState.DUMP_FROZEN); 20402 } else if ("dexopt".equals(cmd)) { 20403 dumpState.setDump(DumpState.DUMP_DEXOPT); 20404 } else if ("compiler-stats".equals(cmd)) { 20405 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20406 } else if ("enabled-overlays".equals(cmd)) { 20407 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20408 } else if ("write".equals(cmd)) { 20409 synchronized (mPackages) { 20410 mSettings.writeLPr(); 20411 pw.println("Settings written."); 20412 return; 20413 } 20414 } 20415 } 20416 20417 if (checkin) { 20418 pw.println("vers,1"); 20419 } 20420 20421 // reader 20422 synchronized (mPackages) { 20423 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20424 if (!checkin) { 20425 if (dumpState.onTitlePrinted()) 20426 pw.println(); 20427 pw.println("Database versions:"); 20428 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20429 } 20430 } 20431 20432 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20433 if (!checkin) { 20434 if (dumpState.onTitlePrinted()) 20435 pw.println(); 20436 pw.println("Verifiers:"); 20437 pw.print(" Required: "); 20438 pw.print(mRequiredVerifierPackage); 20439 pw.print(" (uid="); 20440 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20441 UserHandle.USER_SYSTEM)); 20442 pw.println(")"); 20443 } else if (mRequiredVerifierPackage != null) { 20444 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20445 pw.print(","); 20446 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20447 UserHandle.USER_SYSTEM)); 20448 } 20449 } 20450 20451 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20452 packageName == null) { 20453 if (mIntentFilterVerifierComponent != null) { 20454 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20455 if (!checkin) { 20456 if (dumpState.onTitlePrinted()) 20457 pw.println(); 20458 pw.println("Intent Filter Verifier:"); 20459 pw.print(" Using: "); 20460 pw.print(verifierPackageName); 20461 pw.print(" (uid="); 20462 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20463 UserHandle.USER_SYSTEM)); 20464 pw.println(")"); 20465 } else if (verifierPackageName != null) { 20466 pw.print("ifv,"); pw.print(verifierPackageName); 20467 pw.print(","); 20468 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20469 UserHandle.USER_SYSTEM)); 20470 } 20471 } else { 20472 pw.println(); 20473 pw.println("No Intent Filter Verifier available!"); 20474 } 20475 } 20476 20477 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20478 boolean printedHeader = false; 20479 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20480 while (it.hasNext()) { 20481 String libName = it.next(); 20482 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20483 if (versionedLib == null) { 20484 continue; 20485 } 20486 final int versionCount = versionedLib.size(); 20487 for (int i = 0; i < versionCount; i++) { 20488 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20489 if (!checkin) { 20490 if (!printedHeader) { 20491 if (dumpState.onTitlePrinted()) 20492 pw.println(); 20493 pw.println("Libraries:"); 20494 printedHeader = true; 20495 } 20496 pw.print(" "); 20497 } else { 20498 pw.print("lib,"); 20499 } 20500 pw.print(libEntry.info.getName()); 20501 if (libEntry.info.isStatic()) { 20502 pw.print(" version=" + libEntry.info.getVersion()); 20503 } 20504 if (!checkin) { 20505 pw.print(" -> "); 20506 } 20507 if (libEntry.path != null) { 20508 pw.print(" (jar) "); 20509 pw.print(libEntry.path); 20510 } else { 20511 pw.print(" (apk) "); 20512 pw.print(libEntry.apk); 20513 } 20514 pw.println(); 20515 } 20516 } 20517 } 20518 20519 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20520 if (dumpState.onTitlePrinted()) 20521 pw.println(); 20522 if (!checkin) { 20523 pw.println("Features:"); 20524 } 20525 20526 synchronized (mAvailableFeatures) { 20527 for (FeatureInfo feat : mAvailableFeatures.values()) { 20528 if (checkin) { 20529 pw.print("feat,"); 20530 pw.print(feat.name); 20531 pw.print(","); 20532 pw.println(feat.version); 20533 } else { 20534 pw.print(" "); 20535 pw.print(feat.name); 20536 if (feat.version > 0) { 20537 pw.print(" version="); 20538 pw.print(feat.version); 20539 } 20540 pw.println(); 20541 } 20542 } 20543 } 20544 } 20545 20546 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20547 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20548 : "Activity Resolver Table:", " ", packageName, 20549 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20550 dumpState.setTitlePrinted(true); 20551 } 20552 } 20553 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20554 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20555 : "Receiver Resolver Table:", " ", packageName, 20556 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20557 dumpState.setTitlePrinted(true); 20558 } 20559 } 20560 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20561 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20562 : "Service Resolver Table:", " ", packageName, 20563 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20564 dumpState.setTitlePrinted(true); 20565 } 20566 } 20567 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20568 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20569 : "Provider Resolver Table:", " ", packageName, 20570 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20571 dumpState.setTitlePrinted(true); 20572 } 20573 } 20574 20575 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20576 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20577 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20578 int user = mSettings.mPreferredActivities.keyAt(i); 20579 if (pir.dump(pw, 20580 dumpState.getTitlePrinted() 20581 ? "\nPreferred Activities User " + user + ":" 20582 : "Preferred Activities User " + user + ":", " ", 20583 packageName, true, false)) { 20584 dumpState.setTitlePrinted(true); 20585 } 20586 } 20587 } 20588 20589 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20590 pw.flush(); 20591 FileOutputStream fout = new FileOutputStream(fd); 20592 BufferedOutputStream str = new BufferedOutputStream(fout); 20593 XmlSerializer serializer = new FastXmlSerializer(); 20594 try { 20595 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20596 serializer.startDocument(null, true); 20597 serializer.setFeature( 20598 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20599 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20600 serializer.endDocument(); 20601 serializer.flush(); 20602 } catch (IllegalArgumentException e) { 20603 pw.println("Failed writing: " + e); 20604 } catch (IllegalStateException e) { 20605 pw.println("Failed writing: " + e); 20606 } catch (IOException e) { 20607 pw.println("Failed writing: " + e); 20608 } 20609 } 20610 20611 if (!checkin 20612 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20613 && packageName == null) { 20614 pw.println(); 20615 int count = mSettings.mPackages.size(); 20616 if (count == 0) { 20617 pw.println("No applications!"); 20618 pw.println(); 20619 } else { 20620 final String prefix = " "; 20621 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20622 if (allPackageSettings.size() == 0) { 20623 pw.println("No domain preferred apps!"); 20624 pw.println(); 20625 } else { 20626 pw.println("App verification status:"); 20627 pw.println(); 20628 count = 0; 20629 for (PackageSetting ps : allPackageSettings) { 20630 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20631 if (ivi == null || ivi.getPackageName() == null) continue; 20632 pw.println(prefix + "Package: " + ivi.getPackageName()); 20633 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20634 pw.println(prefix + "Status: " + ivi.getStatusString()); 20635 pw.println(); 20636 count++; 20637 } 20638 if (count == 0) { 20639 pw.println(prefix + "No app verification established."); 20640 pw.println(); 20641 } 20642 for (int userId : sUserManager.getUserIds()) { 20643 pw.println("App linkages for user " + userId + ":"); 20644 pw.println(); 20645 count = 0; 20646 for (PackageSetting ps : allPackageSettings) { 20647 final long status = ps.getDomainVerificationStatusForUser(userId); 20648 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20649 && !DEBUG_DOMAIN_VERIFICATION) { 20650 continue; 20651 } 20652 pw.println(prefix + "Package: " + ps.name); 20653 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20654 String statusStr = IntentFilterVerificationInfo. 20655 getStatusStringFromValue(status); 20656 pw.println(prefix + "Status: " + statusStr); 20657 pw.println(); 20658 count++; 20659 } 20660 if (count == 0) { 20661 pw.println(prefix + "No configured app linkages."); 20662 pw.println(); 20663 } 20664 } 20665 } 20666 } 20667 } 20668 20669 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20670 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20671 if (packageName == null && permissionNames == null) { 20672 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20673 if (iperm == 0) { 20674 if (dumpState.onTitlePrinted()) 20675 pw.println(); 20676 pw.println("AppOp Permissions:"); 20677 } 20678 pw.print(" AppOp Permission "); 20679 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20680 pw.println(":"); 20681 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20682 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20683 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20684 } 20685 } 20686 } 20687 } 20688 20689 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20690 boolean printedSomething = false; 20691 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20692 if (packageName != null && !packageName.equals(p.info.packageName)) { 20693 continue; 20694 } 20695 if (!printedSomething) { 20696 if (dumpState.onTitlePrinted()) 20697 pw.println(); 20698 pw.println("Registered ContentProviders:"); 20699 printedSomething = true; 20700 } 20701 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20702 pw.print(" "); pw.println(p.toString()); 20703 } 20704 printedSomething = false; 20705 for (Map.Entry<String, PackageParser.Provider> entry : 20706 mProvidersByAuthority.entrySet()) { 20707 PackageParser.Provider p = entry.getValue(); 20708 if (packageName != null && !packageName.equals(p.info.packageName)) { 20709 continue; 20710 } 20711 if (!printedSomething) { 20712 if (dumpState.onTitlePrinted()) 20713 pw.println(); 20714 pw.println("ContentProvider Authorities:"); 20715 printedSomething = true; 20716 } 20717 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20718 pw.print(" "); pw.println(p.toString()); 20719 if (p.info != null && p.info.applicationInfo != null) { 20720 final String appInfo = p.info.applicationInfo.toString(); 20721 pw.print(" applicationInfo="); pw.println(appInfo); 20722 } 20723 } 20724 } 20725 20726 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20727 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20728 } 20729 20730 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20731 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20732 } 20733 20734 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20735 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20736 } 20737 20738 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20739 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20740 } 20741 20742 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20743 // XXX should handle packageName != null by dumping only install data that 20744 // the given package is involved with. 20745 if (dumpState.onTitlePrinted()) pw.println(); 20746 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20747 } 20748 20749 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20750 // XXX should handle packageName != null by dumping only install data that 20751 // the given package is involved with. 20752 if (dumpState.onTitlePrinted()) pw.println(); 20753 20754 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20755 ipw.println(); 20756 ipw.println("Frozen packages:"); 20757 ipw.increaseIndent(); 20758 if (mFrozenPackages.size() == 0) { 20759 ipw.println("(none)"); 20760 } else { 20761 for (int i = 0; i < mFrozenPackages.size(); i++) { 20762 ipw.println(mFrozenPackages.valueAt(i)); 20763 } 20764 } 20765 ipw.decreaseIndent(); 20766 } 20767 20768 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20769 if (dumpState.onTitlePrinted()) pw.println(); 20770 dumpDexoptStateLPr(pw, packageName); 20771 } 20772 20773 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20774 if (dumpState.onTitlePrinted()) pw.println(); 20775 dumpCompilerStatsLPr(pw, packageName); 20776 } 20777 20778 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20779 if (dumpState.onTitlePrinted()) pw.println(); 20780 dumpEnabledOverlaysLPr(pw); 20781 } 20782 20783 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20784 if (dumpState.onTitlePrinted()) pw.println(); 20785 mSettings.dumpReadMessagesLPr(pw, dumpState); 20786 20787 pw.println(); 20788 pw.println("Package warning messages:"); 20789 BufferedReader in = null; 20790 String line = null; 20791 try { 20792 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20793 while ((line = in.readLine()) != null) { 20794 if (line.contains("ignored: updated version")) continue; 20795 pw.println(line); 20796 } 20797 } catch (IOException ignored) { 20798 } finally { 20799 IoUtils.closeQuietly(in); 20800 } 20801 } 20802 20803 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20804 BufferedReader in = null; 20805 String line = null; 20806 try { 20807 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20808 while ((line = in.readLine()) != null) { 20809 if (line.contains("ignored: updated version")) continue; 20810 pw.print("msg,"); 20811 pw.println(line); 20812 } 20813 } catch (IOException ignored) { 20814 } finally { 20815 IoUtils.closeQuietly(in); 20816 } 20817 } 20818 } 20819 } 20820 20821 private void dumpProto(FileDescriptor fd) { 20822 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20823 20824 synchronized (mPackages) { 20825 final long requiredVerifierPackageToken = 20826 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20827 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20828 proto.write( 20829 PackageServiceDumpProto.PackageShortProto.UID, 20830 getPackageUid( 20831 mRequiredVerifierPackage, 20832 MATCH_DEBUG_TRIAGED_MISSING, 20833 UserHandle.USER_SYSTEM)); 20834 proto.end(requiredVerifierPackageToken); 20835 20836 if (mIntentFilterVerifierComponent != null) { 20837 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20838 final long verifierPackageToken = 20839 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20840 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20841 proto.write( 20842 PackageServiceDumpProto.PackageShortProto.UID, 20843 getPackageUid( 20844 verifierPackageName, 20845 MATCH_DEBUG_TRIAGED_MISSING, 20846 UserHandle.USER_SYSTEM)); 20847 proto.end(verifierPackageToken); 20848 } 20849 20850 dumpSharedLibrariesProto(proto); 20851 dumpFeaturesProto(proto); 20852 mSettings.dumpPackagesProto(proto); 20853 mSettings.dumpSharedUsersProto(proto); 20854 dumpMessagesProto(proto); 20855 } 20856 proto.flush(); 20857 } 20858 20859 private void dumpMessagesProto(ProtoOutputStream proto) { 20860 BufferedReader in = null; 20861 String line = null; 20862 try { 20863 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20864 while ((line = in.readLine()) != null) { 20865 if (line.contains("ignored: updated version")) continue; 20866 proto.write(PackageServiceDumpProto.MESSAGES, line); 20867 } 20868 } catch (IOException ignored) { 20869 } finally { 20870 IoUtils.closeQuietly(in); 20871 } 20872 } 20873 20874 private void dumpFeaturesProto(ProtoOutputStream proto) { 20875 synchronized (mAvailableFeatures) { 20876 final int count = mAvailableFeatures.size(); 20877 for (int i = 0; i < count; i++) { 20878 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20879 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20880 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20881 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20882 proto.end(featureToken); 20883 } 20884 } 20885 } 20886 20887 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20888 final int count = mSharedLibraries.size(); 20889 for (int i = 0; i < count; i++) { 20890 final String libName = mSharedLibraries.keyAt(i); 20891 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20892 if (versionedLib == null) { 20893 continue; 20894 } 20895 final int versionCount = versionedLib.size(); 20896 for (int j = 0; j < versionCount; j++) { 20897 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20898 final long sharedLibraryToken = 20899 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20900 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20901 final boolean isJar = (libEntry.path != null); 20902 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20903 if (isJar) { 20904 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20905 } else { 20906 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20907 } 20908 proto.end(sharedLibraryToken); 20909 } 20910 } 20911 } 20912 20913 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20914 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20915 ipw.println(); 20916 ipw.println("Dexopt state:"); 20917 ipw.increaseIndent(); 20918 Collection<PackageParser.Package> packages = null; 20919 if (packageName != null) { 20920 PackageParser.Package targetPackage = mPackages.get(packageName); 20921 if (targetPackage != null) { 20922 packages = Collections.singletonList(targetPackage); 20923 } else { 20924 ipw.println("Unable to find package: " + packageName); 20925 return; 20926 } 20927 } else { 20928 packages = mPackages.values(); 20929 } 20930 20931 for (PackageParser.Package pkg : packages) { 20932 ipw.println("[" + pkg.packageName + "]"); 20933 ipw.increaseIndent(); 20934 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20935 ipw.decreaseIndent(); 20936 } 20937 } 20938 20939 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20940 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20941 ipw.println(); 20942 ipw.println("Compiler stats:"); 20943 ipw.increaseIndent(); 20944 Collection<PackageParser.Package> packages = null; 20945 if (packageName != null) { 20946 PackageParser.Package targetPackage = mPackages.get(packageName); 20947 if (targetPackage != null) { 20948 packages = Collections.singletonList(targetPackage); 20949 } else { 20950 ipw.println("Unable to find package: " + packageName); 20951 return; 20952 } 20953 } else { 20954 packages = mPackages.values(); 20955 } 20956 20957 for (PackageParser.Package pkg : packages) { 20958 ipw.println("[" + pkg.packageName + "]"); 20959 ipw.increaseIndent(); 20960 20961 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20962 if (stats == null) { 20963 ipw.println("(No recorded stats)"); 20964 } else { 20965 stats.dump(ipw); 20966 } 20967 ipw.decreaseIndent(); 20968 } 20969 } 20970 20971 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 20972 pw.println("Enabled overlay paths:"); 20973 final int N = mEnabledOverlayPaths.size(); 20974 for (int i = 0; i < N; i++) { 20975 final int userId = mEnabledOverlayPaths.keyAt(i); 20976 pw.println(String.format(" User %d:", userId)); 20977 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 20978 mEnabledOverlayPaths.valueAt(i); 20979 final int M = userSpecificOverlays.size(); 20980 for (int j = 0; j < M; j++) { 20981 final String targetPackageName = userSpecificOverlays.keyAt(j); 20982 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 20983 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 20984 } 20985 } 20986 } 20987 20988 private String dumpDomainString(String packageName) { 20989 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20990 .getList(); 20991 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20992 20993 ArraySet<String> result = new ArraySet<>(); 20994 if (iviList.size() > 0) { 20995 for (IntentFilterVerificationInfo ivi : iviList) { 20996 for (String host : ivi.getDomains()) { 20997 result.add(host); 20998 } 20999 } 21000 } 21001 if (filters != null && filters.size() > 0) { 21002 for (IntentFilter filter : filters) { 21003 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21004 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21005 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21006 result.addAll(filter.getHostsList()); 21007 } 21008 } 21009 } 21010 21011 StringBuilder sb = new StringBuilder(result.size() * 16); 21012 for (String domain : result) { 21013 if (sb.length() > 0) sb.append(" "); 21014 sb.append(domain); 21015 } 21016 return sb.toString(); 21017 } 21018 21019 // ------- apps on sdcard specific code ------- 21020 static final boolean DEBUG_SD_INSTALL = false; 21021 21022 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21023 21024 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21025 21026 private boolean mMediaMounted = false; 21027 21028 static String getEncryptKey() { 21029 try { 21030 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21031 SD_ENCRYPTION_KEYSTORE_NAME); 21032 if (sdEncKey == null) { 21033 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21034 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21035 if (sdEncKey == null) { 21036 Slog.e(TAG, "Failed to create encryption keys"); 21037 return null; 21038 } 21039 } 21040 return sdEncKey; 21041 } catch (NoSuchAlgorithmException nsae) { 21042 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21043 return null; 21044 } catch (IOException ioe) { 21045 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21046 return null; 21047 } 21048 } 21049 21050 /* 21051 * Update media status on PackageManager. 21052 */ 21053 @Override 21054 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21055 int callingUid = Binder.getCallingUid(); 21056 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21057 throw new SecurityException("Media status can only be updated by the system"); 21058 } 21059 // reader; this apparently protects mMediaMounted, but should probably 21060 // be a different lock in that case. 21061 synchronized (mPackages) { 21062 Log.i(TAG, "Updating external media status from " 21063 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21064 + (mediaStatus ? "mounted" : "unmounted")); 21065 if (DEBUG_SD_INSTALL) 21066 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21067 + ", mMediaMounted=" + mMediaMounted); 21068 if (mediaStatus == mMediaMounted) { 21069 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21070 : 0, -1); 21071 mHandler.sendMessage(msg); 21072 return; 21073 } 21074 mMediaMounted = mediaStatus; 21075 } 21076 // Queue up an async operation since the package installation may take a 21077 // little while. 21078 mHandler.post(new Runnable() { 21079 public void run() { 21080 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21081 } 21082 }); 21083 } 21084 21085 /** 21086 * Called by StorageManagerService when the initial ASECs to scan are available. 21087 * Should block until all the ASEC containers are finished being scanned. 21088 */ 21089 public void scanAvailableAsecs() { 21090 updateExternalMediaStatusInner(true, false, false); 21091 } 21092 21093 /* 21094 * Collect information of applications on external media, map them against 21095 * existing containers and update information based on current mount status. 21096 * Please note that we always have to report status if reportStatus has been 21097 * set to true especially when unloading packages. 21098 */ 21099 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21100 boolean externalStorage) { 21101 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21102 int[] uidArr = EmptyArray.INT; 21103 21104 final String[] list = PackageHelper.getSecureContainerList(); 21105 if (ArrayUtils.isEmpty(list)) { 21106 Log.i(TAG, "No secure containers found"); 21107 } else { 21108 // Process list of secure containers and categorize them 21109 // as active or stale based on their package internal state. 21110 21111 // reader 21112 synchronized (mPackages) { 21113 for (String cid : list) { 21114 // Leave stages untouched for now; installer service owns them 21115 if (PackageInstallerService.isStageName(cid)) continue; 21116 21117 if (DEBUG_SD_INSTALL) 21118 Log.i(TAG, "Processing container " + cid); 21119 String pkgName = getAsecPackageName(cid); 21120 if (pkgName == null) { 21121 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21122 continue; 21123 } 21124 if (DEBUG_SD_INSTALL) 21125 Log.i(TAG, "Looking for pkg : " + pkgName); 21126 21127 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21128 if (ps == null) { 21129 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21130 continue; 21131 } 21132 21133 /* 21134 * Skip packages that are not external if we're unmounting 21135 * external storage. 21136 */ 21137 if (externalStorage && !isMounted && !isExternal(ps)) { 21138 continue; 21139 } 21140 21141 final AsecInstallArgs args = new AsecInstallArgs(cid, 21142 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21143 // The package status is changed only if the code path 21144 // matches between settings and the container id. 21145 if (ps.codePathString != null 21146 && ps.codePathString.startsWith(args.getCodePath())) { 21147 if (DEBUG_SD_INSTALL) { 21148 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21149 + " at code path: " + ps.codePathString); 21150 } 21151 21152 // We do have a valid package installed on sdcard 21153 processCids.put(args, ps.codePathString); 21154 final int uid = ps.appId; 21155 if (uid != -1) { 21156 uidArr = ArrayUtils.appendInt(uidArr, uid); 21157 } 21158 } else { 21159 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21160 + ps.codePathString); 21161 } 21162 } 21163 } 21164 21165 Arrays.sort(uidArr); 21166 } 21167 21168 // Process packages with valid entries. 21169 if (isMounted) { 21170 if (DEBUG_SD_INSTALL) 21171 Log.i(TAG, "Loading packages"); 21172 loadMediaPackages(processCids, uidArr, externalStorage); 21173 startCleaningPackages(); 21174 mInstallerService.onSecureContainersAvailable(); 21175 } else { 21176 if (DEBUG_SD_INSTALL) 21177 Log.i(TAG, "Unloading packages"); 21178 unloadMediaPackages(processCids, uidArr, reportStatus); 21179 } 21180 } 21181 21182 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21183 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21184 final int size = infos.size(); 21185 final String[] packageNames = new String[size]; 21186 final int[] packageUids = new int[size]; 21187 for (int i = 0; i < size; i++) { 21188 final ApplicationInfo info = infos.get(i); 21189 packageNames[i] = info.packageName; 21190 packageUids[i] = info.uid; 21191 } 21192 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21193 finishedReceiver); 21194 } 21195 21196 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21197 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21198 sendResourcesChangedBroadcast(mediaStatus, replacing, 21199 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21200 } 21201 21202 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21203 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21204 int size = pkgList.length; 21205 if (size > 0) { 21206 // Send broadcasts here 21207 Bundle extras = new Bundle(); 21208 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21209 if (uidArr != null) { 21210 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21211 } 21212 if (replacing) { 21213 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21214 } 21215 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21216 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21217 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21218 } 21219 } 21220 21221 /* 21222 * Look at potentially valid container ids from processCids If package 21223 * information doesn't match the one on record or package scanning fails, 21224 * the cid is added to list of removeCids. We currently don't delete stale 21225 * containers. 21226 */ 21227 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21228 boolean externalStorage) { 21229 ArrayList<String> pkgList = new ArrayList<String>(); 21230 Set<AsecInstallArgs> keys = processCids.keySet(); 21231 21232 for (AsecInstallArgs args : keys) { 21233 String codePath = processCids.get(args); 21234 if (DEBUG_SD_INSTALL) 21235 Log.i(TAG, "Loading container : " + args.cid); 21236 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21237 try { 21238 // Make sure there are no container errors first. 21239 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21240 Slog.e(TAG, "Failed to mount cid : " + args.cid 21241 + " when installing from sdcard"); 21242 continue; 21243 } 21244 // Check code path here. 21245 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21246 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21247 + " does not match one in settings " + codePath); 21248 continue; 21249 } 21250 // Parse package 21251 int parseFlags = mDefParseFlags; 21252 if (args.isExternalAsec()) { 21253 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21254 } 21255 if (args.isFwdLocked()) { 21256 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21257 } 21258 21259 synchronized (mInstallLock) { 21260 PackageParser.Package pkg = null; 21261 try { 21262 // Sadly we don't know the package name yet to freeze it 21263 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21264 SCAN_IGNORE_FROZEN, 0, null); 21265 } catch (PackageManagerException e) { 21266 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21267 } 21268 // Scan the package 21269 if (pkg != null) { 21270 /* 21271 * TODO why is the lock being held? doPostInstall is 21272 * called in other places without the lock. This needs 21273 * to be straightened out. 21274 */ 21275 // writer 21276 synchronized (mPackages) { 21277 retCode = PackageManager.INSTALL_SUCCEEDED; 21278 pkgList.add(pkg.packageName); 21279 // Post process args 21280 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21281 pkg.applicationInfo.uid); 21282 } 21283 } else { 21284 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21285 } 21286 } 21287 21288 } finally { 21289 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21290 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21291 } 21292 } 21293 } 21294 // writer 21295 synchronized (mPackages) { 21296 // If the platform SDK has changed since the last time we booted, 21297 // we need to re-grant app permission to catch any new ones that 21298 // appear. This is really a hack, and means that apps can in some 21299 // cases get permissions that the user didn't initially explicitly 21300 // allow... it would be nice to have some better way to handle 21301 // this situation. 21302 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21303 : mSettings.getInternalVersion(); 21304 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21305 : StorageManager.UUID_PRIVATE_INTERNAL; 21306 21307 int updateFlags = UPDATE_PERMISSIONS_ALL; 21308 if (ver.sdkVersion != mSdkVersion) { 21309 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21310 + mSdkVersion + "; regranting permissions for external"); 21311 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21312 } 21313 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21314 21315 // Yay, everything is now upgraded 21316 ver.forceCurrent(); 21317 21318 // can downgrade to reader 21319 // Persist settings 21320 mSettings.writeLPr(); 21321 } 21322 // Send a broadcast to let everyone know we are done processing 21323 if (pkgList.size() > 0) { 21324 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21325 } 21326 } 21327 21328 /* 21329 * Utility method to unload a list of specified containers 21330 */ 21331 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21332 // Just unmount all valid containers. 21333 for (AsecInstallArgs arg : cidArgs) { 21334 synchronized (mInstallLock) { 21335 arg.doPostDeleteLI(false); 21336 } 21337 } 21338 } 21339 21340 /* 21341 * Unload packages mounted on external media. This involves deleting package 21342 * data from internal structures, sending broadcasts about disabled packages, 21343 * gc'ing to free up references, unmounting all secure containers 21344 * corresponding to packages on external media, and posting a 21345 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21346 * that we always have to post this message if status has been requested no 21347 * matter what. 21348 */ 21349 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21350 final boolean reportStatus) { 21351 if (DEBUG_SD_INSTALL) 21352 Log.i(TAG, "unloading media packages"); 21353 ArrayList<String> pkgList = new ArrayList<String>(); 21354 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21355 final Set<AsecInstallArgs> keys = processCids.keySet(); 21356 for (AsecInstallArgs args : keys) { 21357 String pkgName = args.getPackageName(); 21358 if (DEBUG_SD_INSTALL) 21359 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21360 // Delete package internally 21361 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21362 synchronized (mInstallLock) { 21363 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21364 final boolean res; 21365 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21366 "unloadMediaPackages")) { 21367 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21368 null); 21369 } 21370 if (res) { 21371 pkgList.add(pkgName); 21372 } else { 21373 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21374 failedList.add(args); 21375 } 21376 } 21377 } 21378 21379 // reader 21380 synchronized (mPackages) { 21381 // We didn't update the settings after removing each package; 21382 // write them now for all packages. 21383 mSettings.writeLPr(); 21384 } 21385 21386 // We have to absolutely send UPDATED_MEDIA_STATUS only 21387 // after confirming that all the receivers processed the ordered 21388 // broadcast when packages get disabled, force a gc to clean things up. 21389 // and unload all the containers. 21390 if (pkgList.size() > 0) { 21391 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21392 new IIntentReceiver.Stub() { 21393 public void performReceive(Intent intent, int resultCode, String data, 21394 Bundle extras, boolean ordered, boolean sticky, 21395 int sendingUser) throws RemoteException { 21396 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21397 reportStatus ? 1 : 0, 1, keys); 21398 mHandler.sendMessage(msg); 21399 } 21400 }); 21401 } else { 21402 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21403 keys); 21404 mHandler.sendMessage(msg); 21405 } 21406 } 21407 21408 private void loadPrivatePackages(final VolumeInfo vol) { 21409 mHandler.post(new Runnable() { 21410 @Override 21411 public void run() { 21412 loadPrivatePackagesInner(vol); 21413 } 21414 }); 21415 } 21416 21417 private void loadPrivatePackagesInner(VolumeInfo vol) { 21418 final String volumeUuid = vol.fsUuid; 21419 if (TextUtils.isEmpty(volumeUuid)) { 21420 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21421 return; 21422 } 21423 21424 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21425 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21426 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21427 21428 final VersionInfo ver; 21429 final List<PackageSetting> packages; 21430 synchronized (mPackages) { 21431 ver = mSettings.findOrCreateVersion(volumeUuid); 21432 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21433 } 21434 21435 for (PackageSetting ps : packages) { 21436 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21437 synchronized (mInstallLock) { 21438 final PackageParser.Package pkg; 21439 try { 21440 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21441 loaded.add(pkg.applicationInfo); 21442 21443 } catch (PackageManagerException e) { 21444 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21445 } 21446 21447 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21448 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21449 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21450 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21451 } 21452 } 21453 } 21454 21455 // Reconcile app data for all started/unlocked users 21456 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21457 final UserManager um = mContext.getSystemService(UserManager.class); 21458 UserManagerInternal umInternal = getUserManagerInternal(); 21459 for (UserInfo user : um.getUsers()) { 21460 final int flags; 21461 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21462 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21463 } else if (umInternal.isUserRunning(user.id)) { 21464 flags = StorageManager.FLAG_STORAGE_DE; 21465 } else { 21466 continue; 21467 } 21468 21469 try { 21470 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21471 synchronized (mInstallLock) { 21472 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21473 } 21474 } catch (IllegalStateException e) { 21475 // Device was probably ejected, and we'll process that event momentarily 21476 Slog.w(TAG, "Failed to prepare storage: " + e); 21477 } 21478 } 21479 21480 synchronized (mPackages) { 21481 int updateFlags = UPDATE_PERMISSIONS_ALL; 21482 if (ver.sdkVersion != mSdkVersion) { 21483 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21484 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21485 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21486 } 21487 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21488 21489 // Yay, everything is now upgraded 21490 ver.forceCurrent(); 21491 21492 mSettings.writeLPr(); 21493 } 21494 21495 for (PackageFreezer freezer : freezers) { 21496 freezer.close(); 21497 } 21498 21499 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21500 sendResourcesChangedBroadcast(true, false, loaded, null); 21501 } 21502 21503 private void unloadPrivatePackages(final VolumeInfo vol) { 21504 mHandler.post(new Runnable() { 21505 @Override 21506 public void run() { 21507 unloadPrivatePackagesInner(vol); 21508 } 21509 }); 21510 } 21511 21512 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21513 final String volumeUuid = vol.fsUuid; 21514 if (TextUtils.isEmpty(volumeUuid)) { 21515 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21516 return; 21517 } 21518 21519 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21520 synchronized (mInstallLock) { 21521 synchronized (mPackages) { 21522 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21523 for (PackageSetting ps : packages) { 21524 if (ps.pkg == null) continue; 21525 21526 final ApplicationInfo info = ps.pkg.applicationInfo; 21527 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21528 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21529 21530 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21531 "unloadPrivatePackagesInner")) { 21532 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21533 false, null)) { 21534 unloaded.add(info); 21535 } else { 21536 Slog.w(TAG, "Failed to unload " + ps.codePath); 21537 } 21538 } 21539 21540 // Try very hard to release any references to this package 21541 // so we don't risk the system server being killed due to 21542 // open FDs 21543 AttributeCache.instance().removePackage(ps.name); 21544 } 21545 21546 mSettings.writeLPr(); 21547 } 21548 } 21549 21550 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21551 sendResourcesChangedBroadcast(false, false, unloaded, null); 21552 21553 // Try very hard to release any references to this path so we don't risk 21554 // the system server being killed due to open FDs 21555 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21556 21557 for (int i = 0; i < 3; i++) { 21558 System.gc(); 21559 System.runFinalization(); 21560 } 21561 } 21562 21563 private void assertPackageKnown(String volumeUuid, String packageName) 21564 throws PackageManagerException { 21565 synchronized (mPackages) { 21566 // Normalize package name to handle renamed packages 21567 packageName = normalizePackageNameLPr(packageName); 21568 21569 final PackageSetting ps = mSettings.mPackages.get(packageName); 21570 if (ps == null) { 21571 throw new PackageManagerException("Package " + packageName + " is unknown"); 21572 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21573 throw new PackageManagerException( 21574 "Package " + packageName + " found on unknown volume " + volumeUuid 21575 + "; expected volume " + ps.volumeUuid); 21576 } 21577 } 21578 } 21579 21580 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21581 throws PackageManagerException { 21582 synchronized (mPackages) { 21583 // Normalize package name to handle renamed packages 21584 packageName = normalizePackageNameLPr(packageName); 21585 21586 final PackageSetting ps = mSettings.mPackages.get(packageName); 21587 if (ps == null) { 21588 throw new PackageManagerException("Package " + packageName + " is unknown"); 21589 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21590 throw new PackageManagerException( 21591 "Package " + packageName + " found on unknown volume " + volumeUuid 21592 + "; expected volume " + ps.volumeUuid); 21593 } else if (!ps.getInstalled(userId)) { 21594 throw new PackageManagerException( 21595 "Package " + packageName + " not installed for user " + userId); 21596 } 21597 } 21598 } 21599 21600 private List<String> collectAbsoluteCodePaths() { 21601 synchronized (mPackages) { 21602 List<String> codePaths = new ArrayList<>(); 21603 final int packageCount = mSettings.mPackages.size(); 21604 for (int i = 0; i < packageCount; i++) { 21605 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21606 codePaths.add(ps.codePath.getAbsolutePath()); 21607 } 21608 return codePaths; 21609 } 21610 } 21611 21612 /** 21613 * Examine all apps present on given mounted volume, and destroy apps that 21614 * aren't expected, either due to uninstallation or reinstallation on 21615 * another volume. 21616 */ 21617 private void reconcileApps(String volumeUuid) { 21618 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21619 List<File> filesToDelete = null; 21620 21621 final File[] files = FileUtils.listFilesOrEmpty( 21622 Environment.getDataAppDirectory(volumeUuid)); 21623 for (File file : files) { 21624 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21625 && !PackageInstallerService.isStageName(file.getName()); 21626 if (!isPackage) { 21627 // Ignore entries which are not packages 21628 continue; 21629 } 21630 21631 String absolutePath = file.getAbsolutePath(); 21632 21633 boolean pathValid = false; 21634 final int absoluteCodePathCount = absoluteCodePaths.size(); 21635 for (int i = 0; i < absoluteCodePathCount; i++) { 21636 String absoluteCodePath = absoluteCodePaths.get(i); 21637 if (absolutePath.startsWith(absoluteCodePath)) { 21638 pathValid = true; 21639 break; 21640 } 21641 } 21642 21643 if (!pathValid) { 21644 if (filesToDelete == null) { 21645 filesToDelete = new ArrayList<>(); 21646 } 21647 filesToDelete.add(file); 21648 } 21649 } 21650 21651 if (filesToDelete != null) { 21652 final int fileToDeleteCount = filesToDelete.size(); 21653 for (int i = 0; i < fileToDeleteCount; i++) { 21654 File fileToDelete = filesToDelete.get(i); 21655 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21656 synchronized (mInstallLock) { 21657 removeCodePathLI(fileToDelete); 21658 } 21659 } 21660 } 21661 } 21662 21663 /** 21664 * Reconcile all app data for the given user. 21665 * <p> 21666 * Verifies that directories exist and that ownership and labeling is 21667 * correct for all installed apps on all mounted volumes. 21668 */ 21669 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21670 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21671 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21672 final String volumeUuid = vol.getFsUuid(); 21673 synchronized (mInstallLock) { 21674 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21675 } 21676 } 21677 } 21678 21679 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21680 boolean migrateAppData) { 21681 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21682 } 21683 21684 /** 21685 * Reconcile all app data on given mounted volume. 21686 * <p> 21687 * Destroys app data that isn't expected, either due to uninstallation or 21688 * reinstallation on another volume. 21689 * <p> 21690 * Verifies that directories exist and that ownership and labeling is 21691 * correct for all installed apps. 21692 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21693 */ 21694 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21695 boolean migrateAppData, boolean onlyCoreApps) { 21696 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21697 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21698 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21699 21700 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21701 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21702 21703 // First look for stale data that doesn't belong, and check if things 21704 // have changed since we did our last restorecon 21705 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21706 if (StorageManager.isFileEncryptedNativeOrEmulated() 21707 && !StorageManager.isUserKeyUnlocked(userId)) { 21708 throw new RuntimeException( 21709 "Yikes, someone asked us to reconcile CE storage while " + userId 21710 + " was still locked; this would have caused massive data loss!"); 21711 } 21712 21713 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21714 for (File file : files) { 21715 final String packageName = file.getName(); 21716 try { 21717 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21718 } catch (PackageManagerException e) { 21719 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21720 try { 21721 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21722 StorageManager.FLAG_STORAGE_CE, 0); 21723 } catch (InstallerException e2) { 21724 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21725 } 21726 } 21727 } 21728 } 21729 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21730 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21731 for (File file : files) { 21732 final String packageName = file.getName(); 21733 try { 21734 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21735 } catch (PackageManagerException e) { 21736 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21737 try { 21738 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21739 StorageManager.FLAG_STORAGE_DE, 0); 21740 } catch (InstallerException e2) { 21741 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21742 } 21743 } 21744 } 21745 } 21746 21747 // Ensure that data directories are ready to roll for all packages 21748 // installed for this volume and user 21749 final List<PackageSetting> packages; 21750 synchronized (mPackages) { 21751 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21752 } 21753 int preparedCount = 0; 21754 for (PackageSetting ps : packages) { 21755 final String packageName = ps.name; 21756 if (ps.pkg == null) { 21757 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21758 // TODO: might be due to legacy ASEC apps; we should circle back 21759 // and reconcile again once they're scanned 21760 continue; 21761 } 21762 // Skip non-core apps if requested 21763 if (onlyCoreApps && !ps.pkg.coreApp) { 21764 result.add(packageName); 21765 continue; 21766 } 21767 21768 if (ps.getInstalled(userId)) { 21769 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21770 preparedCount++; 21771 } 21772 } 21773 21774 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21775 return result; 21776 } 21777 21778 /** 21779 * Prepare app data for the given app just after it was installed or 21780 * upgraded. This method carefully only touches users that it's installed 21781 * for, and it forces a restorecon to handle any seinfo changes. 21782 * <p> 21783 * Verifies that directories exist and that ownership and labeling is 21784 * correct for all installed apps. If there is an ownership mismatch, it 21785 * will try recovering system apps by wiping data; third-party app data is 21786 * left intact. 21787 * <p> 21788 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21789 */ 21790 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21791 final PackageSetting ps; 21792 synchronized (mPackages) { 21793 ps = mSettings.mPackages.get(pkg.packageName); 21794 mSettings.writeKernelMappingLPr(ps); 21795 } 21796 21797 final UserManager um = mContext.getSystemService(UserManager.class); 21798 UserManagerInternal umInternal = getUserManagerInternal(); 21799 for (UserInfo user : um.getUsers()) { 21800 final int flags; 21801 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21802 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21803 } else if (umInternal.isUserRunning(user.id)) { 21804 flags = StorageManager.FLAG_STORAGE_DE; 21805 } else { 21806 continue; 21807 } 21808 21809 if (ps.getInstalled(user.id)) { 21810 // TODO: when user data is locked, mark that we're still dirty 21811 prepareAppDataLIF(pkg, user.id, flags); 21812 } 21813 } 21814 } 21815 21816 /** 21817 * Prepare app data for the given app. 21818 * <p> 21819 * Verifies that directories exist and that ownership and labeling is 21820 * correct for all installed apps. If there is an ownership mismatch, this 21821 * will try recovering system apps by wiping data; third-party app data is 21822 * left intact. 21823 */ 21824 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21825 if (pkg == null) { 21826 Slog.wtf(TAG, "Package was null!", new Throwable()); 21827 return; 21828 } 21829 prepareAppDataLeafLIF(pkg, userId, flags); 21830 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21831 for (int i = 0; i < childCount; i++) { 21832 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21833 } 21834 } 21835 21836 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21837 boolean maybeMigrateAppData) { 21838 prepareAppDataLIF(pkg, userId, flags); 21839 21840 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21841 // We may have just shuffled around app data directories, so 21842 // prepare them one more time 21843 prepareAppDataLIF(pkg, userId, flags); 21844 } 21845 } 21846 21847 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21848 if (DEBUG_APP_DATA) { 21849 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21850 + Integer.toHexString(flags)); 21851 } 21852 21853 final String volumeUuid = pkg.volumeUuid; 21854 final String packageName = pkg.packageName; 21855 final ApplicationInfo app = pkg.applicationInfo; 21856 final int appId = UserHandle.getAppId(app.uid); 21857 21858 Preconditions.checkNotNull(app.seInfo); 21859 21860 long ceDataInode = -1; 21861 try { 21862 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21863 appId, app.seInfo, app.targetSdkVersion); 21864 } catch (InstallerException e) { 21865 if (app.isSystemApp()) { 21866 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21867 + ", but trying to recover: " + e); 21868 destroyAppDataLeafLIF(pkg, userId, flags); 21869 try { 21870 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21871 appId, app.seInfo, app.targetSdkVersion); 21872 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21873 } catch (InstallerException e2) { 21874 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21875 } 21876 } else { 21877 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21878 } 21879 } 21880 21881 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21882 // TODO: mark this structure as dirty so we persist it! 21883 synchronized (mPackages) { 21884 final PackageSetting ps = mSettings.mPackages.get(packageName); 21885 if (ps != null) { 21886 ps.setCeDataInode(ceDataInode, userId); 21887 } 21888 } 21889 } 21890 21891 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21892 } 21893 21894 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21895 if (pkg == null) { 21896 Slog.wtf(TAG, "Package was null!", new Throwable()); 21897 return; 21898 } 21899 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21900 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21901 for (int i = 0; i < childCount; i++) { 21902 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21903 } 21904 } 21905 21906 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21907 final String volumeUuid = pkg.volumeUuid; 21908 final String packageName = pkg.packageName; 21909 final ApplicationInfo app = pkg.applicationInfo; 21910 21911 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21912 // Create a native library symlink only if we have native libraries 21913 // and if the native libraries are 32 bit libraries. We do not provide 21914 // this symlink for 64 bit libraries. 21915 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21916 final String nativeLibPath = app.nativeLibraryDir; 21917 try { 21918 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21919 nativeLibPath, userId); 21920 } catch (InstallerException e) { 21921 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21922 } 21923 } 21924 } 21925 } 21926 21927 /** 21928 * For system apps on non-FBE devices, this method migrates any existing 21929 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21930 * requested by the app. 21931 */ 21932 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21933 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21934 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21935 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21936 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21937 try { 21938 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21939 storageTarget); 21940 } catch (InstallerException e) { 21941 logCriticalInfo(Log.WARN, 21942 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21943 } 21944 return true; 21945 } else { 21946 return false; 21947 } 21948 } 21949 21950 public PackageFreezer freezePackage(String packageName, String killReason) { 21951 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21952 } 21953 21954 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21955 return new PackageFreezer(packageName, userId, killReason); 21956 } 21957 21958 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21959 String killReason) { 21960 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21961 } 21962 21963 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21964 String killReason) { 21965 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21966 return new PackageFreezer(); 21967 } else { 21968 return freezePackage(packageName, userId, killReason); 21969 } 21970 } 21971 21972 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21973 String killReason) { 21974 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21975 } 21976 21977 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21978 String killReason) { 21979 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21980 return new PackageFreezer(); 21981 } else { 21982 return freezePackage(packageName, userId, killReason); 21983 } 21984 } 21985 21986 /** 21987 * Class that freezes and kills the given package upon creation, and 21988 * unfreezes it upon closing. This is typically used when doing surgery on 21989 * app code/data to prevent the app from running while you're working. 21990 */ 21991 private class PackageFreezer implements AutoCloseable { 21992 private final String mPackageName; 21993 private final PackageFreezer[] mChildren; 21994 21995 private final boolean mWeFroze; 21996 21997 private final AtomicBoolean mClosed = new AtomicBoolean(); 21998 private final CloseGuard mCloseGuard = CloseGuard.get(); 21999 22000 /** 22001 * Create and return a stub freezer that doesn't actually do anything, 22002 * typically used when someone requested 22003 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22004 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22005 */ 22006 public PackageFreezer() { 22007 mPackageName = null; 22008 mChildren = null; 22009 mWeFroze = false; 22010 mCloseGuard.open("close"); 22011 } 22012 22013 public PackageFreezer(String packageName, int userId, String killReason) { 22014 synchronized (mPackages) { 22015 mPackageName = packageName; 22016 mWeFroze = mFrozenPackages.add(mPackageName); 22017 22018 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22019 if (ps != null) { 22020 killApplication(ps.name, ps.appId, userId, killReason); 22021 } 22022 22023 final PackageParser.Package p = mPackages.get(packageName); 22024 if (p != null && p.childPackages != null) { 22025 final int N = p.childPackages.size(); 22026 mChildren = new PackageFreezer[N]; 22027 for (int i = 0; i < N; i++) { 22028 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22029 userId, killReason); 22030 } 22031 } else { 22032 mChildren = null; 22033 } 22034 } 22035 mCloseGuard.open("close"); 22036 } 22037 22038 @Override 22039 protected void finalize() throws Throwable { 22040 try { 22041 mCloseGuard.warnIfOpen(); 22042 close(); 22043 } finally { 22044 super.finalize(); 22045 } 22046 } 22047 22048 @Override 22049 public void close() { 22050 mCloseGuard.close(); 22051 if (mClosed.compareAndSet(false, true)) { 22052 synchronized (mPackages) { 22053 if (mWeFroze) { 22054 mFrozenPackages.remove(mPackageName); 22055 } 22056 22057 if (mChildren != null) { 22058 for (PackageFreezer freezer : mChildren) { 22059 freezer.close(); 22060 } 22061 } 22062 } 22063 } 22064 } 22065 } 22066 22067 /** 22068 * Verify that given package is currently frozen. 22069 */ 22070 private void checkPackageFrozen(String packageName) { 22071 synchronized (mPackages) { 22072 if (!mFrozenPackages.contains(packageName)) { 22073 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22074 } 22075 } 22076 } 22077 22078 @Override 22079 public int movePackage(final String packageName, final String volumeUuid) { 22080 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22081 22082 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22083 final int moveId = mNextMoveId.getAndIncrement(); 22084 mHandler.post(new Runnable() { 22085 @Override 22086 public void run() { 22087 try { 22088 movePackageInternal(packageName, volumeUuid, moveId, user); 22089 } catch (PackageManagerException e) { 22090 Slog.w(TAG, "Failed to move " + packageName, e); 22091 mMoveCallbacks.notifyStatusChanged(moveId, 22092 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22093 } 22094 } 22095 }); 22096 return moveId; 22097 } 22098 22099 private void movePackageInternal(final String packageName, final String volumeUuid, 22100 final int moveId, UserHandle user) throws PackageManagerException { 22101 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22102 final PackageManager pm = mContext.getPackageManager(); 22103 22104 final boolean currentAsec; 22105 final String currentVolumeUuid; 22106 final File codeFile; 22107 final String installerPackageName; 22108 final String packageAbiOverride; 22109 final int appId; 22110 final String seinfo; 22111 final String label; 22112 final int targetSdkVersion; 22113 final PackageFreezer freezer; 22114 final int[] installedUserIds; 22115 22116 // reader 22117 synchronized (mPackages) { 22118 final PackageParser.Package pkg = mPackages.get(packageName); 22119 final PackageSetting ps = mSettings.mPackages.get(packageName); 22120 if (pkg == null || ps == null) { 22121 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22122 } 22123 22124 if (pkg.applicationInfo.isSystemApp()) { 22125 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22126 "Cannot move system application"); 22127 } 22128 22129 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22130 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22131 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22132 if (isInternalStorage && !allow3rdPartyOnInternal) { 22133 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22134 "3rd party apps are not allowed on internal storage"); 22135 } 22136 22137 if (pkg.applicationInfo.isExternalAsec()) { 22138 currentAsec = true; 22139 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22140 } else if (pkg.applicationInfo.isForwardLocked()) { 22141 currentAsec = true; 22142 currentVolumeUuid = "forward_locked"; 22143 } else { 22144 currentAsec = false; 22145 currentVolumeUuid = ps.volumeUuid; 22146 22147 final File probe = new File(pkg.codePath); 22148 final File probeOat = new File(probe, "oat"); 22149 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22150 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22151 "Move only supported for modern cluster style installs"); 22152 } 22153 } 22154 22155 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22156 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22157 "Package already moved to " + volumeUuid); 22158 } 22159 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22160 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22161 "Device admin cannot be moved"); 22162 } 22163 22164 if (mFrozenPackages.contains(packageName)) { 22165 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22166 "Failed to move already frozen package"); 22167 } 22168 22169 codeFile = new File(pkg.codePath); 22170 installerPackageName = ps.installerPackageName; 22171 packageAbiOverride = ps.cpuAbiOverrideString; 22172 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22173 seinfo = pkg.applicationInfo.seInfo; 22174 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22175 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22176 freezer = freezePackage(packageName, "movePackageInternal"); 22177 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22178 } 22179 22180 final Bundle extras = new Bundle(); 22181 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22182 extras.putString(Intent.EXTRA_TITLE, label); 22183 mMoveCallbacks.notifyCreated(moveId, extras); 22184 22185 int installFlags; 22186 final boolean moveCompleteApp; 22187 final File measurePath; 22188 22189 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22190 installFlags = INSTALL_INTERNAL; 22191 moveCompleteApp = !currentAsec; 22192 measurePath = Environment.getDataAppDirectory(volumeUuid); 22193 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22194 installFlags = INSTALL_EXTERNAL; 22195 moveCompleteApp = false; 22196 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22197 } else { 22198 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22199 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22200 || !volume.isMountedWritable()) { 22201 freezer.close(); 22202 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22203 "Move location not mounted private volume"); 22204 } 22205 22206 Preconditions.checkState(!currentAsec); 22207 22208 installFlags = INSTALL_INTERNAL; 22209 moveCompleteApp = true; 22210 measurePath = Environment.getDataAppDirectory(volumeUuid); 22211 } 22212 22213 final PackageStats stats = new PackageStats(null, -1); 22214 synchronized (mInstaller) { 22215 for (int userId : installedUserIds) { 22216 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22217 freezer.close(); 22218 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22219 "Failed to measure package size"); 22220 } 22221 } 22222 } 22223 22224 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22225 + stats.dataSize); 22226 22227 final long startFreeBytes = measurePath.getFreeSpace(); 22228 final long sizeBytes; 22229 if (moveCompleteApp) { 22230 sizeBytes = stats.codeSize + stats.dataSize; 22231 } else { 22232 sizeBytes = stats.codeSize; 22233 } 22234 22235 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22236 freezer.close(); 22237 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22238 "Not enough free space to move"); 22239 } 22240 22241 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22242 22243 final CountDownLatch installedLatch = new CountDownLatch(1); 22244 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22245 @Override 22246 public void onUserActionRequired(Intent intent) throws RemoteException { 22247 throw new IllegalStateException(); 22248 } 22249 22250 @Override 22251 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22252 Bundle extras) throws RemoteException { 22253 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22254 + PackageManager.installStatusToString(returnCode, msg)); 22255 22256 installedLatch.countDown(); 22257 freezer.close(); 22258 22259 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22260 switch (status) { 22261 case PackageInstaller.STATUS_SUCCESS: 22262 mMoveCallbacks.notifyStatusChanged(moveId, 22263 PackageManager.MOVE_SUCCEEDED); 22264 break; 22265 case PackageInstaller.STATUS_FAILURE_STORAGE: 22266 mMoveCallbacks.notifyStatusChanged(moveId, 22267 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22268 break; 22269 default: 22270 mMoveCallbacks.notifyStatusChanged(moveId, 22271 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22272 break; 22273 } 22274 } 22275 }; 22276 22277 final MoveInfo move; 22278 if (moveCompleteApp) { 22279 // Kick off a thread to report progress estimates 22280 new Thread() { 22281 @Override 22282 public void run() { 22283 while (true) { 22284 try { 22285 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22286 break; 22287 } 22288 } catch (InterruptedException ignored) { 22289 } 22290 22291 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22292 final int progress = 10 + (int) MathUtils.constrain( 22293 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22294 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22295 } 22296 } 22297 }.start(); 22298 22299 final String dataAppName = codeFile.getName(); 22300 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22301 dataAppName, appId, seinfo, targetSdkVersion); 22302 } else { 22303 move = null; 22304 } 22305 22306 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22307 22308 final Message msg = mHandler.obtainMessage(INIT_COPY); 22309 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22310 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22311 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22312 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22313 PackageManager.INSTALL_REASON_UNKNOWN); 22314 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22315 msg.obj = params; 22316 22317 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22318 System.identityHashCode(msg.obj)); 22319 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22320 System.identityHashCode(msg.obj)); 22321 22322 mHandler.sendMessage(msg); 22323 } 22324 22325 @Override 22326 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22327 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22328 22329 final int realMoveId = mNextMoveId.getAndIncrement(); 22330 final Bundle extras = new Bundle(); 22331 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22332 mMoveCallbacks.notifyCreated(realMoveId, extras); 22333 22334 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22335 @Override 22336 public void onCreated(int moveId, Bundle extras) { 22337 // Ignored 22338 } 22339 22340 @Override 22341 public void onStatusChanged(int moveId, int status, long estMillis) { 22342 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22343 } 22344 }; 22345 22346 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22347 storage.setPrimaryStorageUuid(volumeUuid, callback); 22348 return realMoveId; 22349 } 22350 22351 @Override 22352 public int getMoveStatus(int moveId) { 22353 mContext.enforceCallingOrSelfPermission( 22354 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22355 return mMoveCallbacks.mLastStatus.get(moveId); 22356 } 22357 22358 @Override 22359 public void registerMoveCallback(IPackageMoveObserver callback) { 22360 mContext.enforceCallingOrSelfPermission( 22361 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22362 mMoveCallbacks.register(callback); 22363 } 22364 22365 @Override 22366 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22367 mContext.enforceCallingOrSelfPermission( 22368 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22369 mMoveCallbacks.unregister(callback); 22370 } 22371 22372 @Override 22373 public boolean setInstallLocation(int loc) { 22374 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22375 null); 22376 if (getInstallLocation() == loc) { 22377 return true; 22378 } 22379 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22380 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22381 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22382 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22383 return true; 22384 } 22385 return false; 22386 } 22387 22388 @Override 22389 public int getInstallLocation() { 22390 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22391 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22392 PackageHelper.APP_INSTALL_AUTO); 22393 } 22394 22395 /** Called by UserManagerService */ 22396 void cleanUpUser(UserManagerService userManager, int userHandle) { 22397 synchronized (mPackages) { 22398 mDirtyUsers.remove(userHandle); 22399 mUserNeedsBadging.delete(userHandle); 22400 mSettings.removeUserLPw(userHandle); 22401 mPendingBroadcasts.remove(userHandle); 22402 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22403 removeUnusedPackagesLPw(userManager, userHandle); 22404 } 22405 } 22406 22407 /** 22408 * We're removing userHandle and would like to remove any downloaded packages 22409 * that are no longer in use by any other user. 22410 * @param userHandle the user being removed 22411 */ 22412 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22413 final boolean DEBUG_CLEAN_APKS = false; 22414 int [] users = userManager.getUserIds(); 22415 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22416 while (psit.hasNext()) { 22417 PackageSetting ps = psit.next(); 22418 if (ps.pkg == null) { 22419 continue; 22420 } 22421 final String packageName = ps.pkg.packageName; 22422 // Skip over if system app 22423 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22424 continue; 22425 } 22426 if (DEBUG_CLEAN_APKS) { 22427 Slog.i(TAG, "Checking package " + packageName); 22428 } 22429 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22430 if (keep) { 22431 if (DEBUG_CLEAN_APKS) { 22432 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22433 } 22434 } else { 22435 for (int i = 0; i < users.length; i++) { 22436 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22437 keep = true; 22438 if (DEBUG_CLEAN_APKS) { 22439 Slog.i(TAG, " Keeping package " + packageName + " for user " 22440 + users[i]); 22441 } 22442 break; 22443 } 22444 } 22445 } 22446 if (!keep) { 22447 if (DEBUG_CLEAN_APKS) { 22448 Slog.i(TAG, " Removing package " + packageName); 22449 } 22450 mHandler.post(new Runnable() { 22451 public void run() { 22452 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22453 userHandle, 0); 22454 } //end run 22455 }); 22456 } 22457 } 22458 } 22459 22460 /** Called by UserManagerService */ 22461 void createNewUser(int userId, String[] disallowedPackages) { 22462 synchronized (mInstallLock) { 22463 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22464 } 22465 synchronized (mPackages) { 22466 scheduleWritePackageRestrictionsLocked(userId); 22467 scheduleWritePackageListLocked(userId); 22468 applyFactoryDefaultBrowserLPw(userId); 22469 primeDomainVerificationsLPw(userId); 22470 } 22471 } 22472 22473 void onNewUserCreated(final int userId) { 22474 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22475 // If permission review for legacy apps is required, we represent 22476 // dagerous permissions for such apps as always granted runtime 22477 // permissions to keep per user flag state whether review is needed. 22478 // Hence, if a new user is added we have to propagate dangerous 22479 // permission grants for these legacy apps. 22480 if (mPermissionReviewRequired) { 22481 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22482 | UPDATE_PERMISSIONS_REPLACE_ALL); 22483 } 22484 } 22485 22486 @Override 22487 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22488 mContext.enforceCallingOrSelfPermission( 22489 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22490 "Only package verification agents can read the verifier device identity"); 22491 22492 synchronized (mPackages) { 22493 return mSettings.getVerifierDeviceIdentityLPw(); 22494 } 22495 } 22496 22497 @Override 22498 public void setPermissionEnforced(String permission, boolean enforced) { 22499 // TODO: Now that we no longer change GID for storage, this should to away. 22500 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22501 "setPermissionEnforced"); 22502 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22503 synchronized (mPackages) { 22504 if (mSettings.mReadExternalStorageEnforced == null 22505 || mSettings.mReadExternalStorageEnforced != enforced) { 22506 mSettings.mReadExternalStorageEnforced = enforced; 22507 mSettings.writeLPr(); 22508 } 22509 } 22510 // kill any non-foreground processes so we restart them and 22511 // grant/revoke the GID. 22512 final IActivityManager am = ActivityManager.getService(); 22513 if (am != null) { 22514 final long token = Binder.clearCallingIdentity(); 22515 try { 22516 am.killProcessesBelowForeground("setPermissionEnforcement"); 22517 } catch (RemoteException e) { 22518 } finally { 22519 Binder.restoreCallingIdentity(token); 22520 } 22521 } 22522 } else { 22523 throw new IllegalArgumentException("No selective enforcement for " + permission); 22524 } 22525 } 22526 22527 @Override 22528 @Deprecated 22529 public boolean isPermissionEnforced(String permission) { 22530 return true; 22531 } 22532 22533 @Override 22534 public boolean isStorageLow() { 22535 final long token = Binder.clearCallingIdentity(); 22536 try { 22537 final DeviceStorageMonitorInternal 22538 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22539 if (dsm != null) { 22540 return dsm.isMemoryLow(); 22541 } else { 22542 return false; 22543 } 22544 } finally { 22545 Binder.restoreCallingIdentity(token); 22546 } 22547 } 22548 22549 @Override 22550 public IPackageInstaller getPackageInstaller() { 22551 return mInstallerService; 22552 } 22553 22554 private boolean userNeedsBadging(int userId) { 22555 int index = mUserNeedsBadging.indexOfKey(userId); 22556 if (index < 0) { 22557 final UserInfo userInfo; 22558 final long token = Binder.clearCallingIdentity(); 22559 try { 22560 userInfo = sUserManager.getUserInfo(userId); 22561 } finally { 22562 Binder.restoreCallingIdentity(token); 22563 } 22564 final boolean b; 22565 if (userInfo != null && userInfo.isManagedProfile()) { 22566 b = true; 22567 } else { 22568 b = false; 22569 } 22570 mUserNeedsBadging.put(userId, b); 22571 return b; 22572 } 22573 return mUserNeedsBadging.valueAt(index); 22574 } 22575 22576 @Override 22577 public KeySet getKeySetByAlias(String packageName, String alias) { 22578 if (packageName == null || alias == null) { 22579 return null; 22580 } 22581 synchronized(mPackages) { 22582 final PackageParser.Package pkg = mPackages.get(packageName); 22583 if (pkg == null) { 22584 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22585 throw new IllegalArgumentException("Unknown package: " + packageName); 22586 } 22587 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22588 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22589 } 22590 } 22591 22592 @Override 22593 public KeySet getSigningKeySet(String packageName) { 22594 if (packageName == null) { 22595 return null; 22596 } 22597 synchronized(mPackages) { 22598 final PackageParser.Package pkg = mPackages.get(packageName); 22599 if (pkg == null) { 22600 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22601 throw new IllegalArgumentException("Unknown package: " + packageName); 22602 } 22603 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22604 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22605 throw new SecurityException("May not access signing KeySet of other apps."); 22606 } 22607 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22608 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22609 } 22610 } 22611 22612 @Override 22613 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22614 if (packageName == null || ks == null) { 22615 return false; 22616 } 22617 synchronized(mPackages) { 22618 final PackageParser.Package pkg = mPackages.get(packageName); 22619 if (pkg == null) { 22620 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22621 throw new IllegalArgumentException("Unknown package: " + packageName); 22622 } 22623 IBinder ksh = ks.getToken(); 22624 if (ksh instanceof KeySetHandle) { 22625 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22626 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22627 } 22628 return false; 22629 } 22630 } 22631 22632 @Override 22633 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22634 if (packageName == null || ks == null) { 22635 return false; 22636 } 22637 synchronized(mPackages) { 22638 final PackageParser.Package pkg = mPackages.get(packageName); 22639 if (pkg == null) { 22640 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22641 throw new IllegalArgumentException("Unknown package: " + packageName); 22642 } 22643 IBinder ksh = ks.getToken(); 22644 if (ksh instanceof KeySetHandle) { 22645 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22646 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22647 } 22648 return false; 22649 } 22650 } 22651 22652 private void deletePackageIfUnusedLPr(final String packageName) { 22653 PackageSetting ps = mSettings.mPackages.get(packageName); 22654 if (ps == null) { 22655 return; 22656 } 22657 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22658 // TODO Implement atomic delete if package is unused 22659 // It is currently possible that the package will be deleted even if it is installed 22660 // after this method returns. 22661 mHandler.post(new Runnable() { 22662 public void run() { 22663 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22664 0, PackageManager.DELETE_ALL_USERS); 22665 } 22666 }); 22667 } 22668 } 22669 22670 /** 22671 * Check and throw if the given before/after packages would be considered a 22672 * downgrade. 22673 */ 22674 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22675 throws PackageManagerException { 22676 if (after.versionCode < before.mVersionCode) { 22677 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22678 "Update version code " + after.versionCode + " is older than current " 22679 + before.mVersionCode); 22680 } else if (after.versionCode == before.mVersionCode) { 22681 if (after.baseRevisionCode < before.baseRevisionCode) { 22682 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22683 "Update base revision code " + after.baseRevisionCode 22684 + " is older than current " + before.baseRevisionCode); 22685 } 22686 22687 if (!ArrayUtils.isEmpty(after.splitNames)) { 22688 for (int i = 0; i < after.splitNames.length; i++) { 22689 final String splitName = after.splitNames[i]; 22690 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22691 if (j != -1) { 22692 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22693 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22694 "Update split " + splitName + " revision code " 22695 + after.splitRevisionCodes[i] + " is older than current " 22696 + before.splitRevisionCodes[j]); 22697 } 22698 } 22699 } 22700 } 22701 } 22702 } 22703 22704 private static class MoveCallbacks extends Handler { 22705 private static final int MSG_CREATED = 1; 22706 private static final int MSG_STATUS_CHANGED = 2; 22707 22708 private final RemoteCallbackList<IPackageMoveObserver> 22709 mCallbacks = new RemoteCallbackList<>(); 22710 22711 private final SparseIntArray mLastStatus = new SparseIntArray(); 22712 22713 public MoveCallbacks(Looper looper) { 22714 super(looper); 22715 } 22716 22717 public void register(IPackageMoveObserver callback) { 22718 mCallbacks.register(callback); 22719 } 22720 22721 public void unregister(IPackageMoveObserver callback) { 22722 mCallbacks.unregister(callback); 22723 } 22724 22725 @Override 22726 public void handleMessage(Message msg) { 22727 final SomeArgs args = (SomeArgs) msg.obj; 22728 final int n = mCallbacks.beginBroadcast(); 22729 for (int i = 0; i < n; i++) { 22730 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22731 try { 22732 invokeCallback(callback, msg.what, args); 22733 } catch (RemoteException ignored) { 22734 } 22735 } 22736 mCallbacks.finishBroadcast(); 22737 args.recycle(); 22738 } 22739 22740 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22741 throws RemoteException { 22742 switch (what) { 22743 case MSG_CREATED: { 22744 callback.onCreated(args.argi1, (Bundle) args.arg2); 22745 break; 22746 } 22747 case MSG_STATUS_CHANGED: { 22748 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22749 break; 22750 } 22751 } 22752 } 22753 22754 private void notifyCreated(int moveId, Bundle extras) { 22755 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22756 22757 final SomeArgs args = SomeArgs.obtain(); 22758 args.argi1 = moveId; 22759 args.arg2 = extras; 22760 obtainMessage(MSG_CREATED, args).sendToTarget(); 22761 } 22762 22763 private void notifyStatusChanged(int moveId, int status) { 22764 notifyStatusChanged(moveId, status, -1); 22765 } 22766 22767 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22768 Slog.v(TAG, "Move " + moveId + " status " + status); 22769 22770 final SomeArgs args = SomeArgs.obtain(); 22771 args.argi1 = moveId; 22772 args.argi2 = status; 22773 args.arg3 = estMillis; 22774 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22775 22776 synchronized (mLastStatus) { 22777 mLastStatus.put(moveId, status); 22778 } 22779 } 22780 } 22781 22782 private final static class OnPermissionChangeListeners extends Handler { 22783 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22784 22785 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22786 new RemoteCallbackList<>(); 22787 22788 public OnPermissionChangeListeners(Looper looper) { 22789 super(looper); 22790 } 22791 22792 @Override 22793 public void handleMessage(Message msg) { 22794 switch (msg.what) { 22795 case MSG_ON_PERMISSIONS_CHANGED: { 22796 final int uid = msg.arg1; 22797 handleOnPermissionsChanged(uid); 22798 } break; 22799 } 22800 } 22801 22802 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22803 mPermissionListeners.register(listener); 22804 22805 } 22806 22807 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22808 mPermissionListeners.unregister(listener); 22809 } 22810 22811 public void onPermissionsChanged(int uid) { 22812 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22813 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22814 } 22815 } 22816 22817 private void handleOnPermissionsChanged(int uid) { 22818 final int count = mPermissionListeners.beginBroadcast(); 22819 try { 22820 for (int i = 0; i < count; i++) { 22821 IOnPermissionsChangeListener callback = mPermissionListeners 22822 .getBroadcastItem(i); 22823 try { 22824 callback.onPermissionsChanged(uid); 22825 } catch (RemoteException e) { 22826 Log.e(TAG, "Permission listener is dead", e); 22827 } 22828 } 22829 } finally { 22830 mPermissionListeners.finishBroadcast(); 22831 } 22832 } 22833 } 22834 22835 private class PackageManagerInternalImpl extends PackageManagerInternal { 22836 @Override 22837 public void setLocationPackagesProvider(PackagesProvider provider) { 22838 synchronized (mPackages) { 22839 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22840 } 22841 } 22842 22843 @Override 22844 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22845 synchronized (mPackages) { 22846 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22847 } 22848 } 22849 22850 @Override 22851 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22852 synchronized (mPackages) { 22853 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22854 } 22855 } 22856 22857 @Override 22858 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22859 synchronized (mPackages) { 22860 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22861 } 22862 } 22863 22864 @Override 22865 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22866 synchronized (mPackages) { 22867 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22868 } 22869 } 22870 22871 @Override 22872 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22873 synchronized (mPackages) { 22874 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22875 } 22876 } 22877 22878 @Override 22879 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22880 synchronized (mPackages) { 22881 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22882 packageName, userId); 22883 } 22884 } 22885 22886 @Override 22887 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22888 synchronized (mPackages) { 22889 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22890 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22891 packageName, userId); 22892 } 22893 } 22894 22895 @Override 22896 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22897 synchronized (mPackages) { 22898 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22899 packageName, userId); 22900 } 22901 } 22902 22903 @Override 22904 public void setKeepUninstalledPackages(final List<String> packageList) { 22905 Preconditions.checkNotNull(packageList); 22906 List<String> removedFromList = null; 22907 synchronized (mPackages) { 22908 if (mKeepUninstalledPackages != null) { 22909 final int packagesCount = mKeepUninstalledPackages.size(); 22910 for (int i = 0; i < packagesCount; i++) { 22911 String oldPackage = mKeepUninstalledPackages.get(i); 22912 if (packageList != null && packageList.contains(oldPackage)) { 22913 continue; 22914 } 22915 if (removedFromList == null) { 22916 removedFromList = new ArrayList<>(); 22917 } 22918 removedFromList.add(oldPackage); 22919 } 22920 } 22921 mKeepUninstalledPackages = new ArrayList<>(packageList); 22922 if (removedFromList != null) { 22923 final int removedCount = removedFromList.size(); 22924 for (int i = 0; i < removedCount; i++) { 22925 deletePackageIfUnusedLPr(removedFromList.get(i)); 22926 } 22927 } 22928 } 22929 } 22930 22931 @Override 22932 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22933 synchronized (mPackages) { 22934 // If we do not support permission review, done. 22935 if (!mPermissionReviewRequired) { 22936 return false; 22937 } 22938 22939 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22940 if (packageSetting == null) { 22941 return false; 22942 } 22943 22944 // Permission review applies only to apps not supporting the new permission model. 22945 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22946 return false; 22947 } 22948 22949 // Legacy apps have the permission and get user consent on launch. 22950 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22951 return permissionsState.isPermissionReviewRequired(userId); 22952 } 22953 } 22954 22955 @Override 22956 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22957 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22958 } 22959 22960 @Override 22961 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22962 int userId) { 22963 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22964 } 22965 22966 @Override 22967 public void setDeviceAndProfileOwnerPackages( 22968 int deviceOwnerUserId, String deviceOwnerPackage, 22969 SparseArray<String> profileOwnerPackages) { 22970 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22971 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22972 } 22973 22974 @Override 22975 public boolean isPackageDataProtected(int userId, String packageName) { 22976 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22977 } 22978 22979 @Override 22980 public boolean isPackageEphemeral(int userId, String packageName) { 22981 synchronized (mPackages) { 22982 final PackageSetting ps = mSettings.mPackages.get(packageName); 22983 return ps != null ? ps.getInstantApp(userId) : false; 22984 } 22985 } 22986 22987 @Override 22988 public boolean wasPackageEverLaunched(String packageName, int userId) { 22989 synchronized (mPackages) { 22990 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22991 } 22992 } 22993 22994 @Override 22995 public void grantRuntimePermission(String packageName, String name, int userId, 22996 boolean overridePolicy) { 22997 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22998 overridePolicy); 22999 } 23000 23001 @Override 23002 public void revokeRuntimePermission(String packageName, String name, int userId, 23003 boolean overridePolicy) { 23004 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23005 overridePolicy); 23006 } 23007 23008 @Override 23009 public String getNameForUid(int uid) { 23010 return PackageManagerService.this.getNameForUid(uid); 23011 } 23012 23013 @Override 23014 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23015 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23016 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23017 responseObj, origIntent, resolvedType, callingPackage, userId); 23018 } 23019 23020 @Override 23021 public void grantEphemeralAccess(int userId, Intent intent, 23022 int targetAppId, int ephemeralAppId) { 23023 synchronized (mPackages) { 23024 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23025 targetAppId, ephemeralAppId); 23026 } 23027 } 23028 23029 @Override 23030 public void pruneInstantApps() { 23031 synchronized (mPackages) { 23032 mInstantAppRegistry.pruneInstantAppsLPw(); 23033 } 23034 } 23035 23036 @Override 23037 public String getSetupWizardPackageName() { 23038 return mSetupWizardPackage; 23039 } 23040 23041 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23042 if (policy != null) { 23043 mExternalSourcesPolicy = policy; 23044 } 23045 } 23046 23047 @Override 23048 public boolean isPackagePersistent(String packageName) { 23049 synchronized (mPackages) { 23050 PackageParser.Package pkg = mPackages.get(packageName); 23051 return pkg != null 23052 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23053 | ApplicationInfo.FLAG_PERSISTENT)) == 23054 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23055 : false; 23056 } 23057 } 23058 23059 @Override 23060 public List<PackageInfo> getOverlayPackages(int userId) { 23061 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23062 synchronized (mPackages) { 23063 for (PackageParser.Package p : mPackages.values()) { 23064 if (p.mOverlayTarget != null) { 23065 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23066 if (pkg != null) { 23067 overlayPackages.add(pkg); 23068 } 23069 } 23070 } 23071 } 23072 return overlayPackages; 23073 } 23074 23075 @Override 23076 public List<String> getTargetPackageNames(int userId) { 23077 List<String> targetPackages = new ArrayList<>(); 23078 synchronized (mPackages) { 23079 for (PackageParser.Package p : mPackages.values()) { 23080 if (p.mOverlayTarget == null) { 23081 targetPackages.add(p.packageName); 23082 } 23083 } 23084 } 23085 return targetPackages; 23086 } 23087 23088 @Override 23089 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23090 @Nullable List<String> overlayPackageNames) { 23091 synchronized (mPackages) { 23092 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23093 Slog.e(TAG, "failed to find package " + targetPackageName); 23094 return false; 23095 } 23096 23097 ArrayList<String> paths = null; 23098 if (overlayPackageNames != null) { 23099 final int N = overlayPackageNames.size(); 23100 paths = new ArrayList<>(N); 23101 for (int i = 0; i < N; i++) { 23102 final String packageName = overlayPackageNames.get(i); 23103 final PackageParser.Package pkg = mPackages.get(packageName); 23104 if (pkg == null) { 23105 Slog.e(TAG, "failed to find package " + packageName); 23106 return false; 23107 } 23108 paths.add(pkg.baseCodePath); 23109 } 23110 } 23111 23112 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23113 mEnabledOverlayPaths.get(userId); 23114 if (userSpecificOverlays == null) { 23115 userSpecificOverlays = new ArrayMap<>(); 23116 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23117 } 23118 23119 if (paths != null && paths.size() > 0) { 23120 userSpecificOverlays.put(targetPackageName, paths); 23121 } else { 23122 userSpecificOverlays.remove(targetPackageName); 23123 } 23124 return true; 23125 } 23126 } 23127 23128 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23129 int flags, int userId) { 23130 return resolveIntentInternal( 23131 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23132 } 23133 } 23134 23135 @Override 23136 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23137 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23138 synchronized (mPackages) { 23139 final long identity = Binder.clearCallingIdentity(); 23140 try { 23141 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23142 packageNames, userId); 23143 } finally { 23144 Binder.restoreCallingIdentity(identity); 23145 } 23146 } 23147 } 23148 23149 @Override 23150 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23151 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23152 synchronized (mPackages) { 23153 final long identity = Binder.clearCallingIdentity(); 23154 try { 23155 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23156 packageNames, userId); 23157 } finally { 23158 Binder.restoreCallingIdentity(identity); 23159 } 23160 } 23161 } 23162 23163 private static void enforceSystemOrPhoneCaller(String tag) { 23164 int callingUid = Binder.getCallingUid(); 23165 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23166 throw new SecurityException( 23167 "Cannot call " + tag + " from UID " + callingUid); 23168 } 23169 } 23170 23171 boolean isHistoricalPackageUsageAvailable() { 23172 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23173 } 23174 23175 /** 23176 * Return a <b>copy</b> of the collection of packages known to the package manager. 23177 * @return A copy of the values of mPackages. 23178 */ 23179 Collection<PackageParser.Package> getPackages() { 23180 synchronized (mPackages) { 23181 return new ArrayList<>(mPackages.values()); 23182 } 23183 } 23184 23185 /** 23186 * Logs process start information (including base APK hash) to the security log. 23187 * @hide 23188 */ 23189 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23190 String apkFile, int pid) { 23191 if (!SecurityLog.isLoggingEnabled()) { 23192 return; 23193 } 23194 Bundle data = new Bundle(); 23195 data.putLong("startTimestamp", System.currentTimeMillis()); 23196 data.putString("processName", processName); 23197 data.putInt("uid", uid); 23198 data.putString("seinfo", seinfo); 23199 data.putString("apkFile", apkFile); 23200 data.putInt("pid", pid); 23201 Message msg = mProcessLoggingHandler.obtainMessage( 23202 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23203 msg.setData(data); 23204 mProcessLoggingHandler.sendMessage(msg); 23205 } 23206 23207 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23208 return mCompilerStats.getPackageStats(pkgName); 23209 } 23210 23211 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23212 return getOrCreateCompilerPackageStats(pkg.packageName); 23213 } 23214 23215 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23216 return mCompilerStats.getOrCreatePackageStats(pkgName); 23217 } 23218 23219 public void deleteCompilerPackageStats(String pkgName) { 23220 mCompilerStats.deletePackageStats(pkgName); 23221 } 23222 23223 @Override 23224 public int getInstallReason(String packageName, int userId) { 23225 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23226 true /* requireFullPermission */, false /* checkShell */, 23227 "get install reason"); 23228 synchronized (mPackages) { 23229 final PackageSetting ps = mSettings.mPackages.get(packageName); 23230 if (ps != null) { 23231 return ps.getInstallReason(userId); 23232 } 23233 } 23234 return PackageManager.INSTALL_REASON_UNKNOWN; 23235 } 23236 23237 @Override 23238 public boolean canRequestPackageInstalls(String packageName, int userId) { 23239 int callingUid = Binder.getCallingUid(); 23240 int uid = getPackageUid(packageName, 0, userId); 23241 if (callingUid != uid && callingUid != Process.ROOT_UID 23242 && callingUid != Process.SYSTEM_UID) { 23243 throw new SecurityException( 23244 "Caller uid " + callingUid + " does not own package " + packageName); 23245 } 23246 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23247 if (info == null) { 23248 return false; 23249 } 23250 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23251 throw new UnsupportedOperationException( 23252 "Operation only supported on apps targeting Android O or higher"); 23253 } 23254 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23255 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23256 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23257 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23258 } 23259 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23260 return false; 23261 } 23262 if (mExternalSourcesPolicy != null) { 23263 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23264 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23265 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23266 } 23267 } 23268 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23269 } 23270} 23271