PackageManagerService.java revision b21be12d9db5d0d85afa26e401813eaa360bd2e0
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 ActivityInfo mInstantAppInstallerActivity; 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 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2883 if (ephemeralResolverComponent != null) { 2884 if (DEBUG_EPHEMERAL) { 2885 Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent); 2886 } 2887 mInstantAppResolverConnection = 2888 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2889 } else { 2890 mInstantAppResolverConnection = null; 2891 } 2892 updateInstantAppInstallerLocked(); 2893 2894 // Read and update the usage of dex files. 2895 // Do this at the end of PM init so that all the packages have their 2896 // data directory reconciled. 2897 // At this point we know the code paths of the packages, so we can validate 2898 // the disk file and build the internal cache. 2899 // The usage file is expected to be small so loading and verifying it 2900 // should take a fairly small time compare to the other activities (e.g. package 2901 // scanning). 2902 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2903 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2904 for (int userId : currentUserIds) { 2905 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2906 } 2907 mDexManager.load(userPackages); 2908 } // synchronized (mPackages) 2909 } // synchronized (mInstallLock) 2910 2911 // Now after opening every single application zip, make sure they 2912 // are all flushed. Not really needed, but keeps things nice and 2913 // tidy. 2914 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2915 Runtime.getRuntime().gc(); 2916 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2917 2918 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2919 FallbackCategoryProvider.loadFallbacks(); 2920 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2921 2922 // The initial scanning above does many calls into installd while 2923 // holding the mPackages lock, but we're mostly interested in yelling 2924 // once we have a booted system. 2925 mInstaller.setWarnIfHeld(mPackages); 2926 2927 // Expose private service for system components to use. 2928 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2929 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2930 } 2931 2932 private void updateInstantAppInstallerLocked() { 2933 final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent; 2934 final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr(); 2935 ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null 2936 ? null : newInstantAppInstaller.getComponentName(); 2937 2938 if (newInstantAppInstallerComponent != null 2939 && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) { 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent); 2942 } 2943 setUpInstantAppInstallerActivityLP(newInstantAppInstaller); 2944 } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) { 2945 Slog.d(TAG, "Unset ephemeral installer; none available"); 2946 } 2947 mInstantAppInstallerComponent = newInstantAppInstallerComponent; 2948 } 2949 2950 private static File preparePackageParserCache(boolean isUpgrade) { 2951 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2952 return null; 2953 } 2954 2955 // Disable package parsing on eng builds to allow for faster incremental development. 2956 if ("eng".equals(Build.TYPE)) { 2957 return null; 2958 } 2959 2960 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2961 Slog.i(TAG, "Disabling package parser cache due to system property."); 2962 return null; 2963 } 2964 2965 // The base directory for the package parser cache lives under /data/system/. 2966 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2967 "package_cache"); 2968 if (cacheBaseDir == null) { 2969 return null; 2970 } 2971 2972 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2973 // This also serves to "GC" unused entries when the package cache version changes (which 2974 // can only happen during upgrades). 2975 if (isUpgrade) { 2976 FileUtils.deleteContents(cacheBaseDir); 2977 } 2978 2979 2980 // Return the versioned package cache directory. This is something like 2981 // "/data/system/package_cache/1" 2982 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2983 2984 // The following is a workaround to aid development on non-numbered userdebug 2985 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2986 // the system partition is newer. 2987 // 2988 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2989 // that starts with "eng." to signify that this is an engineering build and not 2990 // destined for release. 2991 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2992 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2993 2994 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2995 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2996 // in general and should not be used for production changes. In this specific case, 2997 // we know that they will work. 2998 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2999 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3000 FileUtils.deleteContents(cacheBaseDir); 3001 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3002 } 3003 } 3004 3005 return cacheDir; 3006 } 3007 3008 @Override 3009 public boolean isFirstBoot() { 3010 return mFirstBoot; 3011 } 3012 3013 @Override 3014 public boolean isOnlyCoreApps() { 3015 return mOnlyCore; 3016 } 3017 3018 @Override 3019 public boolean isUpgrade() { 3020 return mIsUpgrade; 3021 } 3022 3023 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3024 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3025 3026 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3027 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3028 UserHandle.USER_SYSTEM); 3029 if (matches.size() == 1) { 3030 return matches.get(0).getComponentInfo().packageName; 3031 } else if (matches.size() == 0) { 3032 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3033 return null; 3034 } 3035 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3036 } 3037 3038 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3039 synchronized (mPackages) { 3040 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3041 if (libraryEntry == null) { 3042 throw new IllegalStateException("Missing required shared library:" + name); 3043 } 3044 return libraryEntry.apk; 3045 } 3046 } 3047 3048 private @NonNull String getRequiredInstallerLPr() { 3049 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3050 intent.addCategory(Intent.CATEGORY_DEFAULT); 3051 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3052 3053 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3054 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3055 UserHandle.USER_SYSTEM); 3056 if (matches.size() == 1) { 3057 ResolveInfo resolveInfo = matches.get(0); 3058 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3059 throw new RuntimeException("The installer must be a privileged app"); 3060 } 3061 return matches.get(0).getComponentInfo().packageName; 3062 } else { 3063 throw new RuntimeException("There must be exactly one installer; found " + matches); 3064 } 3065 } 3066 3067 private @NonNull String getRequiredUninstallerLPr() { 3068 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3069 intent.addCategory(Intent.CATEGORY_DEFAULT); 3070 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3071 3072 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3073 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3074 UserHandle.USER_SYSTEM); 3075 if (resolveInfo == null || 3076 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3077 throw new RuntimeException("There must be exactly one uninstaller; found " 3078 + resolveInfo); 3079 } 3080 return resolveInfo.getComponentInfo().packageName; 3081 } 3082 3083 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3084 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3085 3086 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3087 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3088 UserHandle.USER_SYSTEM); 3089 ResolveInfo best = null; 3090 final int N = matches.size(); 3091 for (int i = 0; i < N; i++) { 3092 final ResolveInfo cur = matches.get(i); 3093 final String packageName = cur.getComponentInfo().packageName; 3094 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3095 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3096 continue; 3097 } 3098 3099 if (best == null || cur.priority > best.priority) { 3100 best = cur; 3101 } 3102 } 3103 3104 if (best != null) { 3105 return best.getComponentInfo().getComponentName(); 3106 } else { 3107 throw new RuntimeException("There must be at least one intent filter verifier"); 3108 } 3109 } 3110 3111 private @Nullable ComponentName getEphemeralResolverLPr() { 3112 final String[] packageArray = 3113 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3114 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3115 if (DEBUG_EPHEMERAL) { 3116 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3117 } 3118 return null; 3119 } 3120 3121 final int resolveFlags = 3122 MATCH_DIRECT_BOOT_AWARE 3123 | MATCH_DIRECT_BOOT_UNAWARE 3124 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3125 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3126 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3127 resolveFlags, UserHandle.USER_SYSTEM); 3128 3129 final int N = resolvers.size(); 3130 if (N == 0) { 3131 if (DEBUG_EPHEMERAL) { 3132 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3133 } 3134 return null; 3135 } 3136 3137 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3138 for (int i = 0; i < N; i++) { 3139 final ResolveInfo info = resolvers.get(i); 3140 3141 if (info.serviceInfo == null) { 3142 continue; 3143 } 3144 3145 final String packageName = info.serviceInfo.packageName; 3146 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3147 if (DEBUG_EPHEMERAL) { 3148 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3149 + " pkg: " + packageName + ", info:" + info); 3150 } 3151 continue; 3152 } 3153 3154 if (DEBUG_EPHEMERAL) { 3155 Slog.v(TAG, "Ephemeral resolver found;" 3156 + " pkg: " + packageName + ", info:" + info); 3157 } 3158 return new ComponentName(packageName, info.serviceInfo.name); 3159 } 3160 if (DEBUG_EPHEMERAL) { 3161 Slog.v(TAG, "Ephemeral resolver NOT found"); 3162 } 3163 return null; 3164 } 3165 3166 private @Nullable ActivityInfo getEphemeralInstallerLPr() { 3167 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3168 intent.addCategory(Intent.CATEGORY_DEFAULT); 3169 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3170 3171 final int resolveFlags = 3172 MATCH_DIRECT_BOOT_AWARE 3173 | MATCH_DIRECT_BOOT_UNAWARE 3174 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3175 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3176 resolveFlags, UserHandle.USER_SYSTEM); 3177 Iterator<ResolveInfo> iter = matches.iterator(); 3178 while (iter.hasNext()) { 3179 final ResolveInfo rInfo = iter.next(); 3180 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3181 if (ps != null) { 3182 final PermissionsState permissionsState = ps.getPermissionsState(); 3183 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3184 continue; 3185 } 3186 } 3187 iter.remove(); 3188 } 3189 if (matches.size() == 0) { 3190 return null; 3191 } else if (matches.size() == 1) { 3192 return (ActivityInfo) matches.get(0).getComponentInfo(); 3193 } else { 3194 throw new RuntimeException( 3195 "There must be at most one ephemeral installer; found " + matches); 3196 } 3197 } 3198 3199 private void primeDomainVerificationsLPw(int userId) { 3200 if (DEBUG_DOMAIN_VERIFICATION) { 3201 Slog.d(TAG, "Priming domain verifications in user " + userId); 3202 } 3203 3204 SystemConfig systemConfig = SystemConfig.getInstance(); 3205 ArraySet<String> packages = systemConfig.getLinkedApps(); 3206 3207 for (String packageName : packages) { 3208 PackageParser.Package pkg = mPackages.get(packageName); 3209 if (pkg != null) { 3210 if (!pkg.isSystemApp()) { 3211 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3212 continue; 3213 } 3214 3215 ArraySet<String> domains = null; 3216 for (PackageParser.Activity a : pkg.activities) { 3217 for (ActivityIntentInfo filter : a.intents) { 3218 if (hasValidDomains(filter)) { 3219 if (domains == null) { 3220 domains = new ArraySet<String>(); 3221 } 3222 domains.addAll(filter.getHostsList()); 3223 } 3224 } 3225 } 3226 3227 if (domains != null && domains.size() > 0) { 3228 if (DEBUG_DOMAIN_VERIFICATION) { 3229 Slog.v(TAG, " + " + packageName); 3230 } 3231 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3232 // state w.r.t. the formal app-linkage "no verification attempted" state; 3233 // and then 'always' in the per-user state actually used for intent resolution. 3234 final IntentFilterVerificationInfo ivi; 3235 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3236 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3237 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3238 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3239 } else { 3240 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3241 + "' does not handle web links"); 3242 } 3243 } else { 3244 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3245 } 3246 } 3247 3248 scheduleWritePackageRestrictionsLocked(userId); 3249 scheduleWriteSettingsLocked(); 3250 } 3251 3252 private void applyFactoryDefaultBrowserLPw(int userId) { 3253 // The default browser app's package name is stored in a string resource, 3254 // with a product-specific overlay used for vendor customization. 3255 String browserPkg = mContext.getResources().getString( 3256 com.android.internal.R.string.default_browser); 3257 if (!TextUtils.isEmpty(browserPkg)) { 3258 // non-empty string => required to be a known package 3259 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3260 if (ps == null) { 3261 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3262 browserPkg = null; 3263 } else { 3264 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3265 } 3266 } 3267 3268 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3269 // default. If there's more than one, just leave everything alone. 3270 if (browserPkg == null) { 3271 calculateDefaultBrowserLPw(userId); 3272 } 3273 } 3274 3275 private void calculateDefaultBrowserLPw(int userId) { 3276 List<String> allBrowsers = resolveAllBrowserApps(userId); 3277 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3278 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3279 } 3280 3281 private List<String> resolveAllBrowserApps(int userId) { 3282 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3283 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3284 PackageManager.MATCH_ALL, userId); 3285 3286 final int count = list.size(); 3287 List<String> result = new ArrayList<String>(count); 3288 for (int i=0; i<count; i++) { 3289 ResolveInfo info = list.get(i); 3290 if (info.activityInfo == null 3291 || !info.handleAllWebDataURI 3292 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3293 || result.contains(info.activityInfo.packageName)) { 3294 continue; 3295 } 3296 result.add(info.activityInfo.packageName); 3297 } 3298 3299 return result; 3300 } 3301 3302 private boolean packageIsBrowser(String packageName, int userId) { 3303 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3304 PackageManager.MATCH_ALL, userId); 3305 final int N = list.size(); 3306 for (int i = 0; i < N; i++) { 3307 ResolveInfo info = list.get(i); 3308 if (packageName.equals(info.activityInfo.packageName)) { 3309 return true; 3310 } 3311 } 3312 return false; 3313 } 3314 3315 private void checkDefaultBrowser() { 3316 final int myUserId = UserHandle.myUserId(); 3317 final String packageName = getDefaultBrowserPackageName(myUserId); 3318 if (packageName != null) { 3319 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3320 if (info == null) { 3321 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3322 synchronized (mPackages) { 3323 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3324 } 3325 } 3326 } 3327 } 3328 3329 @Override 3330 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3331 throws RemoteException { 3332 try { 3333 return super.onTransact(code, data, reply, flags); 3334 } catch (RuntimeException e) { 3335 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3336 Slog.wtf(TAG, "Package Manager Crash", e); 3337 } 3338 throw e; 3339 } 3340 } 3341 3342 static int[] appendInts(int[] cur, int[] add) { 3343 if (add == null) return cur; 3344 if (cur == null) return add; 3345 final int N = add.length; 3346 for (int i=0; i<N; i++) { 3347 cur = appendInt(cur, add[i]); 3348 } 3349 return cur; 3350 } 3351 3352 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3353 if (!sUserManager.exists(userId)) return null; 3354 if (ps == null) { 3355 return null; 3356 } 3357 final PackageParser.Package p = ps.pkg; 3358 if (p == null) { 3359 return null; 3360 } 3361 // Filter out ephemeral app metadata: 3362 // * The system/shell/root can see metadata for any app 3363 // * An installed app can see metadata for 1) other installed apps 3364 // and 2) ephemeral apps that have explicitly interacted with it 3365 // * Ephemeral apps can only see their own data and exposed installed apps 3366 // * Holding a signature permission allows seeing instant apps 3367 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3368 if (callingAppId != Process.SYSTEM_UID 3369 && callingAppId != Process.SHELL_UID 3370 && callingAppId != Process.ROOT_UID 3371 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3372 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3373 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3374 if (instantAppPackageName != null) { 3375 // ephemeral apps can only get information on themselves or 3376 // installed apps that are exposed. 3377 if (!instantAppPackageName.equals(p.packageName) 3378 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3379 return null; 3380 } 3381 } else { 3382 if (ps.getInstantApp(userId)) { 3383 // only get access to the ephemeral app if we've been granted access 3384 if (!mInstantAppRegistry.isInstantAccessGranted( 3385 userId, callingAppId, ps.appId)) { 3386 return null; 3387 } 3388 } 3389 } 3390 } 3391 3392 final PermissionsState permissionsState = ps.getPermissionsState(); 3393 3394 // Compute GIDs only if requested 3395 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3396 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3397 // Compute granted permissions only if package has requested permissions 3398 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3399 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3400 final PackageUserState state = ps.readUserState(userId); 3401 3402 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3403 && ps.isSystem()) { 3404 flags |= MATCH_ANY_USER; 3405 } 3406 3407 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3408 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3409 3410 if (packageInfo == null) { 3411 return null; 3412 } 3413 3414 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3415 3416 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3417 resolveExternalPackageNameLPr(p); 3418 3419 return packageInfo; 3420 } 3421 3422 @Override 3423 public void checkPackageStartable(String packageName, int userId) { 3424 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3425 3426 synchronized (mPackages) { 3427 final PackageSetting ps = mSettings.mPackages.get(packageName); 3428 if (ps == null) { 3429 throw new SecurityException("Package " + packageName + " was not found!"); 3430 } 3431 3432 if (!ps.getInstalled(userId)) { 3433 throw new SecurityException( 3434 "Package " + packageName + " was not installed for user " + userId + "!"); 3435 } 3436 3437 if (mSafeMode && !ps.isSystem()) { 3438 throw new SecurityException("Package " + packageName + " not a system app!"); 3439 } 3440 3441 if (mFrozenPackages.contains(packageName)) { 3442 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3443 } 3444 3445 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3446 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3447 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3448 } 3449 } 3450 } 3451 3452 @Override 3453 public boolean isPackageAvailable(String packageName, int userId) { 3454 if (!sUserManager.exists(userId)) return false; 3455 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3456 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3457 synchronized (mPackages) { 3458 PackageParser.Package p = mPackages.get(packageName); 3459 if (p != null) { 3460 final PackageSetting ps = (PackageSetting) p.mExtras; 3461 if (ps != null) { 3462 final PackageUserState state = ps.readUserState(userId); 3463 if (state != null) { 3464 return PackageParser.isAvailable(state); 3465 } 3466 } 3467 } 3468 } 3469 return false; 3470 } 3471 3472 @Override 3473 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3474 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3475 flags, userId); 3476 } 3477 3478 @Override 3479 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3480 int flags, int userId) { 3481 return getPackageInfoInternal(versionedPackage.getPackageName(), 3482 // TODO: We will change version code to long, so in the new API it is long 3483 (int) versionedPackage.getVersionCode(), flags, userId); 3484 } 3485 3486 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3487 int flags, int userId) { 3488 if (!sUserManager.exists(userId)) return null; 3489 flags = updateFlagsForPackage(flags, userId, packageName); 3490 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3491 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3492 3493 // reader 3494 synchronized (mPackages) { 3495 // Normalize package name to handle renamed packages and static libs 3496 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3497 3498 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3499 if (matchFactoryOnly) { 3500 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3501 if (ps != null) { 3502 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3503 return null; 3504 } 3505 return generatePackageInfo(ps, flags, userId); 3506 } 3507 } 3508 3509 PackageParser.Package p = mPackages.get(packageName); 3510 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3511 return null; 3512 } 3513 if (DEBUG_PACKAGE_INFO) 3514 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3515 if (p != null) { 3516 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3517 Binder.getCallingUid(), userId)) { 3518 return null; 3519 } 3520 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3521 } 3522 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3523 final PackageSetting ps = mSettings.mPackages.get(packageName); 3524 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3525 return null; 3526 } 3527 return generatePackageInfo(ps, flags, userId); 3528 } 3529 } 3530 return null; 3531 } 3532 3533 3534 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3535 // System/shell/root get to see all static libs 3536 final int appId = UserHandle.getAppId(uid); 3537 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3538 || appId == Process.ROOT_UID) { 3539 return false; 3540 } 3541 3542 // No package means no static lib as it is always on internal storage 3543 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3544 return false; 3545 } 3546 3547 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3548 ps.pkg.staticSharedLibVersion); 3549 if (libEntry == null) { 3550 return false; 3551 } 3552 3553 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3554 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3555 if (uidPackageNames == null) { 3556 return true; 3557 } 3558 3559 for (String uidPackageName : uidPackageNames) { 3560 if (ps.name.equals(uidPackageName)) { 3561 return false; 3562 } 3563 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3564 if (uidPs != null) { 3565 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3566 libEntry.info.getName()); 3567 if (index < 0) { 3568 continue; 3569 } 3570 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3571 return false; 3572 } 3573 } 3574 } 3575 return true; 3576 } 3577 3578 @Override 3579 public String[] currentToCanonicalPackageNames(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 PackageSetting ps = mSettings.mPackages.get(names[i]); 3585 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3586 } 3587 } 3588 return out; 3589 } 3590 3591 @Override 3592 public String[] canonicalToCurrentPackageNames(String[] names) { 3593 String[] out = new String[names.length]; 3594 // reader 3595 synchronized (mPackages) { 3596 for (int i=names.length-1; i>=0; i--) { 3597 String cur = mSettings.getRenamedPackageLPr(names[i]); 3598 out[i] = cur != null ? cur : names[i]; 3599 } 3600 } 3601 return out; 3602 } 3603 3604 @Override 3605 public int getPackageUid(String packageName, int flags, int userId) { 3606 if (!sUserManager.exists(userId)) return -1; 3607 flags = updateFlagsForPackage(flags, userId, packageName); 3608 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3609 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3610 3611 // reader 3612 synchronized (mPackages) { 3613 final PackageParser.Package p = mPackages.get(packageName); 3614 if (p != null && p.isMatch(flags)) { 3615 return UserHandle.getUid(userId, p.applicationInfo.uid); 3616 } 3617 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3618 final PackageSetting ps = mSettings.mPackages.get(packageName); 3619 if (ps != null && ps.isMatch(flags)) { 3620 return UserHandle.getUid(userId, ps.appId); 3621 } 3622 } 3623 } 3624 3625 return -1; 3626 } 3627 3628 @Override 3629 public int[] getPackageGids(String packageName, int flags, int userId) { 3630 if (!sUserManager.exists(userId)) return null; 3631 flags = updateFlagsForPackage(flags, userId, packageName); 3632 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3633 false /* requireFullPermission */, false /* checkShell */, 3634 "getPackageGids"); 3635 3636 // reader 3637 synchronized (mPackages) { 3638 final PackageParser.Package p = mPackages.get(packageName); 3639 if (p != null && p.isMatch(flags)) { 3640 PackageSetting ps = (PackageSetting) p.mExtras; 3641 // TODO: Shouldn't this be checking for package installed state for userId and 3642 // return null? 3643 return ps.getPermissionsState().computeGids(userId); 3644 } 3645 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3646 final PackageSetting ps = mSettings.mPackages.get(packageName); 3647 if (ps != null && ps.isMatch(flags)) { 3648 return ps.getPermissionsState().computeGids(userId); 3649 } 3650 } 3651 } 3652 3653 return null; 3654 } 3655 3656 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3657 if (bp.perm != null) { 3658 return PackageParser.generatePermissionInfo(bp.perm, flags); 3659 } 3660 PermissionInfo pi = new PermissionInfo(); 3661 pi.name = bp.name; 3662 pi.packageName = bp.sourcePackage; 3663 pi.nonLocalizedLabel = bp.name; 3664 pi.protectionLevel = bp.protectionLevel; 3665 return pi; 3666 } 3667 3668 @Override 3669 public PermissionInfo getPermissionInfo(String name, int flags) { 3670 // reader 3671 synchronized (mPackages) { 3672 final BasePermission p = mSettings.mPermissions.get(name); 3673 if (p != null) { 3674 return generatePermissionInfo(p, flags); 3675 } 3676 return null; 3677 } 3678 } 3679 3680 @Override 3681 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3682 int flags) { 3683 // reader 3684 synchronized (mPackages) { 3685 if (group != null && !mPermissionGroups.containsKey(group)) { 3686 // This is thrown as NameNotFoundException 3687 return null; 3688 } 3689 3690 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3691 for (BasePermission p : mSettings.mPermissions.values()) { 3692 if (group == null) { 3693 if (p.perm == null || p.perm.info.group == null) { 3694 out.add(generatePermissionInfo(p, flags)); 3695 } 3696 } else { 3697 if (p.perm != null && group.equals(p.perm.info.group)) { 3698 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3699 } 3700 } 3701 } 3702 return new ParceledListSlice<>(out); 3703 } 3704 } 3705 3706 @Override 3707 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3708 // reader 3709 synchronized (mPackages) { 3710 return PackageParser.generatePermissionGroupInfo( 3711 mPermissionGroups.get(name), flags); 3712 } 3713 } 3714 3715 @Override 3716 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3717 // reader 3718 synchronized (mPackages) { 3719 final int N = mPermissionGroups.size(); 3720 ArrayList<PermissionGroupInfo> out 3721 = new ArrayList<PermissionGroupInfo>(N); 3722 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3723 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3724 } 3725 return new ParceledListSlice<>(out); 3726 } 3727 } 3728 3729 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3730 int uid, int userId) { 3731 if (!sUserManager.exists(userId)) return null; 3732 PackageSetting ps = mSettings.mPackages.get(packageName); 3733 if (ps != null) { 3734 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3735 return null; 3736 } 3737 if (ps.pkg == null) { 3738 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3739 if (pInfo != null) { 3740 return pInfo.applicationInfo; 3741 } 3742 return null; 3743 } 3744 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3745 ps.readUserState(userId), userId); 3746 if (ai != null) { 3747 rebaseEnabledOverlays(ai, userId); 3748 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3749 } 3750 return ai; 3751 } 3752 return null; 3753 } 3754 3755 @Override 3756 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3757 if (!sUserManager.exists(userId)) return null; 3758 flags = updateFlagsForApplication(flags, userId, packageName); 3759 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3760 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3761 3762 // writer 3763 synchronized (mPackages) { 3764 // Normalize package name to handle renamed packages and static libs 3765 packageName = resolveInternalPackageNameLPr(packageName, 3766 PackageManager.VERSION_CODE_HIGHEST); 3767 3768 PackageParser.Package p = mPackages.get(packageName); 3769 if (DEBUG_PACKAGE_INFO) Log.v( 3770 TAG, "getApplicationInfo " + packageName 3771 + ": " + p); 3772 if (p != null) { 3773 PackageSetting ps = mSettings.mPackages.get(packageName); 3774 if (ps == null) return null; 3775 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3776 return null; 3777 } 3778 // Note: isEnabledLP() does not apply here - always return info 3779 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3780 p, flags, ps.readUserState(userId), userId); 3781 if (ai != null) { 3782 rebaseEnabledOverlays(ai, userId); 3783 ai.packageName = resolveExternalPackageNameLPr(p); 3784 } 3785 return ai; 3786 } 3787 if ("android".equals(packageName)||"system".equals(packageName)) { 3788 return mAndroidApplication; 3789 } 3790 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3791 // Already generates the external package name 3792 return generateApplicationInfoFromSettingsLPw(packageName, 3793 Binder.getCallingUid(), flags, userId); 3794 } 3795 } 3796 return null; 3797 } 3798 3799 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3800 List<String> paths = new ArrayList<>(); 3801 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3802 mEnabledOverlayPaths.get(userId); 3803 if (userSpecificOverlays != null) { 3804 if (!"android".equals(ai.packageName)) { 3805 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3806 if (frameworkOverlays != null) { 3807 paths.addAll(frameworkOverlays); 3808 } 3809 } 3810 3811 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3812 if (appOverlays != null) { 3813 paths.addAll(appOverlays); 3814 } 3815 } 3816 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3817 } 3818 3819 private String normalizePackageNameLPr(String packageName) { 3820 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3821 return normalizedPackageName != null ? normalizedPackageName : packageName; 3822 } 3823 3824 @Override 3825 public void deletePreloadsFileCache() { 3826 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3827 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3828 } 3829 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3830 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3831 FileUtils.deleteContents(dir); 3832 } 3833 3834 @Override 3835 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3836 final IPackageDataObserver observer) { 3837 mContext.enforceCallingOrSelfPermission( 3838 android.Manifest.permission.CLEAR_APP_CACHE, null); 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 (observer != null) { 3848 try { 3849 observer.onRemoveCompleted(null, success); 3850 } catch (RemoteException e) { 3851 Slog.w(TAG, e); 3852 } 3853 } 3854 }); 3855 } 3856 3857 @Override 3858 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3859 final IntentSender pi) { 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3862 mHandler.post(() -> { 3863 boolean success = false; 3864 try { 3865 freeStorage(volumeUuid, freeStorageSize, 0); 3866 success = true; 3867 } catch (IOException e) { 3868 Slog.w(TAG, e); 3869 } 3870 if (pi != null) { 3871 try { 3872 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3873 } catch (SendIntentException e) { 3874 Slog.w(TAG, e); 3875 } 3876 } 3877 }); 3878 } 3879 3880 /** 3881 * Blocking call to clear various types of cached data across the system 3882 * until the requested bytes are available. 3883 */ 3884 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3885 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3886 final File file = storage.findPathForUuid(volumeUuid); 3887 if (file.getUsableSpace() >= bytes) return; 3888 3889 if (ENABLE_FREE_CACHE_V2) { 3890 final boolean aggressive = (storageFlags 3891 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3892 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3893 volumeUuid); 3894 3895 // 1. Pre-flight to determine if we have any chance to succeed 3896 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3897 if (internalVolume && (aggressive || SystemProperties 3898 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3899 deletePreloadsFileCache(); 3900 if (file.getUsableSpace() >= bytes) return; 3901 } 3902 3903 // 3. Consider parsed APK data (aggressive only) 3904 if (internalVolume && aggressive) { 3905 FileUtils.deleteContents(mCacheDir); 3906 if (file.getUsableSpace() >= bytes) return; 3907 } 3908 3909 // 4. Consider cached app data (above quotas) 3910 try { 3911 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3912 } catch (InstallerException ignored) { 3913 } 3914 if (file.getUsableSpace() >= bytes) return; 3915 3916 // 5. Consider shared libraries with refcount=0 and age>2h 3917 // 6. Consider dexopt output (aggressive only) 3918 // 7. Consider ephemeral apps not used in last week 3919 3920 // 8. Consider cached app data (below quotas) 3921 try { 3922 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3923 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3924 } catch (InstallerException ignored) { 3925 } 3926 if (file.getUsableSpace() >= bytes) return; 3927 3928 // 9. Consider DropBox entries 3929 // 10. Consider ephemeral cookies 3930 3931 } else { 3932 try { 3933 mInstaller.freeCache(volumeUuid, bytes, 0); 3934 } catch (InstallerException ignored) { 3935 } 3936 if (file.getUsableSpace() >= bytes) return; 3937 } 3938 3939 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3940 } 3941 3942 /** 3943 * Update given flags based on encryption status of current user. 3944 */ 3945 private int updateFlags(int flags, int userId) { 3946 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3947 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3948 // Caller expressed an explicit opinion about what encryption 3949 // aware/unaware components they want to see, so fall through and 3950 // give them what they want 3951 } else { 3952 // Caller expressed no opinion, so match based on user state 3953 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3954 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3955 } else { 3956 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3957 } 3958 } 3959 return flags; 3960 } 3961 3962 private UserManagerInternal getUserManagerInternal() { 3963 if (mUserManagerInternal == null) { 3964 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3965 } 3966 return mUserManagerInternal; 3967 } 3968 3969 private DeviceIdleController.LocalService getDeviceIdleController() { 3970 if (mDeviceIdleController == null) { 3971 mDeviceIdleController = 3972 LocalServices.getService(DeviceIdleController.LocalService.class); 3973 } 3974 return mDeviceIdleController; 3975 } 3976 3977 /** 3978 * Update given flags when being used to request {@link PackageInfo}. 3979 */ 3980 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3981 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3982 boolean triaged = true; 3983 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3984 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3985 // Caller is asking for component details, so they'd better be 3986 // asking for specific encryption matching behavior, or be triaged 3987 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3988 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3989 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3990 triaged = false; 3991 } 3992 } 3993 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3994 | PackageManager.MATCH_SYSTEM_ONLY 3995 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3996 triaged = false; 3997 } 3998 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3999 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4000 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4001 + Debug.getCallers(5)); 4002 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4003 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4004 // If the caller wants all packages and has a restricted profile associated with it, 4005 // then match all users. This is to make sure that launchers that need to access work 4006 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4007 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4008 flags |= PackageManager.MATCH_ANY_USER; 4009 } 4010 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4011 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4012 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4013 } 4014 return updateFlags(flags, userId); 4015 } 4016 4017 /** 4018 * Update given flags when being used to request {@link ApplicationInfo}. 4019 */ 4020 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4021 return updateFlagsForPackage(flags, userId, cookie); 4022 } 4023 4024 /** 4025 * Update given flags when being used to request {@link ComponentInfo}. 4026 */ 4027 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4028 if (cookie instanceof Intent) { 4029 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4030 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4031 } 4032 } 4033 4034 boolean triaged = true; 4035 // Caller is asking for component details, so they'd better be 4036 // asking for specific encryption matching behavior, or be triaged 4037 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4038 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4039 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4040 triaged = false; 4041 } 4042 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4043 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4044 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4045 } 4046 4047 return updateFlags(flags, userId); 4048 } 4049 4050 /** 4051 * Update given intent when being used to request {@link ResolveInfo}. 4052 */ 4053 private Intent updateIntentForResolve(Intent intent) { 4054 if (intent.getSelector() != null) { 4055 intent = intent.getSelector(); 4056 } 4057 if (DEBUG_PREFERRED) { 4058 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4059 } 4060 return intent; 4061 } 4062 4063 /** 4064 * Update given flags when being used to request {@link ResolveInfo}. 4065 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4066 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4067 * flag set. However, this flag is only honoured in three circumstances: 4068 * <ul> 4069 * <li>when called from a system process</li> 4070 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4071 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4072 * action and a {@code android.intent.category.BROWSABLE} category</li> 4073 * </ul> 4074 */ 4075 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4076 // Safe mode means we shouldn't match any third-party components 4077 if (mSafeMode) { 4078 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4079 } 4080 final int callingUid = Binder.getCallingUid(); 4081 if (getInstantAppPackageName(callingUid) != null) { 4082 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4083 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4084 flags |= PackageManager.MATCH_INSTANT; 4085 } else { 4086 // Otherwise, prevent leaking ephemeral components 4087 final boolean isSpecialProcess = 4088 callingUid == Process.SYSTEM_UID 4089 || callingUid == Process.SHELL_UID 4090 || callingUid == 0; 4091 final boolean allowMatchInstant = 4092 (includeInstantApp 4093 && Intent.ACTION_VIEW.equals(intent.getAction()) 4094 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4095 && hasWebURI(intent)) 4096 || isSpecialProcess 4097 || mContext.checkCallingOrSelfPermission( 4098 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4099 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4100 if (!allowMatchInstant) { 4101 flags &= ~PackageManager.MATCH_INSTANT; 4102 } 4103 } 4104 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4105 } 4106 4107 @Override 4108 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4109 if (!sUserManager.exists(userId)) return null; 4110 flags = updateFlagsForComponent(flags, userId, component); 4111 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4112 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4113 synchronized (mPackages) { 4114 PackageParser.Activity a = mActivities.mActivities.get(component); 4115 4116 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4117 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4118 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4119 if (ps == null) return null; 4120 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4121 userId); 4122 } 4123 if (mResolveComponentName.equals(component)) { 4124 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4125 new PackageUserState(), userId); 4126 } 4127 } 4128 return null; 4129 } 4130 4131 @Override 4132 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4133 String resolvedType) { 4134 synchronized (mPackages) { 4135 if (component.equals(mResolveComponentName)) { 4136 // The resolver supports EVERYTHING! 4137 return true; 4138 } 4139 PackageParser.Activity a = mActivities.mActivities.get(component); 4140 if (a == null) { 4141 return false; 4142 } 4143 for (int i=0; i<a.intents.size(); i++) { 4144 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4145 intent.getData(), intent.getCategories(), TAG) >= 0) { 4146 return true; 4147 } 4148 } 4149 return false; 4150 } 4151 } 4152 4153 @Override 4154 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4155 if (!sUserManager.exists(userId)) return null; 4156 flags = updateFlagsForComponent(flags, userId, component); 4157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4158 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4159 synchronized (mPackages) { 4160 PackageParser.Activity a = mReceivers.mActivities.get(component); 4161 if (DEBUG_PACKAGE_INFO) Log.v( 4162 TAG, "getReceiverInfo " + component + ": " + a); 4163 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4164 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4165 if (ps == null) return null; 4166 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4167 ps.readUserState(userId), userId); 4168 if (ri != null) { 4169 rebaseEnabledOverlays(ri.applicationInfo, userId); 4170 } 4171 return ri; 4172 } 4173 } 4174 return null; 4175 } 4176 4177 @Override 4178 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4179 if (!sUserManager.exists(userId)) return null; 4180 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4181 4182 flags = updateFlagsForPackage(flags, userId, null); 4183 4184 final boolean canSeeStaticLibraries = 4185 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4186 == PERMISSION_GRANTED 4187 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4188 == PERMISSION_GRANTED 4189 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4190 == PERMISSION_GRANTED 4191 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4192 == PERMISSION_GRANTED; 4193 4194 synchronized (mPackages) { 4195 List<SharedLibraryInfo> result = null; 4196 4197 final int libCount = mSharedLibraries.size(); 4198 for (int i = 0; i < libCount; i++) { 4199 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4200 if (versionedLib == null) { 4201 continue; 4202 } 4203 4204 final int versionCount = versionedLib.size(); 4205 for (int j = 0; j < versionCount; j++) { 4206 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4207 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4208 break; 4209 } 4210 final long identity = Binder.clearCallingIdentity(); 4211 try { 4212 // TODO: We will change version code to long, so in the new API it is long 4213 PackageInfo packageInfo = getPackageInfoVersioned( 4214 libInfo.getDeclaringPackage(), flags, userId); 4215 if (packageInfo == null) { 4216 continue; 4217 } 4218 } finally { 4219 Binder.restoreCallingIdentity(identity); 4220 } 4221 4222 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4223 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4224 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4225 4226 if (result == null) { 4227 result = new ArrayList<>(); 4228 } 4229 result.add(resLibInfo); 4230 } 4231 } 4232 4233 return result != null ? new ParceledListSlice<>(result) : null; 4234 } 4235 } 4236 4237 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4238 SharedLibraryInfo libInfo, int flags, int userId) { 4239 List<VersionedPackage> versionedPackages = null; 4240 final int packageCount = mSettings.mPackages.size(); 4241 for (int i = 0; i < packageCount; i++) { 4242 PackageSetting ps = mSettings.mPackages.valueAt(i); 4243 4244 if (ps == null) { 4245 continue; 4246 } 4247 4248 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4249 continue; 4250 } 4251 4252 final String libName = libInfo.getName(); 4253 if (libInfo.isStatic()) { 4254 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4255 if (libIdx < 0) { 4256 continue; 4257 } 4258 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4259 continue; 4260 } 4261 if (versionedPackages == null) { 4262 versionedPackages = new ArrayList<>(); 4263 } 4264 // If the dependent is a static shared lib, use the public package name 4265 String dependentPackageName = ps.name; 4266 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4267 dependentPackageName = ps.pkg.manifestPackageName; 4268 } 4269 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4270 } else if (ps.pkg != null) { 4271 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4272 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4273 if (versionedPackages == null) { 4274 versionedPackages = new ArrayList<>(); 4275 } 4276 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4277 } 4278 } 4279 } 4280 4281 return versionedPackages; 4282 } 4283 4284 @Override 4285 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4286 if (!sUserManager.exists(userId)) return null; 4287 flags = updateFlagsForComponent(flags, userId, component); 4288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4289 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4290 synchronized (mPackages) { 4291 PackageParser.Service s = mServices.mServices.get(component); 4292 if (DEBUG_PACKAGE_INFO) Log.v( 4293 TAG, "getServiceInfo " + component + ": " + s); 4294 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4295 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4296 if (ps == null) return null; 4297 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4298 ps.readUserState(userId), userId); 4299 if (si != null) { 4300 rebaseEnabledOverlays(si.applicationInfo, userId); 4301 } 4302 return si; 4303 } 4304 } 4305 return null; 4306 } 4307 4308 @Override 4309 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4310 if (!sUserManager.exists(userId)) return null; 4311 flags = updateFlagsForComponent(flags, userId, component); 4312 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4313 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4314 synchronized (mPackages) { 4315 PackageParser.Provider p = mProviders.mProviders.get(component); 4316 if (DEBUG_PACKAGE_INFO) Log.v( 4317 TAG, "getProviderInfo " + component + ": " + p); 4318 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4319 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4320 if (ps == null) return null; 4321 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4322 ps.readUserState(userId), userId); 4323 if (pi != null) { 4324 rebaseEnabledOverlays(pi.applicationInfo, userId); 4325 } 4326 return pi; 4327 } 4328 } 4329 return null; 4330 } 4331 4332 @Override 4333 public String[] getSystemSharedLibraryNames() { 4334 synchronized (mPackages) { 4335 Set<String> libs = null; 4336 final int libCount = mSharedLibraries.size(); 4337 for (int i = 0; i < libCount; i++) { 4338 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4339 if (versionedLib == null) { 4340 continue; 4341 } 4342 final int versionCount = versionedLib.size(); 4343 for (int j = 0; j < versionCount; j++) { 4344 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4345 if (!libEntry.info.isStatic()) { 4346 if (libs == null) { 4347 libs = new ArraySet<>(); 4348 } 4349 libs.add(libEntry.info.getName()); 4350 break; 4351 } 4352 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4353 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4354 UserHandle.getUserId(Binder.getCallingUid()))) { 4355 if (libs == null) { 4356 libs = new ArraySet<>(); 4357 } 4358 libs.add(libEntry.info.getName()); 4359 break; 4360 } 4361 } 4362 } 4363 4364 if (libs != null) { 4365 String[] libsArray = new String[libs.size()]; 4366 libs.toArray(libsArray); 4367 return libsArray; 4368 } 4369 4370 return null; 4371 } 4372 } 4373 4374 @Override 4375 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4376 synchronized (mPackages) { 4377 return mServicesSystemSharedLibraryPackageName; 4378 } 4379 } 4380 4381 @Override 4382 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4383 synchronized (mPackages) { 4384 return mSharedSystemSharedLibraryPackageName; 4385 } 4386 } 4387 4388 private void updateSequenceNumberLP(String packageName, int[] userList) { 4389 for (int i = userList.length - 1; i >= 0; --i) { 4390 final int userId = userList[i]; 4391 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4392 if (changedPackages == null) { 4393 changedPackages = new SparseArray<>(); 4394 mChangedPackages.put(userId, changedPackages); 4395 } 4396 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4397 if (sequenceNumbers == null) { 4398 sequenceNumbers = new HashMap<>(); 4399 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4400 } 4401 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4402 if (sequenceNumber != null) { 4403 changedPackages.remove(sequenceNumber); 4404 } 4405 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4406 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4407 } 4408 mChangedPackagesSequenceNumber++; 4409 } 4410 4411 @Override 4412 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4413 synchronized (mPackages) { 4414 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4415 return null; 4416 } 4417 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4418 if (changedPackages == null) { 4419 return null; 4420 } 4421 final List<String> packageNames = 4422 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4423 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4424 final String packageName = changedPackages.get(i); 4425 if (packageName != null) { 4426 packageNames.add(packageName); 4427 } 4428 } 4429 return packageNames.isEmpty() 4430 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4431 } 4432 } 4433 4434 @Override 4435 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4436 ArrayList<FeatureInfo> res; 4437 synchronized (mAvailableFeatures) { 4438 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4439 res.addAll(mAvailableFeatures.values()); 4440 } 4441 final FeatureInfo fi = new FeatureInfo(); 4442 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4443 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4444 res.add(fi); 4445 4446 return new ParceledListSlice<>(res); 4447 } 4448 4449 @Override 4450 public boolean hasSystemFeature(String name, int version) { 4451 synchronized (mAvailableFeatures) { 4452 final FeatureInfo feat = mAvailableFeatures.get(name); 4453 if (feat == null) { 4454 return false; 4455 } else { 4456 return feat.version >= version; 4457 } 4458 } 4459 } 4460 4461 @Override 4462 public int checkPermission(String permName, String pkgName, int userId) { 4463 if (!sUserManager.exists(userId)) { 4464 return PackageManager.PERMISSION_DENIED; 4465 } 4466 4467 synchronized (mPackages) { 4468 final PackageParser.Package p = mPackages.get(pkgName); 4469 if (p != null && p.mExtras != null) { 4470 final PackageSetting ps = (PackageSetting) p.mExtras; 4471 final PermissionsState permissionsState = ps.getPermissionsState(); 4472 if (permissionsState.hasPermission(permName, userId)) { 4473 return PackageManager.PERMISSION_GRANTED; 4474 } 4475 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4476 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4477 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4478 return PackageManager.PERMISSION_GRANTED; 4479 } 4480 } 4481 } 4482 4483 return PackageManager.PERMISSION_DENIED; 4484 } 4485 4486 @Override 4487 public int checkUidPermission(String permName, int uid) { 4488 final int userId = UserHandle.getUserId(uid); 4489 4490 if (!sUserManager.exists(userId)) { 4491 return PackageManager.PERMISSION_DENIED; 4492 } 4493 4494 synchronized (mPackages) { 4495 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4496 if (obj != null) { 4497 final SettingBase ps = (SettingBase) obj; 4498 final PermissionsState permissionsState = ps.getPermissionsState(); 4499 if (permissionsState.hasPermission(permName, userId)) { 4500 return PackageManager.PERMISSION_GRANTED; 4501 } 4502 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4503 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4504 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4505 return PackageManager.PERMISSION_GRANTED; 4506 } 4507 } else { 4508 ArraySet<String> perms = mSystemPermissions.get(uid); 4509 if (perms != null) { 4510 if (perms.contains(permName)) { 4511 return PackageManager.PERMISSION_GRANTED; 4512 } 4513 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4514 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4515 return PackageManager.PERMISSION_GRANTED; 4516 } 4517 } 4518 } 4519 } 4520 4521 return PackageManager.PERMISSION_DENIED; 4522 } 4523 4524 @Override 4525 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4526 if (UserHandle.getCallingUserId() != userId) { 4527 mContext.enforceCallingPermission( 4528 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4529 "isPermissionRevokedByPolicy for user " + userId); 4530 } 4531 4532 if (checkPermission(permission, packageName, userId) 4533 == PackageManager.PERMISSION_GRANTED) { 4534 return false; 4535 } 4536 4537 final long identity = Binder.clearCallingIdentity(); 4538 try { 4539 final int flags = getPermissionFlags(permission, packageName, userId); 4540 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4541 } finally { 4542 Binder.restoreCallingIdentity(identity); 4543 } 4544 } 4545 4546 @Override 4547 public String getPermissionControllerPackageName() { 4548 synchronized (mPackages) { 4549 return mRequiredInstallerPackage; 4550 } 4551 } 4552 4553 /** 4554 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4555 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4556 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4557 * @param message the message to log on security exception 4558 */ 4559 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4560 boolean checkShell, String message) { 4561 if (userId < 0) { 4562 throw new IllegalArgumentException("Invalid userId " + userId); 4563 } 4564 if (checkShell) { 4565 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4566 } 4567 if (userId == UserHandle.getUserId(callingUid)) return; 4568 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4569 if (requireFullPermission) { 4570 mContext.enforceCallingOrSelfPermission( 4571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4572 } else { 4573 try { 4574 mContext.enforceCallingOrSelfPermission( 4575 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4576 } catch (SecurityException se) { 4577 mContext.enforceCallingOrSelfPermission( 4578 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4579 } 4580 } 4581 } 4582 } 4583 4584 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4585 if (callingUid == Process.SHELL_UID) { 4586 if (userHandle >= 0 4587 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4588 throw new SecurityException("Shell does not have permission to access user " 4589 + userHandle); 4590 } else if (userHandle < 0) { 4591 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4592 + Debug.getCallers(3)); 4593 } 4594 } 4595 } 4596 4597 private BasePermission findPermissionTreeLP(String permName) { 4598 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4599 if (permName.startsWith(bp.name) && 4600 permName.length() > bp.name.length() && 4601 permName.charAt(bp.name.length()) == '.') { 4602 return bp; 4603 } 4604 } 4605 return null; 4606 } 4607 4608 private BasePermission checkPermissionTreeLP(String permName) { 4609 if (permName != null) { 4610 BasePermission bp = findPermissionTreeLP(permName); 4611 if (bp != null) { 4612 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4613 return bp; 4614 } 4615 throw new SecurityException("Calling uid " 4616 + Binder.getCallingUid() 4617 + " is not allowed to add to permission tree " 4618 + bp.name + " owned by uid " + bp.uid); 4619 } 4620 } 4621 throw new SecurityException("No permission tree found for " + permName); 4622 } 4623 4624 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4625 if (s1 == null) { 4626 return s2 == null; 4627 } 4628 if (s2 == null) { 4629 return false; 4630 } 4631 if (s1.getClass() != s2.getClass()) { 4632 return false; 4633 } 4634 return s1.equals(s2); 4635 } 4636 4637 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4638 if (pi1.icon != pi2.icon) return false; 4639 if (pi1.logo != pi2.logo) return false; 4640 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4641 if (!compareStrings(pi1.name, pi2.name)) return false; 4642 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4643 // We'll take care of setting this one. 4644 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4645 // These are not currently stored in settings. 4646 //if (!compareStrings(pi1.group, pi2.group)) return false; 4647 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4648 //if (pi1.labelRes != pi2.labelRes) return false; 4649 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4650 return true; 4651 } 4652 4653 int permissionInfoFootprint(PermissionInfo info) { 4654 int size = info.name.length(); 4655 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4656 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4657 return size; 4658 } 4659 4660 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4661 int size = 0; 4662 for (BasePermission perm : mSettings.mPermissions.values()) { 4663 if (perm.uid == tree.uid) { 4664 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4665 } 4666 } 4667 return size; 4668 } 4669 4670 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4671 // We calculate the max size of permissions defined by this uid and throw 4672 // if that plus the size of 'info' would exceed our stated maximum. 4673 if (tree.uid != Process.SYSTEM_UID) { 4674 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4675 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4676 throw new SecurityException("Permission tree size cap exceeded"); 4677 } 4678 } 4679 } 4680 4681 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4682 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4683 throw new SecurityException("Label must be specified in permission"); 4684 } 4685 BasePermission tree = checkPermissionTreeLP(info.name); 4686 BasePermission bp = mSettings.mPermissions.get(info.name); 4687 boolean added = bp == null; 4688 boolean changed = true; 4689 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4690 if (added) { 4691 enforcePermissionCapLocked(info, tree); 4692 bp = new BasePermission(info.name, tree.sourcePackage, 4693 BasePermission.TYPE_DYNAMIC); 4694 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4695 throw new SecurityException( 4696 "Not allowed to modify non-dynamic permission " 4697 + info.name); 4698 } else { 4699 if (bp.protectionLevel == fixedLevel 4700 && bp.perm.owner.equals(tree.perm.owner) 4701 && bp.uid == tree.uid 4702 && comparePermissionInfos(bp.perm.info, info)) { 4703 changed = false; 4704 } 4705 } 4706 bp.protectionLevel = fixedLevel; 4707 info = new PermissionInfo(info); 4708 info.protectionLevel = fixedLevel; 4709 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4710 bp.perm.info.packageName = tree.perm.info.packageName; 4711 bp.uid = tree.uid; 4712 if (added) { 4713 mSettings.mPermissions.put(info.name, bp); 4714 } 4715 if (changed) { 4716 if (!async) { 4717 mSettings.writeLPr(); 4718 } else { 4719 scheduleWriteSettingsLocked(); 4720 } 4721 } 4722 return added; 4723 } 4724 4725 @Override 4726 public boolean addPermission(PermissionInfo info) { 4727 synchronized (mPackages) { 4728 return addPermissionLocked(info, false); 4729 } 4730 } 4731 4732 @Override 4733 public boolean addPermissionAsync(PermissionInfo info) { 4734 synchronized (mPackages) { 4735 return addPermissionLocked(info, true); 4736 } 4737 } 4738 4739 @Override 4740 public void removePermission(String name) { 4741 synchronized (mPackages) { 4742 checkPermissionTreeLP(name); 4743 BasePermission bp = mSettings.mPermissions.get(name); 4744 if (bp != null) { 4745 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4746 throw new SecurityException( 4747 "Not allowed to modify non-dynamic permission " 4748 + name); 4749 } 4750 mSettings.mPermissions.remove(name); 4751 mSettings.writeLPr(); 4752 } 4753 } 4754 } 4755 4756 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4757 BasePermission bp) { 4758 int index = pkg.requestedPermissions.indexOf(bp.name); 4759 if (index == -1) { 4760 throw new SecurityException("Package " + pkg.packageName 4761 + " has not requested permission " + bp.name); 4762 } 4763 if (!bp.isRuntime() && !bp.isDevelopment()) { 4764 throw new SecurityException("Permission " + bp.name 4765 + " is not a changeable permission type"); 4766 } 4767 } 4768 4769 @Override 4770 public void grantRuntimePermission(String packageName, String name, final int userId) { 4771 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4772 } 4773 4774 private void grantRuntimePermission(String packageName, String name, final int userId, 4775 boolean overridePolicy) { 4776 if (!sUserManager.exists(userId)) { 4777 Log.e(TAG, "No such user:" + userId); 4778 return; 4779 } 4780 4781 mContext.enforceCallingOrSelfPermission( 4782 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4783 "grantRuntimePermission"); 4784 4785 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4786 true /* requireFullPermission */, true /* checkShell */, 4787 "grantRuntimePermission"); 4788 4789 final int uid; 4790 final SettingBase sb; 4791 4792 synchronized (mPackages) { 4793 final PackageParser.Package pkg = mPackages.get(packageName); 4794 if (pkg == null) { 4795 throw new IllegalArgumentException("Unknown package: " + packageName); 4796 } 4797 4798 final BasePermission bp = mSettings.mPermissions.get(name); 4799 if (bp == null) { 4800 throw new IllegalArgumentException("Unknown permission: " + name); 4801 } 4802 4803 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4804 4805 // If a permission review is required for legacy apps we represent 4806 // their permissions as always granted runtime ones since we need 4807 // to keep the review required permission flag per user while an 4808 // install permission's state is shared across all users. 4809 if (mPermissionReviewRequired 4810 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4811 && bp.isRuntime()) { 4812 return; 4813 } 4814 4815 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4816 sb = (SettingBase) pkg.mExtras; 4817 if (sb == null) { 4818 throw new IllegalArgumentException("Unknown package: " + packageName); 4819 } 4820 4821 final PermissionsState permissionsState = sb.getPermissionsState(); 4822 4823 final int flags = permissionsState.getPermissionFlags(name, userId); 4824 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4825 throw new SecurityException("Cannot grant system fixed permission " 4826 + name + " for package " + packageName); 4827 } 4828 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4829 throw new SecurityException("Cannot grant policy fixed permission " 4830 + name + " for package " + packageName); 4831 } 4832 4833 if (bp.isDevelopment()) { 4834 // Development permissions must be handled specially, since they are not 4835 // normal runtime permissions. For now they apply to all users. 4836 if (permissionsState.grantInstallPermission(bp) != 4837 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4838 scheduleWriteSettingsLocked(); 4839 } 4840 return; 4841 } 4842 4843 final PackageSetting ps = mSettings.mPackages.get(packageName); 4844 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4845 throw new SecurityException("Cannot grant non-ephemeral permission" 4846 + name + " for package " + packageName); 4847 } 4848 4849 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4850 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4851 return; 4852 } 4853 4854 final int result = permissionsState.grantRuntimePermission(bp, userId); 4855 switch (result) { 4856 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4857 return; 4858 } 4859 4860 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4861 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4862 mHandler.post(new Runnable() { 4863 @Override 4864 public void run() { 4865 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4866 } 4867 }); 4868 } 4869 break; 4870 } 4871 4872 if (bp.isRuntime()) { 4873 logPermissionGranted(mContext, name, packageName); 4874 } 4875 4876 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4877 4878 // Not critical if that is lost - app has to request again. 4879 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4880 } 4881 4882 // Only need to do this if user is initialized. Otherwise it's a new user 4883 // and there are no processes running as the user yet and there's no need 4884 // to make an expensive call to remount processes for the changed permissions. 4885 if (READ_EXTERNAL_STORAGE.equals(name) 4886 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4887 final long token = Binder.clearCallingIdentity(); 4888 try { 4889 if (sUserManager.isInitialized(userId)) { 4890 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4891 StorageManagerInternal.class); 4892 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4893 } 4894 } finally { 4895 Binder.restoreCallingIdentity(token); 4896 } 4897 } 4898 } 4899 4900 @Override 4901 public void revokeRuntimePermission(String packageName, String name, int userId) { 4902 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4903 } 4904 4905 private void revokeRuntimePermission(String packageName, String name, int userId, 4906 boolean overridePolicy) { 4907 if (!sUserManager.exists(userId)) { 4908 Log.e(TAG, "No such user:" + userId); 4909 return; 4910 } 4911 4912 mContext.enforceCallingOrSelfPermission( 4913 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4914 "revokeRuntimePermission"); 4915 4916 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4917 true /* requireFullPermission */, true /* checkShell */, 4918 "revokeRuntimePermission"); 4919 4920 final int appId; 4921 4922 synchronized (mPackages) { 4923 final PackageParser.Package pkg = mPackages.get(packageName); 4924 if (pkg == null) { 4925 throw new IllegalArgumentException("Unknown package: " + packageName); 4926 } 4927 4928 final BasePermission bp = mSettings.mPermissions.get(name); 4929 if (bp == null) { 4930 throw new IllegalArgumentException("Unknown permission: " + name); 4931 } 4932 4933 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4934 4935 // If a permission review is required for legacy apps we represent 4936 // their permissions as always granted runtime ones since we need 4937 // to keep the review required permission flag per user while an 4938 // install permission's state is shared across all users. 4939 if (mPermissionReviewRequired 4940 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4941 && bp.isRuntime()) { 4942 return; 4943 } 4944 4945 SettingBase sb = (SettingBase) pkg.mExtras; 4946 if (sb == null) { 4947 throw new IllegalArgumentException("Unknown package: " + packageName); 4948 } 4949 4950 final PermissionsState permissionsState = sb.getPermissionsState(); 4951 4952 final int flags = permissionsState.getPermissionFlags(name, userId); 4953 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4954 throw new SecurityException("Cannot revoke system fixed permission " 4955 + name + " for package " + packageName); 4956 } 4957 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4958 throw new SecurityException("Cannot revoke policy fixed permission " 4959 + name + " for package " + packageName); 4960 } 4961 4962 if (bp.isDevelopment()) { 4963 // Development permissions must be handled specially, since they are not 4964 // normal runtime permissions. For now they apply to all users. 4965 if (permissionsState.revokeInstallPermission(bp) != 4966 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4967 scheduleWriteSettingsLocked(); 4968 } 4969 return; 4970 } 4971 4972 if (permissionsState.revokeRuntimePermission(bp, userId) == 4973 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4974 return; 4975 } 4976 4977 if (bp.isRuntime()) { 4978 logPermissionRevoked(mContext, name, packageName); 4979 } 4980 4981 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4982 4983 // Critical, after this call app should never have the permission. 4984 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4985 4986 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4987 } 4988 4989 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4990 } 4991 4992 /** 4993 * Get the first event id for the permission. 4994 * 4995 * <p>There are four events for each permission: <ul> 4996 * <li>Request permission: first id + 0</li> 4997 * <li>Grant permission: first id + 1</li> 4998 * <li>Request for permission denied: first id + 2</li> 4999 * <li>Revoke permission: first id + 3</li> 5000 * </ul></p> 5001 * 5002 * @param name name of the permission 5003 * 5004 * @return The first event id for the permission 5005 */ 5006 private static int getBaseEventId(@NonNull String name) { 5007 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5008 5009 if (eventIdIndex == -1) { 5010 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5011 || "user".equals(Build.TYPE)) { 5012 Log.i(TAG, "Unknown permission " + name); 5013 5014 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5015 } else { 5016 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5017 // 5018 // Also update 5019 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5020 // - metrics_constants.proto 5021 throw new IllegalStateException("Unknown permission " + name); 5022 } 5023 } 5024 5025 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5026 } 5027 5028 /** 5029 * Log that a permission was revoked. 5030 * 5031 * @param context Context of the caller 5032 * @param name name of the permission 5033 * @param packageName package permission if for 5034 */ 5035 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5036 @NonNull String packageName) { 5037 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5038 } 5039 5040 /** 5041 * Log that a permission request was granted. 5042 * 5043 * @param context Context of the caller 5044 * @param name name of the permission 5045 * @param packageName package permission if for 5046 */ 5047 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5048 @NonNull String packageName) { 5049 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5050 } 5051 5052 @Override 5053 public void resetRuntimePermissions() { 5054 mContext.enforceCallingOrSelfPermission( 5055 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5056 "revokeRuntimePermission"); 5057 5058 int callingUid = Binder.getCallingUid(); 5059 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5060 mContext.enforceCallingOrSelfPermission( 5061 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5062 "resetRuntimePermissions"); 5063 } 5064 5065 synchronized (mPackages) { 5066 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5067 for (int userId : UserManagerService.getInstance().getUserIds()) { 5068 final int packageCount = mPackages.size(); 5069 for (int i = 0; i < packageCount; i++) { 5070 PackageParser.Package pkg = mPackages.valueAt(i); 5071 if (!(pkg.mExtras instanceof PackageSetting)) { 5072 continue; 5073 } 5074 PackageSetting ps = (PackageSetting) pkg.mExtras; 5075 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5076 } 5077 } 5078 } 5079 } 5080 5081 @Override 5082 public int getPermissionFlags(String name, String packageName, int userId) { 5083 if (!sUserManager.exists(userId)) { 5084 return 0; 5085 } 5086 5087 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5088 5089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5090 true /* requireFullPermission */, false /* checkShell */, 5091 "getPermissionFlags"); 5092 5093 synchronized (mPackages) { 5094 final PackageParser.Package pkg = mPackages.get(packageName); 5095 if (pkg == null) { 5096 return 0; 5097 } 5098 5099 final BasePermission bp = mSettings.mPermissions.get(name); 5100 if (bp == null) { 5101 return 0; 5102 } 5103 5104 SettingBase sb = (SettingBase) pkg.mExtras; 5105 if (sb == null) { 5106 return 0; 5107 } 5108 5109 PermissionsState permissionsState = sb.getPermissionsState(); 5110 return permissionsState.getPermissionFlags(name, userId); 5111 } 5112 } 5113 5114 @Override 5115 public void updatePermissionFlags(String name, String packageName, int flagMask, 5116 int flagValues, int userId) { 5117 if (!sUserManager.exists(userId)) { 5118 return; 5119 } 5120 5121 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5122 5123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5124 true /* requireFullPermission */, true /* checkShell */, 5125 "updatePermissionFlags"); 5126 5127 // Only the system can change these flags and nothing else. 5128 if (getCallingUid() != Process.SYSTEM_UID) { 5129 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5130 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5131 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5132 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5133 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5134 } 5135 5136 synchronized (mPackages) { 5137 final PackageParser.Package pkg = mPackages.get(packageName); 5138 if (pkg == null) { 5139 throw new IllegalArgumentException("Unknown package: " + packageName); 5140 } 5141 5142 final BasePermission bp = mSettings.mPermissions.get(name); 5143 if (bp == null) { 5144 throw new IllegalArgumentException("Unknown permission: " + name); 5145 } 5146 5147 SettingBase sb = (SettingBase) pkg.mExtras; 5148 if (sb == null) { 5149 throw new IllegalArgumentException("Unknown package: " + packageName); 5150 } 5151 5152 PermissionsState permissionsState = sb.getPermissionsState(); 5153 5154 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5155 5156 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5157 // Install and runtime permissions are stored in different places, 5158 // so figure out what permission changed and persist the change. 5159 if (permissionsState.getInstallPermissionState(name) != null) { 5160 scheduleWriteSettingsLocked(); 5161 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5162 || hadState) { 5163 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5164 } 5165 } 5166 } 5167 } 5168 5169 /** 5170 * Update the permission flags for all packages and runtime permissions of a user in order 5171 * to allow device or profile owner to remove POLICY_FIXED. 5172 */ 5173 @Override 5174 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5175 if (!sUserManager.exists(userId)) { 5176 return; 5177 } 5178 5179 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5180 5181 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5182 true /* requireFullPermission */, true /* checkShell */, 5183 "updatePermissionFlagsForAllApps"); 5184 5185 // Only the system can change system fixed flags. 5186 if (getCallingUid() != Process.SYSTEM_UID) { 5187 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5188 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5189 } 5190 5191 synchronized (mPackages) { 5192 boolean changed = false; 5193 final int packageCount = mPackages.size(); 5194 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5195 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5196 SettingBase sb = (SettingBase) pkg.mExtras; 5197 if (sb == null) { 5198 continue; 5199 } 5200 PermissionsState permissionsState = sb.getPermissionsState(); 5201 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5202 userId, flagMask, flagValues); 5203 } 5204 if (changed) { 5205 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5206 } 5207 } 5208 } 5209 5210 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5211 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5212 != PackageManager.PERMISSION_GRANTED 5213 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5214 != PackageManager.PERMISSION_GRANTED) { 5215 throw new SecurityException(message + " requires " 5216 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5217 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5218 } 5219 } 5220 5221 @Override 5222 public boolean shouldShowRequestPermissionRationale(String permissionName, 5223 String packageName, int userId) { 5224 if (UserHandle.getCallingUserId() != userId) { 5225 mContext.enforceCallingPermission( 5226 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5227 "canShowRequestPermissionRationale for user " + userId); 5228 } 5229 5230 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5231 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5232 return false; 5233 } 5234 5235 if (checkPermission(permissionName, packageName, userId) 5236 == PackageManager.PERMISSION_GRANTED) { 5237 return false; 5238 } 5239 5240 final int flags; 5241 5242 final long identity = Binder.clearCallingIdentity(); 5243 try { 5244 flags = getPermissionFlags(permissionName, 5245 packageName, userId); 5246 } finally { 5247 Binder.restoreCallingIdentity(identity); 5248 } 5249 5250 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5251 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5252 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5253 5254 if ((flags & fixedFlags) != 0) { 5255 return false; 5256 } 5257 5258 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5259 } 5260 5261 @Override 5262 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5263 mContext.enforceCallingOrSelfPermission( 5264 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5265 "addOnPermissionsChangeListener"); 5266 5267 synchronized (mPackages) { 5268 mOnPermissionChangeListeners.addListenerLocked(listener); 5269 } 5270 } 5271 5272 @Override 5273 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5274 synchronized (mPackages) { 5275 mOnPermissionChangeListeners.removeListenerLocked(listener); 5276 } 5277 } 5278 5279 @Override 5280 public boolean isProtectedBroadcast(String actionName) { 5281 synchronized (mPackages) { 5282 if (mProtectedBroadcasts.contains(actionName)) { 5283 return true; 5284 } else if (actionName != null) { 5285 // TODO: remove these terrible hacks 5286 if (actionName.startsWith("android.net.netmon.lingerExpired") 5287 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5288 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5289 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5290 return true; 5291 } 5292 } 5293 } 5294 return false; 5295 } 5296 5297 @Override 5298 public int checkSignatures(String pkg1, String pkg2) { 5299 synchronized (mPackages) { 5300 final PackageParser.Package p1 = mPackages.get(pkg1); 5301 final PackageParser.Package p2 = mPackages.get(pkg2); 5302 if (p1 == null || p1.mExtras == null 5303 || p2 == null || p2.mExtras == null) { 5304 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5305 } 5306 return compareSignatures(p1.mSignatures, p2.mSignatures); 5307 } 5308 } 5309 5310 @Override 5311 public int checkUidSignatures(int uid1, int uid2) { 5312 // Map to base uids. 5313 uid1 = UserHandle.getAppId(uid1); 5314 uid2 = UserHandle.getAppId(uid2); 5315 // reader 5316 synchronized (mPackages) { 5317 Signature[] s1; 5318 Signature[] s2; 5319 Object obj = mSettings.getUserIdLPr(uid1); 5320 if (obj != null) { 5321 if (obj instanceof SharedUserSetting) { 5322 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5323 } else if (obj instanceof PackageSetting) { 5324 s1 = ((PackageSetting)obj).signatures.mSignatures; 5325 } else { 5326 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5327 } 5328 } else { 5329 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5330 } 5331 obj = mSettings.getUserIdLPr(uid2); 5332 if (obj != null) { 5333 if (obj instanceof SharedUserSetting) { 5334 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5335 } else if (obj instanceof PackageSetting) { 5336 s2 = ((PackageSetting)obj).signatures.mSignatures; 5337 } else { 5338 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5339 } 5340 } else { 5341 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5342 } 5343 return compareSignatures(s1, s2); 5344 } 5345 } 5346 5347 /** 5348 * This method should typically only be used when granting or revoking 5349 * permissions, since the app may immediately restart after this call. 5350 * <p> 5351 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5352 * guard your work against the app being relaunched. 5353 */ 5354 private void killUid(int appId, int userId, String reason) { 5355 final long identity = Binder.clearCallingIdentity(); 5356 try { 5357 IActivityManager am = ActivityManager.getService(); 5358 if (am != null) { 5359 try { 5360 am.killUid(appId, userId, reason); 5361 } catch (RemoteException e) { 5362 /* ignore - same process */ 5363 } 5364 } 5365 } finally { 5366 Binder.restoreCallingIdentity(identity); 5367 } 5368 } 5369 5370 /** 5371 * Compares two sets of signatures. Returns: 5372 * <br /> 5373 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5374 * <br /> 5375 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5376 * <br /> 5377 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5378 * <br /> 5379 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5380 * <br /> 5381 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5382 */ 5383 static int compareSignatures(Signature[] s1, Signature[] s2) { 5384 if (s1 == null) { 5385 return s2 == null 5386 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5387 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5388 } 5389 5390 if (s2 == null) { 5391 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5392 } 5393 5394 if (s1.length != s2.length) { 5395 return PackageManager.SIGNATURE_NO_MATCH; 5396 } 5397 5398 // Since both signature sets are of size 1, we can compare without HashSets. 5399 if (s1.length == 1) { 5400 return s1[0].equals(s2[0]) ? 5401 PackageManager.SIGNATURE_MATCH : 5402 PackageManager.SIGNATURE_NO_MATCH; 5403 } 5404 5405 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5406 for (Signature sig : s1) { 5407 set1.add(sig); 5408 } 5409 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5410 for (Signature sig : s2) { 5411 set2.add(sig); 5412 } 5413 // Make sure s2 contains all signatures in s1. 5414 if (set1.equals(set2)) { 5415 return PackageManager.SIGNATURE_MATCH; 5416 } 5417 return PackageManager.SIGNATURE_NO_MATCH; 5418 } 5419 5420 /** 5421 * If the database version for this type of package (internal storage or 5422 * external storage) is less than the version where package signatures 5423 * were updated, return true. 5424 */ 5425 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5426 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5427 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5428 } 5429 5430 /** 5431 * Used for backward compatibility to make sure any packages with 5432 * certificate chains get upgraded to the new style. {@code existingSigs} 5433 * will be in the old format (since they were stored on disk from before the 5434 * system upgrade) and {@code scannedSigs} will be in the newer format. 5435 */ 5436 private int compareSignaturesCompat(PackageSignatures existingSigs, 5437 PackageParser.Package scannedPkg) { 5438 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5439 return PackageManager.SIGNATURE_NO_MATCH; 5440 } 5441 5442 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5443 for (Signature sig : existingSigs.mSignatures) { 5444 existingSet.add(sig); 5445 } 5446 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5447 for (Signature sig : scannedPkg.mSignatures) { 5448 try { 5449 Signature[] chainSignatures = sig.getChainSignatures(); 5450 for (Signature chainSig : chainSignatures) { 5451 scannedCompatSet.add(chainSig); 5452 } 5453 } catch (CertificateEncodingException e) { 5454 scannedCompatSet.add(sig); 5455 } 5456 } 5457 /* 5458 * Make sure the expanded scanned set contains all signatures in the 5459 * existing one. 5460 */ 5461 if (scannedCompatSet.equals(existingSet)) { 5462 // Migrate the old signatures to the new scheme. 5463 existingSigs.assignSignatures(scannedPkg.mSignatures); 5464 // The new KeySets will be re-added later in the scanning process. 5465 synchronized (mPackages) { 5466 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5467 } 5468 return PackageManager.SIGNATURE_MATCH; 5469 } 5470 return PackageManager.SIGNATURE_NO_MATCH; 5471 } 5472 5473 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5474 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5475 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5476 } 5477 5478 private int compareSignaturesRecover(PackageSignatures existingSigs, 5479 PackageParser.Package scannedPkg) { 5480 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5481 return PackageManager.SIGNATURE_NO_MATCH; 5482 } 5483 5484 String msg = null; 5485 try { 5486 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5487 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5488 + scannedPkg.packageName); 5489 return PackageManager.SIGNATURE_MATCH; 5490 } 5491 } catch (CertificateException e) { 5492 msg = e.getMessage(); 5493 } 5494 5495 logCriticalInfo(Log.INFO, 5496 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5497 return PackageManager.SIGNATURE_NO_MATCH; 5498 } 5499 5500 @Override 5501 public List<String> getAllPackages() { 5502 synchronized (mPackages) { 5503 return new ArrayList<String>(mPackages.keySet()); 5504 } 5505 } 5506 5507 @Override 5508 public String[] getPackagesForUid(int uid) { 5509 final int userId = UserHandle.getUserId(uid); 5510 uid = UserHandle.getAppId(uid); 5511 // reader 5512 synchronized (mPackages) { 5513 Object obj = mSettings.getUserIdLPr(uid); 5514 if (obj instanceof SharedUserSetting) { 5515 final SharedUserSetting sus = (SharedUserSetting) obj; 5516 final int N = sus.packages.size(); 5517 String[] res = new String[N]; 5518 final Iterator<PackageSetting> it = sus.packages.iterator(); 5519 int i = 0; 5520 while (it.hasNext()) { 5521 PackageSetting ps = it.next(); 5522 if (ps.getInstalled(userId)) { 5523 res[i++] = ps.name; 5524 } else { 5525 res = ArrayUtils.removeElement(String.class, res, res[i]); 5526 } 5527 } 5528 return res; 5529 } else if (obj instanceof PackageSetting) { 5530 final PackageSetting ps = (PackageSetting) obj; 5531 if (ps.getInstalled(userId)) { 5532 return new String[]{ps.name}; 5533 } 5534 } 5535 } 5536 return null; 5537 } 5538 5539 @Override 5540 public String getNameForUid(int uid) { 5541 // reader 5542 synchronized (mPackages) { 5543 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5544 if (obj instanceof SharedUserSetting) { 5545 final SharedUserSetting sus = (SharedUserSetting) obj; 5546 return sus.name + ":" + sus.userId; 5547 } else if (obj instanceof PackageSetting) { 5548 final PackageSetting ps = (PackageSetting) obj; 5549 return ps.name; 5550 } 5551 } 5552 return null; 5553 } 5554 5555 @Override 5556 public int getUidForSharedUser(String sharedUserName) { 5557 if(sharedUserName == null) { 5558 return -1; 5559 } 5560 // reader 5561 synchronized (mPackages) { 5562 SharedUserSetting suid; 5563 try { 5564 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5565 if (suid != null) { 5566 return suid.userId; 5567 } 5568 } catch (PackageManagerException ignore) { 5569 // can't happen, but, still need to catch it 5570 } 5571 return -1; 5572 } 5573 } 5574 5575 @Override 5576 public int getFlagsForUid(int uid) { 5577 synchronized (mPackages) { 5578 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5579 if (obj instanceof SharedUserSetting) { 5580 final SharedUserSetting sus = (SharedUserSetting) obj; 5581 return sus.pkgFlags; 5582 } else if (obj instanceof PackageSetting) { 5583 final PackageSetting ps = (PackageSetting) obj; 5584 return ps.pkgFlags; 5585 } 5586 } 5587 return 0; 5588 } 5589 5590 @Override 5591 public int getPrivateFlagsForUid(int uid) { 5592 synchronized (mPackages) { 5593 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5594 if (obj instanceof SharedUserSetting) { 5595 final SharedUserSetting sus = (SharedUserSetting) obj; 5596 return sus.pkgPrivateFlags; 5597 } else if (obj instanceof PackageSetting) { 5598 final PackageSetting ps = (PackageSetting) obj; 5599 return ps.pkgPrivateFlags; 5600 } 5601 } 5602 return 0; 5603 } 5604 5605 @Override 5606 public boolean isUidPrivileged(int uid) { 5607 uid = UserHandle.getAppId(uid); 5608 // reader 5609 synchronized (mPackages) { 5610 Object obj = mSettings.getUserIdLPr(uid); 5611 if (obj instanceof SharedUserSetting) { 5612 final SharedUserSetting sus = (SharedUserSetting) obj; 5613 final Iterator<PackageSetting> it = sus.packages.iterator(); 5614 while (it.hasNext()) { 5615 if (it.next().isPrivileged()) { 5616 return true; 5617 } 5618 } 5619 } else if (obj instanceof PackageSetting) { 5620 final PackageSetting ps = (PackageSetting) obj; 5621 return ps.isPrivileged(); 5622 } 5623 } 5624 return false; 5625 } 5626 5627 @Override 5628 public String[] getAppOpPermissionPackages(String permissionName) { 5629 synchronized (mPackages) { 5630 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5631 if (pkgs == null) { 5632 return null; 5633 } 5634 return pkgs.toArray(new String[pkgs.size()]); 5635 } 5636 } 5637 5638 @Override 5639 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5640 int flags, int userId) { 5641 return resolveIntentInternal( 5642 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5643 } 5644 5645 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5646 int flags, int userId, boolean includeInstantApp) { 5647 try { 5648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5649 5650 if (!sUserManager.exists(userId)) return null; 5651 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5652 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5653 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5654 5655 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5656 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5657 flags, userId, includeInstantApp); 5658 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5659 5660 final ResolveInfo bestChoice = 5661 chooseBestActivity(intent, resolvedType, flags, query, userId); 5662 return bestChoice; 5663 } finally { 5664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5665 } 5666 } 5667 5668 @Override 5669 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5670 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5671 throw new SecurityException( 5672 "findPersistentPreferredActivity can only be run by the system"); 5673 } 5674 if (!sUserManager.exists(userId)) { 5675 return null; 5676 } 5677 intent = updateIntentForResolve(intent); 5678 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5679 final int flags = updateFlagsForResolve(0, userId, intent, false); 5680 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5681 userId); 5682 synchronized (mPackages) { 5683 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5684 userId); 5685 } 5686 } 5687 5688 @Override 5689 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5690 IntentFilter filter, int match, ComponentName activity) { 5691 final int userId = UserHandle.getCallingUserId(); 5692 if (DEBUG_PREFERRED) { 5693 Log.v(TAG, "setLastChosenActivity intent=" + intent 5694 + " resolvedType=" + resolvedType 5695 + " flags=" + flags 5696 + " filter=" + filter 5697 + " match=" + match 5698 + " activity=" + activity); 5699 filter.dump(new PrintStreamPrinter(System.out), " "); 5700 } 5701 intent.setComponent(null); 5702 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5703 userId); 5704 // Find any earlier preferred or last chosen entries and nuke them 5705 findPreferredActivity(intent, resolvedType, 5706 flags, query, 0, false, true, false, userId); 5707 // Add the new activity as the last chosen for this filter 5708 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5709 "Setting last chosen"); 5710 } 5711 5712 @Override 5713 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5714 final int userId = UserHandle.getCallingUserId(); 5715 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5716 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5717 userId); 5718 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5719 false, false, false, userId); 5720 } 5721 5722 /** 5723 * Returns whether or not instant apps have been disabled remotely. 5724 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5725 * held. Otherwise we run the risk of deadlock. 5726 */ 5727 private boolean isEphemeralDisabled() { 5728 // ephemeral apps have been disabled across the board 5729 if (DISABLE_EPHEMERAL_APPS) { 5730 return true; 5731 } 5732 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5733 if (!mSystemReady) { 5734 return true; 5735 } 5736 // we can't get a content resolver until the system is ready; these checks must happen last 5737 final ContentResolver resolver = mContext.getContentResolver(); 5738 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5739 return true; 5740 } 5741 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5742 } 5743 5744 private boolean isEphemeralAllowed( 5745 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5746 boolean skipPackageCheck) { 5747 final int callingUser = UserHandle.getCallingUserId(); 5748 if (callingUser != UserHandle.USER_SYSTEM) { 5749 return false; 5750 } 5751 if (mInstantAppResolverConnection == null) { 5752 return false; 5753 } 5754 if (mInstantAppInstallerComponent == null) { 5755 return false; 5756 } 5757 if (intent.getComponent() != null) { 5758 return false; 5759 } 5760 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5761 return false; 5762 } 5763 if (!skipPackageCheck && intent.getPackage() != null) { 5764 return false; 5765 } 5766 final boolean isWebUri = hasWebURI(intent); 5767 if (!isWebUri || intent.getData().getHost() == null) { 5768 return false; 5769 } 5770 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5771 // Or if there's already an ephemeral app installed that handles the action 5772 synchronized (mPackages) { 5773 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5774 for (int n = 0; n < count; n++) { 5775 ResolveInfo info = resolvedActivities.get(n); 5776 String packageName = info.activityInfo.packageName; 5777 PackageSetting ps = mSettings.mPackages.get(packageName); 5778 if (ps != null) { 5779 // Try to get the status from User settings first 5780 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5781 int status = (int) (packedStatus >> 32); 5782 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5783 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5784 if (DEBUG_EPHEMERAL) { 5785 Slog.v(TAG, "DENY ephemeral apps;" 5786 + " pkg: " + packageName + ", status: " + status); 5787 } 5788 return false; 5789 } 5790 if (ps.getInstantApp(userId)) { 5791 if (DEBUG_EPHEMERAL) { 5792 Slog.v(TAG, "DENY instant app installed;" 5793 + " pkg: " + packageName); 5794 } 5795 return false; 5796 } 5797 } 5798 } 5799 } 5800 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5801 return true; 5802 } 5803 5804 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5805 Intent origIntent, String resolvedType, String callingPackage, 5806 int userId) { 5807 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5808 new InstantAppRequest(responseObj, origIntent, resolvedType, 5809 callingPackage, userId)); 5810 mHandler.sendMessage(msg); 5811 } 5812 5813 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5814 int flags, List<ResolveInfo> query, int userId) { 5815 if (query != null) { 5816 final int N = query.size(); 5817 if (N == 1) { 5818 return query.get(0); 5819 } else if (N > 1) { 5820 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5821 // If there is more than one activity with the same priority, 5822 // then let the user decide between them. 5823 ResolveInfo r0 = query.get(0); 5824 ResolveInfo r1 = query.get(1); 5825 if (DEBUG_INTENT_MATCHING || debug) { 5826 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5827 + r1.activityInfo.name + "=" + r1.priority); 5828 } 5829 // If the first activity has a higher priority, or a different 5830 // default, then it is always desirable to pick it. 5831 if (r0.priority != r1.priority 5832 || r0.preferredOrder != r1.preferredOrder 5833 || r0.isDefault != r1.isDefault) { 5834 return query.get(0); 5835 } 5836 // If we have saved a preference for a preferred activity for 5837 // this Intent, use that. 5838 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5839 flags, query, r0.priority, true, false, debug, userId); 5840 if (ri != null) { 5841 return ri; 5842 } 5843 // If we have an ephemeral app, use it 5844 for (int i = 0; i < N; i++) { 5845 ri = query.get(i); 5846 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5847 return ri; 5848 } 5849 } 5850 ri = new ResolveInfo(mResolveInfo); 5851 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5852 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5853 // If all of the options come from the same package, show the application's 5854 // label and icon instead of the generic resolver's. 5855 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5856 // and then throw away the ResolveInfo itself, meaning that the caller loses 5857 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5858 // a fallback for this case; we only set the target package's resources on 5859 // the ResolveInfo, not the ActivityInfo. 5860 final String intentPackage = intent.getPackage(); 5861 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5862 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5863 ri.resolvePackageName = intentPackage; 5864 if (userNeedsBadging(userId)) { 5865 ri.noResourceId = true; 5866 } else { 5867 ri.icon = appi.icon; 5868 } 5869 ri.iconResourceId = appi.icon; 5870 ri.labelRes = appi.labelRes; 5871 } 5872 ri.activityInfo.applicationInfo = new ApplicationInfo( 5873 ri.activityInfo.applicationInfo); 5874 if (userId != 0) { 5875 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5876 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5877 } 5878 // Make sure that the resolver is displayable in car mode 5879 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5880 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5881 return ri; 5882 } 5883 } 5884 return null; 5885 } 5886 5887 /** 5888 * Return true if the given list is not empty and all of its contents have 5889 * an activityInfo with the given package name. 5890 */ 5891 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5892 if (ArrayUtils.isEmpty(list)) { 5893 return false; 5894 } 5895 for (int i = 0, N = list.size(); i < N; i++) { 5896 final ResolveInfo ri = list.get(i); 5897 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5898 if (ai == null || !packageName.equals(ai.packageName)) { 5899 return false; 5900 } 5901 } 5902 return true; 5903 } 5904 5905 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5906 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5907 final int N = query.size(); 5908 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5909 .get(userId); 5910 // Get the list of persistent preferred activities that handle the intent 5911 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5912 List<PersistentPreferredActivity> pprefs = ppir != null 5913 ? ppir.queryIntent(intent, resolvedType, 5914 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5915 userId) 5916 : null; 5917 if (pprefs != null && pprefs.size() > 0) { 5918 final int M = pprefs.size(); 5919 for (int i=0; i<M; i++) { 5920 final PersistentPreferredActivity ppa = pprefs.get(i); 5921 if (DEBUG_PREFERRED || debug) { 5922 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5923 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5924 + "\n component=" + ppa.mComponent); 5925 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5926 } 5927 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5928 flags | MATCH_DISABLED_COMPONENTS, userId); 5929 if (DEBUG_PREFERRED || debug) { 5930 Slog.v(TAG, "Found persistent preferred activity:"); 5931 if (ai != null) { 5932 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5933 } else { 5934 Slog.v(TAG, " null"); 5935 } 5936 } 5937 if (ai == null) { 5938 // This previously registered persistent preferred activity 5939 // component is no longer known. Ignore it and do NOT remove it. 5940 continue; 5941 } 5942 for (int j=0; j<N; j++) { 5943 final ResolveInfo ri = query.get(j); 5944 if (!ri.activityInfo.applicationInfo.packageName 5945 .equals(ai.applicationInfo.packageName)) { 5946 continue; 5947 } 5948 if (!ri.activityInfo.name.equals(ai.name)) { 5949 continue; 5950 } 5951 // Found a persistent preference that can handle the intent. 5952 if (DEBUG_PREFERRED || debug) { 5953 Slog.v(TAG, "Returning persistent preferred activity: " + 5954 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5955 } 5956 return ri; 5957 } 5958 } 5959 } 5960 return null; 5961 } 5962 5963 // TODO: handle preferred activities missing while user has amnesia 5964 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5965 List<ResolveInfo> query, int priority, boolean always, 5966 boolean removeMatches, boolean debug, int userId) { 5967 if (!sUserManager.exists(userId)) return null; 5968 flags = updateFlagsForResolve(flags, userId, intent, false); 5969 intent = updateIntentForResolve(intent); 5970 // writer 5971 synchronized (mPackages) { 5972 // Try to find a matching persistent preferred activity. 5973 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5974 debug, userId); 5975 5976 // If a persistent preferred activity matched, use it. 5977 if (pri != null) { 5978 return pri; 5979 } 5980 5981 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5982 // Get the list of preferred activities that handle the intent 5983 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5984 List<PreferredActivity> prefs = pir != null 5985 ? pir.queryIntent(intent, resolvedType, 5986 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5987 userId) 5988 : null; 5989 if (prefs != null && prefs.size() > 0) { 5990 boolean changed = false; 5991 try { 5992 // First figure out how good the original match set is. 5993 // We will only allow preferred activities that came 5994 // from the same match quality. 5995 int match = 0; 5996 5997 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5998 5999 final int N = query.size(); 6000 for (int j=0; j<N; j++) { 6001 final ResolveInfo ri = query.get(j); 6002 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6003 + ": 0x" + Integer.toHexString(match)); 6004 if (ri.match > match) { 6005 match = ri.match; 6006 } 6007 } 6008 6009 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6010 + Integer.toHexString(match)); 6011 6012 match &= IntentFilter.MATCH_CATEGORY_MASK; 6013 final int M = prefs.size(); 6014 for (int i=0; i<M; i++) { 6015 final PreferredActivity pa = prefs.get(i); 6016 if (DEBUG_PREFERRED || debug) { 6017 Slog.v(TAG, "Checking PreferredActivity ds=" 6018 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6019 + "\n component=" + pa.mPref.mComponent); 6020 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6021 } 6022 if (pa.mPref.mMatch != match) { 6023 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6024 + Integer.toHexString(pa.mPref.mMatch)); 6025 continue; 6026 } 6027 // If it's not an "always" type preferred activity and that's what we're 6028 // looking for, skip it. 6029 if (always && !pa.mPref.mAlways) { 6030 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6031 continue; 6032 } 6033 final ActivityInfo ai = getActivityInfo( 6034 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6035 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6036 userId); 6037 if (DEBUG_PREFERRED || debug) { 6038 Slog.v(TAG, "Found preferred activity:"); 6039 if (ai != null) { 6040 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6041 } else { 6042 Slog.v(TAG, " null"); 6043 } 6044 } 6045 if (ai == null) { 6046 // This previously registered preferred activity 6047 // component is no longer known. Most likely an update 6048 // to the app was installed and in the new version this 6049 // component no longer exists. Clean it up by removing 6050 // it from the preferred activities list, and skip it. 6051 Slog.w(TAG, "Removing dangling preferred activity: " 6052 + pa.mPref.mComponent); 6053 pir.removeFilter(pa); 6054 changed = true; 6055 continue; 6056 } 6057 for (int j=0; j<N; j++) { 6058 final ResolveInfo ri = query.get(j); 6059 if (!ri.activityInfo.applicationInfo.packageName 6060 .equals(ai.applicationInfo.packageName)) { 6061 continue; 6062 } 6063 if (!ri.activityInfo.name.equals(ai.name)) { 6064 continue; 6065 } 6066 6067 if (removeMatches) { 6068 pir.removeFilter(pa); 6069 changed = true; 6070 if (DEBUG_PREFERRED) { 6071 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6072 } 6073 break; 6074 } 6075 6076 // Okay we found a previously set preferred or last chosen app. 6077 // If the result set is different from when this 6078 // was created, we need to clear it and re-ask the 6079 // user their preference, if we're looking for an "always" type entry. 6080 if (always && !pa.mPref.sameSet(query)) { 6081 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6082 + intent + " type " + resolvedType); 6083 if (DEBUG_PREFERRED) { 6084 Slog.v(TAG, "Removing preferred activity since set changed " 6085 + pa.mPref.mComponent); 6086 } 6087 pir.removeFilter(pa); 6088 // Re-add the filter as a "last chosen" entry (!always) 6089 PreferredActivity lastChosen = new PreferredActivity( 6090 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6091 pir.addFilter(lastChosen); 6092 changed = true; 6093 return null; 6094 } 6095 6096 // Yay! Either the set matched or we're looking for the last chosen 6097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6098 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6099 return ri; 6100 } 6101 } 6102 } finally { 6103 if (changed) { 6104 if (DEBUG_PREFERRED) { 6105 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6106 } 6107 scheduleWritePackageRestrictionsLocked(userId); 6108 } 6109 } 6110 } 6111 } 6112 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6113 return null; 6114 } 6115 6116 /* 6117 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6118 */ 6119 @Override 6120 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6121 int targetUserId) { 6122 mContext.enforceCallingOrSelfPermission( 6123 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6124 List<CrossProfileIntentFilter> matches = 6125 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6126 if (matches != null) { 6127 int size = matches.size(); 6128 for (int i = 0; i < size; i++) { 6129 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6130 } 6131 } 6132 if (hasWebURI(intent)) { 6133 // cross-profile app linking works only towards the parent. 6134 final UserInfo parent = getProfileParent(sourceUserId); 6135 synchronized(mPackages) { 6136 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6137 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6138 intent, resolvedType, flags, sourceUserId, parent.id); 6139 return xpDomainInfo != null; 6140 } 6141 } 6142 return false; 6143 } 6144 6145 private UserInfo getProfileParent(int userId) { 6146 final long identity = Binder.clearCallingIdentity(); 6147 try { 6148 return sUserManager.getProfileParent(userId); 6149 } finally { 6150 Binder.restoreCallingIdentity(identity); 6151 } 6152 } 6153 6154 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6155 String resolvedType, int userId) { 6156 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6157 if (resolver != null) { 6158 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6159 } 6160 return null; 6161 } 6162 6163 @Override 6164 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6165 String resolvedType, int flags, int userId) { 6166 try { 6167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6168 6169 return new ParceledListSlice<>( 6170 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6171 } finally { 6172 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6173 } 6174 } 6175 6176 /** 6177 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6178 * instant, returns {@code null}. 6179 */ 6180 private String getInstantAppPackageName(int callingUid) { 6181 final int appId = UserHandle.getAppId(callingUid); 6182 synchronized (mPackages) { 6183 final Object obj = mSettings.getUserIdLPr(appId); 6184 if (obj instanceof PackageSetting) { 6185 final PackageSetting ps = (PackageSetting) obj; 6186 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6187 return isInstantApp ? ps.pkg.packageName : null; 6188 } 6189 } 6190 return null; 6191 } 6192 6193 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6194 String resolvedType, int flags, int userId) { 6195 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6196 } 6197 6198 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6199 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6200 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6201 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6202 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6203 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6204 false /* requireFullPermission */, false /* checkShell */, 6205 "query intent activities"); 6206 ComponentName comp = intent.getComponent(); 6207 if (comp == null) { 6208 if (intent.getSelector() != null) { 6209 intent = intent.getSelector(); 6210 comp = intent.getComponent(); 6211 } 6212 } 6213 6214 if (comp != null) { 6215 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6216 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6217 if (ai != null) { 6218 // When specifying an explicit component, we prevent the activity from being 6219 // used when either 1) the calling package is normal and the activity is within 6220 // an ephemeral application or 2) the calling package is ephemeral and the 6221 // activity is not visible to ephemeral applications. 6222 final boolean matchInstantApp = 6223 (flags & PackageManager.MATCH_INSTANT) != 0; 6224 final boolean matchVisibleToInstantAppOnly = 6225 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6226 final boolean isCallerInstantApp = 6227 instantAppPkgName != null; 6228 final boolean isTargetSameInstantApp = 6229 comp.getPackageName().equals(instantAppPkgName); 6230 final boolean isTargetInstantApp = 6231 (ai.applicationInfo.privateFlags 6232 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6233 final boolean isTargetHiddenFromInstantApp = 6234 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6235 final boolean blockResolution = 6236 !isTargetSameInstantApp 6237 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6238 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6239 && isTargetHiddenFromInstantApp)); 6240 if (!blockResolution) { 6241 final ResolveInfo ri = new ResolveInfo(); 6242 ri.activityInfo = ai; 6243 list.add(ri); 6244 } 6245 } 6246 return applyPostResolutionFilter(list, instantAppPkgName); 6247 } 6248 6249 // reader 6250 boolean sortResult = false; 6251 boolean addEphemeral = false; 6252 List<ResolveInfo> result; 6253 final String pkgName = intent.getPackage(); 6254 final boolean ephemeralDisabled = isEphemeralDisabled(); 6255 synchronized (mPackages) { 6256 if (pkgName == null) { 6257 List<CrossProfileIntentFilter> matchingFilters = 6258 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6259 // Check for results that need to skip the current profile. 6260 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6261 resolvedType, flags, userId); 6262 if (xpResolveInfo != null) { 6263 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6264 xpResult.add(xpResolveInfo); 6265 return applyPostResolutionFilter( 6266 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6267 } 6268 6269 // Check for results in the current profile. 6270 result = filterIfNotSystemUser(mActivities.queryIntent( 6271 intent, resolvedType, flags, userId), userId); 6272 addEphemeral = !ephemeralDisabled 6273 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6274 // Check for cross profile results. 6275 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6276 xpResolveInfo = queryCrossProfileIntents( 6277 matchingFilters, intent, resolvedType, flags, userId, 6278 hasNonNegativePriorityResult); 6279 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6280 boolean isVisibleToUser = filterIfNotSystemUser( 6281 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6282 if (isVisibleToUser) { 6283 result.add(xpResolveInfo); 6284 sortResult = true; 6285 } 6286 } 6287 if (hasWebURI(intent)) { 6288 CrossProfileDomainInfo xpDomainInfo = null; 6289 final UserInfo parent = getProfileParent(userId); 6290 if (parent != null) { 6291 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6292 flags, userId, parent.id); 6293 } 6294 if (xpDomainInfo != null) { 6295 if (xpResolveInfo != null) { 6296 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6297 // in the result. 6298 result.remove(xpResolveInfo); 6299 } 6300 if (result.size() == 0 && !addEphemeral) { 6301 // No result in current profile, but found candidate in parent user. 6302 // And we are not going to add emphemeral app, so we can return the 6303 // result straight away. 6304 result.add(xpDomainInfo.resolveInfo); 6305 return applyPostResolutionFilter(result, instantAppPkgName); 6306 } 6307 } else if (result.size() <= 1 && !addEphemeral) { 6308 // No result in parent user and <= 1 result in current profile, and we 6309 // are not going to add emphemeral app, so we can return the result without 6310 // further processing. 6311 return applyPostResolutionFilter(result, instantAppPkgName); 6312 } 6313 // We have more than one candidate (combining results from current and parent 6314 // profile), so we need filtering and sorting. 6315 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6316 intent, flags, result, xpDomainInfo, userId); 6317 sortResult = true; 6318 } 6319 } else { 6320 final PackageParser.Package pkg = mPackages.get(pkgName); 6321 if (pkg != null) { 6322 return applyPostResolutionFilter(filterIfNotSystemUser( 6323 mActivities.queryIntentForPackage( 6324 intent, resolvedType, flags, pkg.activities, userId), 6325 userId), instantAppPkgName); 6326 } else { 6327 // the caller wants to resolve for a particular package; however, there 6328 // were no installed results, so, try to find an ephemeral result 6329 addEphemeral = !ephemeralDisabled 6330 && isEphemeralAllowed( 6331 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6332 result = new ArrayList<ResolveInfo>(); 6333 } 6334 } 6335 } 6336 if (addEphemeral) { 6337 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6338 final InstantAppRequest requestObject = new InstantAppRequest( 6339 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6340 null /*callingPackage*/, userId); 6341 final AuxiliaryResolveInfo auxiliaryResponse = 6342 InstantAppResolver.doInstantAppResolutionPhaseOne( 6343 mContext, mInstantAppResolverConnection, requestObject); 6344 if (auxiliaryResponse != null) { 6345 if (DEBUG_EPHEMERAL) { 6346 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6347 } 6348 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6349 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6350 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6351 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6352 // make sure this resolver is the default 6353 ephemeralInstaller.isDefault = true; 6354 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6355 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6356 // add a non-generic filter 6357 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6358 ephemeralInstaller.filter.addDataPath( 6359 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6360 ephemeralInstaller.instantAppAvailable = true; 6361 result.add(ephemeralInstaller); 6362 } 6363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6364 } 6365 if (sortResult) { 6366 Collections.sort(result, mResolvePrioritySorter); 6367 } 6368 return applyPostResolutionFilter(result, instantAppPkgName); 6369 } 6370 6371 private static class CrossProfileDomainInfo { 6372 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6373 ResolveInfo resolveInfo; 6374 /* Best domain verification status of the activities found in the other profile */ 6375 int bestDomainVerificationStatus; 6376 } 6377 6378 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6379 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6380 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6381 sourceUserId)) { 6382 return null; 6383 } 6384 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6385 resolvedType, flags, parentUserId); 6386 6387 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6388 return null; 6389 } 6390 CrossProfileDomainInfo result = null; 6391 int size = resultTargetUser.size(); 6392 for (int i = 0; i < size; i++) { 6393 ResolveInfo riTargetUser = resultTargetUser.get(i); 6394 // Intent filter verification is only for filters that specify a host. So don't return 6395 // those that handle all web uris. 6396 if (riTargetUser.handleAllWebDataURI) { 6397 continue; 6398 } 6399 String packageName = riTargetUser.activityInfo.packageName; 6400 PackageSetting ps = mSettings.mPackages.get(packageName); 6401 if (ps == null) { 6402 continue; 6403 } 6404 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6405 int status = (int)(verificationState >> 32); 6406 if (result == null) { 6407 result = new CrossProfileDomainInfo(); 6408 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6409 sourceUserId, parentUserId); 6410 result.bestDomainVerificationStatus = status; 6411 } else { 6412 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6413 result.bestDomainVerificationStatus); 6414 } 6415 } 6416 // Don't consider matches with status NEVER across profiles. 6417 if (result != null && result.bestDomainVerificationStatus 6418 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6419 return null; 6420 } 6421 return result; 6422 } 6423 6424 /** 6425 * Verification statuses are ordered from the worse to the best, except for 6426 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6427 */ 6428 private int bestDomainVerificationStatus(int status1, int status2) { 6429 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6430 return status2; 6431 } 6432 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6433 return status1; 6434 } 6435 return (int) MathUtils.max(status1, status2); 6436 } 6437 6438 private boolean isUserEnabled(int userId) { 6439 long callingId = Binder.clearCallingIdentity(); 6440 try { 6441 UserInfo userInfo = sUserManager.getUserInfo(userId); 6442 return userInfo != null && userInfo.isEnabled(); 6443 } finally { 6444 Binder.restoreCallingIdentity(callingId); 6445 } 6446 } 6447 6448 /** 6449 * Filter out activities with systemUserOnly flag set, when current user is not System. 6450 * 6451 * @return filtered list 6452 */ 6453 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6454 if (userId == UserHandle.USER_SYSTEM) { 6455 return resolveInfos; 6456 } 6457 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6458 ResolveInfo info = resolveInfos.get(i); 6459 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6460 resolveInfos.remove(i); 6461 } 6462 } 6463 return resolveInfos; 6464 } 6465 6466 /** 6467 * Filters out ephemeral activities. 6468 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6469 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6470 * 6471 * @param resolveInfos The pre-filtered list of resolved activities 6472 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6473 * is performed. 6474 * @return A filtered list of resolved activities. 6475 */ 6476 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6477 String ephemeralPkgName) { 6478 // TODO: When adding on-demand split support for non-instant apps, remove this check 6479 // and always apply post filtering 6480 if (ephemeralPkgName == null) { 6481 return resolveInfos; 6482 } 6483 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6484 final ResolveInfo info = resolveInfos.get(i); 6485 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6486 // allow activities that are defined in the provided package 6487 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6488 if (info.activityInfo.splitName != null 6489 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6490 info.activityInfo.splitName)) { 6491 // requested activity is defined in a split that hasn't been installed yet. 6492 // add the installer to the resolve list 6493 if (DEBUG_EPHEMERAL) { 6494 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6495 } 6496 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6497 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6498 info.activityInfo.packageName, info.activityInfo.splitName, 6499 info.activityInfo.applicationInfo.versionCode); 6500 // make sure this resolver is the default 6501 installerInfo.isDefault = true; 6502 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6503 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6504 // add a non-generic filter 6505 installerInfo.filter = new IntentFilter(); 6506 // load resources from the correct package 6507 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6508 resolveInfos.set(i, installerInfo); 6509 } 6510 continue; 6511 } 6512 // allow activities that have been explicitly exposed to ephemeral apps 6513 if (!isEphemeralApp 6514 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6515 continue; 6516 } 6517 resolveInfos.remove(i); 6518 } 6519 return resolveInfos; 6520 } 6521 6522 /** 6523 * @param resolveInfos list of resolve infos in descending priority order 6524 * @return if the list contains a resolve info with non-negative priority 6525 */ 6526 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6527 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6528 } 6529 6530 private static boolean hasWebURI(Intent intent) { 6531 if (intent.getData() == null) { 6532 return false; 6533 } 6534 final String scheme = intent.getScheme(); 6535 if (TextUtils.isEmpty(scheme)) { 6536 return false; 6537 } 6538 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6539 } 6540 6541 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6542 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6543 int userId) { 6544 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6545 6546 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6547 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6548 candidates.size()); 6549 } 6550 6551 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6552 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6553 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6554 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6555 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6556 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6557 6558 synchronized (mPackages) { 6559 final int count = candidates.size(); 6560 // First, try to use linked apps. Partition the candidates into four lists: 6561 // one for the final results, one for the "do not use ever", one for "undefined status" 6562 // and finally one for "browser app type". 6563 for (int n=0; n<count; n++) { 6564 ResolveInfo info = candidates.get(n); 6565 String packageName = info.activityInfo.packageName; 6566 PackageSetting ps = mSettings.mPackages.get(packageName); 6567 if (ps != null) { 6568 // Add to the special match all list (Browser use case) 6569 if (info.handleAllWebDataURI) { 6570 matchAllList.add(info); 6571 continue; 6572 } 6573 // Try to get the status from User settings first 6574 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6575 int status = (int)(packedStatus >> 32); 6576 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6577 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6578 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6579 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6580 + " : linkgen=" + linkGeneration); 6581 } 6582 // Use link-enabled generation as preferredOrder, i.e. 6583 // prefer newly-enabled over earlier-enabled. 6584 info.preferredOrder = linkGeneration; 6585 alwaysList.add(info); 6586 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6587 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6588 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6589 } 6590 neverList.add(info); 6591 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6592 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6593 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6594 } 6595 alwaysAskList.add(info); 6596 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6597 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6598 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6599 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6600 } 6601 undefinedList.add(info); 6602 } 6603 } 6604 } 6605 6606 // We'll want to include browser possibilities in a few cases 6607 boolean includeBrowser = false; 6608 6609 // First try to add the "always" resolution(s) for the current user, if any 6610 if (alwaysList.size() > 0) { 6611 result.addAll(alwaysList); 6612 } else { 6613 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6614 result.addAll(undefinedList); 6615 // Maybe add one for the other profile. 6616 if (xpDomainInfo != null && ( 6617 xpDomainInfo.bestDomainVerificationStatus 6618 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6619 result.add(xpDomainInfo.resolveInfo); 6620 } 6621 includeBrowser = true; 6622 } 6623 6624 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6625 // If there were 'always' entries their preferred order has been set, so we also 6626 // back that off to make the alternatives equivalent 6627 if (alwaysAskList.size() > 0) { 6628 for (ResolveInfo i : result) { 6629 i.preferredOrder = 0; 6630 } 6631 result.addAll(alwaysAskList); 6632 includeBrowser = true; 6633 } 6634 6635 if (includeBrowser) { 6636 // Also add browsers (all of them or only the default one) 6637 if (DEBUG_DOMAIN_VERIFICATION) { 6638 Slog.v(TAG, " ...including browsers in candidate set"); 6639 } 6640 if ((matchFlags & MATCH_ALL) != 0) { 6641 result.addAll(matchAllList); 6642 } else { 6643 // Browser/generic handling case. If there's a default browser, go straight 6644 // to that (but only if there is no other higher-priority match). 6645 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6646 int maxMatchPrio = 0; 6647 ResolveInfo defaultBrowserMatch = null; 6648 final int numCandidates = matchAllList.size(); 6649 for (int n = 0; n < numCandidates; n++) { 6650 ResolveInfo info = matchAllList.get(n); 6651 // track the highest overall match priority... 6652 if (info.priority > maxMatchPrio) { 6653 maxMatchPrio = info.priority; 6654 } 6655 // ...and the highest-priority default browser match 6656 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6657 if (defaultBrowserMatch == null 6658 || (defaultBrowserMatch.priority < info.priority)) { 6659 if (debug) { 6660 Slog.v(TAG, "Considering default browser match " + info); 6661 } 6662 defaultBrowserMatch = info; 6663 } 6664 } 6665 } 6666 if (defaultBrowserMatch != null 6667 && defaultBrowserMatch.priority >= maxMatchPrio 6668 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6669 { 6670 if (debug) { 6671 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6672 } 6673 result.add(defaultBrowserMatch); 6674 } else { 6675 result.addAll(matchAllList); 6676 } 6677 } 6678 6679 // If there is nothing selected, add all candidates and remove the ones that the user 6680 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6681 if (result.size() == 0) { 6682 result.addAll(candidates); 6683 result.removeAll(neverList); 6684 } 6685 } 6686 } 6687 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6688 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6689 result.size()); 6690 for (ResolveInfo info : result) { 6691 Slog.v(TAG, " + " + info.activityInfo); 6692 } 6693 } 6694 return result; 6695 } 6696 6697 // Returns a packed value as a long: 6698 // 6699 // high 'int'-sized word: link status: undefined/ask/never/always. 6700 // low 'int'-sized word: relative priority among 'always' results. 6701 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6702 long result = ps.getDomainVerificationStatusForUser(userId); 6703 // if none available, get the master status 6704 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6705 if (ps.getIntentFilterVerificationInfo() != null) { 6706 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6707 } 6708 } 6709 return result; 6710 } 6711 6712 private ResolveInfo querySkipCurrentProfileIntents( 6713 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6714 int flags, int sourceUserId) { 6715 if (matchingFilters != null) { 6716 int size = matchingFilters.size(); 6717 for (int i = 0; i < size; i ++) { 6718 CrossProfileIntentFilter filter = matchingFilters.get(i); 6719 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6720 // Checking if there are activities in the target user that can handle the 6721 // intent. 6722 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6723 resolvedType, flags, sourceUserId); 6724 if (resolveInfo != null) { 6725 return resolveInfo; 6726 } 6727 } 6728 } 6729 } 6730 return null; 6731 } 6732 6733 // Return matching ResolveInfo in target user if any. 6734 private ResolveInfo queryCrossProfileIntents( 6735 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6736 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6737 if (matchingFilters != null) { 6738 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6739 // match the same intent. For performance reasons, it is better not to 6740 // run queryIntent twice for the same userId 6741 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6742 int size = matchingFilters.size(); 6743 for (int i = 0; i < size; i++) { 6744 CrossProfileIntentFilter filter = matchingFilters.get(i); 6745 int targetUserId = filter.getTargetUserId(); 6746 boolean skipCurrentProfile = 6747 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6748 boolean skipCurrentProfileIfNoMatchFound = 6749 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6750 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6751 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6752 // Checking if there are activities in the target user that can handle the 6753 // intent. 6754 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6755 resolvedType, flags, sourceUserId); 6756 if (resolveInfo != null) return resolveInfo; 6757 alreadyTriedUserIds.put(targetUserId, true); 6758 } 6759 } 6760 } 6761 return null; 6762 } 6763 6764 /** 6765 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6766 * will forward the intent to the filter's target user. 6767 * Otherwise, returns null. 6768 */ 6769 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6770 String resolvedType, int flags, int sourceUserId) { 6771 int targetUserId = filter.getTargetUserId(); 6772 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6773 resolvedType, flags, targetUserId); 6774 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6775 // If all the matches in the target profile are suspended, return null. 6776 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6777 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6778 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6779 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6780 targetUserId); 6781 } 6782 } 6783 } 6784 return null; 6785 } 6786 6787 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6788 int sourceUserId, int targetUserId) { 6789 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6790 long ident = Binder.clearCallingIdentity(); 6791 boolean targetIsProfile; 6792 try { 6793 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6794 } finally { 6795 Binder.restoreCallingIdentity(ident); 6796 } 6797 String className; 6798 if (targetIsProfile) { 6799 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6800 } else { 6801 className = FORWARD_INTENT_TO_PARENT; 6802 } 6803 ComponentName forwardingActivityComponentName = new ComponentName( 6804 mAndroidApplication.packageName, className); 6805 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6806 sourceUserId); 6807 if (!targetIsProfile) { 6808 forwardingActivityInfo.showUserIcon = targetUserId; 6809 forwardingResolveInfo.noResourceId = true; 6810 } 6811 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6812 forwardingResolveInfo.priority = 0; 6813 forwardingResolveInfo.preferredOrder = 0; 6814 forwardingResolveInfo.match = 0; 6815 forwardingResolveInfo.isDefault = true; 6816 forwardingResolveInfo.filter = filter; 6817 forwardingResolveInfo.targetUserId = targetUserId; 6818 return forwardingResolveInfo; 6819 } 6820 6821 @Override 6822 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6823 Intent[] specifics, String[] specificTypes, Intent intent, 6824 String resolvedType, int flags, int userId) { 6825 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6826 specificTypes, intent, resolvedType, flags, userId)); 6827 } 6828 6829 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6830 Intent[] specifics, String[] specificTypes, Intent intent, 6831 String resolvedType, int flags, int userId) { 6832 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6833 flags = updateFlagsForResolve(flags, userId, intent, false); 6834 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6835 false /* requireFullPermission */, false /* checkShell */, 6836 "query intent activity options"); 6837 final String resultsAction = intent.getAction(); 6838 6839 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6840 | PackageManager.GET_RESOLVED_FILTER, userId); 6841 6842 if (DEBUG_INTENT_MATCHING) { 6843 Log.v(TAG, "Query " + intent + ": " + results); 6844 } 6845 6846 int specificsPos = 0; 6847 int N; 6848 6849 // todo: note that the algorithm used here is O(N^2). This 6850 // isn't a problem in our current environment, but if we start running 6851 // into situations where we have more than 5 or 10 matches then this 6852 // should probably be changed to something smarter... 6853 6854 // First we go through and resolve each of the specific items 6855 // that were supplied, taking care of removing any corresponding 6856 // duplicate items in the generic resolve list. 6857 if (specifics != null) { 6858 for (int i=0; i<specifics.length; i++) { 6859 final Intent sintent = specifics[i]; 6860 if (sintent == null) { 6861 continue; 6862 } 6863 6864 if (DEBUG_INTENT_MATCHING) { 6865 Log.v(TAG, "Specific #" + i + ": " + sintent); 6866 } 6867 6868 String action = sintent.getAction(); 6869 if (resultsAction != null && resultsAction.equals(action)) { 6870 // If this action was explicitly requested, then don't 6871 // remove things that have it. 6872 action = null; 6873 } 6874 6875 ResolveInfo ri = null; 6876 ActivityInfo ai = null; 6877 6878 ComponentName comp = sintent.getComponent(); 6879 if (comp == null) { 6880 ri = resolveIntent( 6881 sintent, 6882 specificTypes != null ? specificTypes[i] : null, 6883 flags, userId); 6884 if (ri == null) { 6885 continue; 6886 } 6887 if (ri == mResolveInfo) { 6888 // ACK! Must do something better with this. 6889 } 6890 ai = ri.activityInfo; 6891 comp = new ComponentName(ai.applicationInfo.packageName, 6892 ai.name); 6893 } else { 6894 ai = getActivityInfo(comp, flags, userId); 6895 if (ai == null) { 6896 continue; 6897 } 6898 } 6899 6900 // Look for any generic query activities that are duplicates 6901 // of this specific one, and remove them from the results. 6902 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6903 N = results.size(); 6904 int j; 6905 for (j=specificsPos; j<N; j++) { 6906 ResolveInfo sri = results.get(j); 6907 if ((sri.activityInfo.name.equals(comp.getClassName()) 6908 && sri.activityInfo.applicationInfo.packageName.equals( 6909 comp.getPackageName())) 6910 || (action != null && sri.filter.matchAction(action))) { 6911 results.remove(j); 6912 if (DEBUG_INTENT_MATCHING) Log.v( 6913 TAG, "Removing duplicate item from " + j 6914 + " due to specific " + specificsPos); 6915 if (ri == null) { 6916 ri = sri; 6917 } 6918 j--; 6919 N--; 6920 } 6921 } 6922 6923 // Add this specific item to its proper place. 6924 if (ri == null) { 6925 ri = new ResolveInfo(); 6926 ri.activityInfo = ai; 6927 } 6928 results.add(specificsPos, ri); 6929 ri.specificIndex = i; 6930 specificsPos++; 6931 } 6932 } 6933 6934 // Now we go through the remaining generic results and remove any 6935 // duplicate actions that are found here. 6936 N = results.size(); 6937 for (int i=specificsPos; i<N-1; i++) { 6938 final ResolveInfo rii = results.get(i); 6939 if (rii.filter == null) { 6940 continue; 6941 } 6942 6943 // Iterate over all of the actions of this result's intent 6944 // filter... typically this should be just one. 6945 final Iterator<String> it = rii.filter.actionsIterator(); 6946 if (it == null) { 6947 continue; 6948 } 6949 while (it.hasNext()) { 6950 final String action = it.next(); 6951 if (resultsAction != null && resultsAction.equals(action)) { 6952 // If this action was explicitly requested, then don't 6953 // remove things that have it. 6954 continue; 6955 } 6956 for (int j=i+1; j<N; j++) { 6957 final ResolveInfo rij = results.get(j); 6958 if (rij.filter != null && rij.filter.hasAction(action)) { 6959 results.remove(j); 6960 if (DEBUG_INTENT_MATCHING) Log.v( 6961 TAG, "Removing duplicate item from " + j 6962 + " due to action " + action + " at " + i); 6963 j--; 6964 N--; 6965 } 6966 } 6967 } 6968 6969 // If the caller didn't request filter information, drop it now 6970 // so we don't have to marshall/unmarshall it. 6971 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6972 rii.filter = null; 6973 } 6974 } 6975 6976 // Filter out the caller activity if so requested. 6977 if (caller != null) { 6978 N = results.size(); 6979 for (int i=0; i<N; i++) { 6980 ActivityInfo ainfo = results.get(i).activityInfo; 6981 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6982 && caller.getClassName().equals(ainfo.name)) { 6983 results.remove(i); 6984 break; 6985 } 6986 } 6987 } 6988 6989 // If the caller didn't request filter information, 6990 // drop them now so we don't have to 6991 // marshall/unmarshall it. 6992 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6993 N = results.size(); 6994 for (int i=0; i<N; i++) { 6995 results.get(i).filter = null; 6996 } 6997 } 6998 6999 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7000 return results; 7001 } 7002 7003 @Override 7004 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7005 String resolvedType, int flags, int userId) { 7006 return new ParceledListSlice<>( 7007 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7008 } 7009 7010 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7011 String resolvedType, int flags, int userId) { 7012 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7013 flags = updateFlagsForResolve(flags, userId, intent, false); 7014 ComponentName comp = intent.getComponent(); 7015 if (comp == null) { 7016 if (intent.getSelector() != null) { 7017 intent = intent.getSelector(); 7018 comp = intent.getComponent(); 7019 } 7020 } 7021 if (comp != null) { 7022 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7023 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7024 if (ai != null) { 7025 ResolveInfo ri = new ResolveInfo(); 7026 ri.activityInfo = ai; 7027 list.add(ri); 7028 } 7029 return list; 7030 } 7031 7032 // reader 7033 synchronized (mPackages) { 7034 String pkgName = intent.getPackage(); 7035 if (pkgName == null) { 7036 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7037 } 7038 final PackageParser.Package pkg = mPackages.get(pkgName); 7039 if (pkg != null) { 7040 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7041 userId); 7042 } 7043 return Collections.emptyList(); 7044 } 7045 } 7046 7047 @Override 7048 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7049 if (!sUserManager.exists(userId)) return null; 7050 flags = updateFlagsForResolve(flags, userId, intent, false); 7051 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 7052 if (query != null) { 7053 if (query.size() >= 1) { 7054 // If there is more than one service with the same priority, 7055 // just arbitrarily pick the first one. 7056 return query.get(0); 7057 } 7058 } 7059 return null; 7060 } 7061 7062 @Override 7063 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7064 String resolvedType, int flags, int userId) { 7065 return new ParceledListSlice<>( 7066 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 7067 } 7068 7069 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7070 String resolvedType, int flags, int userId) { 7071 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7072 flags = updateFlagsForResolve(flags, userId, intent, false); 7073 ComponentName comp = intent.getComponent(); 7074 if (comp == null) { 7075 if (intent.getSelector() != null) { 7076 intent = intent.getSelector(); 7077 comp = intent.getComponent(); 7078 } 7079 } 7080 if (comp != null) { 7081 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7082 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7083 if (si != null) { 7084 final ResolveInfo ri = new ResolveInfo(); 7085 ri.serviceInfo = si; 7086 list.add(ri); 7087 } 7088 return list; 7089 } 7090 7091 // reader 7092 synchronized (mPackages) { 7093 String pkgName = intent.getPackage(); 7094 if (pkgName == null) { 7095 return mServices.queryIntent(intent, resolvedType, flags, userId); 7096 } 7097 final PackageParser.Package pkg = mPackages.get(pkgName); 7098 if (pkg != null) { 7099 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7100 userId); 7101 } 7102 return Collections.emptyList(); 7103 } 7104 } 7105 7106 @Override 7107 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7108 String resolvedType, int flags, int userId) { 7109 return new ParceledListSlice<>( 7110 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7111 } 7112 7113 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7114 Intent intent, String resolvedType, int flags, int userId) { 7115 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7116 flags = updateFlagsForResolve(flags, userId, intent, false); 7117 ComponentName comp = intent.getComponent(); 7118 if (comp == null) { 7119 if (intent.getSelector() != null) { 7120 intent = intent.getSelector(); 7121 comp = intent.getComponent(); 7122 } 7123 } 7124 if (comp != null) { 7125 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7126 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7127 if (pi != null) { 7128 final ResolveInfo ri = new ResolveInfo(); 7129 ri.providerInfo = pi; 7130 list.add(ri); 7131 } 7132 return list; 7133 } 7134 7135 // reader 7136 synchronized (mPackages) { 7137 String pkgName = intent.getPackage(); 7138 if (pkgName == null) { 7139 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7140 } 7141 final PackageParser.Package pkg = mPackages.get(pkgName); 7142 if (pkg != null) { 7143 return mProviders.queryIntentForPackage( 7144 intent, resolvedType, flags, pkg.providers, userId); 7145 } 7146 return Collections.emptyList(); 7147 } 7148 } 7149 7150 @Override 7151 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7152 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7153 flags = updateFlagsForPackage(flags, userId, null); 7154 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7155 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7156 true /* requireFullPermission */, false /* checkShell */, 7157 "get installed packages"); 7158 7159 // writer 7160 synchronized (mPackages) { 7161 ArrayList<PackageInfo> list; 7162 if (listUninstalled) { 7163 list = new ArrayList<>(mSettings.mPackages.size()); 7164 for (PackageSetting ps : mSettings.mPackages.values()) { 7165 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7166 continue; 7167 } 7168 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7169 if (pi != null) { 7170 list.add(pi); 7171 } 7172 } 7173 } else { 7174 list = new ArrayList<>(mPackages.size()); 7175 for (PackageParser.Package p : mPackages.values()) { 7176 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7177 Binder.getCallingUid(), userId)) { 7178 continue; 7179 } 7180 final PackageInfo pi = generatePackageInfo((PackageSetting) 7181 p.mExtras, flags, userId); 7182 if (pi != null) { 7183 list.add(pi); 7184 } 7185 } 7186 } 7187 7188 return new ParceledListSlice<>(list); 7189 } 7190 } 7191 7192 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7193 String[] permissions, boolean[] tmp, int flags, int userId) { 7194 int numMatch = 0; 7195 final PermissionsState permissionsState = ps.getPermissionsState(); 7196 for (int i=0; i<permissions.length; i++) { 7197 final String permission = permissions[i]; 7198 if (permissionsState.hasPermission(permission, userId)) { 7199 tmp[i] = true; 7200 numMatch++; 7201 } else { 7202 tmp[i] = false; 7203 } 7204 } 7205 if (numMatch == 0) { 7206 return; 7207 } 7208 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7209 7210 // The above might return null in cases of uninstalled apps or install-state 7211 // skew across users/profiles. 7212 if (pi != null) { 7213 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7214 if (numMatch == permissions.length) { 7215 pi.requestedPermissions = permissions; 7216 } else { 7217 pi.requestedPermissions = new String[numMatch]; 7218 numMatch = 0; 7219 for (int i=0; i<permissions.length; i++) { 7220 if (tmp[i]) { 7221 pi.requestedPermissions[numMatch] = permissions[i]; 7222 numMatch++; 7223 } 7224 } 7225 } 7226 } 7227 list.add(pi); 7228 } 7229 } 7230 7231 @Override 7232 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7233 String[] permissions, int flags, int userId) { 7234 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7235 flags = updateFlagsForPackage(flags, userId, permissions); 7236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7237 true /* requireFullPermission */, false /* checkShell */, 7238 "get packages holding permissions"); 7239 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7240 7241 // writer 7242 synchronized (mPackages) { 7243 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7244 boolean[] tmpBools = new boolean[permissions.length]; 7245 if (listUninstalled) { 7246 for (PackageSetting ps : mSettings.mPackages.values()) { 7247 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7248 userId); 7249 } 7250 } else { 7251 for (PackageParser.Package pkg : mPackages.values()) { 7252 PackageSetting ps = (PackageSetting)pkg.mExtras; 7253 if (ps != null) { 7254 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7255 userId); 7256 } 7257 } 7258 } 7259 7260 return new ParceledListSlice<PackageInfo>(list); 7261 } 7262 } 7263 7264 @Override 7265 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7266 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7267 flags = updateFlagsForApplication(flags, userId, null); 7268 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7269 7270 // writer 7271 synchronized (mPackages) { 7272 ArrayList<ApplicationInfo> list; 7273 if (listUninstalled) { 7274 list = new ArrayList<>(mSettings.mPackages.size()); 7275 for (PackageSetting ps : mSettings.mPackages.values()) { 7276 ApplicationInfo ai; 7277 int effectiveFlags = flags; 7278 if (ps.isSystem()) { 7279 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7280 } 7281 if (ps.pkg != null) { 7282 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7283 continue; 7284 } 7285 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7286 ps.readUserState(userId), userId); 7287 if (ai != null) { 7288 rebaseEnabledOverlays(ai, userId); 7289 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7290 } 7291 } else { 7292 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7293 // and already converts to externally visible package name 7294 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7295 Binder.getCallingUid(), effectiveFlags, userId); 7296 } 7297 if (ai != null) { 7298 list.add(ai); 7299 } 7300 } 7301 } else { 7302 list = new ArrayList<>(mPackages.size()); 7303 for (PackageParser.Package p : mPackages.values()) { 7304 if (p.mExtras != null) { 7305 PackageSetting ps = (PackageSetting) p.mExtras; 7306 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7307 continue; 7308 } 7309 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7310 ps.readUserState(userId), userId); 7311 if (ai != null) { 7312 rebaseEnabledOverlays(ai, userId); 7313 ai.packageName = resolveExternalPackageNameLPr(p); 7314 list.add(ai); 7315 } 7316 } 7317 } 7318 } 7319 7320 return new ParceledListSlice<>(list); 7321 } 7322 } 7323 7324 @Override 7325 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7326 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7327 return null; 7328 } 7329 7330 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7331 "getEphemeralApplications"); 7332 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7333 true /* requireFullPermission */, false /* checkShell */, 7334 "getEphemeralApplications"); 7335 synchronized (mPackages) { 7336 List<InstantAppInfo> instantApps = mInstantAppRegistry 7337 .getInstantAppsLPr(userId); 7338 if (instantApps != null) { 7339 return new ParceledListSlice<>(instantApps); 7340 } 7341 } 7342 return null; 7343 } 7344 7345 @Override 7346 public boolean isInstantApp(String packageName, int userId) { 7347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7348 true /* requireFullPermission */, false /* checkShell */, 7349 "isInstantApp"); 7350 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7351 return false; 7352 } 7353 7354 synchronized (mPackages) { 7355 final PackageSetting ps = mSettings.mPackages.get(packageName); 7356 final boolean returnAllowed = 7357 ps != null 7358 && (isCallerSameApp(packageName) 7359 || mContext.checkCallingOrSelfPermission( 7360 android.Manifest.permission.ACCESS_INSTANT_APPS) 7361 == PERMISSION_GRANTED 7362 || mInstantAppRegistry.isInstantAccessGranted( 7363 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7364 if (returnAllowed) { 7365 return ps.getInstantApp(userId); 7366 } 7367 } 7368 return false; 7369 } 7370 7371 @Override 7372 public byte[] getInstantAppCookie(String packageName, int userId) { 7373 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7374 return null; 7375 } 7376 7377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7378 true /* requireFullPermission */, false /* checkShell */, 7379 "getInstantAppCookie"); 7380 if (!isCallerSameApp(packageName)) { 7381 return null; 7382 } 7383 synchronized (mPackages) { 7384 return mInstantAppRegistry.getInstantAppCookieLPw( 7385 packageName, userId); 7386 } 7387 } 7388 7389 @Override 7390 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7391 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7392 return true; 7393 } 7394 7395 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7396 true /* requireFullPermission */, true /* checkShell */, 7397 "setInstantAppCookie"); 7398 if (!isCallerSameApp(packageName)) { 7399 return false; 7400 } 7401 synchronized (mPackages) { 7402 return mInstantAppRegistry.setInstantAppCookieLPw( 7403 packageName, cookie, userId); 7404 } 7405 } 7406 7407 @Override 7408 public Bitmap getInstantAppIcon(String packageName, int userId) { 7409 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7410 return null; 7411 } 7412 7413 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7414 "getInstantAppIcon"); 7415 7416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7417 true /* requireFullPermission */, false /* checkShell */, 7418 "getInstantAppIcon"); 7419 7420 synchronized (mPackages) { 7421 return mInstantAppRegistry.getInstantAppIconLPw( 7422 packageName, userId); 7423 } 7424 } 7425 7426 private boolean isCallerSameApp(String packageName) { 7427 PackageParser.Package pkg = mPackages.get(packageName); 7428 return pkg != null 7429 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7430 } 7431 7432 @Override 7433 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7434 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7435 } 7436 7437 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7438 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7439 7440 // reader 7441 synchronized (mPackages) { 7442 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7443 final int userId = UserHandle.getCallingUserId(); 7444 while (i.hasNext()) { 7445 final PackageParser.Package p = i.next(); 7446 if (p.applicationInfo == null) continue; 7447 7448 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7449 && !p.applicationInfo.isDirectBootAware(); 7450 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7451 && p.applicationInfo.isDirectBootAware(); 7452 7453 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7454 && (!mSafeMode || isSystemApp(p)) 7455 && (matchesUnaware || matchesAware)) { 7456 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7457 if (ps != null) { 7458 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7459 ps.readUserState(userId), userId); 7460 if (ai != null) { 7461 rebaseEnabledOverlays(ai, userId); 7462 finalList.add(ai); 7463 } 7464 } 7465 } 7466 } 7467 } 7468 7469 return finalList; 7470 } 7471 7472 @Override 7473 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7474 if (!sUserManager.exists(userId)) return null; 7475 flags = updateFlagsForComponent(flags, userId, name); 7476 // reader 7477 synchronized (mPackages) { 7478 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7479 PackageSetting ps = provider != null 7480 ? mSettings.mPackages.get(provider.owner.packageName) 7481 : null; 7482 return ps != null 7483 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7484 ? PackageParser.generateProviderInfo(provider, flags, 7485 ps.readUserState(userId), userId) 7486 : null; 7487 } 7488 } 7489 7490 /** 7491 * @deprecated 7492 */ 7493 @Deprecated 7494 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7495 // reader 7496 synchronized (mPackages) { 7497 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7498 .entrySet().iterator(); 7499 final int userId = UserHandle.getCallingUserId(); 7500 while (i.hasNext()) { 7501 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7502 PackageParser.Provider p = entry.getValue(); 7503 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7504 7505 if (ps != null && p.syncable 7506 && (!mSafeMode || (p.info.applicationInfo.flags 7507 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7508 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7509 ps.readUserState(userId), userId); 7510 if (info != null) { 7511 outNames.add(entry.getKey()); 7512 outInfo.add(info); 7513 } 7514 } 7515 } 7516 } 7517 } 7518 7519 @Override 7520 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7521 int uid, int flags, String metaDataKey) { 7522 final int userId = processName != null ? UserHandle.getUserId(uid) 7523 : UserHandle.getCallingUserId(); 7524 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7525 flags = updateFlagsForComponent(flags, userId, processName); 7526 7527 ArrayList<ProviderInfo> finalList = null; 7528 // reader 7529 synchronized (mPackages) { 7530 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7531 while (i.hasNext()) { 7532 final PackageParser.Provider p = i.next(); 7533 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7534 if (ps != null && p.info.authority != null 7535 && (processName == null 7536 || (p.info.processName.equals(processName) 7537 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7538 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7539 7540 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7541 // parameter. 7542 if (metaDataKey != null 7543 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7544 continue; 7545 } 7546 7547 if (finalList == null) { 7548 finalList = new ArrayList<ProviderInfo>(3); 7549 } 7550 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7551 ps.readUserState(userId), userId); 7552 if (info != null) { 7553 finalList.add(info); 7554 } 7555 } 7556 } 7557 } 7558 7559 if (finalList != null) { 7560 Collections.sort(finalList, mProviderInitOrderSorter); 7561 return new ParceledListSlice<ProviderInfo>(finalList); 7562 } 7563 7564 return ParceledListSlice.emptyList(); 7565 } 7566 7567 @Override 7568 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7569 // reader 7570 synchronized (mPackages) { 7571 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7572 return PackageParser.generateInstrumentationInfo(i, flags); 7573 } 7574 } 7575 7576 @Override 7577 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7578 String targetPackage, int flags) { 7579 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7580 } 7581 7582 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7583 int flags) { 7584 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7585 7586 // reader 7587 synchronized (mPackages) { 7588 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7589 while (i.hasNext()) { 7590 final PackageParser.Instrumentation p = i.next(); 7591 if (targetPackage == null 7592 || targetPackage.equals(p.info.targetPackage)) { 7593 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7594 flags); 7595 if (ii != null) { 7596 finalList.add(ii); 7597 } 7598 } 7599 } 7600 } 7601 7602 return finalList; 7603 } 7604 7605 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7606 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7607 try { 7608 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7609 } finally { 7610 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7611 } 7612 } 7613 7614 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7615 final File[] files = dir.listFiles(); 7616 if (ArrayUtils.isEmpty(files)) { 7617 Log.d(TAG, "No files in app dir " + dir); 7618 return; 7619 } 7620 7621 if (DEBUG_PACKAGE_SCANNING) { 7622 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7623 + " flags=0x" + Integer.toHexString(parseFlags)); 7624 } 7625 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7626 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7627 7628 // Submit files for parsing in parallel 7629 int fileCount = 0; 7630 for (File file : files) { 7631 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7632 && !PackageInstallerService.isStageName(file.getName()); 7633 if (!isPackage) { 7634 // Ignore entries which are not packages 7635 continue; 7636 } 7637 parallelPackageParser.submit(file, parseFlags); 7638 fileCount++; 7639 } 7640 7641 // Process results one by one 7642 for (; fileCount > 0; fileCount--) { 7643 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7644 Throwable throwable = parseResult.throwable; 7645 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7646 7647 if (throwable == null) { 7648 // Static shared libraries have synthetic package names 7649 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7650 renameStaticSharedLibraryPackage(parseResult.pkg); 7651 } 7652 try { 7653 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7654 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7655 currentTime, null); 7656 } 7657 } catch (PackageManagerException e) { 7658 errorCode = e.error; 7659 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7660 } 7661 } else if (throwable instanceof PackageParser.PackageParserException) { 7662 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7663 throwable; 7664 errorCode = e.error; 7665 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7666 } else { 7667 throw new IllegalStateException("Unexpected exception occurred while parsing " 7668 + parseResult.scanFile, throwable); 7669 } 7670 7671 // Delete invalid userdata apps 7672 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7673 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7674 logCriticalInfo(Log.WARN, 7675 "Deleting invalid package at " + parseResult.scanFile); 7676 removeCodePathLI(parseResult.scanFile); 7677 } 7678 } 7679 parallelPackageParser.close(); 7680 } 7681 7682 private static File getSettingsProblemFile() { 7683 File dataDir = Environment.getDataDirectory(); 7684 File systemDir = new File(dataDir, "system"); 7685 File fname = new File(systemDir, "uiderrors.txt"); 7686 return fname; 7687 } 7688 7689 static void reportSettingsProblem(int priority, String msg) { 7690 logCriticalInfo(priority, msg); 7691 } 7692 7693 public static void logCriticalInfo(int priority, String msg) { 7694 Slog.println(priority, TAG, msg); 7695 EventLogTags.writePmCriticalInfo(msg); 7696 try { 7697 File fname = getSettingsProblemFile(); 7698 FileOutputStream out = new FileOutputStream(fname, true); 7699 PrintWriter pw = new FastPrintWriter(out); 7700 SimpleDateFormat formatter = new SimpleDateFormat(); 7701 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7702 pw.println(dateString + ": " + msg); 7703 pw.close(); 7704 FileUtils.setPermissions( 7705 fname.toString(), 7706 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7707 -1, -1); 7708 } catch (java.io.IOException e) { 7709 } 7710 } 7711 7712 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7713 if (srcFile.isDirectory()) { 7714 final File baseFile = new File(pkg.baseCodePath); 7715 long maxModifiedTime = baseFile.lastModified(); 7716 if (pkg.splitCodePaths != null) { 7717 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7718 final File splitFile = new File(pkg.splitCodePaths[i]); 7719 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7720 } 7721 } 7722 return maxModifiedTime; 7723 } 7724 return srcFile.lastModified(); 7725 } 7726 7727 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7728 final int policyFlags) throws PackageManagerException { 7729 // When upgrading from pre-N MR1, verify the package time stamp using the package 7730 // directory and not the APK file. 7731 final long lastModifiedTime = mIsPreNMR1Upgrade 7732 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7733 if (ps != null 7734 && ps.codePath.equals(srcFile) 7735 && ps.timeStamp == lastModifiedTime 7736 && !isCompatSignatureUpdateNeeded(pkg) 7737 && !isRecoverSignatureUpdateNeeded(pkg)) { 7738 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7739 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7740 ArraySet<PublicKey> signingKs; 7741 synchronized (mPackages) { 7742 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7743 } 7744 if (ps.signatures.mSignatures != null 7745 && ps.signatures.mSignatures.length != 0 7746 && signingKs != null) { 7747 // Optimization: reuse the existing cached certificates 7748 // if the package appears to be unchanged. 7749 pkg.mSignatures = ps.signatures.mSignatures; 7750 pkg.mSigningKeys = signingKs; 7751 return; 7752 } 7753 7754 Slog.w(TAG, "PackageSetting for " + ps.name 7755 + " is missing signatures. Collecting certs again to recover them."); 7756 } else { 7757 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7758 } 7759 7760 try { 7761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7762 PackageParser.collectCertificates(pkg, policyFlags); 7763 } catch (PackageParserException e) { 7764 throw PackageManagerException.from(e); 7765 } finally { 7766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7767 } 7768 } 7769 7770 /** 7771 * Traces a package scan. 7772 * @see #scanPackageLI(File, int, int, long, UserHandle) 7773 */ 7774 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7775 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7776 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7777 try { 7778 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7779 } finally { 7780 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7781 } 7782 } 7783 7784 /** 7785 * Scans a package and returns the newly parsed package. 7786 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7787 */ 7788 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7789 long currentTime, UserHandle user) throws PackageManagerException { 7790 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7791 PackageParser pp = new PackageParser(); 7792 pp.setSeparateProcesses(mSeparateProcesses); 7793 pp.setOnlyCoreApps(mOnlyCore); 7794 pp.setDisplayMetrics(mMetrics); 7795 pp.setCallback(mPackageParserCallback); 7796 7797 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7798 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7799 } 7800 7801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7802 final PackageParser.Package pkg; 7803 try { 7804 pkg = pp.parsePackage(scanFile, parseFlags); 7805 } catch (PackageParserException e) { 7806 throw PackageManagerException.from(e); 7807 } finally { 7808 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7809 } 7810 7811 // Static shared libraries have synthetic package names 7812 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7813 renameStaticSharedLibraryPackage(pkg); 7814 } 7815 7816 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7817 } 7818 7819 /** 7820 * Scans a package and returns the newly parsed package. 7821 * @throws PackageManagerException on a parse error. 7822 */ 7823 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7824 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7825 throws PackageManagerException { 7826 // If the package has children and this is the first dive in the function 7827 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7828 // packages (parent and children) would be successfully scanned before the 7829 // actual scan since scanning mutates internal state and we want to atomically 7830 // install the package and its children. 7831 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7832 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7833 scanFlags |= SCAN_CHECK_ONLY; 7834 } 7835 } else { 7836 scanFlags &= ~SCAN_CHECK_ONLY; 7837 } 7838 7839 // Scan the parent 7840 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7841 scanFlags, currentTime, user); 7842 7843 // Scan the children 7844 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7845 for (int i = 0; i < childCount; i++) { 7846 PackageParser.Package childPackage = pkg.childPackages.get(i); 7847 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7848 currentTime, user); 7849 } 7850 7851 7852 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7853 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7854 } 7855 7856 return scannedPkg; 7857 } 7858 7859 /** 7860 * Scans a package and returns the newly parsed package. 7861 * @throws PackageManagerException on a parse error. 7862 */ 7863 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7864 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7865 throws PackageManagerException { 7866 PackageSetting ps = null; 7867 PackageSetting updatedPkg; 7868 // reader 7869 synchronized (mPackages) { 7870 // Look to see if we already know about this package. 7871 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7872 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7873 // This package has been renamed to its original name. Let's 7874 // use that. 7875 ps = mSettings.getPackageLPr(oldName); 7876 } 7877 // If there was no original package, see one for the real package name. 7878 if (ps == null) { 7879 ps = mSettings.getPackageLPr(pkg.packageName); 7880 } 7881 // Check to see if this package could be hiding/updating a system 7882 // package. Must look for it either under the original or real 7883 // package name depending on our state. 7884 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7885 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7886 7887 // If this is a package we don't know about on the system partition, we 7888 // may need to remove disabled child packages on the system partition 7889 // or may need to not add child packages if the parent apk is updated 7890 // on the data partition and no longer defines this child package. 7891 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7892 // If this is a parent package for an updated system app and this system 7893 // app got an OTA update which no longer defines some of the child packages 7894 // we have to prune them from the disabled system packages. 7895 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7896 if (disabledPs != null) { 7897 final int scannedChildCount = (pkg.childPackages != null) 7898 ? pkg.childPackages.size() : 0; 7899 final int disabledChildCount = disabledPs.childPackageNames != null 7900 ? disabledPs.childPackageNames.size() : 0; 7901 for (int i = 0; i < disabledChildCount; i++) { 7902 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7903 boolean disabledPackageAvailable = false; 7904 for (int j = 0; j < scannedChildCount; j++) { 7905 PackageParser.Package childPkg = pkg.childPackages.get(j); 7906 if (childPkg.packageName.equals(disabledChildPackageName)) { 7907 disabledPackageAvailable = true; 7908 break; 7909 } 7910 } 7911 if (!disabledPackageAvailable) { 7912 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7913 } 7914 } 7915 } 7916 } 7917 } 7918 7919 boolean updatedPkgBetter = false; 7920 // First check if this is a system package that may involve an update 7921 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7922 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7923 // it needs to drop FLAG_PRIVILEGED. 7924 if (locationIsPrivileged(scanFile)) { 7925 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7926 } else { 7927 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7928 } 7929 7930 if (ps != null && !ps.codePath.equals(scanFile)) { 7931 // The path has changed from what was last scanned... check the 7932 // version of the new path against what we have stored to determine 7933 // what to do. 7934 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7935 if (pkg.mVersionCode <= ps.versionCode) { 7936 // The system package has been updated and the code path does not match 7937 // Ignore entry. Skip it. 7938 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7939 + " ignored: updated version " + ps.versionCode 7940 + " better than this " + pkg.mVersionCode); 7941 if (!updatedPkg.codePath.equals(scanFile)) { 7942 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7943 + ps.name + " changing from " + updatedPkg.codePathString 7944 + " to " + scanFile); 7945 updatedPkg.codePath = scanFile; 7946 updatedPkg.codePathString = scanFile.toString(); 7947 updatedPkg.resourcePath = scanFile; 7948 updatedPkg.resourcePathString = scanFile.toString(); 7949 } 7950 updatedPkg.pkg = pkg; 7951 updatedPkg.versionCode = pkg.mVersionCode; 7952 7953 // Update the disabled system child packages to point to the package too. 7954 final int childCount = updatedPkg.childPackageNames != null 7955 ? updatedPkg.childPackageNames.size() : 0; 7956 for (int i = 0; i < childCount; i++) { 7957 String childPackageName = updatedPkg.childPackageNames.get(i); 7958 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7959 childPackageName); 7960 if (updatedChildPkg != null) { 7961 updatedChildPkg.pkg = pkg; 7962 updatedChildPkg.versionCode = pkg.mVersionCode; 7963 } 7964 } 7965 7966 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7967 + scanFile + " ignored: updated version " + ps.versionCode 7968 + " better than this " + pkg.mVersionCode); 7969 } else { 7970 // The current app on the system partition is better than 7971 // what we have updated to on the data partition; switch 7972 // back to the system partition version. 7973 // At this point, its safely assumed that package installation for 7974 // apps in system partition will go through. If not there won't be a working 7975 // version of the app 7976 // writer 7977 synchronized (mPackages) { 7978 // Just remove the loaded entries from package lists. 7979 mPackages.remove(ps.name); 7980 } 7981 7982 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7983 + " reverting from " + ps.codePathString 7984 + ": new version " + pkg.mVersionCode 7985 + " better than installed " + ps.versionCode); 7986 7987 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7988 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7989 synchronized (mInstallLock) { 7990 args.cleanUpResourcesLI(); 7991 } 7992 synchronized (mPackages) { 7993 mSettings.enableSystemPackageLPw(ps.name); 7994 } 7995 updatedPkgBetter = true; 7996 } 7997 } 7998 } 7999 8000 if (updatedPkg != null) { 8001 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8002 // initially 8003 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8004 8005 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8006 // flag set initially 8007 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8008 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8009 } 8010 } 8011 8012 // Verify certificates against what was last scanned 8013 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8014 8015 /* 8016 * A new system app appeared, but we already had a non-system one of the 8017 * same name installed earlier. 8018 */ 8019 boolean shouldHideSystemApp = false; 8020 if (updatedPkg == null && ps != null 8021 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8022 /* 8023 * Check to make sure the signatures match first. If they don't, 8024 * wipe the installed application and its data. 8025 */ 8026 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8027 != PackageManager.SIGNATURE_MATCH) { 8028 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8029 + " signatures don't match existing userdata copy; removing"); 8030 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8031 "scanPackageInternalLI")) { 8032 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8033 } 8034 ps = null; 8035 } else { 8036 /* 8037 * If the newly-added system app is an older version than the 8038 * already installed version, hide it. It will be scanned later 8039 * and re-added like an update. 8040 */ 8041 if (pkg.mVersionCode <= ps.versionCode) { 8042 shouldHideSystemApp = true; 8043 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8044 + " but new version " + pkg.mVersionCode + " better than installed " 8045 + ps.versionCode + "; hiding system"); 8046 } else { 8047 /* 8048 * The newly found system app is a newer version that the 8049 * one previously installed. Simply remove the 8050 * already-installed application and replace it with our own 8051 * while keeping the application data. 8052 */ 8053 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8054 + " reverting from " + ps.codePathString + ": new version " 8055 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8056 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8057 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8058 synchronized (mInstallLock) { 8059 args.cleanUpResourcesLI(); 8060 } 8061 } 8062 } 8063 } 8064 8065 // The apk is forward locked (not public) if its code and resources 8066 // are kept in different files. (except for app in either system or 8067 // vendor path). 8068 // TODO grab this value from PackageSettings 8069 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8070 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8071 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8072 } 8073 } 8074 8075 // TODO: extend to support forward-locked splits 8076 String resourcePath = null; 8077 String baseResourcePath = null; 8078 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8079 if (ps != null && ps.resourcePathString != null) { 8080 resourcePath = ps.resourcePathString; 8081 baseResourcePath = ps.resourcePathString; 8082 } else { 8083 // Should not happen at all. Just log an error. 8084 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8085 } 8086 } else { 8087 resourcePath = pkg.codePath; 8088 baseResourcePath = pkg.baseCodePath; 8089 } 8090 8091 // Set application objects path explicitly. 8092 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8093 pkg.setApplicationInfoCodePath(pkg.codePath); 8094 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8095 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8096 pkg.setApplicationInfoResourcePath(resourcePath); 8097 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8098 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8099 8100 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8101 if (ps != null && ps.getInstantApp(userId)) { 8102 scanFlags |= SCAN_AS_INSTANT_APP; 8103 } 8104 8105 // Note that we invoke the following method only if we are about to unpack an application 8106 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8107 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8108 8109 /* 8110 * If the system app should be overridden by a previously installed 8111 * data, hide the system app now and let the /data/app scan pick it up 8112 * again. 8113 */ 8114 if (shouldHideSystemApp) { 8115 synchronized (mPackages) { 8116 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8117 } 8118 } 8119 8120 return scannedPkg; 8121 } 8122 8123 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8124 // Derive the new package synthetic package name 8125 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8126 + pkg.staticSharedLibVersion); 8127 } 8128 8129 private static String fixProcessName(String defProcessName, 8130 String processName) { 8131 if (processName == null) { 8132 return defProcessName; 8133 } 8134 return processName; 8135 } 8136 8137 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8138 throws PackageManagerException { 8139 if (pkgSetting.signatures.mSignatures != null) { 8140 // Already existing package. Make sure signatures match 8141 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8142 == PackageManager.SIGNATURE_MATCH; 8143 if (!match) { 8144 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8145 == PackageManager.SIGNATURE_MATCH; 8146 } 8147 if (!match) { 8148 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8149 == PackageManager.SIGNATURE_MATCH; 8150 } 8151 if (!match) { 8152 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8153 + pkg.packageName + " signatures do not match the " 8154 + "previously installed version; ignoring!"); 8155 } 8156 } 8157 8158 // Check for shared user signatures 8159 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8160 // Already existing package. Make sure signatures match 8161 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8162 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8163 if (!match) { 8164 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8165 == PackageManager.SIGNATURE_MATCH; 8166 } 8167 if (!match) { 8168 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8169 == PackageManager.SIGNATURE_MATCH; 8170 } 8171 if (!match) { 8172 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8173 "Package " + pkg.packageName 8174 + " has no signatures that match those in shared user " 8175 + pkgSetting.sharedUser.name + "; ignoring!"); 8176 } 8177 } 8178 } 8179 8180 /** 8181 * Enforces that only the system UID or root's UID can call a method exposed 8182 * via Binder. 8183 * 8184 * @param message used as message if SecurityException is thrown 8185 * @throws SecurityException if the caller is not system or root 8186 */ 8187 private static final void enforceSystemOrRoot(String message) { 8188 final int uid = Binder.getCallingUid(); 8189 if (uid != Process.SYSTEM_UID && uid != 0) { 8190 throw new SecurityException(message); 8191 } 8192 } 8193 8194 @Override 8195 public void performFstrimIfNeeded() { 8196 enforceSystemOrRoot("Only the system can request fstrim"); 8197 8198 // Before everything else, see whether we need to fstrim. 8199 try { 8200 IStorageManager sm = PackageHelper.getStorageManager(); 8201 if (sm != null) { 8202 boolean doTrim = false; 8203 final long interval = android.provider.Settings.Global.getLong( 8204 mContext.getContentResolver(), 8205 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8206 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8207 if (interval > 0) { 8208 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8209 if (timeSinceLast > interval) { 8210 doTrim = true; 8211 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8212 + "; running immediately"); 8213 } 8214 } 8215 if (doTrim) { 8216 final boolean dexOptDialogShown; 8217 synchronized (mPackages) { 8218 dexOptDialogShown = mDexOptDialogShown; 8219 } 8220 if (!isFirstBoot() && dexOptDialogShown) { 8221 try { 8222 ActivityManager.getService().showBootMessage( 8223 mContext.getResources().getString( 8224 R.string.android_upgrading_fstrim), true); 8225 } catch (RemoteException e) { 8226 } 8227 } 8228 sm.runMaintenance(); 8229 } 8230 } else { 8231 Slog.e(TAG, "storageManager service unavailable!"); 8232 } 8233 } catch (RemoteException e) { 8234 // Can't happen; StorageManagerService is local 8235 } 8236 } 8237 8238 @Override 8239 public void updatePackagesIfNeeded() { 8240 enforceSystemOrRoot("Only the system can request package update"); 8241 8242 // We need to re-extract after an OTA. 8243 boolean causeUpgrade = isUpgrade(); 8244 8245 // First boot or factory reset. 8246 // Note: we also handle devices that are upgrading to N right now as if it is their 8247 // first boot, as they do not have profile data. 8248 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8249 8250 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8251 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8252 8253 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8254 return; 8255 } 8256 8257 List<PackageParser.Package> pkgs; 8258 synchronized (mPackages) { 8259 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8260 } 8261 8262 final long startTime = System.nanoTime(); 8263 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8264 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8265 8266 final int elapsedTimeSeconds = 8267 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8268 8269 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8270 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8271 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8272 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8273 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8274 } 8275 8276 /** 8277 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8278 * containing statistics about the invocation. The array consists of three elements, 8279 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8280 * and {@code numberOfPackagesFailed}. 8281 */ 8282 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8283 String compilerFilter) { 8284 8285 int numberOfPackagesVisited = 0; 8286 int numberOfPackagesOptimized = 0; 8287 int numberOfPackagesSkipped = 0; 8288 int numberOfPackagesFailed = 0; 8289 final int numberOfPackagesToDexopt = pkgs.size(); 8290 8291 for (PackageParser.Package pkg : pkgs) { 8292 numberOfPackagesVisited++; 8293 8294 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8295 if (DEBUG_DEXOPT) { 8296 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8297 } 8298 numberOfPackagesSkipped++; 8299 continue; 8300 } 8301 8302 if (DEBUG_DEXOPT) { 8303 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8304 numberOfPackagesToDexopt + ": " + pkg.packageName); 8305 } 8306 8307 if (showDialog) { 8308 try { 8309 ActivityManager.getService().showBootMessage( 8310 mContext.getResources().getString(R.string.android_upgrading_apk, 8311 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8312 } catch (RemoteException e) { 8313 } 8314 synchronized (mPackages) { 8315 mDexOptDialogShown = true; 8316 } 8317 } 8318 8319 // If the OTA updates a system app which was previously preopted to a non-preopted state 8320 // the app might end up being verified at runtime. That's because by default the apps 8321 // are verify-profile but for preopted apps there's no profile. 8322 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8323 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8324 // filter (by default interpret-only). 8325 // Note that at this stage unused apps are already filtered. 8326 if (isSystemApp(pkg) && 8327 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8328 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8329 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8330 } 8331 8332 // checkProfiles is false to avoid merging profiles during boot which 8333 // might interfere with background compilation (b/28612421). 8334 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8335 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8336 // trade-off worth doing to save boot time work. 8337 int dexOptStatus = performDexOptTraced(pkg.packageName, 8338 false /* checkProfiles */, 8339 compilerFilter, 8340 false /* force */); 8341 switch (dexOptStatus) { 8342 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8343 numberOfPackagesOptimized++; 8344 break; 8345 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8346 numberOfPackagesSkipped++; 8347 break; 8348 case PackageDexOptimizer.DEX_OPT_FAILED: 8349 numberOfPackagesFailed++; 8350 break; 8351 default: 8352 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8353 break; 8354 } 8355 } 8356 8357 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8358 numberOfPackagesFailed }; 8359 } 8360 8361 @Override 8362 public void notifyPackageUse(String packageName, int reason) { 8363 synchronized (mPackages) { 8364 PackageParser.Package p = mPackages.get(packageName); 8365 if (p == null) { 8366 return; 8367 } 8368 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8369 } 8370 } 8371 8372 @Override 8373 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8374 int userId = UserHandle.getCallingUserId(); 8375 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8376 if (ai == null) { 8377 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8378 + loadingPackageName + ", user=" + userId); 8379 return; 8380 } 8381 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8382 } 8383 8384 // TODO: this is not used nor needed. Delete it. 8385 @Override 8386 public boolean performDexOptIfNeeded(String packageName) { 8387 int dexOptStatus = performDexOptTraced(packageName, 8388 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8389 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8390 } 8391 8392 @Override 8393 public boolean performDexOpt(String packageName, 8394 boolean checkProfiles, int compileReason, boolean force) { 8395 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8396 getCompilerFilterForReason(compileReason), force); 8397 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8398 } 8399 8400 @Override 8401 public boolean performDexOptMode(String packageName, 8402 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8403 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8404 targetCompilerFilter, force); 8405 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8406 } 8407 8408 private int performDexOptTraced(String packageName, 8409 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8410 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8411 try { 8412 return performDexOptInternal(packageName, checkProfiles, 8413 targetCompilerFilter, force); 8414 } finally { 8415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8416 } 8417 } 8418 8419 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8420 // if the package can now be considered up to date for the given filter. 8421 private int performDexOptInternal(String packageName, 8422 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8423 PackageParser.Package p; 8424 synchronized (mPackages) { 8425 p = mPackages.get(packageName); 8426 if (p == null) { 8427 // Package could not be found. Report failure. 8428 return PackageDexOptimizer.DEX_OPT_FAILED; 8429 } 8430 mPackageUsage.maybeWriteAsync(mPackages); 8431 mCompilerStats.maybeWriteAsync(); 8432 } 8433 long callingId = Binder.clearCallingIdentity(); 8434 try { 8435 synchronized (mInstallLock) { 8436 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8437 targetCompilerFilter, force); 8438 } 8439 } finally { 8440 Binder.restoreCallingIdentity(callingId); 8441 } 8442 } 8443 8444 public ArraySet<String> getOptimizablePackages() { 8445 ArraySet<String> pkgs = new ArraySet<String>(); 8446 synchronized (mPackages) { 8447 for (PackageParser.Package p : mPackages.values()) { 8448 if (PackageDexOptimizer.canOptimizePackage(p)) { 8449 pkgs.add(p.packageName); 8450 } 8451 } 8452 } 8453 return pkgs; 8454 } 8455 8456 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8457 boolean checkProfiles, String targetCompilerFilter, 8458 boolean force) { 8459 // Select the dex optimizer based on the force parameter. 8460 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8461 // allocate an object here. 8462 PackageDexOptimizer pdo = force 8463 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8464 : mPackageDexOptimizer; 8465 8466 // Optimize all dependencies first. Note: we ignore the return value and march on 8467 // on errors. 8468 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8469 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8470 if (!deps.isEmpty()) { 8471 for (PackageParser.Package depPackage : deps) { 8472 // TODO: Analyze and investigate if we (should) profile libraries. 8473 // Currently this will do a full compilation of the library by default. 8474 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8475 false /* checkProfiles */, 8476 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8477 getOrCreateCompilerPackageStats(depPackage), 8478 mDexManager.isUsedByOtherApps(p.packageName)); 8479 } 8480 } 8481 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8482 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8483 mDexManager.isUsedByOtherApps(p.packageName)); 8484 } 8485 8486 // Performs dexopt on the used secondary dex files belonging to the given package. 8487 // Returns true if all dex files were process successfully (which could mean either dexopt or 8488 // skip). Returns false if any of the files caused errors. 8489 @Override 8490 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8491 boolean force) { 8492 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8493 } 8494 8495 public boolean performDexOptSecondary(String packageName, int compileReason, 8496 boolean force) { 8497 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8498 } 8499 8500 /** 8501 * Reconcile the information we have about the secondary dex files belonging to 8502 * {@code packagName} and the actual dex files. For all dex files that were 8503 * deleted, update the internal records and delete the generated oat files. 8504 */ 8505 @Override 8506 public void reconcileSecondaryDexFiles(String packageName) { 8507 mDexManager.reconcileSecondaryDexFiles(packageName); 8508 } 8509 8510 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8511 // a reference there. 8512 /*package*/ DexManager getDexManager() { 8513 return mDexManager; 8514 } 8515 8516 /** 8517 * Execute the background dexopt job immediately. 8518 */ 8519 @Override 8520 public boolean runBackgroundDexoptJob() { 8521 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8522 } 8523 8524 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8525 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8526 || p.usesStaticLibraries != null) { 8527 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8528 Set<String> collectedNames = new HashSet<>(); 8529 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8530 8531 retValue.remove(p); 8532 8533 return retValue; 8534 } else { 8535 return Collections.emptyList(); 8536 } 8537 } 8538 8539 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8540 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8541 if (!collectedNames.contains(p.packageName)) { 8542 collectedNames.add(p.packageName); 8543 collected.add(p); 8544 8545 if (p.usesLibraries != null) { 8546 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8547 null, collected, collectedNames); 8548 } 8549 if (p.usesOptionalLibraries != null) { 8550 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8551 null, collected, collectedNames); 8552 } 8553 if (p.usesStaticLibraries != null) { 8554 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8555 p.usesStaticLibrariesVersions, collected, collectedNames); 8556 } 8557 } 8558 } 8559 8560 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8561 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8562 final int libNameCount = libs.size(); 8563 for (int i = 0; i < libNameCount; i++) { 8564 String libName = libs.get(i); 8565 int version = (versions != null && versions.length == libNameCount) 8566 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8567 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8568 if (libPkg != null) { 8569 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8570 } 8571 } 8572 } 8573 8574 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8575 synchronized (mPackages) { 8576 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8577 if (libEntry != null) { 8578 return mPackages.get(libEntry.apk); 8579 } 8580 return null; 8581 } 8582 } 8583 8584 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8585 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8586 if (versionedLib == null) { 8587 return null; 8588 } 8589 return versionedLib.get(version); 8590 } 8591 8592 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8593 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8594 pkg.staticSharedLibName); 8595 if (versionedLib == null) { 8596 return null; 8597 } 8598 int previousLibVersion = -1; 8599 final int versionCount = versionedLib.size(); 8600 for (int i = 0; i < versionCount; i++) { 8601 final int libVersion = versionedLib.keyAt(i); 8602 if (libVersion < pkg.staticSharedLibVersion) { 8603 previousLibVersion = Math.max(previousLibVersion, libVersion); 8604 } 8605 } 8606 if (previousLibVersion >= 0) { 8607 return versionedLib.get(previousLibVersion); 8608 } 8609 return null; 8610 } 8611 8612 public void shutdown() { 8613 mPackageUsage.writeNow(mPackages); 8614 mCompilerStats.writeNow(); 8615 } 8616 8617 @Override 8618 public void dumpProfiles(String packageName) { 8619 PackageParser.Package pkg; 8620 synchronized (mPackages) { 8621 pkg = mPackages.get(packageName); 8622 if (pkg == null) { 8623 throw new IllegalArgumentException("Unknown package: " + packageName); 8624 } 8625 } 8626 /* Only the shell, root, or the app user should be able to dump profiles. */ 8627 int callingUid = Binder.getCallingUid(); 8628 if (callingUid != Process.SHELL_UID && 8629 callingUid != Process.ROOT_UID && 8630 callingUid != pkg.applicationInfo.uid) { 8631 throw new SecurityException("dumpProfiles"); 8632 } 8633 8634 synchronized (mInstallLock) { 8635 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8636 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8637 try { 8638 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8639 String codePaths = TextUtils.join(";", allCodePaths); 8640 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8641 } catch (InstallerException e) { 8642 Slog.w(TAG, "Failed to dump profiles", e); 8643 } 8644 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8645 } 8646 } 8647 8648 @Override 8649 public void forceDexOpt(String packageName) { 8650 enforceSystemOrRoot("forceDexOpt"); 8651 8652 PackageParser.Package pkg; 8653 synchronized (mPackages) { 8654 pkg = mPackages.get(packageName); 8655 if (pkg == null) { 8656 throw new IllegalArgumentException("Unknown package: " + packageName); 8657 } 8658 } 8659 8660 synchronized (mInstallLock) { 8661 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8662 8663 // Whoever is calling forceDexOpt wants a fully compiled package. 8664 // Don't use profiles since that may cause compilation to be skipped. 8665 final int res = performDexOptInternalWithDependenciesLI(pkg, 8666 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8667 true /* force */); 8668 8669 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8670 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8671 throw new IllegalStateException("Failed to dexopt: " + res); 8672 } 8673 } 8674 } 8675 8676 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8677 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8678 Slog.w(TAG, "Unable to update from " + oldPkg.name 8679 + " to " + newPkg.packageName 8680 + ": old package not in system partition"); 8681 return false; 8682 } else if (mPackages.get(oldPkg.name) != null) { 8683 Slog.w(TAG, "Unable to update from " + oldPkg.name 8684 + " to " + newPkg.packageName 8685 + ": old package still exists"); 8686 return false; 8687 } 8688 return true; 8689 } 8690 8691 void removeCodePathLI(File codePath) { 8692 if (codePath.isDirectory()) { 8693 try { 8694 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8695 } catch (InstallerException e) { 8696 Slog.w(TAG, "Failed to remove code path", e); 8697 } 8698 } else { 8699 codePath.delete(); 8700 } 8701 } 8702 8703 private int[] resolveUserIds(int userId) { 8704 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8705 } 8706 8707 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8708 if (pkg == null) { 8709 Slog.wtf(TAG, "Package was null!", new Throwable()); 8710 return; 8711 } 8712 clearAppDataLeafLIF(pkg, userId, flags); 8713 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8714 for (int i = 0; i < childCount; i++) { 8715 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8716 } 8717 } 8718 8719 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8720 final PackageSetting ps; 8721 synchronized (mPackages) { 8722 ps = mSettings.mPackages.get(pkg.packageName); 8723 } 8724 for (int realUserId : resolveUserIds(userId)) { 8725 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8726 try { 8727 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8728 ceDataInode); 8729 } catch (InstallerException e) { 8730 Slog.w(TAG, String.valueOf(e)); 8731 } 8732 } 8733 } 8734 8735 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8736 if (pkg == null) { 8737 Slog.wtf(TAG, "Package was null!", new Throwable()); 8738 return; 8739 } 8740 destroyAppDataLeafLIF(pkg, userId, flags); 8741 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8742 for (int i = 0; i < childCount; i++) { 8743 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8744 } 8745 } 8746 8747 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8748 final PackageSetting ps; 8749 synchronized (mPackages) { 8750 ps = mSettings.mPackages.get(pkg.packageName); 8751 } 8752 for (int realUserId : resolveUserIds(userId)) { 8753 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8754 try { 8755 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8756 ceDataInode); 8757 } catch (InstallerException e) { 8758 Slog.w(TAG, String.valueOf(e)); 8759 } 8760 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8761 } 8762 } 8763 8764 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8765 if (pkg == null) { 8766 Slog.wtf(TAG, "Package was null!", new Throwable()); 8767 return; 8768 } 8769 destroyAppProfilesLeafLIF(pkg); 8770 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8771 for (int i = 0; i < childCount; i++) { 8772 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8773 } 8774 } 8775 8776 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8777 try { 8778 mInstaller.destroyAppProfiles(pkg.packageName); 8779 } catch (InstallerException e) { 8780 Slog.w(TAG, String.valueOf(e)); 8781 } 8782 } 8783 8784 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8785 if (pkg == null) { 8786 Slog.wtf(TAG, "Package was null!", new Throwable()); 8787 return; 8788 } 8789 clearAppProfilesLeafLIF(pkg); 8790 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8791 for (int i = 0; i < childCount; i++) { 8792 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8793 } 8794 } 8795 8796 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8797 try { 8798 mInstaller.clearAppProfiles(pkg.packageName); 8799 } catch (InstallerException e) { 8800 Slog.w(TAG, String.valueOf(e)); 8801 } 8802 } 8803 8804 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8805 long lastUpdateTime) { 8806 // Set parent install/update time 8807 PackageSetting ps = (PackageSetting) pkg.mExtras; 8808 if (ps != null) { 8809 ps.firstInstallTime = firstInstallTime; 8810 ps.lastUpdateTime = lastUpdateTime; 8811 } 8812 // Set children install/update time 8813 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8814 for (int i = 0; i < childCount; i++) { 8815 PackageParser.Package childPkg = pkg.childPackages.get(i); 8816 ps = (PackageSetting) childPkg.mExtras; 8817 if (ps != null) { 8818 ps.firstInstallTime = firstInstallTime; 8819 ps.lastUpdateTime = lastUpdateTime; 8820 } 8821 } 8822 } 8823 8824 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8825 PackageParser.Package changingLib) { 8826 if (file.path != null) { 8827 usesLibraryFiles.add(file.path); 8828 return; 8829 } 8830 PackageParser.Package p = mPackages.get(file.apk); 8831 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8832 // If we are doing this while in the middle of updating a library apk, 8833 // then we need to make sure to use that new apk for determining the 8834 // dependencies here. (We haven't yet finished committing the new apk 8835 // to the package manager state.) 8836 if (p == null || p.packageName.equals(changingLib.packageName)) { 8837 p = changingLib; 8838 } 8839 } 8840 if (p != null) { 8841 usesLibraryFiles.addAll(p.getAllCodePaths()); 8842 } 8843 } 8844 8845 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8846 PackageParser.Package changingLib) throws PackageManagerException { 8847 if (pkg == null) { 8848 return; 8849 } 8850 ArraySet<String> usesLibraryFiles = null; 8851 if (pkg.usesLibraries != null) { 8852 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8853 null, null, pkg.packageName, changingLib, true, null); 8854 } 8855 if (pkg.usesStaticLibraries != null) { 8856 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8857 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8858 pkg.packageName, changingLib, true, usesLibraryFiles); 8859 } 8860 if (pkg.usesOptionalLibraries != null) { 8861 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8862 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8863 } 8864 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8865 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8866 } else { 8867 pkg.usesLibraryFiles = null; 8868 } 8869 } 8870 8871 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8872 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8873 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8874 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8875 throws PackageManagerException { 8876 final int libCount = requestedLibraries.size(); 8877 for (int i = 0; i < libCount; i++) { 8878 final String libName = requestedLibraries.get(i); 8879 final int libVersion = requiredVersions != null ? requiredVersions[i] 8880 : SharedLibraryInfo.VERSION_UNDEFINED; 8881 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8882 if (libEntry == null) { 8883 if (required) { 8884 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8885 "Package " + packageName + " requires unavailable shared library " 8886 + libName + "; failing!"); 8887 } else { 8888 Slog.w(TAG, "Package " + packageName 8889 + " desires unavailable shared library " 8890 + libName + "; ignoring!"); 8891 } 8892 } else { 8893 if (requiredVersions != null && requiredCertDigests != null) { 8894 if (libEntry.info.getVersion() != requiredVersions[i]) { 8895 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8896 "Package " + packageName + " requires unavailable static shared" 8897 + " library " + libName + " version " 8898 + libEntry.info.getVersion() + "; failing!"); 8899 } 8900 8901 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8902 if (libPkg == null) { 8903 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8904 "Package " + packageName + " requires unavailable static shared" 8905 + " library; failing!"); 8906 } 8907 8908 String expectedCertDigest = requiredCertDigests[i]; 8909 String libCertDigest = PackageUtils.computeCertSha256Digest( 8910 libPkg.mSignatures[0]); 8911 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8912 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8913 "Package " + packageName + " requires differently signed" + 8914 " static shared library; failing!"); 8915 } 8916 } 8917 8918 if (outUsedLibraries == null) { 8919 outUsedLibraries = new ArraySet<>(); 8920 } 8921 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8922 } 8923 } 8924 return outUsedLibraries; 8925 } 8926 8927 private static boolean hasString(List<String> list, List<String> which) { 8928 if (list == null) { 8929 return false; 8930 } 8931 for (int i=list.size()-1; i>=0; i--) { 8932 for (int j=which.size()-1; j>=0; j--) { 8933 if (which.get(j).equals(list.get(i))) { 8934 return true; 8935 } 8936 } 8937 } 8938 return false; 8939 } 8940 8941 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8942 PackageParser.Package changingPkg) { 8943 ArrayList<PackageParser.Package> res = null; 8944 for (PackageParser.Package pkg : mPackages.values()) { 8945 if (changingPkg != null 8946 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8947 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8948 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8949 changingPkg.staticSharedLibName)) { 8950 return null; 8951 } 8952 if (res == null) { 8953 res = new ArrayList<>(); 8954 } 8955 res.add(pkg); 8956 try { 8957 updateSharedLibrariesLPr(pkg, changingPkg); 8958 } catch (PackageManagerException e) { 8959 // If a system app update or an app and a required lib missing we 8960 // delete the package and for updated system apps keep the data as 8961 // it is better for the user to reinstall than to be in an limbo 8962 // state. Also libs disappearing under an app should never happen 8963 // - just in case. 8964 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8965 final int flags = pkg.isUpdatedSystemApp() 8966 ? PackageManager.DELETE_KEEP_DATA : 0; 8967 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8968 flags , null, true, null); 8969 } 8970 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8971 } 8972 } 8973 return res; 8974 } 8975 8976 /** 8977 * Derive the value of the {@code cpuAbiOverride} based on the provided 8978 * value and an optional stored value from the package settings. 8979 */ 8980 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8981 String cpuAbiOverride = null; 8982 8983 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8984 cpuAbiOverride = null; 8985 } else if (abiOverride != null) { 8986 cpuAbiOverride = abiOverride; 8987 } else if (settings != null) { 8988 cpuAbiOverride = settings.cpuAbiOverrideString; 8989 } 8990 8991 return cpuAbiOverride; 8992 } 8993 8994 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8995 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8996 throws PackageManagerException { 8997 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8998 // If the package has children and this is the first dive in the function 8999 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9000 // whether all packages (parent and children) would be successfully scanned 9001 // before the actual scan since scanning mutates internal state and we want 9002 // to atomically install the package and its children. 9003 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9004 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9005 scanFlags |= SCAN_CHECK_ONLY; 9006 } 9007 } else { 9008 scanFlags &= ~SCAN_CHECK_ONLY; 9009 } 9010 9011 final PackageParser.Package scannedPkg; 9012 try { 9013 // Scan the parent 9014 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9015 // Scan the children 9016 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9017 for (int i = 0; i < childCount; i++) { 9018 PackageParser.Package childPkg = pkg.childPackages.get(i); 9019 scanPackageLI(childPkg, policyFlags, 9020 scanFlags, currentTime, user); 9021 } 9022 } finally { 9023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9024 } 9025 9026 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9027 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9028 } 9029 9030 return scannedPkg; 9031 } 9032 9033 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9034 int scanFlags, long currentTime, @Nullable UserHandle user) 9035 throws PackageManagerException { 9036 boolean success = false; 9037 try { 9038 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9039 currentTime, user); 9040 success = true; 9041 return res; 9042 } finally { 9043 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9044 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9045 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9046 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9047 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9048 } 9049 } 9050 } 9051 9052 /** 9053 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9054 */ 9055 private static boolean apkHasCode(String fileName) { 9056 StrictJarFile jarFile = null; 9057 try { 9058 jarFile = new StrictJarFile(fileName, 9059 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9060 return jarFile.findEntry("classes.dex") != null; 9061 } catch (IOException ignore) { 9062 } finally { 9063 try { 9064 if (jarFile != null) { 9065 jarFile.close(); 9066 } 9067 } catch (IOException ignore) {} 9068 } 9069 return false; 9070 } 9071 9072 /** 9073 * Enforces code policy for the package. This ensures that if an APK has 9074 * declared hasCode="true" in its manifest that the APK actually contains 9075 * code. 9076 * 9077 * @throws PackageManagerException If bytecode could not be found when it should exist 9078 */ 9079 private static void assertCodePolicy(PackageParser.Package pkg) 9080 throws PackageManagerException { 9081 final boolean shouldHaveCode = 9082 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9083 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9084 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9085 "Package " + pkg.baseCodePath + " code is missing"); 9086 } 9087 9088 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9089 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9090 final boolean splitShouldHaveCode = 9091 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9092 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9093 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9094 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9095 } 9096 } 9097 } 9098 } 9099 9100 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9101 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9102 throws PackageManagerException { 9103 if (DEBUG_PACKAGE_SCANNING) { 9104 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9105 Log.d(TAG, "Scanning package " + pkg.packageName); 9106 } 9107 9108 applyPolicy(pkg, policyFlags); 9109 9110 assertPackageIsValid(pkg, policyFlags, scanFlags); 9111 9112 // Initialize package source and resource directories 9113 final File scanFile = new File(pkg.codePath); 9114 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9115 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9116 9117 SharedUserSetting suid = null; 9118 PackageSetting pkgSetting = null; 9119 9120 // Getting the package setting may have a side-effect, so if we 9121 // are only checking if scan would succeed, stash a copy of the 9122 // old setting to restore at the end. 9123 PackageSetting nonMutatedPs = null; 9124 9125 // We keep references to the derived CPU Abis from settings in oder to reuse 9126 // them in the case where we're not upgrading or booting for the first time. 9127 String primaryCpuAbiFromSettings = null; 9128 String secondaryCpuAbiFromSettings = null; 9129 9130 // writer 9131 synchronized (mPackages) { 9132 if (pkg.mSharedUserId != null) { 9133 // SIDE EFFECTS; may potentially allocate a new shared user 9134 suid = mSettings.getSharedUserLPw( 9135 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9136 if (DEBUG_PACKAGE_SCANNING) { 9137 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9138 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9139 + "): packages=" + suid.packages); 9140 } 9141 } 9142 9143 // Check if we are renaming from an original package name. 9144 PackageSetting origPackage = null; 9145 String realName = null; 9146 if (pkg.mOriginalPackages != null) { 9147 // This package may need to be renamed to a previously 9148 // installed name. Let's check on that... 9149 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9150 if (pkg.mOriginalPackages.contains(renamed)) { 9151 // This package had originally been installed as the 9152 // original name, and we have already taken care of 9153 // transitioning to the new one. Just update the new 9154 // one to continue using the old name. 9155 realName = pkg.mRealPackage; 9156 if (!pkg.packageName.equals(renamed)) { 9157 // Callers into this function may have already taken 9158 // care of renaming the package; only do it here if 9159 // it is not already done. 9160 pkg.setPackageName(renamed); 9161 } 9162 } else { 9163 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9164 if ((origPackage = mSettings.getPackageLPr( 9165 pkg.mOriginalPackages.get(i))) != null) { 9166 // We do have the package already installed under its 9167 // original name... should we use it? 9168 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9169 // New package is not compatible with original. 9170 origPackage = null; 9171 continue; 9172 } else if (origPackage.sharedUser != null) { 9173 // Make sure uid is compatible between packages. 9174 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9175 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9176 + " to " + pkg.packageName + ": old uid " 9177 + origPackage.sharedUser.name 9178 + " differs from " + pkg.mSharedUserId); 9179 origPackage = null; 9180 continue; 9181 } 9182 // TODO: Add case when shared user id is added [b/28144775] 9183 } else { 9184 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9185 + pkg.packageName + " to old name " + origPackage.name); 9186 } 9187 break; 9188 } 9189 } 9190 } 9191 } 9192 9193 if (mTransferedPackages.contains(pkg.packageName)) { 9194 Slog.w(TAG, "Package " + pkg.packageName 9195 + " was transferred to another, but its .apk remains"); 9196 } 9197 9198 // See comments in nonMutatedPs declaration 9199 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9200 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9201 if (foundPs != null) { 9202 nonMutatedPs = new PackageSetting(foundPs); 9203 } 9204 } 9205 9206 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9207 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9208 if (foundPs != null) { 9209 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9210 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9211 } 9212 } 9213 9214 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9215 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9216 PackageManagerService.reportSettingsProblem(Log.WARN, 9217 "Package " + pkg.packageName + " shared user changed from " 9218 + (pkgSetting.sharedUser != null 9219 ? pkgSetting.sharedUser.name : "<nothing>") 9220 + " to " 9221 + (suid != null ? suid.name : "<nothing>") 9222 + "; replacing with new"); 9223 pkgSetting = null; 9224 } 9225 final PackageSetting oldPkgSetting = 9226 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9227 final PackageSetting disabledPkgSetting = 9228 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9229 9230 String[] usesStaticLibraries = null; 9231 if (pkg.usesStaticLibraries != null) { 9232 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9233 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9234 } 9235 9236 if (pkgSetting == null) { 9237 final String parentPackageName = (pkg.parentPackage != null) 9238 ? pkg.parentPackage.packageName : null; 9239 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9240 // REMOVE SharedUserSetting from method; update in a separate call 9241 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9242 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9243 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9244 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9245 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9246 true /*allowInstall*/, instantApp, parentPackageName, 9247 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9248 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9249 // SIDE EFFECTS; updates system state; move elsewhere 9250 if (origPackage != null) { 9251 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9252 } 9253 mSettings.addUserToSettingLPw(pkgSetting); 9254 } else { 9255 // REMOVE SharedUserSetting from method; update in a separate call. 9256 // 9257 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9258 // secondaryCpuAbi are not known at this point so we always update them 9259 // to null here, only to reset them at a later point. 9260 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9261 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9262 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9263 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9264 UserManagerService.getInstance(), usesStaticLibraries, 9265 pkg.usesStaticLibrariesVersions); 9266 } 9267 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9268 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9269 9270 // SIDE EFFECTS; modifies system state; move elsewhere 9271 if (pkgSetting.origPackage != null) { 9272 // If we are first transitioning from an original package, 9273 // fix up the new package's name now. We need to do this after 9274 // looking up the package under its new name, so getPackageLP 9275 // can take care of fiddling things correctly. 9276 pkg.setPackageName(origPackage.name); 9277 9278 // File a report about this. 9279 String msg = "New package " + pkgSetting.realName 9280 + " renamed to replace old package " + pkgSetting.name; 9281 reportSettingsProblem(Log.WARN, msg); 9282 9283 // Make a note of it. 9284 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9285 mTransferedPackages.add(origPackage.name); 9286 } 9287 9288 // No longer need to retain this. 9289 pkgSetting.origPackage = null; 9290 } 9291 9292 // SIDE EFFECTS; modifies system state; move elsewhere 9293 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9294 // Make a note of it. 9295 mTransferedPackages.add(pkg.packageName); 9296 } 9297 9298 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9299 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9300 } 9301 9302 if ((scanFlags & SCAN_BOOTING) == 0 9303 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9304 // Check all shared libraries and map to their actual file path. 9305 // We only do this here for apps not on a system dir, because those 9306 // are the only ones that can fail an install due to this. We 9307 // will take care of the system apps by updating all of their 9308 // library paths after the scan is done. Also during the initial 9309 // scan don't update any libs as we do this wholesale after all 9310 // apps are scanned to avoid dependency based scanning. 9311 updateSharedLibrariesLPr(pkg, null); 9312 } 9313 9314 if (mFoundPolicyFile) { 9315 SELinuxMMAC.assignSeInfoValue(pkg); 9316 } 9317 pkg.applicationInfo.uid = pkgSetting.appId; 9318 pkg.mExtras = pkgSetting; 9319 9320 9321 // Static shared libs have same package with different versions where 9322 // we internally use a synthetic package name to allow multiple versions 9323 // of the same package, therefore we need to compare signatures against 9324 // the package setting for the latest library version. 9325 PackageSetting signatureCheckPs = pkgSetting; 9326 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9327 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9328 if (libraryEntry != null) { 9329 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9330 } 9331 } 9332 9333 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9334 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9335 // We just determined the app is signed correctly, so bring 9336 // over the latest parsed certs. 9337 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9338 } else { 9339 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9340 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9341 "Package " + pkg.packageName + " upgrade keys do not match the " 9342 + "previously installed version"); 9343 } else { 9344 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9345 String msg = "System package " + pkg.packageName 9346 + " signature changed; retaining data."; 9347 reportSettingsProblem(Log.WARN, msg); 9348 } 9349 } 9350 } else { 9351 try { 9352 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9353 verifySignaturesLP(signatureCheckPs, pkg); 9354 // We just determined the app is signed correctly, so bring 9355 // over the latest parsed certs. 9356 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9357 } catch (PackageManagerException e) { 9358 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9359 throw e; 9360 } 9361 // The signature has changed, but this package is in the system 9362 // image... let's recover! 9363 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9364 // However... if this package is part of a shared user, but it 9365 // doesn't match the signature of the shared user, let's fail. 9366 // What this means is that you can't change the signatures 9367 // associated with an overall shared user, which doesn't seem all 9368 // that unreasonable. 9369 if (signatureCheckPs.sharedUser != null) { 9370 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9371 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9372 throw new PackageManagerException( 9373 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9374 "Signature mismatch for shared user: " 9375 + pkgSetting.sharedUser); 9376 } 9377 } 9378 // File a report about this. 9379 String msg = "System package " + pkg.packageName 9380 + " signature changed; retaining data."; 9381 reportSettingsProblem(Log.WARN, msg); 9382 } 9383 } 9384 9385 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9386 // This package wants to adopt ownership of permissions from 9387 // another package. 9388 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9389 final String origName = pkg.mAdoptPermissions.get(i); 9390 final PackageSetting orig = mSettings.getPackageLPr(origName); 9391 if (orig != null) { 9392 if (verifyPackageUpdateLPr(orig, pkg)) { 9393 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9394 + pkg.packageName); 9395 // SIDE EFFECTS; updates permissions system state; move elsewhere 9396 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9397 } 9398 } 9399 } 9400 } 9401 } 9402 9403 pkg.applicationInfo.processName = fixProcessName( 9404 pkg.applicationInfo.packageName, 9405 pkg.applicationInfo.processName); 9406 9407 if (pkg != mPlatformPackage) { 9408 // Get all of our default paths setup 9409 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9410 } 9411 9412 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9413 9414 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9415 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9417 derivePackageAbi( 9418 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9420 9421 // Some system apps still use directory structure for native libraries 9422 // in which case we might end up not detecting abi solely based on apk 9423 // structure. Try to detect abi based on directory structure. 9424 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9425 pkg.applicationInfo.primaryCpuAbi == null) { 9426 setBundledAppAbisAndRoots(pkg, pkgSetting); 9427 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9428 } 9429 } else { 9430 // This is not a first boot or an upgrade, don't bother deriving the 9431 // ABI during the scan. Instead, trust the value that was stored in the 9432 // package setting. 9433 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9434 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9435 9436 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9437 9438 if (DEBUG_ABI_SELECTION) { 9439 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9440 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9441 pkg.applicationInfo.secondaryCpuAbi); 9442 } 9443 } 9444 } else { 9445 if ((scanFlags & SCAN_MOVE) != 0) { 9446 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9447 // but we already have this packages package info in the PackageSetting. We just 9448 // use that and derive the native library path based on the new codepath. 9449 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9450 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9451 } 9452 9453 // Set native library paths again. For moves, the path will be updated based on the 9454 // ABIs we've determined above. For non-moves, the path will be updated based on the 9455 // ABIs we determined during compilation, but the path will depend on the final 9456 // package path (after the rename away from the stage path). 9457 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9458 } 9459 9460 // This is a special case for the "system" package, where the ABI is 9461 // dictated by the zygote configuration (and init.rc). We should keep track 9462 // of this ABI so that we can deal with "normal" applications that run under 9463 // the same UID correctly. 9464 if (mPlatformPackage == pkg) { 9465 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9466 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9467 } 9468 9469 // If there's a mismatch between the abi-override in the package setting 9470 // and the abiOverride specified for the install. Warn about this because we 9471 // would've already compiled the app without taking the package setting into 9472 // account. 9473 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9474 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9475 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9476 " for package " + pkg.packageName); 9477 } 9478 } 9479 9480 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9481 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9482 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9483 9484 // Copy the derived override back to the parsed package, so that we can 9485 // update the package settings accordingly. 9486 pkg.cpuAbiOverride = cpuAbiOverride; 9487 9488 if (DEBUG_ABI_SELECTION) { 9489 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9490 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9491 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9492 } 9493 9494 // Push the derived path down into PackageSettings so we know what to 9495 // clean up at uninstall time. 9496 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9497 9498 if (DEBUG_ABI_SELECTION) { 9499 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9500 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9501 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9502 } 9503 9504 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9505 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9506 // We don't do this here during boot because we can do it all 9507 // at once after scanning all existing packages. 9508 // 9509 // We also do this *before* we perform dexopt on this package, so that 9510 // we can avoid redundant dexopts, and also to make sure we've got the 9511 // code and package path correct. 9512 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9513 } 9514 9515 if (mFactoryTest && pkg.requestedPermissions.contains( 9516 android.Manifest.permission.FACTORY_TEST)) { 9517 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9518 } 9519 9520 if (isSystemApp(pkg)) { 9521 pkgSetting.isOrphaned = true; 9522 } 9523 9524 // Take care of first install / last update times. 9525 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9526 if (currentTime != 0) { 9527 if (pkgSetting.firstInstallTime == 0) { 9528 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9529 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9530 pkgSetting.lastUpdateTime = currentTime; 9531 } 9532 } else if (pkgSetting.firstInstallTime == 0) { 9533 // We need *something*. Take time time stamp of the file. 9534 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9535 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9536 if (scanFileTime != pkgSetting.timeStamp) { 9537 // A package on the system image has changed; consider this 9538 // to be an update. 9539 pkgSetting.lastUpdateTime = scanFileTime; 9540 } 9541 } 9542 pkgSetting.setTimeStamp(scanFileTime); 9543 9544 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9545 if (nonMutatedPs != null) { 9546 synchronized (mPackages) { 9547 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9548 } 9549 } 9550 } else { 9551 final int userId = user == null ? 0 : user.getIdentifier(); 9552 // Modify state for the given package setting 9553 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9554 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9555 if (pkgSetting.getInstantApp(userId)) { 9556 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9557 } 9558 } 9559 return pkg; 9560 } 9561 9562 /** 9563 * Applies policy to the parsed package based upon the given policy flags. 9564 * Ensures the package is in a good state. 9565 * <p> 9566 * Implementation detail: This method must NOT have any side effect. It would 9567 * ideally be static, but, it requires locks to read system state. 9568 */ 9569 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9570 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9571 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9572 if (pkg.applicationInfo.isDirectBootAware()) { 9573 // we're direct boot aware; set for all components 9574 for (PackageParser.Service s : pkg.services) { 9575 s.info.encryptionAware = s.info.directBootAware = true; 9576 } 9577 for (PackageParser.Provider p : pkg.providers) { 9578 p.info.encryptionAware = p.info.directBootAware = true; 9579 } 9580 for (PackageParser.Activity a : pkg.activities) { 9581 a.info.encryptionAware = a.info.directBootAware = true; 9582 } 9583 for (PackageParser.Activity r : pkg.receivers) { 9584 r.info.encryptionAware = r.info.directBootAware = true; 9585 } 9586 } 9587 } else { 9588 // Only allow system apps to be flagged as core apps. 9589 pkg.coreApp = false; 9590 // clear flags not applicable to regular apps 9591 pkg.applicationInfo.privateFlags &= 9592 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9593 pkg.applicationInfo.privateFlags &= 9594 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9595 } 9596 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9597 9598 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9599 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9600 } 9601 9602 if (!isSystemApp(pkg)) { 9603 // Only system apps can use these features. 9604 pkg.mOriginalPackages = null; 9605 pkg.mRealPackage = null; 9606 pkg.mAdoptPermissions = null; 9607 } 9608 } 9609 9610 /** 9611 * Asserts the parsed package is valid according to the given policy. If the 9612 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9613 * <p> 9614 * Implementation detail: This method must NOT have any side effects. It would 9615 * ideally be static, but, it requires locks to read system state. 9616 * 9617 * @throws PackageManagerException If the package fails any of the validation checks 9618 */ 9619 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9620 throws PackageManagerException { 9621 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9622 assertCodePolicy(pkg); 9623 } 9624 9625 if (pkg.applicationInfo.getCodePath() == null || 9626 pkg.applicationInfo.getResourcePath() == null) { 9627 // Bail out. The resource and code paths haven't been set. 9628 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9629 "Code and resource paths haven't been set correctly"); 9630 } 9631 9632 // Make sure we're not adding any bogus keyset info 9633 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9634 ksms.assertScannedPackageValid(pkg); 9635 9636 synchronized (mPackages) { 9637 // The special "android" package can only be defined once 9638 if (pkg.packageName.equals("android")) { 9639 if (mAndroidApplication != null) { 9640 Slog.w(TAG, "*************************************************"); 9641 Slog.w(TAG, "Core android package being redefined. Skipping."); 9642 Slog.w(TAG, " codePath=" + pkg.codePath); 9643 Slog.w(TAG, "*************************************************"); 9644 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9645 "Core android package being redefined. Skipping."); 9646 } 9647 } 9648 9649 // A package name must be unique; don't allow duplicates 9650 if (mPackages.containsKey(pkg.packageName)) { 9651 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9652 "Application package " + pkg.packageName 9653 + " already installed. Skipping duplicate."); 9654 } 9655 9656 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9657 // Static libs have a synthetic package name containing the version 9658 // but we still want the base name to be unique. 9659 if (mPackages.containsKey(pkg.manifestPackageName)) { 9660 throw new PackageManagerException( 9661 "Duplicate static shared lib provider package"); 9662 } 9663 9664 // Static shared libraries should have at least O target SDK 9665 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9666 throw new PackageManagerException( 9667 "Packages declaring static-shared libs must target O SDK or higher"); 9668 } 9669 9670 // Package declaring static a shared lib cannot be instant apps 9671 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9672 throw new PackageManagerException( 9673 "Packages declaring static-shared libs cannot be instant apps"); 9674 } 9675 9676 // Package declaring static a shared lib cannot be renamed since the package 9677 // name is synthetic and apps can't code around package manager internals. 9678 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9679 throw new PackageManagerException( 9680 "Packages declaring static-shared libs cannot be renamed"); 9681 } 9682 9683 // Package declaring static a shared lib cannot declare child packages 9684 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9685 throw new PackageManagerException( 9686 "Packages declaring static-shared libs cannot have child packages"); 9687 } 9688 9689 // Package declaring static a shared lib cannot declare dynamic libs 9690 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9691 throw new PackageManagerException( 9692 "Packages declaring static-shared libs cannot declare dynamic libs"); 9693 } 9694 9695 // Package declaring static a shared lib cannot declare shared users 9696 if (pkg.mSharedUserId != null) { 9697 throw new PackageManagerException( 9698 "Packages declaring static-shared libs cannot declare shared users"); 9699 } 9700 9701 // Static shared libs cannot declare activities 9702 if (!pkg.activities.isEmpty()) { 9703 throw new PackageManagerException( 9704 "Static shared libs cannot declare activities"); 9705 } 9706 9707 // Static shared libs cannot declare services 9708 if (!pkg.services.isEmpty()) { 9709 throw new PackageManagerException( 9710 "Static shared libs cannot declare services"); 9711 } 9712 9713 // Static shared libs cannot declare providers 9714 if (!pkg.providers.isEmpty()) { 9715 throw new PackageManagerException( 9716 "Static shared libs cannot declare content providers"); 9717 } 9718 9719 // Static shared libs cannot declare receivers 9720 if (!pkg.receivers.isEmpty()) { 9721 throw new PackageManagerException( 9722 "Static shared libs cannot declare broadcast receivers"); 9723 } 9724 9725 // Static shared libs cannot declare permission groups 9726 if (!pkg.permissionGroups.isEmpty()) { 9727 throw new PackageManagerException( 9728 "Static shared libs cannot declare permission groups"); 9729 } 9730 9731 // Static shared libs cannot declare permissions 9732 if (!pkg.permissions.isEmpty()) { 9733 throw new PackageManagerException( 9734 "Static shared libs cannot declare permissions"); 9735 } 9736 9737 // Static shared libs cannot declare protected broadcasts 9738 if (pkg.protectedBroadcasts != null) { 9739 throw new PackageManagerException( 9740 "Static shared libs cannot declare protected broadcasts"); 9741 } 9742 9743 // Static shared libs cannot be overlay targets 9744 if (pkg.mOverlayTarget != null) { 9745 throw new PackageManagerException( 9746 "Static shared libs cannot be overlay targets"); 9747 } 9748 9749 // The version codes must be ordered as lib versions 9750 int minVersionCode = Integer.MIN_VALUE; 9751 int maxVersionCode = Integer.MAX_VALUE; 9752 9753 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9754 pkg.staticSharedLibName); 9755 if (versionedLib != null) { 9756 final int versionCount = versionedLib.size(); 9757 for (int i = 0; i < versionCount; i++) { 9758 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9759 // TODO: We will change version code to long, so in the new API it is long 9760 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9761 .getVersionCode(); 9762 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9763 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9764 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9765 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9766 } else { 9767 minVersionCode = maxVersionCode = libVersionCode; 9768 break; 9769 } 9770 } 9771 } 9772 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9773 throw new PackageManagerException("Static shared" 9774 + " lib version codes must be ordered as lib versions"); 9775 } 9776 } 9777 9778 // Only privileged apps and updated privileged apps can add child packages. 9779 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9780 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9781 throw new PackageManagerException("Only privileged apps can add child " 9782 + "packages. Ignoring package " + pkg.packageName); 9783 } 9784 final int childCount = pkg.childPackages.size(); 9785 for (int i = 0; i < childCount; i++) { 9786 PackageParser.Package childPkg = pkg.childPackages.get(i); 9787 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9788 childPkg.packageName)) { 9789 throw new PackageManagerException("Can't override child of " 9790 + "another disabled app. Ignoring package " + pkg.packageName); 9791 } 9792 } 9793 } 9794 9795 // If we're only installing presumed-existing packages, require that the 9796 // scanned APK is both already known and at the path previously established 9797 // for it. Previously unknown packages we pick up normally, but if we have an 9798 // a priori expectation about this package's install presence, enforce it. 9799 // With a singular exception for new system packages. When an OTA contains 9800 // a new system package, we allow the codepath to change from a system location 9801 // to the user-installed location. If we don't allow this change, any newer, 9802 // user-installed version of the application will be ignored. 9803 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9804 if (mExpectingBetter.containsKey(pkg.packageName)) { 9805 logCriticalInfo(Log.WARN, 9806 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9807 } else { 9808 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9809 if (known != null) { 9810 if (DEBUG_PACKAGE_SCANNING) { 9811 Log.d(TAG, "Examining " + pkg.codePath 9812 + " and requiring known paths " + known.codePathString 9813 + " & " + known.resourcePathString); 9814 } 9815 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9816 || !pkg.applicationInfo.getResourcePath().equals( 9817 known.resourcePathString)) { 9818 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9819 "Application package " + pkg.packageName 9820 + " found at " + pkg.applicationInfo.getCodePath() 9821 + " but expected at " + known.codePathString 9822 + "; ignoring."); 9823 } 9824 } 9825 } 9826 } 9827 9828 // Verify that this new package doesn't have any content providers 9829 // that conflict with existing packages. Only do this if the 9830 // package isn't already installed, since we don't want to break 9831 // things that are installed. 9832 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9833 final int N = pkg.providers.size(); 9834 int i; 9835 for (i=0; i<N; i++) { 9836 PackageParser.Provider p = pkg.providers.get(i); 9837 if (p.info.authority != null) { 9838 String names[] = p.info.authority.split(";"); 9839 for (int j = 0; j < names.length; j++) { 9840 if (mProvidersByAuthority.containsKey(names[j])) { 9841 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9842 final String otherPackageName = 9843 ((other != null && other.getComponentName() != null) ? 9844 other.getComponentName().getPackageName() : "?"); 9845 throw new PackageManagerException( 9846 INSTALL_FAILED_CONFLICTING_PROVIDER, 9847 "Can't install because provider name " + names[j] 9848 + " (in package " + pkg.applicationInfo.packageName 9849 + ") is already used by " + otherPackageName); 9850 } 9851 } 9852 } 9853 } 9854 } 9855 } 9856 } 9857 9858 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9859 int type, String declaringPackageName, int declaringVersionCode) { 9860 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9861 if (versionedLib == null) { 9862 versionedLib = new SparseArray<>(); 9863 mSharedLibraries.put(name, versionedLib); 9864 if (type == SharedLibraryInfo.TYPE_STATIC) { 9865 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9866 } 9867 } else if (versionedLib.indexOfKey(version) >= 0) { 9868 return false; 9869 } 9870 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9871 version, type, declaringPackageName, declaringVersionCode); 9872 versionedLib.put(version, libEntry); 9873 return true; 9874 } 9875 9876 private boolean removeSharedLibraryLPw(String name, int version) { 9877 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9878 if (versionedLib == null) { 9879 return false; 9880 } 9881 final int libIdx = versionedLib.indexOfKey(version); 9882 if (libIdx < 0) { 9883 return false; 9884 } 9885 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9886 versionedLib.remove(version); 9887 if (versionedLib.size() <= 0) { 9888 mSharedLibraries.remove(name); 9889 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9890 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9891 .getPackageName()); 9892 } 9893 } 9894 return true; 9895 } 9896 9897 /** 9898 * Adds a scanned package to the system. When this method is finished, the package will 9899 * be available for query, resolution, etc... 9900 */ 9901 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9902 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9903 final String pkgName = pkg.packageName; 9904 if (mCustomResolverComponentName != null && 9905 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9906 setUpCustomResolverActivity(pkg); 9907 } 9908 9909 if (pkg.packageName.equals("android")) { 9910 synchronized (mPackages) { 9911 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9912 // Set up information for our fall-back user intent resolution activity. 9913 mPlatformPackage = pkg; 9914 pkg.mVersionCode = mSdkVersion; 9915 mAndroidApplication = pkg.applicationInfo; 9916 if (!mResolverReplaced) { 9917 mResolveActivity.applicationInfo = mAndroidApplication; 9918 mResolveActivity.name = ResolverActivity.class.getName(); 9919 mResolveActivity.packageName = mAndroidApplication.packageName; 9920 mResolveActivity.processName = "system:ui"; 9921 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9922 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9923 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9924 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9925 mResolveActivity.exported = true; 9926 mResolveActivity.enabled = true; 9927 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9928 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9929 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9930 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9931 | ActivityInfo.CONFIG_ORIENTATION 9932 | ActivityInfo.CONFIG_KEYBOARD 9933 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9934 mResolveInfo.activityInfo = mResolveActivity; 9935 mResolveInfo.priority = 0; 9936 mResolveInfo.preferredOrder = 0; 9937 mResolveInfo.match = 0; 9938 mResolveComponentName = new ComponentName( 9939 mAndroidApplication.packageName, mResolveActivity.name); 9940 } 9941 } 9942 } 9943 } 9944 9945 ArrayList<PackageParser.Package> clientLibPkgs = null; 9946 // writer 9947 synchronized (mPackages) { 9948 boolean hasStaticSharedLibs = false; 9949 9950 // Any app can add new static shared libraries 9951 if (pkg.staticSharedLibName != null) { 9952 // Static shared libs don't allow renaming as they have synthetic package 9953 // names to allow install of multiple versions, so use name from manifest. 9954 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9955 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9956 pkg.manifestPackageName, pkg.mVersionCode)) { 9957 hasStaticSharedLibs = true; 9958 } else { 9959 Slog.w(TAG, "Package " + pkg.packageName + " library " 9960 + pkg.staticSharedLibName + " already exists; skipping"); 9961 } 9962 // Static shared libs cannot be updated once installed since they 9963 // use synthetic package name which includes the version code, so 9964 // not need to update other packages's shared lib dependencies. 9965 } 9966 9967 if (!hasStaticSharedLibs 9968 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9969 // Only system apps can add new dynamic shared libraries. 9970 if (pkg.libraryNames != null) { 9971 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9972 String name = pkg.libraryNames.get(i); 9973 boolean allowed = false; 9974 if (pkg.isUpdatedSystemApp()) { 9975 // New library entries can only be added through the 9976 // system image. This is important to get rid of a lot 9977 // of nasty edge cases: for example if we allowed a non- 9978 // system update of the app to add a library, then uninstalling 9979 // the update would make the library go away, and assumptions 9980 // we made such as through app install filtering would now 9981 // have allowed apps on the device which aren't compatible 9982 // with it. Better to just have the restriction here, be 9983 // conservative, and create many fewer cases that can negatively 9984 // impact the user experience. 9985 final PackageSetting sysPs = mSettings 9986 .getDisabledSystemPkgLPr(pkg.packageName); 9987 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9988 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9989 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9990 allowed = true; 9991 break; 9992 } 9993 } 9994 } 9995 } else { 9996 allowed = true; 9997 } 9998 if (allowed) { 9999 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10000 SharedLibraryInfo.VERSION_UNDEFINED, 10001 SharedLibraryInfo.TYPE_DYNAMIC, 10002 pkg.packageName, pkg.mVersionCode)) { 10003 Slog.w(TAG, "Package " + pkg.packageName + " library " 10004 + name + " already exists; skipping"); 10005 } 10006 } else { 10007 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10008 + name + " that is not declared on system image; skipping"); 10009 } 10010 } 10011 10012 if ((scanFlags & SCAN_BOOTING) == 0) { 10013 // If we are not booting, we need to update any applications 10014 // that are clients of our shared library. If we are booting, 10015 // this will all be done once the scan is complete. 10016 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10017 } 10018 } 10019 } 10020 } 10021 10022 if ((scanFlags & SCAN_BOOTING) != 0) { 10023 // No apps can run during boot scan, so they don't need to be frozen 10024 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10025 // Caller asked to not kill app, so it's probably not frozen 10026 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10027 // Caller asked us to ignore frozen check for some reason; they 10028 // probably didn't know the package name 10029 } else { 10030 // We're doing major surgery on this package, so it better be frozen 10031 // right now to keep it from launching 10032 checkPackageFrozen(pkgName); 10033 } 10034 10035 // Also need to kill any apps that are dependent on the library. 10036 if (clientLibPkgs != null) { 10037 for (int i=0; i<clientLibPkgs.size(); i++) { 10038 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10039 killApplication(clientPkg.applicationInfo.packageName, 10040 clientPkg.applicationInfo.uid, "update lib"); 10041 } 10042 } 10043 10044 // writer 10045 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10046 10047 synchronized (mPackages) { 10048 // We don't expect installation to fail beyond this point 10049 10050 // Add the new setting to mSettings 10051 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10052 // Add the new setting to mPackages 10053 mPackages.put(pkg.applicationInfo.packageName, pkg); 10054 // Make sure we don't accidentally delete its data. 10055 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10056 while (iter.hasNext()) { 10057 PackageCleanItem item = iter.next(); 10058 if (pkgName.equals(item.packageName)) { 10059 iter.remove(); 10060 } 10061 } 10062 10063 // Add the package's KeySets to the global KeySetManagerService 10064 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10065 ksms.addScannedPackageLPw(pkg); 10066 10067 int N = pkg.providers.size(); 10068 StringBuilder r = null; 10069 int i; 10070 for (i=0; i<N; i++) { 10071 PackageParser.Provider p = pkg.providers.get(i); 10072 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10073 p.info.processName); 10074 mProviders.addProvider(p); 10075 p.syncable = p.info.isSyncable; 10076 if (p.info.authority != null) { 10077 String names[] = p.info.authority.split(";"); 10078 p.info.authority = null; 10079 for (int j = 0; j < names.length; j++) { 10080 if (j == 1 && p.syncable) { 10081 // We only want the first authority for a provider to possibly be 10082 // syncable, so if we already added this provider using a different 10083 // authority clear the syncable flag. We copy the provider before 10084 // changing it because the mProviders object contains a reference 10085 // to a provider that we don't want to change. 10086 // Only do this for the second authority since the resulting provider 10087 // object can be the same for all future authorities for this provider. 10088 p = new PackageParser.Provider(p); 10089 p.syncable = false; 10090 } 10091 if (!mProvidersByAuthority.containsKey(names[j])) { 10092 mProvidersByAuthority.put(names[j], p); 10093 if (p.info.authority == null) { 10094 p.info.authority = names[j]; 10095 } else { 10096 p.info.authority = p.info.authority + ";" + names[j]; 10097 } 10098 if (DEBUG_PACKAGE_SCANNING) { 10099 if (chatty) 10100 Log.d(TAG, "Registered content provider: " + names[j] 10101 + ", className = " + p.info.name + ", isSyncable = " 10102 + p.info.isSyncable); 10103 } 10104 } else { 10105 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10106 Slog.w(TAG, "Skipping provider name " + names[j] + 10107 " (in package " + pkg.applicationInfo.packageName + 10108 "): name already used by " 10109 + ((other != null && other.getComponentName() != null) 10110 ? other.getComponentName().getPackageName() : "?")); 10111 } 10112 } 10113 } 10114 if (chatty) { 10115 if (r == null) { 10116 r = new StringBuilder(256); 10117 } else { 10118 r.append(' '); 10119 } 10120 r.append(p.info.name); 10121 } 10122 } 10123 if (r != null) { 10124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10125 } 10126 10127 N = pkg.services.size(); 10128 r = null; 10129 for (i=0; i<N; i++) { 10130 PackageParser.Service s = pkg.services.get(i); 10131 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10132 s.info.processName); 10133 mServices.addService(s); 10134 if (chatty) { 10135 if (r == null) { 10136 r = new StringBuilder(256); 10137 } else { 10138 r.append(' '); 10139 } 10140 r.append(s.info.name); 10141 } 10142 } 10143 if (r != null) { 10144 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10145 } 10146 10147 N = pkg.receivers.size(); 10148 r = null; 10149 for (i=0; i<N; i++) { 10150 PackageParser.Activity a = pkg.receivers.get(i); 10151 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10152 a.info.processName); 10153 mReceivers.addActivity(a, "receiver"); 10154 if (chatty) { 10155 if (r == null) { 10156 r = new StringBuilder(256); 10157 } else { 10158 r.append(' '); 10159 } 10160 r.append(a.info.name); 10161 } 10162 } 10163 if (r != null) { 10164 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10165 } 10166 10167 N = pkg.activities.size(); 10168 r = null; 10169 for (i=0; i<N; i++) { 10170 PackageParser.Activity a = pkg.activities.get(i); 10171 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10172 a.info.processName); 10173 mActivities.addActivity(a, "activity"); 10174 if (chatty) { 10175 if (r == null) { 10176 r = new StringBuilder(256); 10177 } else { 10178 r.append(' '); 10179 } 10180 r.append(a.info.name); 10181 } 10182 } 10183 if (r != null) { 10184 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10185 } 10186 10187 N = pkg.permissionGroups.size(); 10188 r = null; 10189 for (i=0; i<N; i++) { 10190 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10191 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10192 final String curPackageName = cur == null ? null : cur.info.packageName; 10193 // Dont allow ephemeral apps to define new permission groups. 10194 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10195 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10196 + pg.info.packageName 10197 + " ignored: instant apps cannot define new permission groups."); 10198 continue; 10199 } 10200 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10201 if (cur == null || isPackageUpdate) { 10202 mPermissionGroups.put(pg.info.name, pg); 10203 if (chatty) { 10204 if (r == null) { 10205 r = new StringBuilder(256); 10206 } else { 10207 r.append(' '); 10208 } 10209 if (isPackageUpdate) { 10210 r.append("UPD:"); 10211 } 10212 r.append(pg.info.name); 10213 } 10214 } else { 10215 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10216 + pg.info.packageName + " ignored: original from " 10217 + cur.info.packageName); 10218 if (chatty) { 10219 if (r == null) { 10220 r = new StringBuilder(256); 10221 } else { 10222 r.append(' '); 10223 } 10224 r.append("DUP:"); 10225 r.append(pg.info.name); 10226 } 10227 } 10228 } 10229 if (r != null) { 10230 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10231 } 10232 10233 N = pkg.permissions.size(); 10234 r = null; 10235 for (i=0; i<N; i++) { 10236 PackageParser.Permission p = pkg.permissions.get(i); 10237 10238 // Dont allow ephemeral apps to define new permissions. 10239 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10240 Slog.w(TAG, "Permission " + p.info.name + " from package " 10241 + p.info.packageName 10242 + " ignored: instant apps cannot define new permissions."); 10243 continue; 10244 } 10245 10246 // Assume by default that we did not install this permission into the system. 10247 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10248 10249 // Now that permission groups have a special meaning, we ignore permission 10250 // groups for legacy apps to prevent unexpected behavior. In particular, 10251 // permissions for one app being granted to someone just becase they happen 10252 // to be in a group defined by another app (before this had no implications). 10253 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10254 p.group = mPermissionGroups.get(p.info.group); 10255 // Warn for a permission in an unknown group. 10256 if (p.info.group != null && p.group == null) { 10257 Slog.w(TAG, "Permission " + p.info.name + " from package " 10258 + p.info.packageName + " in an unknown group " + p.info.group); 10259 } 10260 } 10261 10262 ArrayMap<String, BasePermission> permissionMap = 10263 p.tree ? mSettings.mPermissionTrees 10264 : mSettings.mPermissions; 10265 BasePermission bp = permissionMap.get(p.info.name); 10266 10267 // Allow system apps to redefine non-system permissions 10268 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10269 final boolean currentOwnerIsSystem = (bp.perm != null 10270 && isSystemApp(bp.perm.owner)); 10271 if (isSystemApp(p.owner)) { 10272 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10273 // It's a built-in permission and no owner, take ownership now 10274 bp.packageSetting = pkgSetting; 10275 bp.perm = p; 10276 bp.uid = pkg.applicationInfo.uid; 10277 bp.sourcePackage = p.info.packageName; 10278 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10279 } else if (!currentOwnerIsSystem) { 10280 String msg = "New decl " + p.owner + " of permission " 10281 + p.info.name + " is system; overriding " + bp.sourcePackage; 10282 reportSettingsProblem(Log.WARN, msg); 10283 bp = null; 10284 } 10285 } 10286 } 10287 10288 if (bp == null) { 10289 bp = new BasePermission(p.info.name, p.info.packageName, 10290 BasePermission.TYPE_NORMAL); 10291 permissionMap.put(p.info.name, bp); 10292 } 10293 10294 if (bp.perm == null) { 10295 if (bp.sourcePackage == null 10296 || bp.sourcePackage.equals(p.info.packageName)) { 10297 BasePermission tree = findPermissionTreeLP(p.info.name); 10298 if (tree == null 10299 || tree.sourcePackage.equals(p.info.packageName)) { 10300 bp.packageSetting = pkgSetting; 10301 bp.perm = p; 10302 bp.uid = pkg.applicationInfo.uid; 10303 bp.sourcePackage = p.info.packageName; 10304 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10305 if (chatty) { 10306 if (r == null) { 10307 r = new StringBuilder(256); 10308 } else { 10309 r.append(' '); 10310 } 10311 r.append(p.info.name); 10312 } 10313 } else { 10314 Slog.w(TAG, "Permission " + p.info.name + " from package " 10315 + p.info.packageName + " ignored: base tree " 10316 + tree.name + " is from package " 10317 + tree.sourcePackage); 10318 } 10319 } else { 10320 Slog.w(TAG, "Permission " + p.info.name + " from package " 10321 + p.info.packageName + " ignored: original from " 10322 + bp.sourcePackage); 10323 } 10324 } else if (chatty) { 10325 if (r == null) { 10326 r = new StringBuilder(256); 10327 } else { 10328 r.append(' '); 10329 } 10330 r.append("DUP:"); 10331 r.append(p.info.name); 10332 } 10333 if (bp.perm == p) { 10334 bp.protectionLevel = p.info.protectionLevel; 10335 } 10336 } 10337 10338 if (r != null) { 10339 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10340 } 10341 10342 N = pkg.instrumentation.size(); 10343 r = null; 10344 for (i=0; i<N; i++) { 10345 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10346 a.info.packageName = pkg.applicationInfo.packageName; 10347 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10348 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10349 a.info.splitNames = pkg.splitNames; 10350 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10351 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10352 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10353 a.info.dataDir = pkg.applicationInfo.dataDir; 10354 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10355 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10356 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10357 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10358 mInstrumentation.put(a.getComponentName(), a); 10359 if (chatty) { 10360 if (r == null) { 10361 r = new StringBuilder(256); 10362 } else { 10363 r.append(' '); 10364 } 10365 r.append(a.info.name); 10366 } 10367 } 10368 if (r != null) { 10369 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10370 } 10371 10372 if (pkg.protectedBroadcasts != null) { 10373 N = pkg.protectedBroadcasts.size(); 10374 for (i=0; i<N; i++) { 10375 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10376 } 10377 } 10378 } 10379 10380 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10381 } 10382 10383 /** 10384 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10385 * is derived purely on the basis of the contents of {@code scanFile} and 10386 * {@code cpuAbiOverride}. 10387 * 10388 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10389 */ 10390 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10391 String cpuAbiOverride, boolean extractLibs, 10392 File appLib32InstallDir) 10393 throws PackageManagerException { 10394 // Give ourselves some initial paths; we'll come back for another 10395 // pass once we've determined ABI below. 10396 setNativeLibraryPaths(pkg, appLib32InstallDir); 10397 10398 // We would never need to extract libs for forward-locked and external packages, 10399 // since the container service will do it for us. We shouldn't attempt to 10400 // extract libs from system app when it was not updated. 10401 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10402 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10403 extractLibs = false; 10404 } 10405 10406 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10407 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10408 10409 NativeLibraryHelper.Handle handle = null; 10410 try { 10411 handle = NativeLibraryHelper.Handle.create(pkg); 10412 // TODO(multiArch): This can be null for apps that didn't go through the 10413 // usual installation process. We can calculate it again, like we 10414 // do during install time. 10415 // 10416 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10417 // unnecessary. 10418 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10419 10420 // Null out the abis so that they can be recalculated. 10421 pkg.applicationInfo.primaryCpuAbi = null; 10422 pkg.applicationInfo.secondaryCpuAbi = null; 10423 if (isMultiArch(pkg.applicationInfo)) { 10424 // Warn if we've set an abiOverride for multi-lib packages.. 10425 // By definition, we need to copy both 32 and 64 bit libraries for 10426 // such packages. 10427 if (pkg.cpuAbiOverride != null 10428 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10429 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10430 } 10431 10432 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10433 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10434 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10435 if (extractLibs) { 10436 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10437 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10438 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10439 useIsaSpecificSubdirs); 10440 } else { 10441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10442 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10443 } 10444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10445 } 10446 10447 maybeThrowExceptionForMultiArchCopy( 10448 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10449 10450 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10451 if (extractLibs) { 10452 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10453 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10454 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10455 useIsaSpecificSubdirs); 10456 } else { 10457 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10458 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10459 } 10460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10461 } 10462 10463 maybeThrowExceptionForMultiArchCopy( 10464 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10465 10466 if (abi64 >= 0) { 10467 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10468 } 10469 10470 if (abi32 >= 0) { 10471 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10472 if (abi64 >= 0) { 10473 if (pkg.use32bitAbi) { 10474 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10475 pkg.applicationInfo.primaryCpuAbi = abi; 10476 } else { 10477 pkg.applicationInfo.secondaryCpuAbi = abi; 10478 } 10479 } else { 10480 pkg.applicationInfo.primaryCpuAbi = abi; 10481 } 10482 } 10483 10484 } else { 10485 String[] abiList = (cpuAbiOverride != null) ? 10486 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10487 10488 // Enable gross and lame hacks for apps that are built with old 10489 // SDK tools. We must scan their APKs for renderscript bitcode and 10490 // not launch them if it's present. Don't bother checking on devices 10491 // that don't have 64 bit support. 10492 boolean needsRenderScriptOverride = false; 10493 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10494 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10495 abiList = Build.SUPPORTED_32_BIT_ABIS; 10496 needsRenderScriptOverride = true; 10497 } 10498 10499 final int copyRet; 10500 if (extractLibs) { 10501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10502 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10503 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10504 } else { 10505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10506 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10507 } 10508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10509 10510 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10511 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10512 "Error unpackaging native libs for app, errorCode=" + copyRet); 10513 } 10514 10515 if (copyRet >= 0) { 10516 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10517 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10518 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10519 } else if (needsRenderScriptOverride) { 10520 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10521 } 10522 } 10523 } catch (IOException ioe) { 10524 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10525 } finally { 10526 IoUtils.closeQuietly(handle); 10527 } 10528 10529 // Now that we've calculated the ABIs and determined if it's an internal app, 10530 // we will go ahead and populate the nativeLibraryPath. 10531 setNativeLibraryPaths(pkg, appLib32InstallDir); 10532 } 10533 10534 /** 10535 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10536 * i.e, so that all packages can be run inside a single process if required. 10537 * 10538 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10539 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10540 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10541 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10542 * updating a package that belongs to a shared user. 10543 * 10544 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10545 * adds unnecessary complexity. 10546 */ 10547 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10548 PackageParser.Package scannedPackage) { 10549 String requiredInstructionSet = null; 10550 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10551 requiredInstructionSet = VMRuntime.getInstructionSet( 10552 scannedPackage.applicationInfo.primaryCpuAbi); 10553 } 10554 10555 PackageSetting requirer = null; 10556 for (PackageSetting ps : packagesForUser) { 10557 // If packagesForUser contains scannedPackage, we skip it. This will happen 10558 // when scannedPackage is an update of an existing package. Without this check, 10559 // we will never be able to change the ABI of any package belonging to a shared 10560 // user, even if it's compatible with other packages. 10561 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10562 if (ps.primaryCpuAbiString == null) { 10563 continue; 10564 } 10565 10566 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10567 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10568 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10569 // this but there's not much we can do. 10570 String errorMessage = "Instruction set mismatch, " 10571 + ((requirer == null) ? "[caller]" : requirer) 10572 + " requires " + requiredInstructionSet + " whereas " + ps 10573 + " requires " + instructionSet; 10574 Slog.w(TAG, errorMessage); 10575 } 10576 10577 if (requiredInstructionSet == null) { 10578 requiredInstructionSet = instructionSet; 10579 requirer = ps; 10580 } 10581 } 10582 } 10583 10584 if (requiredInstructionSet != null) { 10585 String adjustedAbi; 10586 if (requirer != null) { 10587 // requirer != null implies that either scannedPackage was null or that scannedPackage 10588 // did not require an ABI, in which case we have to adjust scannedPackage to match 10589 // the ABI of the set (which is the same as requirer's ABI) 10590 adjustedAbi = requirer.primaryCpuAbiString; 10591 if (scannedPackage != null) { 10592 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10593 } 10594 } else { 10595 // requirer == null implies that we're updating all ABIs in the set to 10596 // match scannedPackage. 10597 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10598 } 10599 10600 for (PackageSetting ps : packagesForUser) { 10601 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10602 if (ps.primaryCpuAbiString != null) { 10603 continue; 10604 } 10605 10606 ps.primaryCpuAbiString = adjustedAbi; 10607 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10608 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10609 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10610 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10611 + " (requirer=" 10612 + (requirer != null ? requirer.pkg : "null") 10613 + ", scannedPackage=" 10614 + (scannedPackage != null ? scannedPackage : "null") 10615 + ")"); 10616 try { 10617 mInstaller.rmdex(ps.codePathString, 10618 getDexCodeInstructionSet(getPreferredInstructionSet())); 10619 } catch (InstallerException ignored) { 10620 } 10621 } 10622 } 10623 } 10624 } 10625 } 10626 10627 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10628 synchronized (mPackages) { 10629 mResolverReplaced = true; 10630 // Set up information for custom user intent resolution activity. 10631 mResolveActivity.applicationInfo = pkg.applicationInfo; 10632 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10633 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10634 mResolveActivity.processName = pkg.applicationInfo.packageName; 10635 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10636 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10637 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10638 mResolveActivity.theme = 0; 10639 mResolveActivity.exported = true; 10640 mResolveActivity.enabled = true; 10641 mResolveInfo.activityInfo = mResolveActivity; 10642 mResolveInfo.priority = 0; 10643 mResolveInfo.preferredOrder = 0; 10644 mResolveInfo.match = 0; 10645 mResolveComponentName = mCustomResolverComponentName; 10646 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10647 mResolveComponentName); 10648 } 10649 } 10650 10651 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10652 if (installerActivity == null) { 10653 if (DEBUG_EPHEMERAL) { 10654 Slog.d(TAG, "Clear ephemeral installer activity"); 10655 } 10656 mInstantAppInstallerActivity = null; 10657 return; 10658 } 10659 10660 if (DEBUG_EPHEMERAL) { 10661 Slog.d(TAG, "Set ephemeral installer activity: " 10662 + installerActivity.getComponentName()); 10663 } 10664 // Set up information for ephemeral installer activity 10665 mInstantAppInstallerActivity = installerActivity; 10666 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10667 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10668 mInstantAppInstallerActivity.exported = true; 10669 mInstantAppInstallerActivity.enabled = true; 10670 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10671 mInstantAppInstallerInfo.priority = 0; 10672 mInstantAppInstallerInfo.preferredOrder = 1; 10673 mInstantAppInstallerInfo.isDefault = true; 10674 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10675 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10676 } 10677 10678 private static String calculateBundledApkRoot(final String codePathString) { 10679 final File codePath = new File(codePathString); 10680 final File codeRoot; 10681 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10682 codeRoot = Environment.getRootDirectory(); 10683 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10684 codeRoot = Environment.getOemDirectory(); 10685 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10686 codeRoot = Environment.getVendorDirectory(); 10687 } else { 10688 // Unrecognized code path; take its top real segment as the apk root: 10689 // e.g. /something/app/blah.apk => /something 10690 try { 10691 File f = codePath.getCanonicalFile(); 10692 File parent = f.getParentFile(); // non-null because codePath is a file 10693 File tmp; 10694 while ((tmp = parent.getParentFile()) != null) { 10695 f = parent; 10696 parent = tmp; 10697 } 10698 codeRoot = f; 10699 Slog.w(TAG, "Unrecognized code path " 10700 + codePath + " - using " + codeRoot); 10701 } catch (IOException e) { 10702 // Can't canonicalize the code path -- shenanigans? 10703 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10704 return Environment.getRootDirectory().getPath(); 10705 } 10706 } 10707 return codeRoot.getPath(); 10708 } 10709 10710 /** 10711 * Derive and set the location of native libraries for the given package, 10712 * which varies depending on where and how the package was installed. 10713 */ 10714 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10715 final ApplicationInfo info = pkg.applicationInfo; 10716 final String codePath = pkg.codePath; 10717 final File codeFile = new File(codePath); 10718 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10719 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10720 10721 info.nativeLibraryRootDir = null; 10722 info.nativeLibraryRootRequiresIsa = false; 10723 info.nativeLibraryDir = null; 10724 info.secondaryNativeLibraryDir = null; 10725 10726 if (isApkFile(codeFile)) { 10727 // Monolithic install 10728 if (bundledApp) { 10729 // If "/system/lib64/apkname" exists, assume that is the per-package 10730 // native library directory to use; otherwise use "/system/lib/apkname". 10731 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10732 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10733 getPrimaryInstructionSet(info)); 10734 10735 // This is a bundled system app so choose the path based on the ABI. 10736 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10737 // is just the default path. 10738 final String apkName = deriveCodePathName(codePath); 10739 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10740 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10741 apkName).getAbsolutePath(); 10742 10743 if (info.secondaryCpuAbi != null) { 10744 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10745 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10746 secondaryLibDir, apkName).getAbsolutePath(); 10747 } 10748 } else if (asecApp) { 10749 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10750 .getAbsolutePath(); 10751 } else { 10752 final String apkName = deriveCodePathName(codePath); 10753 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10754 .getAbsolutePath(); 10755 } 10756 10757 info.nativeLibraryRootRequiresIsa = false; 10758 info.nativeLibraryDir = info.nativeLibraryRootDir; 10759 } else { 10760 // Cluster install 10761 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10762 info.nativeLibraryRootRequiresIsa = true; 10763 10764 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10765 getPrimaryInstructionSet(info)).getAbsolutePath(); 10766 10767 if (info.secondaryCpuAbi != null) { 10768 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10769 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10770 } 10771 } 10772 } 10773 10774 /** 10775 * Calculate the abis and roots for a bundled app. These can uniquely 10776 * be determined from the contents of the system partition, i.e whether 10777 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10778 * of this information, and instead assume that the system was built 10779 * sensibly. 10780 */ 10781 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10782 PackageSetting pkgSetting) { 10783 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10784 10785 // If "/system/lib64/apkname" exists, assume that is the per-package 10786 // native library directory to use; otherwise use "/system/lib/apkname". 10787 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10788 setBundledAppAbi(pkg, apkRoot, apkName); 10789 // pkgSetting might be null during rescan following uninstall of updates 10790 // to a bundled app, so accommodate that possibility. The settings in 10791 // that case will be established later from the parsed package. 10792 // 10793 // If the settings aren't null, sync them up with what we've just derived. 10794 // note that apkRoot isn't stored in the package settings. 10795 if (pkgSetting != null) { 10796 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10797 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10798 } 10799 } 10800 10801 /** 10802 * Deduces the ABI of a bundled app and sets the relevant fields on the 10803 * parsed pkg object. 10804 * 10805 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10806 * under which system libraries are installed. 10807 * @param apkName the name of the installed package. 10808 */ 10809 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10810 final File codeFile = new File(pkg.codePath); 10811 10812 final boolean has64BitLibs; 10813 final boolean has32BitLibs; 10814 if (isApkFile(codeFile)) { 10815 // Monolithic install 10816 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10817 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10818 } else { 10819 // Cluster install 10820 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10821 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10822 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10823 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10824 has64BitLibs = (new File(rootDir, isa)).exists(); 10825 } else { 10826 has64BitLibs = false; 10827 } 10828 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10829 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10830 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10831 has32BitLibs = (new File(rootDir, isa)).exists(); 10832 } else { 10833 has32BitLibs = false; 10834 } 10835 } 10836 10837 if (has64BitLibs && !has32BitLibs) { 10838 // The package has 64 bit libs, but not 32 bit libs. Its primary 10839 // ABI should be 64 bit. We can safely assume here that the bundled 10840 // native libraries correspond to the most preferred ABI in the list. 10841 10842 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10843 pkg.applicationInfo.secondaryCpuAbi = null; 10844 } else if (has32BitLibs && !has64BitLibs) { 10845 // The package has 32 bit libs but not 64 bit libs. Its primary 10846 // ABI should be 32 bit. 10847 10848 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10849 pkg.applicationInfo.secondaryCpuAbi = null; 10850 } else if (has32BitLibs && has64BitLibs) { 10851 // The application has both 64 and 32 bit bundled libraries. We check 10852 // here that the app declares multiArch support, and warn if it doesn't. 10853 // 10854 // We will be lenient here and record both ABIs. The primary will be the 10855 // ABI that's higher on the list, i.e, a device that's configured to prefer 10856 // 64 bit apps will see a 64 bit primary ABI, 10857 10858 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10859 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10860 } 10861 10862 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10863 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10864 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10865 } else { 10866 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10867 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10868 } 10869 } else { 10870 pkg.applicationInfo.primaryCpuAbi = null; 10871 pkg.applicationInfo.secondaryCpuAbi = null; 10872 } 10873 } 10874 10875 private void killApplication(String pkgName, int appId, String reason) { 10876 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10877 } 10878 10879 private void killApplication(String pkgName, int appId, int userId, String reason) { 10880 // Request the ActivityManager to kill the process(only for existing packages) 10881 // so that we do not end up in a confused state while the user is still using the older 10882 // version of the application while the new one gets installed. 10883 final long token = Binder.clearCallingIdentity(); 10884 try { 10885 IActivityManager am = ActivityManager.getService(); 10886 if (am != null) { 10887 try { 10888 am.killApplication(pkgName, appId, userId, reason); 10889 } catch (RemoteException e) { 10890 } 10891 } 10892 } finally { 10893 Binder.restoreCallingIdentity(token); 10894 } 10895 } 10896 10897 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10898 // Remove the parent package setting 10899 PackageSetting ps = (PackageSetting) pkg.mExtras; 10900 if (ps != null) { 10901 removePackageLI(ps, chatty); 10902 } 10903 // Remove the child package setting 10904 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10905 for (int i = 0; i < childCount; i++) { 10906 PackageParser.Package childPkg = pkg.childPackages.get(i); 10907 ps = (PackageSetting) childPkg.mExtras; 10908 if (ps != null) { 10909 removePackageLI(ps, chatty); 10910 } 10911 } 10912 } 10913 10914 void removePackageLI(PackageSetting ps, boolean chatty) { 10915 if (DEBUG_INSTALL) { 10916 if (chatty) 10917 Log.d(TAG, "Removing package " + ps.name); 10918 } 10919 10920 // writer 10921 synchronized (mPackages) { 10922 mPackages.remove(ps.name); 10923 final PackageParser.Package pkg = ps.pkg; 10924 if (pkg != null) { 10925 cleanPackageDataStructuresLILPw(pkg, chatty); 10926 } 10927 } 10928 } 10929 10930 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10931 if (DEBUG_INSTALL) { 10932 if (chatty) 10933 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10934 } 10935 10936 // writer 10937 synchronized (mPackages) { 10938 // Remove the parent package 10939 mPackages.remove(pkg.applicationInfo.packageName); 10940 cleanPackageDataStructuresLILPw(pkg, chatty); 10941 10942 // Remove the child packages 10943 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10944 for (int i = 0; i < childCount; i++) { 10945 PackageParser.Package childPkg = pkg.childPackages.get(i); 10946 mPackages.remove(childPkg.applicationInfo.packageName); 10947 cleanPackageDataStructuresLILPw(childPkg, chatty); 10948 } 10949 } 10950 } 10951 10952 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10953 int N = pkg.providers.size(); 10954 StringBuilder r = null; 10955 int i; 10956 for (i=0; i<N; i++) { 10957 PackageParser.Provider p = pkg.providers.get(i); 10958 mProviders.removeProvider(p); 10959 if (p.info.authority == null) { 10960 10961 /* There was another ContentProvider with this authority when 10962 * this app was installed so this authority is null, 10963 * Ignore it as we don't have to unregister the provider. 10964 */ 10965 continue; 10966 } 10967 String names[] = p.info.authority.split(";"); 10968 for (int j = 0; j < names.length; j++) { 10969 if (mProvidersByAuthority.get(names[j]) == p) { 10970 mProvidersByAuthority.remove(names[j]); 10971 if (DEBUG_REMOVE) { 10972 if (chatty) 10973 Log.d(TAG, "Unregistered content provider: " + names[j] 10974 + ", className = " + p.info.name + ", isSyncable = " 10975 + p.info.isSyncable); 10976 } 10977 } 10978 } 10979 if (DEBUG_REMOVE && chatty) { 10980 if (r == null) { 10981 r = new StringBuilder(256); 10982 } else { 10983 r.append(' '); 10984 } 10985 r.append(p.info.name); 10986 } 10987 } 10988 if (r != null) { 10989 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10990 } 10991 10992 N = pkg.services.size(); 10993 r = null; 10994 for (i=0; i<N; i++) { 10995 PackageParser.Service s = pkg.services.get(i); 10996 mServices.removeService(s); 10997 if (chatty) { 10998 if (r == null) { 10999 r = new StringBuilder(256); 11000 } else { 11001 r.append(' '); 11002 } 11003 r.append(s.info.name); 11004 } 11005 } 11006 if (r != null) { 11007 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11008 } 11009 11010 N = pkg.receivers.size(); 11011 r = null; 11012 for (i=0; i<N; i++) { 11013 PackageParser.Activity a = pkg.receivers.get(i); 11014 mReceivers.removeActivity(a, "receiver"); 11015 if (DEBUG_REMOVE && chatty) { 11016 if (r == null) { 11017 r = new StringBuilder(256); 11018 } else { 11019 r.append(' '); 11020 } 11021 r.append(a.info.name); 11022 } 11023 } 11024 if (r != null) { 11025 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11026 } 11027 11028 N = pkg.activities.size(); 11029 r = null; 11030 for (i=0; i<N; i++) { 11031 PackageParser.Activity a = pkg.activities.get(i); 11032 mActivities.removeActivity(a, "activity"); 11033 if (DEBUG_REMOVE && chatty) { 11034 if (r == null) { 11035 r = new StringBuilder(256); 11036 } else { 11037 r.append(' '); 11038 } 11039 r.append(a.info.name); 11040 } 11041 } 11042 if (r != null) { 11043 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11044 } 11045 11046 N = pkg.permissions.size(); 11047 r = null; 11048 for (i=0; i<N; i++) { 11049 PackageParser.Permission p = pkg.permissions.get(i); 11050 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11051 if (bp == null) { 11052 bp = mSettings.mPermissionTrees.get(p.info.name); 11053 } 11054 if (bp != null && bp.perm == p) { 11055 bp.perm = null; 11056 if (DEBUG_REMOVE && chatty) { 11057 if (r == null) { 11058 r = new StringBuilder(256); 11059 } else { 11060 r.append(' '); 11061 } 11062 r.append(p.info.name); 11063 } 11064 } 11065 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11066 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11067 if (appOpPkgs != null) { 11068 appOpPkgs.remove(pkg.packageName); 11069 } 11070 } 11071 } 11072 if (r != null) { 11073 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11074 } 11075 11076 N = pkg.requestedPermissions.size(); 11077 r = null; 11078 for (i=0; i<N; i++) { 11079 String perm = pkg.requestedPermissions.get(i); 11080 BasePermission bp = mSettings.mPermissions.get(perm); 11081 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11082 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11083 if (appOpPkgs != null) { 11084 appOpPkgs.remove(pkg.packageName); 11085 if (appOpPkgs.isEmpty()) { 11086 mAppOpPermissionPackages.remove(perm); 11087 } 11088 } 11089 } 11090 } 11091 if (r != null) { 11092 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11093 } 11094 11095 N = pkg.instrumentation.size(); 11096 r = null; 11097 for (i=0; i<N; i++) { 11098 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11099 mInstrumentation.remove(a.getComponentName()); 11100 if (DEBUG_REMOVE && chatty) { 11101 if (r == null) { 11102 r = new StringBuilder(256); 11103 } else { 11104 r.append(' '); 11105 } 11106 r.append(a.info.name); 11107 } 11108 } 11109 if (r != null) { 11110 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11111 } 11112 11113 r = null; 11114 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11115 // Only system apps can hold shared libraries. 11116 if (pkg.libraryNames != null) { 11117 for (i = 0; i < pkg.libraryNames.size(); i++) { 11118 String name = pkg.libraryNames.get(i); 11119 if (removeSharedLibraryLPw(name, 0)) { 11120 if (DEBUG_REMOVE && chatty) { 11121 if (r == null) { 11122 r = new StringBuilder(256); 11123 } else { 11124 r.append(' '); 11125 } 11126 r.append(name); 11127 } 11128 } 11129 } 11130 } 11131 } 11132 11133 r = null; 11134 11135 // Any package can hold static shared libraries. 11136 if (pkg.staticSharedLibName != null) { 11137 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11138 if (DEBUG_REMOVE && chatty) { 11139 if (r == null) { 11140 r = new StringBuilder(256); 11141 } else { 11142 r.append(' '); 11143 } 11144 r.append(pkg.staticSharedLibName); 11145 } 11146 } 11147 } 11148 11149 if (r != null) { 11150 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11151 } 11152 } 11153 11154 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11155 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11156 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11157 return true; 11158 } 11159 } 11160 return false; 11161 } 11162 11163 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11164 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11165 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11166 11167 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11168 // Update the parent permissions 11169 updatePermissionsLPw(pkg.packageName, pkg, flags); 11170 // Update the child permissions 11171 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11172 for (int i = 0; i < childCount; i++) { 11173 PackageParser.Package childPkg = pkg.childPackages.get(i); 11174 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11175 } 11176 } 11177 11178 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11179 int flags) { 11180 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11181 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11182 } 11183 11184 private void updatePermissionsLPw(String changingPkg, 11185 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11186 // Make sure there are no dangling permission trees. 11187 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11188 while (it.hasNext()) { 11189 final BasePermission bp = it.next(); 11190 if (bp.packageSetting == null) { 11191 // We may not yet have parsed the package, so just see if 11192 // we still know about its settings. 11193 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11194 } 11195 if (bp.packageSetting == null) { 11196 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11197 + " from package " + bp.sourcePackage); 11198 it.remove(); 11199 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11200 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11201 Slog.i(TAG, "Removing old permission tree: " + bp.name 11202 + " from package " + bp.sourcePackage); 11203 flags |= UPDATE_PERMISSIONS_ALL; 11204 it.remove(); 11205 } 11206 } 11207 } 11208 11209 // Make sure all dynamic permissions have been assigned to a package, 11210 // and make sure there are no dangling permissions. 11211 it = mSettings.mPermissions.values().iterator(); 11212 while (it.hasNext()) { 11213 final BasePermission bp = it.next(); 11214 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11215 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11216 + bp.name + " pkg=" + bp.sourcePackage 11217 + " info=" + bp.pendingInfo); 11218 if (bp.packageSetting == null && bp.pendingInfo != null) { 11219 final BasePermission tree = findPermissionTreeLP(bp.name); 11220 if (tree != null && tree.perm != null) { 11221 bp.packageSetting = tree.packageSetting; 11222 bp.perm = new PackageParser.Permission(tree.perm.owner, 11223 new PermissionInfo(bp.pendingInfo)); 11224 bp.perm.info.packageName = tree.perm.info.packageName; 11225 bp.perm.info.name = bp.name; 11226 bp.uid = tree.uid; 11227 } 11228 } 11229 } 11230 if (bp.packageSetting == null) { 11231 // We may not yet have parsed the package, so just see if 11232 // we still know about its settings. 11233 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11234 } 11235 if (bp.packageSetting == null) { 11236 Slog.w(TAG, "Removing dangling permission: " + bp.name 11237 + " from package " + bp.sourcePackage); 11238 it.remove(); 11239 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11240 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11241 Slog.i(TAG, "Removing old permission: " + bp.name 11242 + " from package " + bp.sourcePackage); 11243 flags |= UPDATE_PERMISSIONS_ALL; 11244 it.remove(); 11245 } 11246 } 11247 } 11248 11249 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11250 // Now update the permissions for all packages, in particular 11251 // replace the granted permissions of the system packages. 11252 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11253 for (PackageParser.Package pkg : mPackages.values()) { 11254 if (pkg != pkgInfo) { 11255 // Only replace for packages on requested volume 11256 final String volumeUuid = getVolumeUuidForPackage(pkg); 11257 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11258 && Objects.equals(replaceVolumeUuid, volumeUuid); 11259 grantPermissionsLPw(pkg, replace, changingPkg); 11260 } 11261 } 11262 } 11263 11264 if (pkgInfo != null) { 11265 // Only replace for packages on requested volume 11266 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11267 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11268 && Objects.equals(replaceVolumeUuid, volumeUuid); 11269 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11270 } 11271 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11272 } 11273 11274 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11275 String packageOfInterest) { 11276 // IMPORTANT: There are two types of permissions: install and runtime. 11277 // Install time permissions are granted when the app is installed to 11278 // all device users and users added in the future. Runtime permissions 11279 // are granted at runtime explicitly to specific users. Normal and signature 11280 // protected permissions are install time permissions. Dangerous permissions 11281 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11282 // otherwise they are runtime permissions. This function does not manage 11283 // runtime permissions except for the case an app targeting Lollipop MR1 11284 // being upgraded to target a newer SDK, in which case dangerous permissions 11285 // are transformed from install time to runtime ones. 11286 11287 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11288 if (ps == null) { 11289 return; 11290 } 11291 11292 PermissionsState permissionsState = ps.getPermissionsState(); 11293 PermissionsState origPermissions = permissionsState; 11294 11295 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11296 11297 boolean runtimePermissionsRevoked = false; 11298 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11299 11300 boolean changedInstallPermission = false; 11301 11302 if (replace) { 11303 ps.installPermissionsFixed = false; 11304 if (!ps.isSharedUser()) { 11305 origPermissions = new PermissionsState(permissionsState); 11306 permissionsState.reset(); 11307 } else { 11308 // We need to know only about runtime permission changes since the 11309 // calling code always writes the install permissions state but 11310 // the runtime ones are written only if changed. The only cases of 11311 // changed runtime permissions here are promotion of an install to 11312 // runtime and revocation of a runtime from a shared user. 11313 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11314 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11315 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11316 runtimePermissionsRevoked = true; 11317 } 11318 } 11319 } 11320 11321 permissionsState.setGlobalGids(mGlobalGids); 11322 11323 final int N = pkg.requestedPermissions.size(); 11324 for (int i=0; i<N; i++) { 11325 final String name = pkg.requestedPermissions.get(i); 11326 final BasePermission bp = mSettings.mPermissions.get(name); 11327 11328 if (DEBUG_INSTALL) { 11329 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11330 } 11331 11332 if (bp == null || bp.packageSetting == null) { 11333 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11334 Slog.w(TAG, "Unknown permission " + name 11335 + " in package " + pkg.packageName); 11336 } 11337 continue; 11338 } 11339 11340 11341 // Limit ephemeral apps to ephemeral allowed permissions. 11342 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11343 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11344 + pkg.packageName); 11345 continue; 11346 } 11347 11348 final String perm = bp.name; 11349 boolean allowedSig = false; 11350 int grant = GRANT_DENIED; 11351 11352 // Keep track of app op permissions. 11353 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11354 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11355 if (pkgs == null) { 11356 pkgs = new ArraySet<>(); 11357 mAppOpPermissionPackages.put(bp.name, pkgs); 11358 } 11359 pkgs.add(pkg.packageName); 11360 } 11361 11362 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11363 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11364 >= Build.VERSION_CODES.M; 11365 switch (level) { 11366 case PermissionInfo.PROTECTION_NORMAL: { 11367 // For all apps normal permissions are install time ones. 11368 grant = GRANT_INSTALL; 11369 } break; 11370 11371 case PermissionInfo.PROTECTION_DANGEROUS: { 11372 // If a permission review is required for legacy apps we represent 11373 // their permissions as always granted runtime ones since we need 11374 // to keep the review required permission flag per user while an 11375 // install permission's state is shared across all users. 11376 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11377 // For legacy apps dangerous permissions are install time ones. 11378 grant = GRANT_INSTALL; 11379 } else if (origPermissions.hasInstallPermission(bp.name)) { 11380 // For legacy apps that became modern, install becomes runtime. 11381 grant = GRANT_UPGRADE; 11382 } else if (mPromoteSystemApps 11383 && isSystemApp(ps) 11384 && mExistingSystemPackages.contains(ps.name)) { 11385 // For legacy system apps, install becomes runtime. 11386 // We cannot check hasInstallPermission() for system apps since those 11387 // permissions were granted implicitly and not persisted pre-M. 11388 grant = GRANT_UPGRADE; 11389 } else { 11390 // For modern apps keep runtime permissions unchanged. 11391 grant = GRANT_RUNTIME; 11392 } 11393 } break; 11394 11395 case PermissionInfo.PROTECTION_SIGNATURE: { 11396 // For all apps signature permissions are install time ones. 11397 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11398 if (allowedSig) { 11399 grant = GRANT_INSTALL; 11400 } 11401 } break; 11402 } 11403 11404 if (DEBUG_INSTALL) { 11405 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11406 } 11407 11408 if (grant != GRANT_DENIED) { 11409 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11410 // If this is an existing, non-system package, then 11411 // we can't add any new permissions to it. 11412 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11413 // Except... if this is a permission that was added 11414 // to the platform (note: need to only do this when 11415 // updating the platform). 11416 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11417 grant = GRANT_DENIED; 11418 } 11419 } 11420 } 11421 11422 switch (grant) { 11423 case GRANT_INSTALL: { 11424 // Revoke this as runtime permission to handle the case of 11425 // a runtime permission being downgraded to an install one. 11426 // Also in permission review mode we keep dangerous permissions 11427 // for legacy apps 11428 for (int userId : UserManagerService.getInstance().getUserIds()) { 11429 if (origPermissions.getRuntimePermissionState( 11430 bp.name, userId) != null) { 11431 // Revoke the runtime permission and clear the flags. 11432 origPermissions.revokeRuntimePermission(bp, userId); 11433 origPermissions.updatePermissionFlags(bp, userId, 11434 PackageManager.MASK_PERMISSION_FLAGS, 0); 11435 // If we revoked a permission permission, we have to write. 11436 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11437 changedRuntimePermissionUserIds, userId); 11438 } 11439 } 11440 // Grant an install permission. 11441 if (permissionsState.grantInstallPermission(bp) != 11442 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11443 changedInstallPermission = true; 11444 } 11445 } break; 11446 11447 case GRANT_RUNTIME: { 11448 // Grant previously granted runtime permissions. 11449 for (int userId : UserManagerService.getInstance().getUserIds()) { 11450 PermissionState permissionState = origPermissions 11451 .getRuntimePermissionState(bp.name, userId); 11452 int flags = permissionState != null 11453 ? permissionState.getFlags() : 0; 11454 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11455 // Don't propagate the permission in a permission review mode if 11456 // the former was revoked, i.e. marked to not propagate on upgrade. 11457 // Note that in a permission review mode install permissions are 11458 // represented as constantly granted runtime ones since we need to 11459 // keep a per user state associated with the permission. Also the 11460 // revoke on upgrade flag is no longer applicable and is reset. 11461 final boolean revokeOnUpgrade = (flags & PackageManager 11462 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11463 if (revokeOnUpgrade) { 11464 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11465 // Since we changed the flags, we have to write. 11466 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11467 changedRuntimePermissionUserIds, userId); 11468 } 11469 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11470 if (permissionsState.grantRuntimePermission(bp, userId) == 11471 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11472 // If we cannot put the permission as it was, 11473 // we have to write. 11474 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11475 changedRuntimePermissionUserIds, userId); 11476 } 11477 } 11478 11479 // If the app supports runtime permissions no need for a review. 11480 if (mPermissionReviewRequired 11481 && appSupportsRuntimePermissions 11482 && (flags & PackageManager 11483 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11484 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11485 // Since we changed the flags, we have to write. 11486 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11487 changedRuntimePermissionUserIds, userId); 11488 } 11489 } else if (mPermissionReviewRequired 11490 && !appSupportsRuntimePermissions) { 11491 // For legacy apps that need a permission review, every new 11492 // runtime permission is granted but it is pending a review. 11493 // We also need to review only platform defined runtime 11494 // permissions as these are the only ones the platform knows 11495 // how to disable the API to simulate revocation as legacy 11496 // apps don't expect to run with revoked permissions. 11497 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11498 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11499 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11500 // We changed the flags, hence have to write. 11501 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11502 changedRuntimePermissionUserIds, userId); 11503 } 11504 } 11505 if (permissionsState.grantRuntimePermission(bp, userId) 11506 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11507 // We changed the permission, hence have to write. 11508 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11509 changedRuntimePermissionUserIds, userId); 11510 } 11511 } 11512 // Propagate the permission flags. 11513 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11514 } 11515 } break; 11516 11517 case GRANT_UPGRADE: { 11518 // Grant runtime permissions for a previously held install permission. 11519 PermissionState permissionState = origPermissions 11520 .getInstallPermissionState(bp.name); 11521 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11522 11523 if (origPermissions.revokeInstallPermission(bp) 11524 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11525 // We will be transferring the permission flags, so clear them. 11526 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11527 PackageManager.MASK_PERMISSION_FLAGS, 0); 11528 changedInstallPermission = true; 11529 } 11530 11531 // If the permission is not to be promoted to runtime we ignore it and 11532 // also its other flags as they are not applicable to install permissions. 11533 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11534 for (int userId : currentUserIds) { 11535 if (permissionsState.grantRuntimePermission(bp, userId) != 11536 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11537 // Transfer the permission flags. 11538 permissionsState.updatePermissionFlags(bp, userId, 11539 flags, flags); 11540 // If we granted the permission, we have to write. 11541 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11542 changedRuntimePermissionUserIds, userId); 11543 } 11544 } 11545 } 11546 } break; 11547 11548 default: { 11549 if (packageOfInterest == null 11550 || packageOfInterest.equals(pkg.packageName)) { 11551 Slog.w(TAG, "Not granting permission " + perm 11552 + " to package " + pkg.packageName 11553 + " because it was previously installed without"); 11554 } 11555 } break; 11556 } 11557 } else { 11558 if (permissionsState.revokeInstallPermission(bp) != 11559 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11560 // Also drop the permission flags. 11561 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11562 PackageManager.MASK_PERMISSION_FLAGS, 0); 11563 changedInstallPermission = true; 11564 Slog.i(TAG, "Un-granting permission " + perm 11565 + " from package " + pkg.packageName 11566 + " (protectionLevel=" + bp.protectionLevel 11567 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11568 + ")"); 11569 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11570 // Don't print warning for app op permissions, since it is fine for them 11571 // not to be granted, there is a UI for the user to decide. 11572 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11573 Slog.w(TAG, "Not granting permission " + perm 11574 + " to package " + pkg.packageName 11575 + " (protectionLevel=" + bp.protectionLevel 11576 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11577 + ")"); 11578 } 11579 } 11580 } 11581 } 11582 11583 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11584 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11585 // This is the first that we have heard about this package, so the 11586 // permissions we have now selected are fixed until explicitly 11587 // changed. 11588 ps.installPermissionsFixed = true; 11589 } 11590 11591 // Persist the runtime permissions state for users with changes. If permissions 11592 // were revoked because no app in the shared user declares them we have to 11593 // write synchronously to avoid losing runtime permissions state. 11594 for (int userId : changedRuntimePermissionUserIds) { 11595 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11596 } 11597 } 11598 11599 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11600 boolean allowed = false; 11601 final int NP = PackageParser.NEW_PERMISSIONS.length; 11602 for (int ip=0; ip<NP; ip++) { 11603 final PackageParser.NewPermissionInfo npi 11604 = PackageParser.NEW_PERMISSIONS[ip]; 11605 if (npi.name.equals(perm) 11606 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11607 allowed = true; 11608 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11609 + pkg.packageName); 11610 break; 11611 } 11612 } 11613 return allowed; 11614 } 11615 11616 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11617 BasePermission bp, PermissionsState origPermissions) { 11618 boolean privilegedPermission = (bp.protectionLevel 11619 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11620 boolean privappPermissionsDisable = 11621 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11622 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11623 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11624 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11625 && !platformPackage && platformPermission) { 11626 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11627 .getPrivAppPermissions(pkg.packageName); 11628 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11629 if (!whitelisted) { 11630 Slog.w(TAG, "Privileged permission " + perm + " for package " 11631 + pkg.packageName + " - not in privapp-permissions whitelist"); 11632 // Only report violations for apps on system image 11633 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11634 if (mPrivappPermissionsViolations == null) { 11635 mPrivappPermissionsViolations = new ArraySet<>(); 11636 } 11637 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11638 } 11639 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11640 return false; 11641 } 11642 } 11643 } 11644 boolean allowed = (compareSignatures( 11645 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11646 == PackageManager.SIGNATURE_MATCH) 11647 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11648 == PackageManager.SIGNATURE_MATCH); 11649 if (!allowed && privilegedPermission) { 11650 if (isSystemApp(pkg)) { 11651 // For updated system applications, a system permission 11652 // is granted only if it had been defined by the original application. 11653 if (pkg.isUpdatedSystemApp()) { 11654 final PackageSetting sysPs = mSettings 11655 .getDisabledSystemPkgLPr(pkg.packageName); 11656 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11657 // If the original was granted this permission, we take 11658 // that grant decision as read and propagate it to the 11659 // update. 11660 if (sysPs.isPrivileged()) { 11661 allowed = true; 11662 } 11663 } else { 11664 // The system apk may have been updated with an older 11665 // version of the one on the data partition, but which 11666 // granted a new system permission that it didn't have 11667 // before. In this case we do want to allow the app to 11668 // now get the new permission if the ancestral apk is 11669 // privileged to get it. 11670 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11671 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11672 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11673 allowed = true; 11674 break; 11675 } 11676 } 11677 } 11678 // Also if a privileged parent package on the system image or any of 11679 // its children requested a privileged permission, the updated child 11680 // packages can also get the permission. 11681 if (pkg.parentPackage != null) { 11682 final PackageSetting disabledSysParentPs = mSettings 11683 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11684 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11685 && disabledSysParentPs.isPrivileged()) { 11686 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11687 allowed = true; 11688 } else if (disabledSysParentPs.pkg.childPackages != null) { 11689 final int count = disabledSysParentPs.pkg.childPackages.size(); 11690 for (int i = 0; i < count; i++) { 11691 PackageParser.Package disabledSysChildPkg = 11692 disabledSysParentPs.pkg.childPackages.get(i); 11693 if (isPackageRequestingPermission(disabledSysChildPkg, 11694 perm)) { 11695 allowed = true; 11696 break; 11697 } 11698 } 11699 } 11700 } 11701 } 11702 } 11703 } else { 11704 allowed = isPrivilegedApp(pkg); 11705 } 11706 } 11707 } 11708 if (!allowed) { 11709 if (!allowed && (bp.protectionLevel 11710 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11711 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11712 // If this was a previously normal/dangerous permission that got moved 11713 // to a system permission as part of the runtime permission redesign, then 11714 // we still want to blindly grant it to old apps. 11715 allowed = true; 11716 } 11717 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11718 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11719 // If this permission is to be granted to the system installer and 11720 // this app is an installer, then it gets the permission. 11721 allowed = true; 11722 } 11723 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11724 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11725 // If this permission is to be granted to the system verifier and 11726 // this app is a verifier, then it gets the permission. 11727 allowed = true; 11728 } 11729 if (!allowed && (bp.protectionLevel 11730 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11731 && isSystemApp(pkg)) { 11732 // Any pre-installed system app is allowed to get this permission. 11733 allowed = true; 11734 } 11735 if (!allowed && (bp.protectionLevel 11736 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11737 // For development permissions, a development permission 11738 // is granted only if it was already granted. 11739 allowed = origPermissions.hasInstallPermission(perm); 11740 } 11741 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11742 && pkg.packageName.equals(mSetupWizardPackage)) { 11743 // If this permission is to be granted to the system setup wizard and 11744 // this app is a setup wizard, then it gets the permission. 11745 allowed = true; 11746 } 11747 } 11748 return allowed; 11749 } 11750 11751 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11752 final int permCount = pkg.requestedPermissions.size(); 11753 for (int j = 0; j < permCount; j++) { 11754 String requestedPermission = pkg.requestedPermissions.get(j); 11755 if (permission.equals(requestedPermission)) { 11756 return true; 11757 } 11758 } 11759 return false; 11760 } 11761 11762 final class ActivityIntentResolver 11763 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11764 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11765 boolean defaultOnly, int userId) { 11766 if (!sUserManager.exists(userId)) return null; 11767 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11768 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11769 } 11770 11771 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11772 int userId) { 11773 if (!sUserManager.exists(userId)) return null; 11774 mFlags = flags; 11775 return super.queryIntent(intent, resolvedType, 11776 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11777 userId); 11778 } 11779 11780 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11781 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11782 if (!sUserManager.exists(userId)) return null; 11783 if (packageActivities == null) { 11784 return null; 11785 } 11786 mFlags = flags; 11787 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11788 final int N = packageActivities.size(); 11789 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11790 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11791 11792 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11793 for (int i = 0; i < N; ++i) { 11794 intentFilters = packageActivities.get(i).intents; 11795 if (intentFilters != null && intentFilters.size() > 0) { 11796 PackageParser.ActivityIntentInfo[] array = 11797 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11798 intentFilters.toArray(array); 11799 listCut.add(array); 11800 } 11801 } 11802 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11803 } 11804 11805 /** 11806 * Finds a privileged activity that matches the specified activity names. 11807 */ 11808 private PackageParser.Activity findMatchingActivity( 11809 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11810 for (PackageParser.Activity sysActivity : activityList) { 11811 if (sysActivity.info.name.equals(activityInfo.name)) { 11812 return sysActivity; 11813 } 11814 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11815 return sysActivity; 11816 } 11817 if (sysActivity.info.targetActivity != null) { 11818 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11819 return sysActivity; 11820 } 11821 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11822 return sysActivity; 11823 } 11824 } 11825 } 11826 return null; 11827 } 11828 11829 public class IterGenerator<E> { 11830 public Iterator<E> generate(ActivityIntentInfo info) { 11831 return null; 11832 } 11833 } 11834 11835 public class ActionIterGenerator extends IterGenerator<String> { 11836 @Override 11837 public Iterator<String> generate(ActivityIntentInfo info) { 11838 return info.actionsIterator(); 11839 } 11840 } 11841 11842 public class CategoriesIterGenerator extends IterGenerator<String> { 11843 @Override 11844 public Iterator<String> generate(ActivityIntentInfo info) { 11845 return info.categoriesIterator(); 11846 } 11847 } 11848 11849 public class SchemesIterGenerator extends IterGenerator<String> { 11850 @Override 11851 public Iterator<String> generate(ActivityIntentInfo info) { 11852 return info.schemesIterator(); 11853 } 11854 } 11855 11856 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11857 @Override 11858 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11859 return info.authoritiesIterator(); 11860 } 11861 } 11862 11863 /** 11864 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11865 * MODIFIED. Do not pass in a list that should not be changed. 11866 */ 11867 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11868 IterGenerator<T> generator, Iterator<T> searchIterator) { 11869 // loop through the set of actions; every one must be found in the intent filter 11870 while (searchIterator.hasNext()) { 11871 // we must have at least one filter in the list to consider a match 11872 if (intentList.size() == 0) { 11873 break; 11874 } 11875 11876 final T searchAction = searchIterator.next(); 11877 11878 // loop through the set of intent filters 11879 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11880 while (intentIter.hasNext()) { 11881 final ActivityIntentInfo intentInfo = intentIter.next(); 11882 boolean selectionFound = false; 11883 11884 // loop through the intent filter's selection criteria; at least one 11885 // of them must match the searched criteria 11886 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11887 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11888 final T intentSelection = intentSelectionIter.next(); 11889 if (intentSelection != null && intentSelection.equals(searchAction)) { 11890 selectionFound = true; 11891 break; 11892 } 11893 } 11894 11895 // the selection criteria wasn't found in this filter's set; this filter 11896 // is not a potential match 11897 if (!selectionFound) { 11898 intentIter.remove(); 11899 } 11900 } 11901 } 11902 } 11903 11904 private boolean isProtectedAction(ActivityIntentInfo filter) { 11905 final Iterator<String> actionsIter = filter.actionsIterator(); 11906 while (actionsIter != null && actionsIter.hasNext()) { 11907 final String filterAction = actionsIter.next(); 11908 if (PROTECTED_ACTIONS.contains(filterAction)) { 11909 return true; 11910 } 11911 } 11912 return false; 11913 } 11914 11915 /** 11916 * Adjusts the priority of the given intent filter according to policy. 11917 * <p> 11918 * <ul> 11919 * <li>The priority for non privileged applications is capped to '0'</li> 11920 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11921 * <li>The priority for unbundled updates to privileged applications is capped to the 11922 * priority defined on the system partition</li> 11923 * </ul> 11924 * <p> 11925 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11926 * allowed to obtain any priority on any action. 11927 */ 11928 private void adjustPriority( 11929 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11930 // nothing to do; priority is fine as-is 11931 if (intent.getPriority() <= 0) { 11932 return; 11933 } 11934 11935 final ActivityInfo activityInfo = intent.activity.info; 11936 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11937 11938 final boolean privilegedApp = 11939 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11940 if (!privilegedApp) { 11941 // non-privileged applications can never define a priority >0 11942 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11943 + " package: " + applicationInfo.packageName 11944 + " activity: " + intent.activity.className 11945 + " origPrio: " + intent.getPriority()); 11946 intent.setPriority(0); 11947 return; 11948 } 11949 11950 if (systemActivities == null) { 11951 // the system package is not disabled; we're parsing the system partition 11952 if (isProtectedAction(intent)) { 11953 if (mDeferProtectedFilters) { 11954 // We can't deal with these just yet. No component should ever obtain a 11955 // >0 priority for a protected actions, with ONE exception -- the setup 11956 // wizard. The setup wizard, however, cannot be known until we're able to 11957 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11958 // until all intent filters have been processed. Chicken, meet egg. 11959 // Let the filter temporarily have a high priority and rectify the 11960 // priorities after all system packages have been scanned. 11961 mProtectedFilters.add(intent); 11962 if (DEBUG_FILTERS) { 11963 Slog.i(TAG, "Protected action; save for later;" 11964 + " package: " + applicationInfo.packageName 11965 + " activity: " + intent.activity.className 11966 + " origPrio: " + intent.getPriority()); 11967 } 11968 return; 11969 } else { 11970 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11971 Slog.i(TAG, "No setup wizard;" 11972 + " All protected intents capped to priority 0"); 11973 } 11974 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11975 if (DEBUG_FILTERS) { 11976 Slog.i(TAG, "Found setup wizard;" 11977 + " allow priority " + intent.getPriority() + ";" 11978 + " package: " + intent.activity.info.packageName 11979 + " activity: " + intent.activity.className 11980 + " priority: " + intent.getPriority()); 11981 } 11982 // setup wizard gets whatever it wants 11983 return; 11984 } 11985 Slog.w(TAG, "Protected action; cap priority to 0;" 11986 + " package: " + intent.activity.info.packageName 11987 + " activity: " + intent.activity.className 11988 + " origPrio: " + intent.getPriority()); 11989 intent.setPriority(0); 11990 return; 11991 } 11992 } 11993 // privileged apps on the system image get whatever priority they request 11994 return; 11995 } 11996 11997 // privileged app unbundled update ... try to find the same activity 11998 final PackageParser.Activity foundActivity = 11999 findMatchingActivity(systemActivities, activityInfo); 12000 if (foundActivity == null) { 12001 // this is a new activity; it cannot obtain >0 priority 12002 if (DEBUG_FILTERS) { 12003 Slog.i(TAG, "New activity; cap priority to 0;" 12004 + " package: " + applicationInfo.packageName 12005 + " activity: " + intent.activity.className 12006 + " origPrio: " + intent.getPriority()); 12007 } 12008 intent.setPriority(0); 12009 return; 12010 } 12011 12012 // found activity, now check for filter equivalence 12013 12014 // a shallow copy is enough; we modify the list, not its contents 12015 final List<ActivityIntentInfo> intentListCopy = 12016 new ArrayList<>(foundActivity.intents); 12017 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12018 12019 // find matching action subsets 12020 final Iterator<String> actionsIterator = intent.actionsIterator(); 12021 if (actionsIterator != null) { 12022 getIntentListSubset( 12023 intentListCopy, new ActionIterGenerator(), actionsIterator); 12024 if (intentListCopy.size() == 0) { 12025 // no more intents to match; we're not equivalent 12026 if (DEBUG_FILTERS) { 12027 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12028 + " package: " + applicationInfo.packageName 12029 + " activity: " + intent.activity.className 12030 + " origPrio: " + intent.getPriority()); 12031 } 12032 intent.setPriority(0); 12033 return; 12034 } 12035 } 12036 12037 // find matching category subsets 12038 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12039 if (categoriesIterator != null) { 12040 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12041 categoriesIterator); 12042 if (intentListCopy.size() == 0) { 12043 // no more intents to match; we're not equivalent 12044 if (DEBUG_FILTERS) { 12045 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12046 + " package: " + applicationInfo.packageName 12047 + " activity: " + intent.activity.className 12048 + " origPrio: " + intent.getPriority()); 12049 } 12050 intent.setPriority(0); 12051 return; 12052 } 12053 } 12054 12055 // find matching schemes subsets 12056 final Iterator<String> schemesIterator = intent.schemesIterator(); 12057 if (schemesIterator != null) { 12058 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12059 schemesIterator); 12060 if (intentListCopy.size() == 0) { 12061 // no more intents to match; we're not equivalent 12062 if (DEBUG_FILTERS) { 12063 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12064 + " package: " + applicationInfo.packageName 12065 + " activity: " + intent.activity.className 12066 + " origPrio: " + intent.getPriority()); 12067 } 12068 intent.setPriority(0); 12069 return; 12070 } 12071 } 12072 12073 // find matching authorities subsets 12074 final Iterator<IntentFilter.AuthorityEntry> 12075 authoritiesIterator = intent.authoritiesIterator(); 12076 if (authoritiesIterator != null) { 12077 getIntentListSubset(intentListCopy, 12078 new AuthoritiesIterGenerator(), 12079 authoritiesIterator); 12080 if (intentListCopy.size() == 0) { 12081 // no more intents to match; we're not equivalent 12082 if (DEBUG_FILTERS) { 12083 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12084 + " package: " + applicationInfo.packageName 12085 + " activity: " + intent.activity.className 12086 + " origPrio: " + intent.getPriority()); 12087 } 12088 intent.setPriority(0); 12089 return; 12090 } 12091 } 12092 12093 // we found matching filter(s); app gets the max priority of all intents 12094 int cappedPriority = 0; 12095 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12096 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12097 } 12098 if (intent.getPriority() > cappedPriority) { 12099 if (DEBUG_FILTERS) { 12100 Slog.i(TAG, "Found matching filter(s);" 12101 + " cap priority to " + cappedPriority + ";" 12102 + " package: " + applicationInfo.packageName 12103 + " activity: " + intent.activity.className 12104 + " origPrio: " + intent.getPriority()); 12105 } 12106 intent.setPriority(cappedPriority); 12107 return; 12108 } 12109 // all this for nothing; the requested priority was <= what was on the system 12110 } 12111 12112 public final void addActivity(PackageParser.Activity a, String type) { 12113 mActivities.put(a.getComponentName(), a); 12114 if (DEBUG_SHOW_INFO) 12115 Log.v( 12116 TAG, " " + type + " " + 12117 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12118 if (DEBUG_SHOW_INFO) 12119 Log.v(TAG, " Class=" + a.info.name); 12120 final int NI = a.intents.size(); 12121 for (int j=0; j<NI; j++) { 12122 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12123 if ("activity".equals(type)) { 12124 final PackageSetting ps = 12125 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12126 final List<PackageParser.Activity> systemActivities = 12127 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12128 adjustPriority(systemActivities, intent); 12129 } 12130 if (DEBUG_SHOW_INFO) { 12131 Log.v(TAG, " IntentFilter:"); 12132 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12133 } 12134 if (!intent.debugCheck()) { 12135 Log.w(TAG, "==> For Activity " + a.info.name); 12136 } 12137 addFilter(intent); 12138 } 12139 } 12140 12141 public final void removeActivity(PackageParser.Activity a, String type) { 12142 mActivities.remove(a.getComponentName()); 12143 if (DEBUG_SHOW_INFO) { 12144 Log.v(TAG, " " + type + " " 12145 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12146 : a.info.name) + ":"); 12147 Log.v(TAG, " Class=" + a.info.name); 12148 } 12149 final int NI = a.intents.size(); 12150 for (int j=0; j<NI; j++) { 12151 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12152 if (DEBUG_SHOW_INFO) { 12153 Log.v(TAG, " IntentFilter:"); 12154 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12155 } 12156 removeFilter(intent); 12157 } 12158 } 12159 12160 @Override 12161 protected boolean allowFilterResult( 12162 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12163 ActivityInfo filterAi = filter.activity.info; 12164 for (int i=dest.size()-1; i>=0; i--) { 12165 ActivityInfo destAi = dest.get(i).activityInfo; 12166 if (destAi.name == filterAi.name 12167 && destAi.packageName == filterAi.packageName) { 12168 return false; 12169 } 12170 } 12171 return true; 12172 } 12173 12174 @Override 12175 protected ActivityIntentInfo[] newArray(int size) { 12176 return new ActivityIntentInfo[size]; 12177 } 12178 12179 @Override 12180 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12181 if (!sUserManager.exists(userId)) return true; 12182 PackageParser.Package p = filter.activity.owner; 12183 if (p != null) { 12184 PackageSetting ps = (PackageSetting)p.mExtras; 12185 if (ps != null) { 12186 // System apps are never considered stopped for purposes of 12187 // filtering, because there may be no way for the user to 12188 // actually re-launch them. 12189 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12190 && ps.getStopped(userId); 12191 } 12192 } 12193 return false; 12194 } 12195 12196 @Override 12197 protected boolean isPackageForFilter(String packageName, 12198 PackageParser.ActivityIntentInfo info) { 12199 return packageName.equals(info.activity.owner.packageName); 12200 } 12201 12202 @Override 12203 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12204 int match, int userId) { 12205 if (!sUserManager.exists(userId)) return null; 12206 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12207 return null; 12208 } 12209 final PackageParser.Activity activity = info.activity; 12210 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12211 if (ps == null) { 12212 return null; 12213 } 12214 final PackageUserState userState = ps.readUserState(userId); 12215 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12216 userState, userId); 12217 if (ai == null) { 12218 return null; 12219 } 12220 final boolean matchVisibleToInstantApp = 12221 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12222 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12223 // throw out filters that aren't visible to ephemeral apps 12224 if (matchVisibleToInstantApp 12225 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12226 return null; 12227 } 12228 // throw out ephemeral filters if we're not explicitly requesting them 12229 if (!isInstantApp && userState.instantApp) { 12230 return null; 12231 } 12232 // throw out instant app filters if updates are available; will trigger 12233 // instant app resolution 12234 if (userState.instantApp && ps.isUpdateAvailable()) { 12235 return null; 12236 } 12237 final ResolveInfo res = new ResolveInfo(); 12238 res.activityInfo = ai; 12239 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12240 res.filter = info; 12241 } 12242 if (info != null) { 12243 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12244 } 12245 res.priority = info.getPriority(); 12246 res.preferredOrder = activity.owner.mPreferredOrder; 12247 //System.out.println("Result: " + res.activityInfo.className + 12248 // " = " + res.priority); 12249 res.match = match; 12250 res.isDefault = info.hasDefault; 12251 res.labelRes = info.labelRes; 12252 res.nonLocalizedLabel = info.nonLocalizedLabel; 12253 if (userNeedsBadging(userId)) { 12254 res.noResourceId = true; 12255 } else { 12256 res.icon = info.icon; 12257 } 12258 res.iconResourceId = info.icon; 12259 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12260 res.instantAppAvailable = userState.instantApp; 12261 return res; 12262 } 12263 12264 @Override 12265 protected void sortResults(List<ResolveInfo> results) { 12266 Collections.sort(results, mResolvePrioritySorter); 12267 } 12268 12269 @Override 12270 protected void dumpFilter(PrintWriter out, String prefix, 12271 PackageParser.ActivityIntentInfo filter) { 12272 out.print(prefix); out.print( 12273 Integer.toHexString(System.identityHashCode(filter.activity))); 12274 out.print(' '); 12275 filter.activity.printComponentShortName(out); 12276 out.print(" filter "); 12277 out.println(Integer.toHexString(System.identityHashCode(filter))); 12278 } 12279 12280 @Override 12281 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12282 return filter.activity; 12283 } 12284 12285 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12286 PackageParser.Activity activity = (PackageParser.Activity)label; 12287 out.print(prefix); out.print( 12288 Integer.toHexString(System.identityHashCode(activity))); 12289 out.print(' '); 12290 activity.printComponentShortName(out); 12291 if (count > 1) { 12292 out.print(" ("); out.print(count); out.print(" filters)"); 12293 } 12294 out.println(); 12295 } 12296 12297 // Keys are String (activity class name), values are Activity. 12298 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12299 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12300 private int mFlags; 12301 } 12302 12303 private final class ServiceIntentResolver 12304 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12305 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12306 boolean defaultOnly, int userId) { 12307 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12308 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12309 } 12310 12311 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12312 int userId) { 12313 if (!sUserManager.exists(userId)) return null; 12314 mFlags = flags; 12315 return super.queryIntent(intent, resolvedType, 12316 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12317 userId); 12318 } 12319 12320 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12321 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12322 if (!sUserManager.exists(userId)) return null; 12323 if (packageServices == null) { 12324 return null; 12325 } 12326 mFlags = flags; 12327 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12328 final int N = packageServices.size(); 12329 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12330 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12331 12332 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12333 for (int i = 0; i < N; ++i) { 12334 intentFilters = packageServices.get(i).intents; 12335 if (intentFilters != null && intentFilters.size() > 0) { 12336 PackageParser.ServiceIntentInfo[] array = 12337 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12338 intentFilters.toArray(array); 12339 listCut.add(array); 12340 } 12341 } 12342 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12343 } 12344 12345 public final void addService(PackageParser.Service s) { 12346 mServices.put(s.getComponentName(), s); 12347 if (DEBUG_SHOW_INFO) { 12348 Log.v(TAG, " " 12349 + (s.info.nonLocalizedLabel != null 12350 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12351 Log.v(TAG, " Class=" + s.info.name); 12352 } 12353 final int NI = s.intents.size(); 12354 int j; 12355 for (j=0; j<NI; j++) { 12356 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12357 if (DEBUG_SHOW_INFO) { 12358 Log.v(TAG, " IntentFilter:"); 12359 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12360 } 12361 if (!intent.debugCheck()) { 12362 Log.w(TAG, "==> For Service " + s.info.name); 12363 } 12364 addFilter(intent); 12365 } 12366 } 12367 12368 public final void removeService(PackageParser.Service s) { 12369 mServices.remove(s.getComponentName()); 12370 if (DEBUG_SHOW_INFO) { 12371 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12372 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12373 Log.v(TAG, " Class=" + s.info.name); 12374 } 12375 final int NI = s.intents.size(); 12376 int j; 12377 for (j=0; j<NI; j++) { 12378 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12379 if (DEBUG_SHOW_INFO) { 12380 Log.v(TAG, " IntentFilter:"); 12381 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12382 } 12383 removeFilter(intent); 12384 } 12385 } 12386 12387 @Override 12388 protected boolean allowFilterResult( 12389 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12390 ServiceInfo filterSi = filter.service.info; 12391 for (int i=dest.size()-1; i>=0; i--) { 12392 ServiceInfo destAi = dest.get(i).serviceInfo; 12393 if (destAi.name == filterSi.name 12394 && destAi.packageName == filterSi.packageName) { 12395 return false; 12396 } 12397 } 12398 return true; 12399 } 12400 12401 @Override 12402 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12403 return new PackageParser.ServiceIntentInfo[size]; 12404 } 12405 12406 @Override 12407 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12408 if (!sUserManager.exists(userId)) return true; 12409 PackageParser.Package p = filter.service.owner; 12410 if (p != null) { 12411 PackageSetting ps = (PackageSetting)p.mExtras; 12412 if (ps != null) { 12413 // System apps are never considered stopped for purposes of 12414 // filtering, because there may be no way for the user to 12415 // actually re-launch them. 12416 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12417 && ps.getStopped(userId); 12418 } 12419 } 12420 return false; 12421 } 12422 12423 @Override 12424 protected boolean isPackageForFilter(String packageName, 12425 PackageParser.ServiceIntentInfo info) { 12426 return packageName.equals(info.service.owner.packageName); 12427 } 12428 12429 @Override 12430 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12431 int match, int userId) { 12432 if (!sUserManager.exists(userId)) return null; 12433 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12434 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12435 return null; 12436 } 12437 final PackageParser.Service service = info.service; 12438 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12439 if (ps == null) { 12440 return null; 12441 } 12442 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12443 ps.readUserState(userId), userId); 12444 if (si == null) { 12445 return null; 12446 } 12447 final ResolveInfo res = new ResolveInfo(); 12448 res.serviceInfo = si; 12449 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12450 res.filter = filter; 12451 } 12452 res.priority = info.getPriority(); 12453 res.preferredOrder = service.owner.mPreferredOrder; 12454 res.match = match; 12455 res.isDefault = info.hasDefault; 12456 res.labelRes = info.labelRes; 12457 res.nonLocalizedLabel = info.nonLocalizedLabel; 12458 res.icon = info.icon; 12459 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12460 return res; 12461 } 12462 12463 @Override 12464 protected void sortResults(List<ResolveInfo> results) { 12465 Collections.sort(results, mResolvePrioritySorter); 12466 } 12467 12468 @Override 12469 protected void dumpFilter(PrintWriter out, String prefix, 12470 PackageParser.ServiceIntentInfo filter) { 12471 out.print(prefix); out.print( 12472 Integer.toHexString(System.identityHashCode(filter.service))); 12473 out.print(' '); 12474 filter.service.printComponentShortName(out); 12475 out.print(" filter "); 12476 out.println(Integer.toHexString(System.identityHashCode(filter))); 12477 } 12478 12479 @Override 12480 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12481 return filter.service; 12482 } 12483 12484 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12485 PackageParser.Service service = (PackageParser.Service)label; 12486 out.print(prefix); out.print( 12487 Integer.toHexString(System.identityHashCode(service))); 12488 out.print(' '); 12489 service.printComponentShortName(out); 12490 if (count > 1) { 12491 out.print(" ("); out.print(count); out.print(" filters)"); 12492 } 12493 out.println(); 12494 } 12495 12496// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12497// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12498// final List<ResolveInfo> retList = Lists.newArrayList(); 12499// while (i.hasNext()) { 12500// final ResolveInfo resolveInfo = (ResolveInfo) i; 12501// if (isEnabledLP(resolveInfo.serviceInfo)) { 12502// retList.add(resolveInfo); 12503// } 12504// } 12505// return retList; 12506// } 12507 12508 // Keys are String (activity class name), values are Activity. 12509 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12510 = new ArrayMap<ComponentName, PackageParser.Service>(); 12511 private int mFlags; 12512 } 12513 12514 private final class ProviderIntentResolver 12515 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12516 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12517 boolean defaultOnly, int userId) { 12518 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12519 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12520 } 12521 12522 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12523 int userId) { 12524 if (!sUserManager.exists(userId)) 12525 return null; 12526 mFlags = flags; 12527 return super.queryIntent(intent, resolvedType, 12528 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12529 userId); 12530 } 12531 12532 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12533 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12534 if (!sUserManager.exists(userId)) 12535 return null; 12536 if (packageProviders == null) { 12537 return null; 12538 } 12539 mFlags = flags; 12540 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12541 final int N = packageProviders.size(); 12542 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12543 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12544 12545 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12546 for (int i = 0; i < N; ++i) { 12547 intentFilters = packageProviders.get(i).intents; 12548 if (intentFilters != null && intentFilters.size() > 0) { 12549 PackageParser.ProviderIntentInfo[] array = 12550 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12551 intentFilters.toArray(array); 12552 listCut.add(array); 12553 } 12554 } 12555 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12556 } 12557 12558 public final void addProvider(PackageParser.Provider p) { 12559 if (mProviders.containsKey(p.getComponentName())) { 12560 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12561 return; 12562 } 12563 12564 mProviders.put(p.getComponentName(), p); 12565 if (DEBUG_SHOW_INFO) { 12566 Log.v(TAG, " " 12567 + (p.info.nonLocalizedLabel != null 12568 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12569 Log.v(TAG, " Class=" + p.info.name); 12570 } 12571 final int NI = p.intents.size(); 12572 int j; 12573 for (j = 0; j < NI; j++) { 12574 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12575 if (DEBUG_SHOW_INFO) { 12576 Log.v(TAG, " IntentFilter:"); 12577 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12578 } 12579 if (!intent.debugCheck()) { 12580 Log.w(TAG, "==> For Provider " + p.info.name); 12581 } 12582 addFilter(intent); 12583 } 12584 } 12585 12586 public final void removeProvider(PackageParser.Provider p) { 12587 mProviders.remove(p.getComponentName()); 12588 if (DEBUG_SHOW_INFO) { 12589 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12590 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12591 Log.v(TAG, " Class=" + p.info.name); 12592 } 12593 final int NI = p.intents.size(); 12594 int j; 12595 for (j = 0; j < NI; j++) { 12596 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12597 if (DEBUG_SHOW_INFO) { 12598 Log.v(TAG, " IntentFilter:"); 12599 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12600 } 12601 removeFilter(intent); 12602 } 12603 } 12604 12605 @Override 12606 protected boolean allowFilterResult( 12607 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12608 ProviderInfo filterPi = filter.provider.info; 12609 for (int i = dest.size() - 1; i >= 0; i--) { 12610 ProviderInfo destPi = dest.get(i).providerInfo; 12611 if (destPi.name == filterPi.name 12612 && destPi.packageName == filterPi.packageName) { 12613 return false; 12614 } 12615 } 12616 return true; 12617 } 12618 12619 @Override 12620 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12621 return new PackageParser.ProviderIntentInfo[size]; 12622 } 12623 12624 @Override 12625 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12626 if (!sUserManager.exists(userId)) 12627 return true; 12628 PackageParser.Package p = filter.provider.owner; 12629 if (p != null) { 12630 PackageSetting ps = (PackageSetting) p.mExtras; 12631 if (ps != null) { 12632 // System apps are never considered stopped for purposes of 12633 // filtering, because there may be no way for the user to 12634 // actually re-launch them. 12635 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12636 && ps.getStopped(userId); 12637 } 12638 } 12639 return false; 12640 } 12641 12642 @Override 12643 protected boolean isPackageForFilter(String packageName, 12644 PackageParser.ProviderIntentInfo info) { 12645 return packageName.equals(info.provider.owner.packageName); 12646 } 12647 12648 @Override 12649 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12650 int match, int userId) { 12651 if (!sUserManager.exists(userId)) 12652 return null; 12653 final PackageParser.ProviderIntentInfo info = filter; 12654 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12655 return null; 12656 } 12657 final PackageParser.Provider provider = info.provider; 12658 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12659 if (ps == null) { 12660 return null; 12661 } 12662 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12663 ps.readUserState(userId), userId); 12664 if (pi == null) { 12665 return null; 12666 } 12667 final ResolveInfo res = new ResolveInfo(); 12668 res.providerInfo = pi; 12669 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12670 res.filter = filter; 12671 } 12672 res.priority = info.getPriority(); 12673 res.preferredOrder = provider.owner.mPreferredOrder; 12674 res.match = match; 12675 res.isDefault = info.hasDefault; 12676 res.labelRes = info.labelRes; 12677 res.nonLocalizedLabel = info.nonLocalizedLabel; 12678 res.icon = info.icon; 12679 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12680 return res; 12681 } 12682 12683 @Override 12684 protected void sortResults(List<ResolveInfo> results) { 12685 Collections.sort(results, mResolvePrioritySorter); 12686 } 12687 12688 @Override 12689 protected void dumpFilter(PrintWriter out, String prefix, 12690 PackageParser.ProviderIntentInfo filter) { 12691 out.print(prefix); 12692 out.print( 12693 Integer.toHexString(System.identityHashCode(filter.provider))); 12694 out.print(' '); 12695 filter.provider.printComponentShortName(out); 12696 out.print(" filter "); 12697 out.println(Integer.toHexString(System.identityHashCode(filter))); 12698 } 12699 12700 @Override 12701 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12702 return filter.provider; 12703 } 12704 12705 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12706 PackageParser.Provider provider = (PackageParser.Provider)label; 12707 out.print(prefix); out.print( 12708 Integer.toHexString(System.identityHashCode(provider))); 12709 out.print(' '); 12710 provider.printComponentShortName(out); 12711 if (count > 1) { 12712 out.print(" ("); out.print(count); out.print(" filters)"); 12713 } 12714 out.println(); 12715 } 12716 12717 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12718 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12719 private int mFlags; 12720 } 12721 12722 static final class EphemeralIntentResolver 12723 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12724 /** 12725 * The result that has the highest defined order. Ordering applies on a 12726 * per-package basis. Mapping is from package name to Pair of order and 12727 * EphemeralResolveInfo. 12728 * <p> 12729 * NOTE: This is implemented as a field variable for convenience and efficiency. 12730 * By having a field variable, we're able to track filter ordering as soon as 12731 * a non-zero order is defined. Otherwise, multiple loops across the result set 12732 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12733 * this needs to be contained entirely within {@link #filterResults}. 12734 */ 12735 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12736 12737 @Override 12738 protected AuxiliaryResolveInfo[] newArray(int size) { 12739 return new AuxiliaryResolveInfo[size]; 12740 } 12741 12742 @Override 12743 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12744 return true; 12745 } 12746 12747 @Override 12748 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12749 int userId) { 12750 if (!sUserManager.exists(userId)) { 12751 return null; 12752 } 12753 final String packageName = responseObj.resolveInfo.getPackageName(); 12754 final Integer order = responseObj.getOrder(); 12755 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12756 mOrderResult.get(packageName); 12757 // ordering is enabled and this item's order isn't high enough 12758 if (lastOrderResult != null && lastOrderResult.first >= order) { 12759 return null; 12760 } 12761 final InstantAppResolveInfo res = responseObj.resolveInfo; 12762 if (order > 0) { 12763 // non-zero order, enable ordering 12764 mOrderResult.put(packageName, new Pair<>(order, res)); 12765 } 12766 return responseObj; 12767 } 12768 12769 @Override 12770 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12771 // only do work if ordering is enabled [most of the time it won't be] 12772 if (mOrderResult.size() == 0) { 12773 return; 12774 } 12775 int resultSize = results.size(); 12776 for (int i = 0; i < resultSize; i++) { 12777 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12778 final String packageName = info.getPackageName(); 12779 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12780 if (savedInfo == null) { 12781 // package doesn't having ordering 12782 continue; 12783 } 12784 if (savedInfo.second == info) { 12785 // circled back to the highest ordered item; remove from order list 12786 mOrderResult.remove(savedInfo); 12787 if (mOrderResult.size() == 0) { 12788 // no more ordered items 12789 break; 12790 } 12791 continue; 12792 } 12793 // item has a worse order, remove it from the result list 12794 results.remove(i); 12795 resultSize--; 12796 i--; 12797 } 12798 } 12799 } 12800 12801 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12802 new Comparator<ResolveInfo>() { 12803 public int compare(ResolveInfo r1, ResolveInfo r2) { 12804 int v1 = r1.priority; 12805 int v2 = r2.priority; 12806 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12807 if (v1 != v2) { 12808 return (v1 > v2) ? -1 : 1; 12809 } 12810 v1 = r1.preferredOrder; 12811 v2 = r2.preferredOrder; 12812 if (v1 != v2) { 12813 return (v1 > v2) ? -1 : 1; 12814 } 12815 if (r1.isDefault != r2.isDefault) { 12816 return r1.isDefault ? -1 : 1; 12817 } 12818 v1 = r1.match; 12819 v2 = r2.match; 12820 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12821 if (v1 != v2) { 12822 return (v1 > v2) ? -1 : 1; 12823 } 12824 if (r1.system != r2.system) { 12825 return r1.system ? -1 : 1; 12826 } 12827 if (r1.activityInfo != null) { 12828 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12829 } 12830 if (r1.serviceInfo != null) { 12831 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12832 } 12833 if (r1.providerInfo != null) { 12834 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12835 } 12836 return 0; 12837 } 12838 }; 12839 12840 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12841 new Comparator<ProviderInfo>() { 12842 public int compare(ProviderInfo p1, ProviderInfo p2) { 12843 final int v1 = p1.initOrder; 12844 final int v2 = p2.initOrder; 12845 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12846 } 12847 }; 12848 12849 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12850 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12851 final int[] userIds) { 12852 mHandler.post(new Runnable() { 12853 @Override 12854 public void run() { 12855 try { 12856 final IActivityManager am = ActivityManager.getService(); 12857 if (am == null) return; 12858 final int[] resolvedUserIds; 12859 if (userIds == null) { 12860 resolvedUserIds = am.getRunningUserIds(); 12861 } else { 12862 resolvedUserIds = userIds; 12863 } 12864 for (int id : resolvedUserIds) { 12865 final Intent intent = new Intent(action, 12866 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12867 if (extras != null) { 12868 intent.putExtras(extras); 12869 } 12870 if (targetPkg != null) { 12871 intent.setPackage(targetPkg); 12872 } 12873 // Modify the UID when posting to other users 12874 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12875 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12876 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12877 intent.putExtra(Intent.EXTRA_UID, uid); 12878 } 12879 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12880 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12881 if (DEBUG_BROADCASTS) { 12882 RuntimeException here = new RuntimeException("here"); 12883 here.fillInStackTrace(); 12884 Slog.d(TAG, "Sending to user " + id + ": " 12885 + intent.toShortString(false, true, false, false) 12886 + " " + intent.getExtras(), here); 12887 } 12888 am.broadcastIntent(null, intent, null, finishedReceiver, 12889 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12890 null, finishedReceiver != null, false, id); 12891 } 12892 } catch (RemoteException ex) { 12893 } 12894 } 12895 }); 12896 } 12897 12898 /** 12899 * Check if the external storage media is available. This is true if there 12900 * is a mounted external storage medium or if the external storage is 12901 * emulated. 12902 */ 12903 private boolean isExternalMediaAvailable() { 12904 return mMediaMounted || Environment.isExternalStorageEmulated(); 12905 } 12906 12907 @Override 12908 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12909 // writer 12910 synchronized (mPackages) { 12911 if (!isExternalMediaAvailable()) { 12912 // If the external storage is no longer mounted at this point, 12913 // the caller may not have been able to delete all of this 12914 // packages files and can not delete any more. Bail. 12915 return null; 12916 } 12917 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12918 if (lastPackage != null) { 12919 pkgs.remove(lastPackage); 12920 } 12921 if (pkgs.size() > 0) { 12922 return pkgs.get(0); 12923 } 12924 } 12925 return null; 12926 } 12927 12928 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12929 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12930 userId, andCode ? 1 : 0, packageName); 12931 if (mSystemReady) { 12932 msg.sendToTarget(); 12933 } else { 12934 if (mPostSystemReadyMessages == null) { 12935 mPostSystemReadyMessages = new ArrayList<>(); 12936 } 12937 mPostSystemReadyMessages.add(msg); 12938 } 12939 } 12940 12941 void startCleaningPackages() { 12942 // reader 12943 if (!isExternalMediaAvailable()) { 12944 return; 12945 } 12946 synchronized (mPackages) { 12947 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12948 return; 12949 } 12950 } 12951 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12952 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12953 IActivityManager am = ActivityManager.getService(); 12954 if (am != null) { 12955 try { 12956 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12957 UserHandle.USER_SYSTEM); 12958 } catch (RemoteException e) { 12959 } 12960 } 12961 } 12962 12963 @Override 12964 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12965 int installFlags, String installerPackageName, int userId) { 12966 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12967 12968 final int callingUid = Binder.getCallingUid(); 12969 enforceCrossUserPermission(callingUid, userId, 12970 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12971 12972 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12973 try { 12974 if (observer != null) { 12975 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12976 } 12977 } catch (RemoteException re) { 12978 } 12979 return; 12980 } 12981 12982 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12983 installFlags |= PackageManager.INSTALL_FROM_ADB; 12984 12985 } else { 12986 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12987 // about installerPackageName. 12988 12989 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12990 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12991 } 12992 12993 UserHandle user; 12994 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12995 user = UserHandle.ALL; 12996 } else { 12997 user = new UserHandle(userId); 12998 } 12999 13000 // Only system components can circumvent runtime permissions when installing. 13001 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13002 && mContext.checkCallingOrSelfPermission(Manifest.permission 13003 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13004 throw new SecurityException("You need the " 13005 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13006 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13007 } 13008 13009 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13010 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13011 throw new IllegalArgumentException( 13012 "New installs into ASEC containers no longer supported"); 13013 } 13014 13015 final File originFile = new File(originPath); 13016 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13017 13018 final Message msg = mHandler.obtainMessage(INIT_COPY); 13019 final VerificationInfo verificationInfo = new VerificationInfo( 13020 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13021 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13022 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13023 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13024 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13025 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13026 msg.obj = params; 13027 13028 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13029 System.identityHashCode(msg.obj)); 13030 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13031 System.identityHashCode(msg.obj)); 13032 13033 mHandler.sendMessage(msg); 13034 } 13035 13036 13037 /** 13038 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13039 * it is acting on behalf on an enterprise or the user). 13040 * 13041 * Note that the ordering of the conditionals in this method is important. The checks we perform 13042 * are as follows, in this order: 13043 * 13044 * 1) If the install is being performed by a system app, we can trust the app to have set the 13045 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13046 * what it is. 13047 * 2) If the install is being performed by a device or profile owner app, the install reason 13048 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13049 * set the install reason correctly. If the app targets an older SDK version where install 13050 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13051 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13052 * 3) In all other cases, the install is being performed by a regular app that is neither part 13053 * of the system nor a device or profile owner. We have no reason to believe that this app is 13054 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13055 * set to enterprise policy and if so, change it to unknown instead. 13056 */ 13057 private int fixUpInstallReason(String installerPackageName, int installerUid, 13058 int installReason) { 13059 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13060 == PERMISSION_GRANTED) { 13061 // If the install is being performed by a system app, we trust that app to have set the 13062 // install reason correctly. 13063 return installReason; 13064 } 13065 13066 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13067 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13068 if (dpm != null) { 13069 ComponentName owner = null; 13070 try { 13071 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13072 if (owner == null) { 13073 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13074 } 13075 } catch (RemoteException e) { 13076 } 13077 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13078 // If the install is being performed by a device or profile owner, the install 13079 // reason should be enterprise policy. 13080 return PackageManager.INSTALL_REASON_POLICY; 13081 } 13082 } 13083 13084 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13085 // If the install is being performed by a regular app (i.e. neither system app nor 13086 // device or profile owner), we have no reason to believe that the app is acting on 13087 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13088 // change it to unknown instead. 13089 return PackageManager.INSTALL_REASON_UNKNOWN; 13090 } 13091 13092 // If the install is being performed by a regular app and the install reason was set to any 13093 // value but enterprise policy, leave the install reason unchanged. 13094 return installReason; 13095 } 13096 13097 void installStage(String packageName, File stagedDir, String stagedCid, 13098 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13099 String installerPackageName, int installerUid, UserHandle user, 13100 Certificate[][] certificates) { 13101 if (DEBUG_EPHEMERAL) { 13102 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13103 Slog.d(TAG, "Ephemeral install of " + packageName); 13104 } 13105 } 13106 final VerificationInfo verificationInfo = new VerificationInfo( 13107 sessionParams.originatingUri, sessionParams.referrerUri, 13108 sessionParams.originatingUid, installerUid); 13109 13110 final OriginInfo origin; 13111 if (stagedDir != null) { 13112 origin = OriginInfo.fromStagedFile(stagedDir); 13113 } else { 13114 origin = OriginInfo.fromStagedContainer(stagedCid); 13115 } 13116 13117 final Message msg = mHandler.obtainMessage(INIT_COPY); 13118 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13119 sessionParams.installReason); 13120 final InstallParams params = new InstallParams(origin, null, observer, 13121 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13122 verificationInfo, user, sessionParams.abiOverride, 13123 sessionParams.grantedRuntimePermissions, certificates, installReason); 13124 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13125 msg.obj = params; 13126 13127 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13128 System.identityHashCode(msg.obj)); 13129 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13130 System.identityHashCode(msg.obj)); 13131 13132 mHandler.sendMessage(msg); 13133 } 13134 13135 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13136 int userId) { 13137 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13138 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13139 } 13140 13141 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13142 int appId, int... userIds) { 13143 if (ArrayUtils.isEmpty(userIds)) { 13144 return; 13145 } 13146 Bundle extras = new Bundle(1); 13147 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13148 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13149 13150 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13151 packageName, extras, 0, null, null, userIds); 13152 if (isSystem) { 13153 mHandler.post(() -> { 13154 for (int userId : userIds) { 13155 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13156 } 13157 } 13158 ); 13159 } 13160 } 13161 13162 /** 13163 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13164 * automatically without needing an explicit launch. 13165 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13166 */ 13167 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13168 // If user is not running, the app didn't miss any broadcast 13169 if (!mUserManagerInternal.isUserRunning(userId)) { 13170 return; 13171 } 13172 final IActivityManager am = ActivityManager.getService(); 13173 try { 13174 // Deliver LOCKED_BOOT_COMPLETED first 13175 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13176 .setPackage(packageName); 13177 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13178 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13179 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13180 13181 // Deliver BOOT_COMPLETED only if user is unlocked 13182 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13183 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13184 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13185 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13186 } 13187 } catch (RemoteException e) { 13188 throw e.rethrowFromSystemServer(); 13189 } 13190 } 13191 13192 @Override 13193 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13194 int userId) { 13195 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13196 PackageSetting pkgSetting; 13197 final int uid = Binder.getCallingUid(); 13198 enforceCrossUserPermission(uid, userId, 13199 true /* requireFullPermission */, true /* checkShell */, 13200 "setApplicationHiddenSetting for user " + userId); 13201 13202 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13203 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13204 return false; 13205 } 13206 13207 long callingId = Binder.clearCallingIdentity(); 13208 try { 13209 boolean sendAdded = false; 13210 boolean sendRemoved = false; 13211 // writer 13212 synchronized (mPackages) { 13213 pkgSetting = mSettings.mPackages.get(packageName); 13214 if (pkgSetting == null) { 13215 return false; 13216 } 13217 // Do not allow "android" is being disabled 13218 if ("android".equals(packageName)) { 13219 Slog.w(TAG, "Cannot hide package: android"); 13220 return false; 13221 } 13222 // Cannot hide static shared libs as they are considered 13223 // a part of the using app (emulating static linking). Also 13224 // static libs are installed always on internal storage. 13225 PackageParser.Package pkg = mPackages.get(packageName); 13226 if (pkg != null && pkg.staticSharedLibName != null) { 13227 Slog.w(TAG, "Cannot hide package: " + packageName 13228 + " providing static shared library: " 13229 + pkg.staticSharedLibName); 13230 return false; 13231 } 13232 // Only allow protected packages to hide themselves. 13233 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13234 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13235 Slog.w(TAG, "Not hiding protected package: " + packageName); 13236 return false; 13237 } 13238 13239 if (pkgSetting.getHidden(userId) != hidden) { 13240 pkgSetting.setHidden(hidden, userId); 13241 mSettings.writePackageRestrictionsLPr(userId); 13242 if (hidden) { 13243 sendRemoved = true; 13244 } else { 13245 sendAdded = true; 13246 } 13247 } 13248 } 13249 if (sendAdded) { 13250 sendPackageAddedForUser(packageName, pkgSetting, userId); 13251 return true; 13252 } 13253 if (sendRemoved) { 13254 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13255 "hiding pkg"); 13256 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13257 return true; 13258 } 13259 } finally { 13260 Binder.restoreCallingIdentity(callingId); 13261 } 13262 return false; 13263 } 13264 13265 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13266 int userId) { 13267 final PackageRemovedInfo info = new PackageRemovedInfo(); 13268 info.removedPackage = packageName; 13269 info.removedUsers = new int[] {userId}; 13270 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13271 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13272 } 13273 13274 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13275 if (pkgList.length > 0) { 13276 Bundle extras = new Bundle(1); 13277 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13278 13279 sendPackageBroadcast( 13280 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13281 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13282 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13283 new int[] {userId}); 13284 } 13285 } 13286 13287 /** 13288 * Returns true if application is not found or there was an error. Otherwise it returns 13289 * the hidden state of the package for the given user. 13290 */ 13291 @Override 13292 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13295 true /* requireFullPermission */, false /* checkShell */, 13296 "getApplicationHidden for user " + userId); 13297 PackageSetting pkgSetting; 13298 long callingId = Binder.clearCallingIdentity(); 13299 try { 13300 // writer 13301 synchronized (mPackages) { 13302 pkgSetting = mSettings.mPackages.get(packageName); 13303 if (pkgSetting == null) { 13304 return true; 13305 } 13306 return pkgSetting.getHidden(userId); 13307 } 13308 } finally { 13309 Binder.restoreCallingIdentity(callingId); 13310 } 13311 } 13312 13313 /** 13314 * @hide 13315 */ 13316 @Override 13317 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13318 int installReason) { 13319 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13320 null); 13321 PackageSetting pkgSetting; 13322 final int uid = Binder.getCallingUid(); 13323 enforceCrossUserPermission(uid, userId, 13324 true /* requireFullPermission */, true /* checkShell */, 13325 "installExistingPackage for user " + userId); 13326 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13327 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13328 } 13329 13330 long callingId = Binder.clearCallingIdentity(); 13331 try { 13332 boolean installed = false; 13333 final boolean instantApp = 13334 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13335 final boolean fullApp = 13336 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13337 13338 // writer 13339 synchronized (mPackages) { 13340 pkgSetting = mSettings.mPackages.get(packageName); 13341 if (pkgSetting == null) { 13342 return PackageManager.INSTALL_FAILED_INVALID_URI; 13343 } 13344 if (!pkgSetting.getInstalled(userId)) { 13345 pkgSetting.setInstalled(true, userId); 13346 pkgSetting.setHidden(false, userId); 13347 pkgSetting.setInstallReason(installReason, userId); 13348 mSettings.writePackageRestrictionsLPr(userId); 13349 mSettings.writeKernelMappingLPr(pkgSetting); 13350 installed = true; 13351 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13352 // upgrade app from instant to full; we don't allow app downgrade 13353 installed = true; 13354 } 13355 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13356 } 13357 13358 if (installed) { 13359 if (pkgSetting.pkg != null) { 13360 synchronized (mInstallLock) { 13361 // We don't need to freeze for a brand new install 13362 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13363 } 13364 } 13365 sendPackageAddedForUser(packageName, pkgSetting, userId); 13366 synchronized (mPackages) { 13367 updateSequenceNumberLP(packageName, new int[]{ userId }); 13368 } 13369 } 13370 } finally { 13371 Binder.restoreCallingIdentity(callingId); 13372 } 13373 13374 return PackageManager.INSTALL_SUCCEEDED; 13375 } 13376 13377 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13378 boolean instantApp, boolean fullApp) { 13379 // no state specified; do nothing 13380 if (!instantApp && !fullApp) { 13381 return; 13382 } 13383 if (userId != UserHandle.USER_ALL) { 13384 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13385 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13386 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13387 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13388 } 13389 } else { 13390 for (int currentUserId : sUserManager.getUserIds()) { 13391 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13392 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13393 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13394 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13395 } 13396 } 13397 } 13398 } 13399 13400 boolean isUserRestricted(int userId, String restrictionKey) { 13401 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13402 if (restrictions.getBoolean(restrictionKey, false)) { 13403 Log.w(TAG, "User is restricted: " + restrictionKey); 13404 return true; 13405 } 13406 return false; 13407 } 13408 13409 @Override 13410 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13411 int userId) { 13412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13414 true /* requireFullPermission */, true /* checkShell */, 13415 "setPackagesSuspended for user " + userId); 13416 13417 if (ArrayUtils.isEmpty(packageNames)) { 13418 return packageNames; 13419 } 13420 13421 // List of package names for whom the suspended state has changed. 13422 List<String> changedPackages = new ArrayList<>(packageNames.length); 13423 // List of package names for whom the suspended state is not set as requested in this 13424 // method. 13425 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13426 long callingId = Binder.clearCallingIdentity(); 13427 try { 13428 for (int i = 0; i < packageNames.length; i++) { 13429 String packageName = packageNames[i]; 13430 boolean changed = false; 13431 final int appId; 13432 synchronized (mPackages) { 13433 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13434 if (pkgSetting == null) { 13435 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13436 + "\". Skipping suspending/un-suspending."); 13437 unactionedPackages.add(packageName); 13438 continue; 13439 } 13440 appId = pkgSetting.appId; 13441 if (pkgSetting.getSuspended(userId) != suspended) { 13442 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13443 unactionedPackages.add(packageName); 13444 continue; 13445 } 13446 pkgSetting.setSuspended(suspended, userId); 13447 mSettings.writePackageRestrictionsLPr(userId); 13448 changed = true; 13449 changedPackages.add(packageName); 13450 } 13451 } 13452 13453 if (changed && suspended) { 13454 killApplication(packageName, UserHandle.getUid(userId, appId), 13455 "suspending package"); 13456 } 13457 } 13458 } finally { 13459 Binder.restoreCallingIdentity(callingId); 13460 } 13461 13462 if (!changedPackages.isEmpty()) { 13463 sendPackagesSuspendedForUser(changedPackages.toArray( 13464 new String[changedPackages.size()]), userId, suspended); 13465 } 13466 13467 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13468 } 13469 13470 @Override 13471 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13473 true /* requireFullPermission */, false /* checkShell */, 13474 "isPackageSuspendedForUser for user " + userId); 13475 synchronized (mPackages) { 13476 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13477 if (pkgSetting == null) { 13478 throw new IllegalArgumentException("Unknown target package: " + packageName); 13479 } 13480 return pkgSetting.getSuspended(userId); 13481 } 13482 } 13483 13484 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13485 if (isPackageDeviceAdmin(packageName, userId)) { 13486 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13487 + "\": has an active device admin"); 13488 return false; 13489 } 13490 13491 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13492 if (packageName.equals(activeLauncherPackageName)) { 13493 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13494 + "\": contains the active launcher"); 13495 return false; 13496 } 13497 13498 if (packageName.equals(mRequiredInstallerPackage)) { 13499 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13500 + "\": required for package installation"); 13501 return false; 13502 } 13503 13504 if (packageName.equals(mRequiredUninstallerPackage)) { 13505 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13506 + "\": required for package uninstallation"); 13507 return false; 13508 } 13509 13510 if (packageName.equals(mRequiredVerifierPackage)) { 13511 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13512 + "\": required for package verification"); 13513 return false; 13514 } 13515 13516 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13517 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13518 + "\": is the default dialer"); 13519 return false; 13520 } 13521 13522 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13523 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13524 + "\": protected package"); 13525 return false; 13526 } 13527 13528 // Cannot suspend static shared libs as they are considered 13529 // a part of the using app (emulating static linking). Also 13530 // static libs are installed always on internal storage. 13531 PackageParser.Package pkg = mPackages.get(packageName); 13532 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13533 Slog.w(TAG, "Cannot suspend package: " + packageName 13534 + " providing static shared library: " 13535 + pkg.staticSharedLibName); 13536 return false; 13537 } 13538 13539 return true; 13540 } 13541 13542 private String getActiveLauncherPackageName(int userId) { 13543 Intent intent = new Intent(Intent.ACTION_MAIN); 13544 intent.addCategory(Intent.CATEGORY_HOME); 13545 ResolveInfo resolveInfo = resolveIntent( 13546 intent, 13547 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13548 PackageManager.MATCH_DEFAULT_ONLY, 13549 userId); 13550 13551 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13552 } 13553 13554 private String getDefaultDialerPackageName(int userId) { 13555 synchronized (mPackages) { 13556 return mSettings.getDefaultDialerPackageNameLPw(userId); 13557 } 13558 } 13559 13560 @Override 13561 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13562 mContext.enforceCallingOrSelfPermission( 13563 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13564 "Only package verification agents can verify applications"); 13565 13566 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13567 final PackageVerificationResponse response = new PackageVerificationResponse( 13568 verificationCode, Binder.getCallingUid()); 13569 msg.arg1 = id; 13570 msg.obj = response; 13571 mHandler.sendMessage(msg); 13572 } 13573 13574 @Override 13575 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13576 long millisecondsToDelay) { 13577 mContext.enforceCallingOrSelfPermission( 13578 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13579 "Only package verification agents can extend verification timeouts"); 13580 13581 final PackageVerificationState state = mPendingVerification.get(id); 13582 final PackageVerificationResponse response = new PackageVerificationResponse( 13583 verificationCodeAtTimeout, Binder.getCallingUid()); 13584 13585 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13586 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13587 } 13588 if (millisecondsToDelay < 0) { 13589 millisecondsToDelay = 0; 13590 } 13591 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13592 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13593 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13594 } 13595 13596 if ((state != null) && !state.timeoutExtended()) { 13597 state.extendTimeout(); 13598 13599 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13600 msg.arg1 = id; 13601 msg.obj = response; 13602 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13603 } 13604 } 13605 13606 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13607 int verificationCode, UserHandle user) { 13608 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13609 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13610 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13611 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13612 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13613 13614 mContext.sendBroadcastAsUser(intent, user, 13615 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13616 } 13617 13618 private ComponentName matchComponentForVerifier(String packageName, 13619 List<ResolveInfo> receivers) { 13620 ActivityInfo targetReceiver = null; 13621 13622 final int NR = receivers.size(); 13623 for (int i = 0; i < NR; i++) { 13624 final ResolveInfo info = receivers.get(i); 13625 if (info.activityInfo == null) { 13626 continue; 13627 } 13628 13629 if (packageName.equals(info.activityInfo.packageName)) { 13630 targetReceiver = info.activityInfo; 13631 break; 13632 } 13633 } 13634 13635 if (targetReceiver == null) { 13636 return null; 13637 } 13638 13639 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13640 } 13641 13642 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13643 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13644 if (pkgInfo.verifiers.length == 0) { 13645 return null; 13646 } 13647 13648 final int N = pkgInfo.verifiers.length; 13649 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13650 for (int i = 0; i < N; i++) { 13651 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13652 13653 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13654 receivers); 13655 if (comp == null) { 13656 continue; 13657 } 13658 13659 final int verifierUid = getUidForVerifier(verifierInfo); 13660 if (verifierUid == -1) { 13661 continue; 13662 } 13663 13664 if (DEBUG_VERIFY) { 13665 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13666 + " with the correct signature"); 13667 } 13668 sufficientVerifiers.add(comp); 13669 verificationState.addSufficientVerifier(verifierUid); 13670 } 13671 13672 return sufficientVerifiers; 13673 } 13674 13675 private int getUidForVerifier(VerifierInfo verifierInfo) { 13676 synchronized (mPackages) { 13677 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13678 if (pkg == null) { 13679 return -1; 13680 } else if (pkg.mSignatures.length != 1) { 13681 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13682 + " has more than one signature; ignoring"); 13683 return -1; 13684 } 13685 13686 /* 13687 * If the public key of the package's signature does not match 13688 * our expected public key, then this is a different package and 13689 * we should skip. 13690 */ 13691 13692 final byte[] expectedPublicKey; 13693 try { 13694 final Signature verifierSig = pkg.mSignatures[0]; 13695 final PublicKey publicKey = verifierSig.getPublicKey(); 13696 expectedPublicKey = publicKey.getEncoded(); 13697 } catch (CertificateException e) { 13698 return -1; 13699 } 13700 13701 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13702 13703 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13704 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13705 + " does not have the expected public key; ignoring"); 13706 return -1; 13707 } 13708 13709 return pkg.applicationInfo.uid; 13710 } 13711 } 13712 13713 @Override 13714 public void finishPackageInstall(int token, boolean didLaunch) { 13715 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13716 13717 if (DEBUG_INSTALL) { 13718 Slog.v(TAG, "BM finishing package install for " + token); 13719 } 13720 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13721 13722 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13723 mHandler.sendMessage(msg); 13724 } 13725 13726 /** 13727 * Get the verification agent timeout. 13728 * 13729 * @return verification timeout in milliseconds 13730 */ 13731 private long getVerificationTimeout() { 13732 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13733 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13734 DEFAULT_VERIFICATION_TIMEOUT); 13735 } 13736 13737 /** 13738 * Get the default verification agent response code. 13739 * 13740 * @return default verification response code 13741 */ 13742 private int getDefaultVerificationResponse() { 13743 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13744 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13745 DEFAULT_VERIFICATION_RESPONSE); 13746 } 13747 13748 /** 13749 * Check whether or not package verification has been enabled. 13750 * 13751 * @return true if verification should be performed 13752 */ 13753 private boolean isVerificationEnabled(int userId, int installFlags) { 13754 if (!DEFAULT_VERIFY_ENABLE) { 13755 return false; 13756 } 13757 13758 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13759 13760 // Check if installing from ADB 13761 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13762 // Do not run verification in a test harness environment 13763 if (ActivityManager.isRunningInTestHarness()) { 13764 return false; 13765 } 13766 if (ensureVerifyAppsEnabled) { 13767 return true; 13768 } 13769 // Check if the developer does not want package verification for ADB installs 13770 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13771 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13772 return false; 13773 } 13774 } 13775 13776 if (ensureVerifyAppsEnabled) { 13777 return true; 13778 } 13779 13780 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13781 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13782 } 13783 13784 @Override 13785 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13786 throws RemoteException { 13787 mContext.enforceCallingOrSelfPermission( 13788 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13789 "Only intentfilter verification agents can verify applications"); 13790 13791 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13792 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13793 Binder.getCallingUid(), verificationCode, failedDomains); 13794 msg.arg1 = id; 13795 msg.obj = response; 13796 mHandler.sendMessage(msg); 13797 } 13798 13799 @Override 13800 public int getIntentVerificationStatus(String packageName, int userId) { 13801 synchronized (mPackages) { 13802 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13803 } 13804 } 13805 13806 @Override 13807 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13808 mContext.enforceCallingOrSelfPermission( 13809 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13810 13811 boolean result = false; 13812 synchronized (mPackages) { 13813 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13814 } 13815 if (result) { 13816 scheduleWritePackageRestrictionsLocked(userId); 13817 } 13818 return result; 13819 } 13820 13821 @Override 13822 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13823 String packageName) { 13824 synchronized (mPackages) { 13825 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13826 } 13827 } 13828 13829 @Override 13830 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13831 if (TextUtils.isEmpty(packageName)) { 13832 return ParceledListSlice.emptyList(); 13833 } 13834 synchronized (mPackages) { 13835 PackageParser.Package pkg = mPackages.get(packageName); 13836 if (pkg == null || pkg.activities == null) { 13837 return ParceledListSlice.emptyList(); 13838 } 13839 final int count = pkg.activities.size(); 13840 ArrayList<IntentFilter> result = new ArrayList<>(); 13841 for (int n=0; n<count; n++) { 13842 PackageParser.Activity activity = pkg.activities.get(n); 13843 if (activity.intents != null && activity.intents.size() > 0) { 13844 result.addAll(activity.intents); 13845 } 13846 } 13847 return new ParceledListSlice<>(result); 13848 } 13849 } 13850 13851 @Override 13852 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13853 mContext.enforceCallingOrSelfPermission( 13854 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13855 13856 synchronized (mPackages) { 13857 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13858 if (packageName != null) { 13859 result |= updateIntentVerificationStatus(packageName, 13860 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13861 userId); 13862 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13863 packageName, userId); 13864 } 13865 return result; 13866 } 13867 } 13868 13869 @Override 13870 public String getDefaultBrowserPackageName(int userId) { 13871 synchronized (mPackages) { 13872 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13873 } 13874 } 13875 13876 /** 13877 * Get the "allow unknown sources" setting. 13878 * 13879 * @return the current "allow unknown sources" setting 13880 */ 13881 private int getUnknownSourcesSettings() { 13882 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13883 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13884 -1); 13885 } 13886 13887 @Override 13888 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13889 final int uid = Binder.getCallingUid(); 13890 // writer 13891 synchronized (mPackages) { 13892 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13893 if (targetPackageSetting == null) { 13894 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13895 } 13896 13897 PackageSetting installerPackageSetting; 13898 if (installerPackageName != null) { 13899 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13900 if (installerPackageSetting == null) { 13901 throw new IllegalArgumentException("Unknown installer package: " 13902 + installerPackageName); 13903 } 13904 } else { 13905 installerPackageSetting = null; 13906 } 13907 13908 Signature[] callerSignature; 13909 Object obj = mSettings.getUserIdLPr(uid); 13910 if (obj != null) { 13911 if (obj instanceof SharedUserSetting) { 13912 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13913 } else if (obj instanceof PackageSetting) { 13914 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13915 } else { 13916 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13917 } 13918 } else { 13919 throw new SecurityException("Unknown calling UID: " + uid); 13920 } 13921 13922 // Verify: can't set installerPackageName to a package that is 13923 // not signed with the same cert as the caller. 13924 if (installerPackageSetting != null) { 13925 if (compareSignatures(callerSignature, 13926 installerPackageSetting.signatures.mSignatures) 13927 != PackageManager.SIGNATURE_MATCH) { 13928 throw new SecurityException( 13929 "Caller does not have same cert as new installer package " 13930 + installerPackageName); 13931 } 13932 } 13933 13934 // Verify: if target already has an installer package, it must 13935 // be signed with the same cert as the caller. 13936 if (targetPackageSetting.installerPackageName != null) { 13937 PackageSetting setting = mSettings.mPackages.get( 13938 targetPackageSetting.installerPackageName); 13939 // If the currently set package isn't valid, then it's always 13940 // okay to change it. 13941 if (setting != null) { 13942 if (compareSignatures(callerSignature, 13943 setting.signatures.mSignatures) 13944 != PackageManager.SIGNATURE_MATCH) { 13945 throw new SecurityException( 13946 "Caller does not have same cert as old installer package " 13947 + targetPackageSetting.installerPackageName); 13948 } 13949 } 13950 } 13951 13952 // Okay! 13953 targetPackageSetting.installerPackageName = installerPackageName; 13954 if (installerPackageName != null) { 13955 mSettings.mInstallerPackages.add(installerPackageName); 13956 } 13957 scheduleWriteSettingsLocked(); 13958 } 13959 } 13960 13961 @Override 13962 public void setApplicationCategoryHint(String packageName, int categoryHint, 13963 String callerPackageName) { 13964 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13965 callerPackageName); 13966 synchronized (mPackages) { 13967 PackageSetting ps = mSettings.mPackages.get(packageName); 13968 if (ps == null) { 13969 throw new IllegalArgumentException("Unknown target package " + packageName); 13970 } 13971 13972 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13973 throw new IllegalArgumentException("Calling package " + callerPackageName 13974 + " is not installer for " + packageName); 13975 } 13976 13977 if (ps.categoryHint != categoryHint) { 13978 ps.categoryHint = categoryHint; 13979 scheduleWriteSettingsLocked(); 13980 } 13981 } 13982 } 13983 13984 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13985 // Queue up an async operation since the package installation may take a little while. 13986 mHandler.post(new Runnable() { 13987 public void run() { 13988 mHandler.removeCallbacks(this); 13989 // Result object to be returned 13990 PackageInstalledInfo res = new PackageInstalledInfo(); 13991 res.setReturnCode(currentStatus); 13992 res.uid = -1; 13993 res.pkg = null; 13994 res.removedInfo = null; 13995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13996 args.doPreInstall(res.returnCode); 13997 synchronized (mInstallLock) { 13998 installPackageTracedLI(args, res); 13999 } 14000 args.doPostInstall(res.returnCode, res.uid); 14001 } 14002 14003 // A restore should be performed at this point if (a) the install 14004 // succeeded, (b) the operation is not an update, and (c) the new 14005 // package has not opted out of backup participation. 14006 final boolean update = res.removedInfo != null 14007 && res.removedInfo.removedPackage != null; 14008 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14009 boolean doRestore = !update 14010 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14011 14012 // Set up the post-install work request bookkeeping. This will be used 14013 // and cleaned up by the post-install event handling regardless of whether 14014 // there's a restore pass performed. Token values are >= 1. 14015 int token; 14016 if (mNextInstallToken < 0) mNextInstallToken = 1; 14017 token = mNextInstallToken++; 14018 14019 PostInstallData data = new PostInstallData(args, res); 14020 mRunningInstalls.put(token, data); 14021 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14022 14023 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14024 // Pass responsibility to the Backup Manager. It will perform a 14025 // restore if appropriate, then pass responsibility back to the 14026 // Package Manager to run the post-install observer callbacks 14027 // and broadcasts. 14028 IBackupManager bm = IBackupManager.Stub.asInterface( 14029 ServiceManager.getService(Context.BACKUP_SERVICE)); 14030 if (bm != null) { 14031 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14032 + " to BM for possible restore"); 14033 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14034 try { 14035 // TODO: http://b/22388012 14036 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14037 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14038 } else { 14039 doRestore = false; 14040 } 14041 } catch (RemoteException e) { 14042 // can't happen; the backup manager is local 14043 } catch (Exception e) { 14044 Slog.e(TAG, "Exception trying to enqueue restore", e); 14045 doRestore = false; 14046 } 14047 } else { 14048 Slog.e(TAG, "Backup Manager not found!"); 14049 doRestore = false; 14050 } 14051 } 14052 14053 if (!doRestore) { 14054 // No restore possible, or the Backup Manager was mysteriously not 14055 // available -- just fire the post-install work request directly. 14056 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14057 14058 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14059 14060 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14061 mHandler.sendMessage(msg); 14062 } 14063 } 14064 }); 14065 } 14066 14067 /** 14068 * Callback from PackageSettings whenever an app is first transitioned out of the 14069 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14070 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14071 * here whether the app is the target of an ongoing install, and only send the 14072 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14073 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14074 * handling. 14075 */ 14076 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14077 // Serialize this with the rest of the install-process message chain. In the 14078 // restore-at-install case, this Runnable will necessarily run before the 14079 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14080 // are coherent. In the non-restore case, the app has already completed install 14081 // and been launched through some other means, so it is not in a problematic 14082 // state for observers to see the FIRST_LAUNCH signal. 14083 mHandler.post(new Runnable() { 14084 @Override 14085 public void run() { 14086 for (int i = 0; i < mRunningInstalls.size(); i++) { 14087 final PostInstallData data = mRunningInstalls.valueAt(i); 14088 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14089 continue; 14090 } 14091 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14092 // right package; but is it for the right user? 14093 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14094 if (userId == data.res.newUsers[uIndex]) { 14095 if (DEBUG_BACKUP) { 14096 Slog.i(TAG, "Package " + pkgName 14097 + " being restored so deferring FIRST_LAUNCH"); 14098 } 14099 return; 14100 } 14101 } 14102 } 14103 } 14104 // didn't find it, so not being restored 14105 if (DEBUG_BACKUP) { 14106 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14107 } 14108 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14109 } 14110 }); 14111 } 14112 14113 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14114 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14115 installerPkg, null, userIds); 14116 } 14117 14118 private abstract class HandlerParams { 14119 private static final int MAX_RETRIES = 4; 14120 14121 /** 14122 * Number of times startCopy() has been attempted and had a non-fatal 14123 * error. 14124 */ 14125 private int mRetries = 0; 14126 14127 /** User handle for the user requesting the information or installation. */ 14128 private final UserHandle mUser; 14129 String traceMethod; 14130 int traceCookie; 14131 14132 HandlerParams(UserHandle user) { 14133 mUser = user; 14134 } 14135 14136 UserHandle getUser() { 14137 return mUser; 14138 } 14139 14140 HandlerParams setTraceMethod(String traceMethod) { 14141 this.traceMethod = traceMethod; 14142 return this; 14143 } 14144 14145 HandlerParams setTraceCookie(int traceCookie) { 14146 this.traceCookie = traceCookie; 14147 return this; 14148 } 14149 14150 final boolean startCopy() { 14151 boolean res; 14152 try { 14153 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14154 14155 if (++mRetries > MAX_RETRIES) { 14156 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14157 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14158 handleServiceError(); 14159 return false; 14160 } else { 14161 handleStartCopy(); 14162 res = true; 14163 } 14164 } catch (RemoteException e) { 14165 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14166 mHandler.sendEmptyMessage(MCS_RECONNECT); 14167 res = false; 14168 } 14169 handleReturnCode(); 14170 return res; 14171 } 14172 14173 final void serviceError() { 14174 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14175 handleServiceError(); 14176 handleReturnCode(); 14177 } 14178 14179 abstract void handleStartCopy() throws RemoteException; 14180 abstract void handleServiceError(); 14181 abstract void handleReturnCode(); 14182 } 14183 14184 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14185 for (File path : paths) { 14186 try { 14187 mcs.clearDirectory(path.getAbsolutePath()); 14188 } catch (RemoteException e) { 14189 } 14190 } 14191 } 14192 14193 static class OriginInfo { 14194 /** 14195 * Location where install is coming from, before it has been 14196 * copied/renamed into place. This could be a single monolithic APK 14197 * file, or a cluster directory. This location may be untrusted. 14198 */ 14199 final File file; 14200 final String cid; 14201 14202 /** 14203 * Flag indicating that {@link #file} or {@link #cid} has already been 14204 * staged, meaning downstream users don't need to defensively copy the 14205 * contents. 14206 */ 14207 final boolean staged; 14208 14209 /** 14210 * Flag indicating that {@link #file} or {@link #cid} is an already 14211 * installed app that is being moved. 14212 */ 14213 final boolean existing; 14214 14215 final String resolvedPath; 14216 final File resolvedFile; 14217 14218 static OriginInfo fromNothing() { 14219 return new OriginInfo(null, null, false, false); 14220 } 14221 14222 static OriginInfo fromUntrustedFile(File file) { 14223 return new OriginInfo(file, null, false, false); 14224 } 14225 14226 static OriginInfo fromExistingFile(File file) { 14227 return new OriginInfo(file, null, false, true); 14228 } 14229 14230 static OriginInfo fromStagedFile(File file) { 14231 return new OriginInfo(file, null, true, false); 14232 } 14233 14234 static OriginInfo fromStagedContainer(String cid) { 14235 return new OriginInfo(null, cid, true, false); 14236 } 14237 14238 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14239 this.file = file; 14240 this.cid = cid; 14241 this.staged = staged; 14242 this.existing = existing; 14243 14244 if (cid != null) { 14245 resolvedPath = PackageHelper.getSdDir(cid); 14246 resolvedFile = new File(resolvedPath); 14247 } else if (file != null) { 14248 resolvedPath = file.getAbsolutePath(); 14249 resolvedFile = file; 14250 } else { 14251 resolvedPath = null; 14252 resolvedFile = null; 14253 } 14254 } 14255 } 14256 14257 static class MoveInfo { 14258 final int moveId; 14259 final String fromUuid; 14260 final String toUuid; 14261 final String packageName; 14262 final String dataAppName; 14263 final int appId; 14264 final String seinfo; 14265 final int targetSdkVersion; 14266 14267 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14268 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14269 this.moveId = moveId; 14270 this.fromUuid = fromUuid; 14271 this.toUuid = toUuid; 14272 this.packageName = packageName; 14273 this.dataAppName = dataAppName; 14274 this.appId = appId; 14275 this.seinfo = seinfo; 14276 this.targetSdkVersion = targetSdkVersion; 14277 } 14278 } 14279 14280 static class VerificationInfo { 14281 /** A constant used to indicate that a uid value is not present. */ 14282 public static final int NO_UID = -1; 14283 14284 /** URI referencing where the package was downloaded from. */ 14285 final Uri originatingUri; 14286 14287 /** HTTP referrer URI associated with the originatingURI. */ 14288 final Uri referrer; 14289 14290 /** UID of the application that the install request originated from. */ 14291 final int originatingUid; 14292 14293 /** UID of application requesting the install */ 14294 final int installerUid; 14295 14296 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14297 this.originatingUri = originatingUri; 14298 this.referrer = referrer; 14299 this.originatingUid = originatingUid; 14300 this.installerUid = installerUid; 14301 } 14302 } 14303 14304 class InstallParams extends HandlerParams { 14305 final OriginInfo origin; 14306 final MoveInfo move; 14307 final IPackageInstallObserver2 observer; 14308 int installFlags; 14309 final String installerPackageName; 14310 final String volumeUuid; 14311 private InstallArgs mArgs; 14312 private int mRet; 14313 final String packageAbiOverride; 14314 final String[] grantedRuntimePermissions; 14315 final VerificationInfo verificationInfo; 14316 final Certificate[][] certificates; 14317 final int installReason; 14318 14319 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14320 int installFlags, String installerPackageName, String volumeUuid, 14321 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14322 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14323 super(user); 14324 this.origin = origin; 14325 this.move = move; 14326 this.observer = observer; 14327 this.installFlags = installFlags; 14328 this.installerPackageName = installerPackageName; 14329 this.volumeUuid = volumeUuid; 14330 this.verificationInfo = verificationInfo; 14331 this.packageAbiOverride = packageAbiOverride; 14332 this.grantedRuntimePermissions = grantedPermissions; 14333 this.certificates = certificates; 14334 this.installReason = installReason; 14335 } 14336 14337 @Override 14338 public String toString() { 14339 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14340 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14341 } 14342 14343 private int installLocationPolicy(PackageInfoLite pkgLite) { 14344 String packageName = pkgLite.packageName; 14345 int installLocation = pkgLite.installLocation; 14346 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14347 // reader 14348 synchronized (mPackages) { 14349 // Currently installed package which the new package is attempting to replace or 14350 // null if no such package is installed. 14351 PackageParser.Package installedPkg = mPackages.get(packageName); 14352 // Package which currently owns the data which the new package will own if installed. 14353 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14354 // will be null whereas dataOwnerPkg will contain information about the package 14355 // which was uninstalled while keeping its data. 14356 PackageParser.Package dataOwnerPkg = installedPkg; 14357 if (dataOwnerPkg == null) { 14358 PackageSetting ps = mSettings.mPackages.get(packageName); 14359 if (ps != null) { 14360 dataOwnerPkg = ps.pkg; 14361 } 14362 } 14363 14364 if (dataOwnerPkg != null) { 14365 // If installed, the package will get access to data left on the device by its 14366 // predecessor. As a security measure, this is permited only if this is not a 14367 // version downgrade or if the predecessor package is marked as debuggable and 14368 // a downgrade is explicitly requested. 14369 // 14370 // On debuggable platform builds, downgrades are permitted even for 14371 // non-debuggable packages to make testing easier. Debuggable platform builds do 14372 // not offer security guarantees and thus it's OK to disable some security 14373 // mechanisms to make debugging/testing easier on those builds. However, even on 14374 // debuggable builds downgrades of packages are permitted only if requested via 14375 // installFlags. This is because we aim to keep the behavior of debuggable 14376 // platform builds as close as possible to the behavior of non-debuggable 14377 // platform builds. 14378 final boolean downgradeRequested = 14379 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14380 final boolean packageDebuggable = 14381 (dataOwnerPkg.applicationInfo.flags 14382 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14383 final boolean downgradePermitted = 14384 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14385 if (!downgradePermitted) { 14386 try { 14387 checkDowngrade(dataOwnerPkg, pkgLite); 14388 } catch (PackageManagerException e) { 14389 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14390 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14391 } 14392 } 14393 } 14394 14395 if (installedPkg != null) { 14396 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14397 // Check for updated system application. 14398 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14399 if (onSd) { 14400 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14401 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14402 } 14403 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14404 } else { 14405 if (onSd) { 14406 // Install flag overrides everything. 14407 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14408 } 14409 // If current upgrade specifies particular preference 14410 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14411 // Application explicitly specified internal. 14412 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14413 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14414 // App explictly prefers external. Let policy decide 14415 } else { 14416 // Prefer previous location 14417 if (isExternal(installedPkg)) { 14418 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14419 } 14420 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14421 } 14422 } 14423 } else { 14424 // Invalid install. Return error code 14425 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14426 } 14427 } 14428 } 14429 // All the special cases have been taken care of. 14430 // Return result based on recommended install location. 14431 if (onSd) { 14432 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14433 } 14434 return pkgLite.recommendedInstallLocation; 14435 } 14436 14437 /* 14438 * Invoke remote method to get package information and install 14439 * location values. Override install location based on default 14440 * policy if needed and then create install arguments based 14441 * on the install location. 14442 */ 14443 public void handleStartCopy() throws RemoteException { 14444 int ret = PackageManager.INSTALL_SUCCEEDED; 14445 14446 // If we're already staged, we've firmly committed to an install location 14447 if (origin.staged) { 14448 if (origin.file != null) { 14449 installFlags |= PackageManager.INSTALL_INTERNAL; 14450 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14451 } else if (origin.cid != null) { 14452 installFlags |= PackageManager.INSTALL_EXTERNAL; 14453 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14454 } else { 14455 throw new IllegalStateException("Invalid stage location"); 14456 } 14457 } 14458 14459 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14460 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14461 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14462 PackageInfoLite pkgLite = null; 14463 14464 if (onInt && onSd) { 14465 // Check if both bits are set. 14466 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14467 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14468 } else if (onSd && ephemeral) { 14469 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14470 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14471 } else { 14472 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14473 packageAbiOverride); 14474 14475 if (DEBUG_EPHEMERAL && ephemeral) { 14476 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14477 } 14478 14479 /* 14480 * If we have too little free space, try to free cache 14481 * before giving up. 14482 */ 14483 if (!origin.staged && pkgLite.recommendedInstallLocation 14484 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14485 // TODO: focus freeing disk space on the target device 14486 final StorageManager storage = StorageManager.from(mContext); 14487 final long lowThreshold = storage.getStorageLowBytes( 14488 Environment.getDataDirectory()); 14489 14490 final long sizeBytes = mContainerService.calculateInstalledSize( 14491 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14492 14493 try { 14494 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14495 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14496 installFlags, packageAbiOverride); 14497 } catch (InstallerException e) { 14498 Slog.w(TAG, "Failed to free cache", e); 14499 } 14500 14501 /* 14502 * The cache free must have deleted the file we 14503 * downloaded to install. 14504 * 14505 * TODO: fix the "freeCache" call to not delete 14506 * the file we care about. 14507 */ 14508 if (pkgLite.recommendedInstallLocation 14509 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14510 pkgLite.recommendedInstallLocation 14511 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14512 } 14513 } 14514 } 14515 14516 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14517 int loc = pkgLite.recommendedInstallLocation; 14518 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14519 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14520 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14521 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14522 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14523 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14524 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14525 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14526 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14527 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14528 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14529 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14530 } else { 14531 // Override with defaults if needed. 14532 loc = installLocationPolicy(pkgLite); 14533 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14534 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14535 } else if (!onSd && !onInt) { 14536 // Override install location with flags 14537 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14538 // Set the flag to install on external media. 14539 installFlags |= PackageManager.INSTALL_EXTERNAL; 14540 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14541 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14542 if (DEBUG_EPHEMERAL) { 14543 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14544 } 14545 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14546 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14547 |PackageManager.INSTALL_INTERNAL); 14548 } else { 14549 // Make sure the flag for installing on external 14550 // media is unset 14551 installFlags |= PackageManager.INSTALL_INTERNAL; 14552 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14553 } 14554 } 14555 } 14556 } 14557 14558 final InstallArgs args = createInstallArgs(this); 14559 mArgs = args; 14560 14561 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14562 // TODO: http://b/22976637 14563 // Apps installed for "all" users use the device owner to verify the app 14564 UserHandle verifierUser = getUser(); 14565 if (verifierUser == UserHandle.ALL) { 14566 verifierUser = UserHandle.SYSTEM; 14567 } 14568 14569 /* 14570 * Determine if we have any installed package verifiers. If we 14571 * do, then we'll defer to them to verify the packages. 14572 */ 14573 final int requiredUid = mRequiredVerifierPackage == null ? -1 14574 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14575 verifierUser.getIdentifier()); 14576 if (!origin.existing && requiredUid != -1 14577 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14578 final Intent verification = new Intent( 14579 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14580 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14581 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14582 PACKAGE_MIME_TYPE); 14583 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14584 14585 // Query all live verifiers based on current user state 14586 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14587 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14588 14589 if (DEBUG_VERIFY) { 14590 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14591 + verification.toString() + " with " + pkgLite.verifiers.length 14592 + " optional verifiers"); 14593 } 14594 14595 final int verificationId = mPendingVerificationToken++; 14596 14597 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14598 14599 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14600 installerPackageName); 14601 14602 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14603 installFlags); 14604 14605 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14606 pkgLite.packageName); 14607 14608 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14609 pkgLite.versionCode); 14610 14611 if (verificationInfo != null) { 14612 if (verificationInfo.originatingUri != null) { 14613 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14614 verificationInfo.originatingUri); 14615 } 14616 if (verificationInfo.referrer != null) { 14617 verification.putExtra(Intent.EXTRA_REFERRER, 14618 verificationInfo.referrer); 14619 } 14620 if (verificationInfo.originatingUid >= 0) { 14621 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14622 verificationInfo.originatingUid); 14623 } 14624 if (verificationInfo.installerUid >= 0) { 14625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14626 verificationInfo.installerUid); 14627 } 14628 } 14629 14630 final PackageVerificationState verificationState = new PackageVerificationState( 14631 requiredUid, args); 14632 14633 mPendingVerification.append(verificationId, verificationState); 14634 14635 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14636 receivers, verificationState); 14637 14638 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14639 final long idleDuration = getVerificationTimeout(); 14640 14641 /* 14642 * If any sufficient verifiers were listed in the package 14643 * manifest, attempt to ask them. 14644 */ 14645 if (sufficientVerifiers != null) { 14646 final int N = sufficientVerifiers.size(); 14647 if (N == 0) { 14648 Slog.i(TAG, "Additional verifiers required, but none installed."); 14649 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14650 } else { 14651 for (int i = 0; i < N; i++) { 14652 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14653 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14654 verifierComponent.getPackageName(), idleDuration, 14655 verifierUser.getIdentifier(), false, "package verifier"); 14656 14657 final Intent sufficientIntent = new Intent(verification); 14658 sufficientIntent.setComponent(verifierComponent); 14659 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14660 } 14661 } 14662 } 14663 14664 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14665 mRequiredVerifierPackage, receivers); 14666 if (ret == PackageManager.INSTALL_SUCCEEDED 14667 && mRequiredVerifierPackage != null) { 14668 Trace.asyncTraceBegin( 14669 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14670 /* 14671 * Send the intent to the required verification agent, 14672 * but only start the verification timeout after the 14673 * target BroadcastReceivers have run. 14674 */ 14675 verification.setComponent(requiredVerifierComponent); 14676 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14677 mRequiredVerifierPackage, idleDuration, 14678 verifierUser.getIdentifier(), false, "package verifier"); 14679 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14680 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14681 new BroadcastReceiver() { 14682 @Override 14683 public void onReceive(Context context, Intent intent) { 14684 final Message msg = mHandler 14685 .obtainMessage(CHECK_PENDING_VERIFICATION); 14686 msg.arg1 = verificationId; 14687 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14688 } 14689 }, null, 0, null, null); 14690 14691 /* 14692 * We don't want the copy to proceed until verification 14693 * succeeds, so null out this field. 14694 */ 14695 mArgs = null; 14696 } 14697 } else { 14698 /* 14699 * No package verification is enabled, so immediately start 14700 * the remote call to initiate copy using temporary file. 14701 */ 14702 ret = args.copyApk(mContainerService, true); 14703 } 14704 } 14705 14706 mRet = ret; 14707 } 14708 14709 @Override 14710 void handleReturnCode() { 14711 // If mArgs is null, then MCS couldn't be reached. When it 14712 // reconnects, it will try again to install. At that point, this 14713 // will succeed. 14714 if (mArgs != null) { 14715 processPendingInstall(mArgs, mRet); 14716 } 14717 } 14718 14719 @Override 14720 void handleServiceError() { 14721 mArgs = createInstallArgs(this); 14722 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14723 } 14724 14725 public boolean isForwardLocked() { 14726 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14727 } 14728 } 14729 14730 /** 14731 * Used during creation of InstallArgs 14732 * 14733 * @param installFlags package installation flags 14734 * @return true if should be installed on external storage 14735 */ 14736 private static boolean installOnExternalAsec(int installFlags) { 14737 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14738 return false; 14739 } 14740 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14741 return true; 14742 } 14743 return false; 14744 } 14745 14746 /** 14747 * Used during creation of InstallArgs 14748 * 14749 * @param installFlags package installation flags 14750 * @return true if should be installed as forward locked 14751 */ 14752 private static boolean installForwardLocked(int installFlags) { 14753 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14754 } 14755 14756 private InstallArgs createInstallArgs(InstallParams params) { 14757 if (params.move != null) { 14758 return new MoveInstallArgs(params); 14759 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14760 return new AsecInstallArgs(params); 14761 } else { 14762 return new FileInstallArgs(params); 14763 } 14764 } 14765 14766 /** 14767 * Create args that describe an existing installed package. Typically used 14768 * when cleaning up old installs, or used as a move source. 14769 */ 14770 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14771 String resourcePath, String[] instructionSets) { 14772 final boolean isInAsec; 14773 if (installOnExternalAsec(installFlags)) { 14774 /* Apps on SD card are always in ASEC containers. */ 14775 isInAsec = true; 14776 } else if (installForwardLocked(installFlags) 14777 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14778 /* 14779 * Forward-locked apps are only in ASEC containers if they're the 14780 * new style 14781 */ 14782 isInAsec = true; 14783 } else { 14784 isInAsec = false; 14785 } 14786 14787 if (isInAsec) { 14788 return new AsecInstallArgs(codePath, instructionSets, 14789 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14790 } else { 14791 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14792 } 14793 } 14794 14795 static abstract class InstallArgs { 14796 /** @see InstallParams#origin */ 14797 final OriginInfo origin; 14798 /** @see InstallParams#move */ 14799 final MoveInfo move; 14800 14801 final IPackageInstallObserver2 observer; 14802 // Always refers to PackageManager flags only 14803 final int installFlags; 14804 final String installerPackageName; 14805 final String volumeUuid; 14806 final UserHandle user; 14807 final String abiOverride; 14808 final String[] installGrantPermissions; 14809 /** If non-null, drop an async trace when the install completes */ 14810 final String traceMethod; 14811 final int traceCookie; 14812 final Certificate[][] certificates; 14813 final int installReason; 14814 14815 // The list of instruction sets supported by this app. This is currently 14816 // only used during the rmdex() phase to clean up resources. We can get rid of this 14817 // if we move dex files under the common app path. 14818 /* nullable */ String[] instructionSets; 14819 14820 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14821 int installFlags, String installerPackageName, String volumeUuid, 14822 UserHandle user, String[] instructionSets, 14823 String abiOverride, String[] installGrantPermissions, 14824 String traceMethod, int traceCookie, Certificate[][] certificates, 14825 int installReason) { 14826 this.origin = origin; 14827 this.move = move; 14828 this.installFlags = installFlags; 14829 this.observer = observer; 14830 this.installerPackageName = installerPackageName; 14831 this.volumeUuid = volumeUuid; 14832 this.user = user; 14833 this.instructionSets = instructionSets; 14834 this.abiOverride = abiOverride; 14835 this.installGrantPermissions = installGrantPermissions; 14836 this.traceMethod = traceMethod; 14837 this.traceCookie = traceCookie; 14838 this.certificates = certificates; 14839 this.installReason = installReason; 14840 } 14841 14842 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14843 abstract int doPreInstall(int status); 14844 14845 /** 14846 * Rename package into final resting place. All paths on the given 14847 * scanned package should be updated to reflect the rename. 14848 */ 14849 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14850 abstract int doPostInstall(int status, int uid); 14851 14852 /** @see PackageSettingBase#codePathString */ 14853 abstract String getCodePath(); 14854 /** @see PackageSettingBase#resourcePathString */ 14855 abstract String getResourcePath(); 14856 14857 // Need installer lock especially for dex file removal. 14858 abstract void cleanUpResourcesLI(); 14859 abstract boolean doPostDeleteLI(boolean delete); 14860 14861 /** 14862 * Called before the source arguments are copied. This is used mostly 14863 * for MoveParams when it needs to read the source file to put it in the 14864 * destination. 14865 */ 14866 int doPreCopy() { 14867 return PackageManager.INSTALL_SUCCEEDED; 14868 } 14869 14870 /** 14871 * Called after the source arguments are copied. This is used mostly for 14872 * MoveParams when it needs to read the source file to put it in the 14873 * destination. 14874 */ 14875 int doPostCopy(int uid) { 14876 return PackageManager.INSTALL_SUCCEEDED; 14877 } 14878 14879 protected boolean isFwdLocked() { 14880 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14881 } 14882 14883 protected boolean isExternalAsec() { 14884 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14885 } 14886 14887 protected boolean isEphemeral() { 14888 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14889 } 14890 14891 UserHandle getUser() { 14892 return user; 14893 } 14894 } 14895 14896 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14897 if (!allCodePaths.isEmpty()) { 14898 if (instructionSets == null) { 14899 throw new IllegalStateException("instructionSet == null"); 14900 } 14901 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14902 for (String codePath : allCodePaths) { 14903 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14904 try { 14905 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14906 } catch (InstallerException ignored) { 14907 } 14908 } 14909 } 14910 } 14911 } 14912 14913 /** 14914 * Logic to handle installation of non-ASEC applications, including copying 14915 * and renaming logic. 14916 */ 14917 class FileInstallArgs extends InstallArgs { 14918 private File codeFile; 14919 private File resourceFile; 14920 14921 // Example topology: 14922 // /data/app/com.example/base.apk 14923 // /data/app/com.example/split_foo.apk 14924 // /data/app/com.example/lib/arm/libfoo.so 14925 // /data/app/com.example/lib/arm64/libfoo.so 14926 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14927 14928 /** New install */ 14929 FileInstallArgs(InstallParams params) { 14930 super(params.origin, params.move, params.observer, params.installFlags, 14931 params.installerPackageName, params.volumeUuid, 14932 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14933 params.grantedRuntimePermissions, 14934 params.traceMethod, params.traceCookie, params.certificates, 14935 params.installReason); 14936 if (isFwdLocked()) { 14937 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14938 } 14939 } 14940 14941 /** Existing install */ 14942 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14943 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14944 null, null, null, 0, null /*certificates*/, 14945 PackageManager.INSTALL_REASON_UNKNOWN); 14946 this.codeFile = (codePath != null) ? new File(codePath) : null; 14947 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14948 } 14949 14950 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14951 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14952 try { 14953 return doCopyApk(imcs, temp); 14954 } finally { 14955 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14956 } 14957 } 14958 14959 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14960 if (origin.staged) { 14961 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14962 codeFile = origin.file; 14963 resourceFile = origin.file; 14964 return PackageManager.INSTALL_SUCCEEDED; 14965 } 14966 14967 try { 14968 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14969 final File tempDir = 14970 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14971 codeFile = tempDir; 14972 resourceFile = tempDir; 14973 } catch (IOException e) { 14974 Slog.w(TAG, "Failed to create copy file: " + e); 14975 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14976 } 14977 14978 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14979 @Override 14980 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14981 if (!FileUtils.isValidExtFilename(name)) { 14982 throw new IllegalArgumentException("Invalid filename: " + name); 14983 } 14984 try { 14985 final File file = new File(codeFile, name); 14986 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14987 O_RDWR | O_CREAT, 0644); 14988 Os.chmod(file.getAbsolutePath(), 0644); 14989 return new ParcelFileDescriptor(fd); 14990 } catch (ErrnoException e) { 14991 throw new RemoteException("Failed to open: " + e.getMessage()); 14992 } 14993 } 14994 }; 14995 14996 int ret = PackageManager.INSTALL_SUCCEEDED; 14997 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14998 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14999 Slog.e(TAG, "Failed to copy package"); 15000 return ret; 15001 } 15002 15003 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15004 NativeLibraryHelper.Handle handle = null; 15005 try { 15006 handle = NativeLibraryHelper.Handle.create(codeFile); 15007 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15008 abiOverride); 15009 } catch (IOException e) { 15010 Slog.e(TAG, "Copying native libraries failed", e); 15011 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15012 } finally { 15013 IoUtils.closeQuietly(handle); 15014 } 15015 15016 return ret; 15017 } 15018 15019 int doPreInstall(int status) { 15020 if (status != PackageManager.INSTALL_SUCCEEDED) { 15021 cleanUp(); 15022 } 15023 return status; 15024 } 15025 15026 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15027 if (status != PackageManager.INSTALL_SUCCEEDED) { 15028 cleanUp(); 15029 return false; 15030 } 15031 15032 final File targetDir = codeFile.getParentFile(); 15033 final File beforeCodeFile = codeFile; 15034 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15035 15036 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15037 try { 15038 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15039 } catch (ErrnoException e) { 15040 Slog.w(TAG, "Failed to rename", e); 15041 return false; 15042 } 15043 15044 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15045 Slog.w(TAG, "Failed to restorecon"); 15046 return false; 15047 } 15048 15049 // Reflect the rename internally 15050 codeFile = afterCodeFile; 15051 resourceFile = afterCodeFile; 15052 15053 // Reflect the rename in scanned details 15054 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15055 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15056 afterCodeFile, pkg.baseCodePath)); 15057 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15058 afterCodeFile, pkg.splitCodePaths)); 15059 15060 // Reflect the rename in app info 15061 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15062 pkg.setApplicationInfoCodePath(pkg.codePath); 15063 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15064 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15065 pkg.setApplicationInfoResourcePath(pkg.codePath); 15066 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15067 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15068 15069 return true; 15070 } 15071 15072 int doPostInstall(int status, int uid) { 15073 if (status != PackageManager.INSTALL_SUCCEEDED) { 15074 cleanUp(); 15075 } 15076 return status; 15077 } 15078 15079 @Override 15080 String getCodePath() { 15081 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15082 } 15083 15084 @Override 15085 String getResourcePath() { 15086 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15087 } 15088 15089 private boolean cleanUp() { 15090 if (codeFile == null || !codeFile.exists()) { 15091 return false; 15092 } 15093 15094 removeCodePathLI(codeFile); 15095 15096 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15097 resourceFile.delete(); 15098 } 15099 15100 return true; 15101 } 15102 15103 void cleanUpResourcesLI() { 15104 // Try enumerating all code paths before deleting 15105 List<String> allCodePaths = Collections.EMPTY_LIST; 15106 if (codeFile != null && codeFile.exists()) { 15107 try { 15108 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15109 allCodePaths = pkg.getAllCodePaths(); 15110 } catch (PackageParserException e) { 15111 // Ignored; we tried our best 15112 } 15113 } 15114 15115 cleanUp(); 15116 removeDexFiles(allCodePaths, instructionSets); 15117 } 15118 15119 boolean doPostDeleteLI(boolean delete) { 15120 // XXX err, shouldn't we respect the delete flag? 15121 cleanUpResourcesLI(); 15122 return true; 15123 } 15124 } 15125 15126 private boolean isAsecExternal(String cid) { 15127 final String asecPath = PackageHelper.getSdFilesystem(cid); 15128 return !asecPath.startsWith(mAsecInternalPath); 15129 } 15130 15131 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15132 PackageManagerException { 15133 if (copyRet < 0) { 15134 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15135 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15136 throw new PackageManagerException(copyRet, message); 15137 } 15138 } 15139 } 15140 15141 /** 15142 * Extract the StorageManagerService "container ID" from the full code path of an 15143 * .apk. 15144 */ 15145 static String cidFromCodePath(String fullCodePath) { 15146 int eidx = fullCodePath.lastIndexOf("/"); 15147 String subStr1 = fullCodePath.substring(0, eidx); 15148 int sidx = subStr1.lastIndexOf("/"); 15149 return subStr1.substring(sidx+1, eidx); 15150 } 15151 15152 /** 15153 * Logic to handle installation of ASEC applications, including copying and 15154 * renaming logic. 15155 */ 15156 class AsecInstallArgs extends InstallArgs { 15157 static final String RES_FILE_NAME = "pkg.apk"; 15158 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15159 15160 String cid; 15161 String packagePath; 15162 String resourcePath; 15163 15164 /** New install */ 15165 AsecInstallArgs(InstallParams params) { 15166 super(params.origin, params.move, params.observer, params.installFlags, 15167 params.installerPackageName, params.volumeUuid, 15168 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15169 params.grantedRuntimePermissions, 15170 params.traceMethod, params.traceCookie, params.certificates, 15171 params.installReason); 15172 } 15173 15174 /** Existing install */ 15175 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15176 boolean isExternal, boolean isForwardLocked) { 15177 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15178 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15179 instructionSets, null, null, null, 0, null /*certificates*/, 15180 PackageManager.INSTALL_REASON_UNKNOWN); 15181 // Hackily pretend we're still looking at a full code path 15182 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15183 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15184 } 15185 15186 // Extract cid from fullCodePath 15187 int eidx = fullCodePath.lastIndexOf("/"); 15188 String subStr1 = fullCodePath.substring(0, eidx); 15189 int sidx = subStr1.lastIndexOf("/"); 15190 cid = subStr1.substring(sidx+1, eidx); 15191 setMountPath(subStr1); 15192 } 15193 15194 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15195 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15196 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15197 instructionSets, null, null, null, 0, null /*certificates*/, 15198 PackageManager.INSTALL_REASON_UNKNOWN); 15199 this.cid = cid; 15200 setMountPath(PackageHelper.getSdDir(cid)); 15201 } 15202 15203 void createCopyFile() { 15204 cid = mInstallerService.allocateExternalStageCidLegacy(); 15205 } 15206 15207 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15208 if (origin.staged && origin.cid != null) { 15209 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15210 cid = origin.cid; 15211 setMountPath(PackageHelper.getSdDir(cid)); 15212 return PackageManager.INSTALL_SUCCEEDED; 15213 } 15214 15215 if (temp) { 15216 createCopyFile(); 15217 } else { 15218 /* 15219 * Pre-emptively destroy the container since it's destroyed if 15220 * copying fails due to it existing anyway. 15221 */ 15222 PackageHelper.destroySdDir(cid); 15223 } 15224 15225 final String newMountPath = imcs.copyPackageToContainer( 15226 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15227 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15228 15229 if (newMountPath != null) { 15230 setMountPath(newMountPath); 15231 return PackageManager.INSTALL_SUCCEEDED; 15232 } else { 15233 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15234 } 15235 } 15236 15237 @Override 15238 String getCodePath() { 15239 return packagePath; 15240 } 15241 15242 @Override 15243 String getResourcePath() { 15244 return resourcePath; 15245 } 15246 15247 int doPreInstall(int status) { 15248 if (status != PackageManager.INSTALL_SUCCEEDED) { 15249 // Destroy container 15250 PackageHelper.destroySdDir(cid); 15251 } else { 15252 boolean mounted = PackageHelper.isContainerMounted(cid); 15253 if (!mounted) { 15254 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15255 Process.SYSTEM_UID); 15256 if (newMountPath != null) { 15257 setMountPath(newMountPath); 15258 } else { 15259 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15260 } 15261 } 15262 } 15263 return status; 15264 } 15265 15266 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15267 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15268 String newMountPath = null; 15269 if (PackageHelper.isContainerMounted(cid)) { 15270 // Unmount the container 15271 if (!PackageHelper.unMountSdDir(cid)) { 15272 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15273 return false; 15274 } 15275 } 15276 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15277 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15278 " which might be stale. Will try to clean up."); 15279 // Clean up the stale container and proceed to recreate. 15280 if (!PackageHelper.destroySdDir(newCacheId)) { 15281 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15282 return false; 15283 } 15284 // Successfully cleaned up stale container. Try to rename again. 15285 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15286 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15287 + " inspite of cleaning it up."); 15288 return false; 15289 } 15290 } 15291 if (!PackageHelper.isContainerMounted(newCacheId)) { 15292 Slog.w(TAG, "Mounting container " + newCacheId); 15293 newMountPath = PackageHelper.mountSdDir(newCacheId, 15294 getEncryptKey(), Process.SYSTEM_UID); 15295 } else { 15296 newMountPath = PackageHelper.getSdDir(newCacheId); 15297 } 15298 if (newMountPath == null) { 15299 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15300 return false; 15301 } 15302 Log.i(TAG, "Succesfully renamed " + cid + 15303 " to " + newCacheId + 15304 " at new path: " + newMountPath); 15305 cid = newCacheId; 15306 15307 final File beforeCodeFile = new File(packagePath); 15308 setMountPath(newMountPath); 15309 final File afterCodeFile = new File(packagePath); 15310 15311 // Reflect the rename in scanned details 15312 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15313 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15314 afterCodeFile, pkg.baseCodePath)); 15315 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15316 afterCodeFile, pkg.splitCodePaths)); 15317 15318 // Reflect the rename in app info 15319 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15320 pkg.setApplicationInfoCodePath(pkg.codePath); 15321 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15322 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15323 pkg.setApplicationInfoResourcePath(pkg.codePath); 15324 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15325 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15326 15327 return true; 15328 } 15329 15330 private void setMountPath(String mountPath) { 15331 final File mountFile = new File(mountPath); 15332 15333 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15334 if (monolithicFile.exists()) { 15335 packagePath = monolithicFile.getAbsolutePath(); 15336 if (isFwdLocked()) { 15337 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15338 } else { 15339 resourcePath = packagePath; 15340 } 15341 } else { 15342 packagePath = mountFile.getAbsolutePath(); 15343 resourcePath = packagePath; 15344 } 15345 } 15346 15347 int doPostInstall(int status, int uid) { 15348 if (status != PackageManager.INSTALL_SUCCEEDED) { 15349 cleanUp(); 15350 } else { 15351 final int groupOwner; 15352 final String protectedFile; 15353 if (isFwdLocked()) { 15354 groupOwner = UserHandle.getSharedAppGid(uid); 15355 protectedFile = RES_FILE_NAME; 15356 } else { 15357 groupOwner = -1; 15358 protectedFile = null; 15359 } 15360 15361 if (uid < Process.FIRST_APPLICATION_UID 15362 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15363 Slog.e(TAG, "Failed to finalize " + cid); 15364 PackageHelper.destroySdDir(cid); 15365 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15366 } 15367 15368 boolean mounted = PackageHelper.isContainerMounted(cid); 15369 if (!mounted) { 15370 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15371 } 15372 } 15373 return status; 15374 } 15375 15376 private void cleanUp() { 15377 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15378 15379 // Destroy secure container 15380 PackageHelper.destroySdDir(cid); 15381 } 15382 15383 private List<String> getAllCodePaths() { 15384 final File codeFile = new File(getCodePath()); 15385 if (codeFile != null && codeFile.exists()) { 15386 try { 15387 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15388 return pkg.getAllCodePaths(); 15389 } catch (PackageParserException e) { 15390 // Ignored; we tried our best 15391 } 15392 } 15393 return Collections.EMPTY_LIST; 15394 } 15395 15396 void cleanUpResourcesLI() { 15397 // Enumerate all code paths before deleting 15398 cleanUpResourcesLI(getAllCodePaths()); 15399 } 15400 15401 private void cleanUpResourcesLI(List<String> allCodePaths) { 15402 cleanUp(); 15403 removeDexFiles(allCodePaths, instructionSets); 15404 } 15405 15406 String getPackageName() { 15407 return getAsecPackageName(cid); 15408 } 15409 15410 boolean doPostDeleteLI(boolean delete) { 15411 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15412 final List<String> allCodePaths = getAllCodePaths(); 15413 boolean mounted = PackageHelper.isContainerMounted(cid); 15414 if (mounted) { 15415 // Unmount first 15416 if (PackageHelper.unMountSdDir(cid)) { 15417 mounted = false; 15418 } 15419 } 15420 if (!mounted && delete) { 15421 cleanUpResourcesLI(allCodePaths); 15422 } 15423 return !mounted; 15424 } 15425 15426 @Override 15427 int doPreCopy() { 15428 if (isFwdLocked()) { 15429 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15430 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15431 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15432 } 15433 } 15434 15435 return PackageManager.INSTALL_SUCCEEDED; 15436 } 15437 15438 @Override 15439 int doPostCopy(int uid) { 15440 if (isFwdLocked()) { 15441 if (uid < Process.FIRST_APPLICATION_UID 15442 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15443 RES_FILE_NAME)) { 15444 Slog.e(TAG, "Failed to finalize " + cid); 15445 PackageHelper.destroySdDir(cid); 15446 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15447 } 15448 } 15449 15450 return PackageManager.INSTALL_SUCCEEDED; 15451 } 15452 } 15453 15454 /** 15455 * Logic to handle movement of existing installed applications. 15456 */ 15457 class MoveInstallArgs extends InstallArgs { 15458 private File codeFile; 15459 private File resourceFile; 15460 15461 /** New install */ 15462 MoveInstallArgs(InstallParams params) { 15463 super(params.origin, params.move, params.observer, params.installFlags, 15464 params.installerPackageName, params.volumeUuid, 15465 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15466 params.grantedRuntimePermissions, 15467 params.traceMethod, params.traceCookie, params.certificates, 15468 params.installReason); 15469 } 15470 15471 int copyApk(IMediaContainerService imcs, boolean temp) { 15472 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15473 + move.fromUuid + " to " + move.toUuid); 15474 synchronized (mInstaller) { 15475 try { 15476 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15477 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15478 } catch (InstallerException e) { 15479 Slog.w(TAG, "Failed to move app", e); 15480 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15481 } 15482 } 15483 15484 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15485 resourceFile = codeFile; 15486 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15487 15488 return PackageManager.INSTALL_SUCCEEDED; 15489 } 15490 15491 int doPreInstall(int status) { 15492 if (status != PackageManager.INSTALL_SUCCEEDED) { 15493 cleanUp(move.toUuid); 15494 } 15495 return status; 15496 } 15497 15498 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15499 if (status != PackageManager.INSTALL_SUCCEEDED) { 15500 cleanUp(move.toUuid); 15501 return false; 15502 } 15503 15504 // Reflect the move in app info 15505 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15506 pkg.setApplicationInfoCodePath(pkg.codePath); 15507 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15508 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15509 pkg.setApplicationInfoResourcePath(pkg.codePath); 15510 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15511 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15512 15513 return true; 15514 } 15515 15516 int doPostInstall(int status, int uid) { 15517 if (status == PackageManager.INSTALL_SUCCEEDED) { 15518 cleanUp(move.fromUuid); 15519 } else { 15520 cleanUp(move.toUuid); 15521 } 15522 return status; 15523 } 15524 15525 @Override 15526 String getCodePath() { 15527 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15528 } 15529 15530 @Override 15531 String getResourcePath() { 15532 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15533 } 15534 15535 private boolean cleanUp(String volumeUuid) { 15536 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15537 move.dataAppName); 15538 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15539 final int[] userIds = sUserManager.getUserIds(); 15540 synchronized (mInstallLock) { 15541 // Clean up both app data and code 15542 // All package moves are frozen until finished 15543 for (int userId : userIds) { 15544 try { 15545 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15546 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15547 } catch (InstallerException e) { 15548 Slog.w(TAG, String.valueOf(e)); 15549 } 15550 } 15551 removeCodePathLI(codeFile); 15552 } 15553 return true; 15554 } 15555 15556 void cleanUpResourcesLI() { 15557 throw new UnsupportedOperationException(); 15558 } 15559 15560 boolean doPostDeleteLI(boolean delete) { 15561 throw new UnsupportedOperationException(); 15562 } 15563 } 15564 15565 static String getAsecPackageName(String packageCid) { 15566 int idx = packageCid.lastIndexOf("-"); 15567 if (idx == -1) { 15568 return packageCid; 15569 } 15570 return packageCid.substring(0, idx); 15571 } 15572 15573 // Utility method used to create code paths based on package name and available index. 15574 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15575 String idxStr = ""; 15576 int idx = 1; 15577 // Fall back to default value of idx=1 if prefix is not 15578 // part of oldCodePath 15579 if (oldCodePath != null) { 15580 String subStr = oldCodePath; 15581 // Drop the suffix right away 15582 if (suffix != null && subStr.endsWith(suffix)) { 15583 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15584 } 15585 // If oldCodePath already contains prefix find out the 15586 // ending index to either increment or decrement. 15587 int sidx = subStr.lastIndexOf(prefix); 15588 if (sidx != -1) { 15589 subStr = subStr.substring(sidx + prefix.length()); 15590 if (subStr != null) { 15591 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15592 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15593 } 15594 try { 15595 idx = Integer.parseInt(subStr); 15596 if (idx <= 1) { 15597 idx++; 15598 } else { 15599 idx--; 15600 } 15601 } catch(NumberFormatException e) { 15602 } 15603 } 15604 } 15605 } 15606 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15607 return prefix + idxStr; 15608 } 15609 15610 private File getNextCodePath(File targetDir, String packageName) { 15611 File result; 15612 SecureRandom random = new SecureRandom(); 15613 byte[] bytes = new byte[16]; 15614 do { 15615 random.nextBytes(bytes); 15616 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15617 result = new File(targetDir, packageName + "-" + suffix); 15618 } while (result.exists()); 15619 return result; 15620 } 15621 15622 // Utility method that returns the relative package path with respect 15623 // to the installation directory. Like say for /data/data/com.test-1.apk 15624 // string com.test-1 is returned. 15625 static String deriveCodePathName(String codePath) { 15626 if (codePath == null) { 15627 return null; 15628 } 15629 final File codeFile = new File(codePath); 15630 final String name = codeFile.getName(); 15631 if (codeFile.isDirectory()) { 15632 return name; 15633 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15634 final int lastDot = name.lastIndexOf('.'); 15635 return name.substring(0, lastDot); 15636 } else { 15637 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15638 return null; 15639 } 15640 } 15641 15642 static class PackageInstalledInfo { 15643 String name; 15644 int uid; 15645 // The set of users that originally had this package installed. 15646 int[] origUsers; 15647 // The set of users that now have this package installed. 15648 int[] newUsers; 15649 PackageParser.Package pkg; 15650 int returnCode; 15651 String returnMsg; 15652 PackageRemovedInfo removedInfo; 15653 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15654 15655 public void setError(int code, String msg) { 15656 setReturnCode(code); 15657 setReturnMessage(msg); 15658 Slog.w(TAG, msg); 15659 } 15660 15661 public void setError(String msg, PackageParserException e) { 15662 setReturnCode(e.error); 15663 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15664 Slog.w(TAG, msg, e); 15665 } 15666 15667 public void setError(String msg, PackageManagerException e) { 15668 returnCode = e.error; 15669 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15670 Slog.w(TAG, msg, e); 15671 } 15672 15673 public void setReturnCode(int returnCode) { 15674 this.returnCode = returnCode; 15675 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15676 for (int i = 0; i < childCount; i++) { 15677 addedChildPackages.valueAt(i).returnCode = returnCode; 15678 } 15679 } 15680 15681 private void setReturnMessage(String returnMsg) { 15682 this.returnMsg = returnMsg; 15683 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15684 for (int i = 0; i < childCount; i++) { 15685 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15686 } 15687 } 15688 15689 // In some error cases we want to convey more info back to the observer 15690 String origPackage; 15691 String origPermission; 15692 } 15693 15694 /* 15695 * Install a non-existing package. 15696 */ 15697 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15698 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15699 PackageInstalledInfo res, int installReason) { 15700 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15701 15702 // Remember this for later, in case we need to rollback this install 15703 String pkgName = pkg.packageName; 15704 15705 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15706 15707 synchronized(mPackages) { 15708 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15709 if (renamedPackage != null) { 15710 // A package with the same name is already installed, though 15711 // it has been renamed to an older name. The package we 15712 // are trying to install should be installed as an update to 15713 // the existing one, but that has not been requested, so bail. 15714 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15715 + " without first uninstalling package running as " 15716 + renamedPackage); 15717 return; 15718 } 15719 if (mPackages.containsKey(pkgName)) { 15720 // Don't allow installation over an existing package with the same name. 15721 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15722 + " without first uninstalling."); 15723 return; 15724 } 15725 } 15726 15727 try { 15728 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15729 System.currentTimeMillis(), user); 15730 15731 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15732 15733 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15734 prepareAppDataAfterInstallLIF(newPackage); 15735 15736 } else { 15737 // Remove package from internal structures, but keep around any 15738 // data that might have already existed 15739 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15740 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15741 } 15742 } catch (PackageManagerException e) { 15743 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15744 } 15745 15746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15747 } 15748 15749 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15750 // Can't rotate keys during boot or if sharedUser. 15751 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15752 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15753 return false; 15754 } 15755 // app is using upgradeKeySets; make sure all are valid 15756 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15757 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15758 for (int i = 0; i < upgradeKeySets.length; i++) { 15759 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15760 Slog.wtf(TAG, "Package " 15761 + (oldPs.name != null ? oldPs.name : "<null>") 15762 + " contains upgrade-key-set reference to unknown key-set: " 15763 + upgradeKeySets[i] 15764 + " reverting to signatures check."); 15765 return false; 15766 } 15767 } 15768 return true; 15769 } 15770 15771 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15772 // Upgrade keysets are being used. Determine if new package has a superset of the 15773 // required keys. 15774 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15775 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15776 for (int i = 0; i < upgradeKeySets.length; i++) { 15777 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15778 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15779 return true; 15780 } 15781 } 15782 return false; 15783 } 15784 15785 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15786 try (DigestInputStream digestStream = 15787 new DigestInputStream(new FileInputStream(file), digest)) { 15788 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15789 } 15790 } 15791 15792 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15793 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15794 int installReason) { 15795 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15796 15797 final PackageParser.Package oldPackage; 15798 final String pkgName = pkg.packageName; 15799 final int[] allUsers; 15800 final int[] installedUsers; 15801 15802 synchronized(mPackages) { 15803 oldPackage = mPackages.get(pkgName); 15804 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15805 15806 // don't allow upgrade to target a release SDK from a pre-release SDK 15807 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15808 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15809 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15810 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15811 if (oldTargetsPreRelease 15812 && !newTargetsPreRelease 15813 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15814 Slog.w(TAG, "Can't install package targeting released sdk"); 15815 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15816 return; 15817 } 15818 15819 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15820 15821 // verify signatures are valid 15822 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15823 if (!checkUpgradeKeySetLP(ps, pkg)) { 15824 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15825 "New package not signed by keys specified by upgrade-keysets: " 15826 + pkgName); 15827 return; 15828 } 15829 } else { 15830 // default to original signature matching 15831 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15832 != PackageManager.SIGNATURE_MATCH) { 15833 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15834 "New package has a different signature: " + pkgName); 15835 return; 15836 } 15837 } 15838 15839 // don't allow a system upgrade unless the upgrade hash matches 15840 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15841 byte[] digestBytes = null; 15842 try { 15843 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15844 updateDigest(digest, new File(pkg.baseCodePath)); 15845 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15846 for (String path : pkg.splitCodePaths) { 15847 updateDigest(digest, new File(path)); 15848 } 15849 } 15850 digestBytes = digest.digest(); 15851 } catch (NoSuchAlgorithmException | IOException e) { 15852 res.setError(INSTALL_FAILED_INVALID_APK, 15853 "Could not compute hash: " + pkgName); 15854 return; 15855 } 15856 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15857 res.setError(INSTALL_FAILED_INVALID_APK, 15858 "New package fails restrict-update check: " + pkgName); 15859 return; 15860 } 15861 // retain upgrade restriction 15862 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15863 } 15864 15865 // Check for shared user id changes 15866 String invalidPackageName = 15867 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15868 if (invalidPackageName != null) { 15869 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15870 "Package " + invalidPackageName + " tried to change user " 15871 + oldPackage.mSharedUserId); 15872 return; 15873 } 15874 15875 // In case of rollback, remember per-user/profile install state 15876 allUsers = sUserManager.getUserIds(); 15877 installedUsers = ps.queryInstalledUsers(allUsers, true); 15878 15879 // don't allow an upgrade from full to ephemeral 15880 if (isInstantApp) { 15881 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15882 for (int currentUser : allUsers) { 15883 if (!ps.getInstantApp(currentUser)) { 15884 // can't downgrade from full to instant 15885 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15886 + " for user: " + currentUser); 15887 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15888 return; 15889 } 15890 } 15891 } else if (!ps.getInstantApp(user.getIdentifier())) { 15892 // can't downgrade from full to instant 15893 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15894 + " for user: " + user.getIdentifier()); 15895 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15896 return; 15897 } 15898 } 15899 } 15900 15901 // Update what is removed 15902 res.removedInfo = new PackageRemovedInfo(); 15903 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15904 res.removedInfo.removedPackage = oldPackage.packageName; 15905 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15906 res.removedInfo.isUpdate = true; 15907 res.removedInfo.origUsers = installedUsers; 15908 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15909 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15910 for (int i = 0; i < installedUsers.length; i++) { 15911 final int userId = installedUsers[i]; 15912 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15913 } 15914 15915 final int childCount = (oldPackage.childPackages != null) 15916 ? oldPackage.childPackages.size() : 0; 15917 for (int i = 0; i < childCount; i++) { 15918 boolean childPackageUpdated = false; 15919 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15920 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15921 if (res.addedChildPackages != null) { 15922 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15923 if (childRes != null) { 15924 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15925 childRes.removedInfo.removedPackage = childPkg.packageName; 15926 childRes.removedInfo.isUpdate = true; 15927 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15928 childPackageUpdated = true; 15929 } 15930 } 15931 if (!childPackageUpdated) { 15932 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15933 childRemovedRes.removedPackage = childPkg.packageName; 15934 childRemovedRes.isUpdate = false; 15935 childRemovedRes.dataRemoved = true; 15936 synchronized (mPackages) { 15937 if (childPs != null) { 15938 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15939 } 15940 } 15941 if (res.removedInfo.removedChildPackages == null) { 15942 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15943 } 15944 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15945 } 15946 } 15947 15948 boolean sysPkg = (isSystemApp(oldPackage)); 15949 if (sysPkg) { 15950 // Set the system/privileged flags as needed 15951 final boolean privileged = 15952 (oldPackage.applicationInfo.privateFlags 15953 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15954 final int systemPolicyFlags = policyFlags 15955 | PackageParser.PARSE_IS_SYSTEM 15956 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15957 15958 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15959 user, allUsers, installerPackageName, res, installReason); 15960 } else { 15961 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15962 user, allUsers, installerPackageName, res, installReason); 15963 } 15964 } 15965 15966 public List<String> getPreviousCodePaths(String packageName) { 15967 final PackageSetting ps = mSettings.mPackages.get(packageName); 15968 final List<String> result = new ArrayList<String>(); 15969 if (ps != null && ps.oldCodePaths != null) { 15970 result.addAll(ps.oldCodePaths); 15971 } 15972 return result; 15973 } 15974 15975 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15976 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15977 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15978 int installReason) { 15979 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15980 + deletedPackage); 15981 15982 String pkgName = deletedPackage.packageName; 15983 boolean deletedPkg = true; 15984 boolean addedPkg = false; 15985 boolean updatedSettings = false; 15986 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15987 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15988 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15989 15990 final long origUpdateTime = (pkg.mExtras != null) 15991 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15992 15993 // First delete the existing package while retaining the data directory 15994 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15995 res.removedInfo, true, pkg)) { 15996 // If the existing package wasn't successfully deleted 15997 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15998 deletedPkg = false; 15999 } else { 16000 // Successfully deleted the old package; proceed with replace. 16001 16002 // If deleted package lived in a container, give users a chance to 16003 // relinquish resources before killing. 16004 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16005 if (DEBUG_INSTALL) { 16006 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16007 } 16008 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16009 final ArrayList<String> pkgList = new ArrayList<String>(1); 16010 pkgList.add(deletedPackage.applicationInfo.packageName); 16011 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16012 } 16013 16014 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16015 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16016 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16017 16018 try { 16019 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16020 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16021 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16022 installReason); 16023 16024 // Update the in-memory copy of the previous code paths. 16025 PackageSetting ps = mSettings.mPackages.get(pkgName); 16026 if (!killApp) { 16027 if (ps.oldCodePaths == null) { 16028 ps.oldCodePaths = new ArraySet<>(); 16029 } 16030 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16031 if (deletedPackage.splitCodePaths != null) { 16032 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16033 } 16034 } else { 16035 ps.oldCodePaths = null; 16036 } 16037 if (ps.childPackageNames != null) { 16038 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16039 final String childPkgName = ps.childPackageNames.get(i); 16040 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16041 childPs.oldCodePaths = ps.oldCodePaths; 16042 } 16043 } 16044 // set instant app status, but, only if it's explicitly specified 16045 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16046 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16047 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16048 prepareAppDataAfterInstallLIF(newPackage); 16049 addedPkg = true; 16050 mDexManager.notifyPackageUpdated(newPackage.packageName, 16051 newPackage.baseCodePath, newPackage.splitCodePaths); 16052 } catch (PackageManagerException e) { 16053 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16054 } 16055 } 16056 16057 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16058 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16059 16060 // Revert all internal state mutations and added folders for the failed install 16061 if (addedPkg) { 16062 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16063 res.removedInfo, true, null); 16064 } 16065 16066 // Restore the old package 16067 if (deletedPkg) { 16068 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16069 File restoreFile = new File(deletedPackage.codePath); 16070 // Parse old package 16071 boolean oldExternal = isExternal(deletedPackage); 16072 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16073 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16074 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16075 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16076 try { 16077 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16078 null); 16079 } catch (PackageManagerException e) { 16080 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16081 + e.getMessage()); 16082 return; 16083 } 16084 16085 synchronized (mPackages) { 16086 // Ensure the installer package name up to date 16087 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16088 16089 // Update permissions for restored package 16090 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16091 16092 mSettings.writeLPr(); 16093 } 16094 16095 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16096 } 16097 } else { 16098 synchronized (mPackages) { 16099 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16100 if (ps != null) { 16101 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16102 if (res.removedInfo.removedChildPackages != null) { 16103 final int childCount = res.removedInfo.removedChildPackages.size(); 16104 // Iterate in reverse as we may modify the collection 16105 for (int i = childCount - 1; i >= 0; i--) { 16106 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16107 if (res.addedChildPackages.containsKey(childPackageName)) { 16108 res.removedInfo.removedChildPackages.removeAt(i); 16109 } else { 16110 PackageRemovedInfo childInfo = res.removedInfo 16111 .removedChildPackages.valueAt(i); 16112 childInfo.removedForAllUsers = mPackages.get( 16113 childInfo.removedPackage) == null; 16114 } 16115 } 16116 } 16117 } 16118 } 16119 } 16120 } 16121 16122 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16123 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16124 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16125 int installReason) { 16126 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16127 + ", old=" + deletedPackage); 16128 16129 final boolean disabledSystem; 16130 16131 // Remove existing system package 16132 removePackageLI(deletedPackage, true); 16133 16134 synchronized (mPackages) { 16135 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16136 } 16137 if (!disabledSystem) { 16138 // We didn't need to disable the .apk as a current system package, 16139 // which means we are replacing another update that is already 16140 // installed. We need to make sure to delete the older one's .apk. 16141 res.removedInfo.args = createInstallArgsForExisting(0, 16142 deletedPackage.applicationInfo.getCodePath(), 16143 deletedPackage.applicationInfo.getResourcePath(), 16144 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16145 } else { 16146 res.removedInfo.args = null; 16147 } 16148 16149 // Successfully disabled the old package. Now proceed with re-installation 16150 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16151 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16152 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16153 16154 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16155 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16156 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16157 16158 PackageParser.Package newPackage = null; 16159 try { 16160 // Add the package to the internal data structures 16161 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16162 16163 // Set the update and install times 16164 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16165 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16166 System.currentTimeMillis()); 16167 16168 // Update the package dynamic state if succeeded 16169 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16170 // Now that the install succeeded make sure we remove data 16171 // directories for any child package the update removed. 16172 final int deletedChildCount = (deletedPackage.childPackages != null) 16173 ? deletedPackage.childPackages.size() : 0; 16174 final int newChildCount = (newPackage.childPackages != null) 16175 ? newPackage.childPackages.size() : 0; 16176 for (int i = 0; i < deletedChildCount; i++) { 16177 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16178 boolean childPackageDeleted = true; 16179 for (int j = 0; j < newChildCount; j++) { 16180 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16181 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16182 childPackageDeleted = false; 16183 break; 16184 } 16185 } 16186 if (childPackageDeleted) { 16187 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16188 deletedChildPkg.packageName); 16189 if (ps != null && res.removedInfo.removedChildPackages != null) { 16190 PackageRemovedInfo removedChildRes = res.removedInfo 16191 .removedChildPackages.get(deletedChildPkg.packageName); 16192 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16193 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16194 } 16195 } 16196 } 16197 16198 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16199 installReason); 16200 prepareAppDataAfterInstallLIF(newPackage); 16201 16202 mDexManager.notifyPackageUpdated(newPackage.packageName, 16203 newPackage.baseCodePath, newPackage.splitCodePaths); 16204 } 16205 } catch (PackageManagerException e) { 16206 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16207 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16208 } 16209 16210 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16211 // Re installation failed. Restore old information 16212 // Remove new pkg information 16213 if (newPackage != null) { 16214 removeInstalledPackageLI(newPackage, true); 16215 } 16216 // Add back the old system package 16217 try { 16218 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16219 } catch (PackageManagerException e) { 16220 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16221 } 16222 16223 synchronized (mPackages) { 16224 if (disabledSystem) { 16225 enableSystemPackageLPw(deletedPackage); 16226 } 16227 16228 // Ensure the installer package name up to date 16229 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16230 16231 // Update permissions for restored package 16232 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16233 16234 mSettings.writeLPr(); 16235 } 16236 16237 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16238 + " after failed upgrade"); 16239 } 16240 } 16241 16242 /** 16243 * Checks whether the parent or any of the child packages have a change shared 16244 * user. For a package to be a valid update the shred users of the parent and 16245 * the children should match. We may later support changing child shared users. 16246 * @param oldPkg The updated package. 16247 * @param newPkg The update package. 16248 * @return The shared user that change between the versions. 16249 */ 16250 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16251 PackageParser.Package newPkg) { 16252 // Check parent shared user 16253 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16254 return newPkg.packageName; 16255 } 16256 // Check child shared users 16257 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16258 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16259 for (int i = 0; i < newChildCount; i++) { 16260 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16261 // If this child was present, did it have the same shared user? 16262 for (int j = 0; j < oldChildCount; j++) { 16263 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16264 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16265 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16266 return newChildPkg.packageName; 16267 } 16268 } 16269 } 16270 return null; 16271 } 16272 16273 private void removeNativeBinariesLI(PackageSetting ps) { 16274 // Remove the lib path for the parent package 16275 if (ps != null) { 16276 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16277 // Remove the lib path for the child packages 16278 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16279 for (int i = 0; i < childCount; i++) { 16280 PackageSetting childPs = null; 16281 synchronized (mPackages) { 16282 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16283 } 16284 if (childPs != null) { 16285 NativeLibraryHelper.removeNativeBinariesLI(childPs 16286 .legacyNativeLibraryPathString); 16287 } 16288 } 16289 } 16290 } 16291 16292 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16293 // Enable the parent package 16294 mSettings.enableSystemPackageLPw(pkg.packageName); 16295 // Enable the child packages 16296 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16297 for (int i = 0; i < childCount; i++) { 16298 PackageParser.Package childPkg = pkg.childPackages.get(i); 16299 mSettings.enableSystemPackageLPw(childPkg.packageName); 16300 } 16301 } 16302 16303 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16304 PackageParser.Package newPkg) { 16305 // Disable the parent package (parent always replaced) 16306 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16307 // Disable the child packages 16308 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16309 for (int i = 0; i < childCount; i++) { 16310 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16311 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16312 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16313 } 16314 return disabled; 16315 } 16316 16317 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16318 String installerPackageName) { 16319 // Enable the parent package 16320 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16321 // Enable the child packages 16322 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16323 for (int i = 0; i < childCount; i++) { 16324 PackageParser.Package childPkg = pkg.childPackages.get(i); 16325 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16326 } 16327 } 16328 16329 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16330 // Collect all used permissions in the UID 16331 ArraySet<String> usedPermissions = new ArraySet<>(); 16332 final int packageCount = su.packages.size(); 16333 for (int i = 0; i < packageCount; i++) { 16334 PackageSetting ps = su.packages.valueAt(i); 16335 if (ps.pkg == null) { 16336 continue; 16337 } 16338 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16339 for (int j = 0; j < requestedPermCount; j++) { 16340 String permission = ps.pkg.requestedPermissions.get(j); 16341 BasePermission bp = mSettings.mPermissions.get(permission); 16342 if (bp != null) { 16343 usedPermissions.add(permission); 16344 } 16345 } 16346 } 16347 16348 PermissionsState permissionsState = su.getPermissionsState(); 16349 // Prune install permissions 16350 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16351 final int installPermCount = installPermStates.size(); 16352 for (int i = installPermCount - 1; i >= 0; i--) { 16353 PermissionState permissionState = installPermStates.get(i); 16354 if (!usedPermissions.contains(permissionState.getName())) { 16355 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16356 if (bp != null) { 16357 permissionsState.revokeInstallPermission(bp); 16358 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16359 PackageManager.MASK_PERMISSION_FLAGS, 0); 16360 } 16361 } 16362 } 16363 16364 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16365 16366 // Prune runtime permissions 16367 for (int userId : allUserIds) { 16368 List<PermissionState> runtimePermStates = permissionsState 16369 .getRuntimePermissionStates(userId); 16370 final int runtimePermCount = runtimePermStates.size(); 16371 for (int i = runtimePermCount - 1; i >= 0; i--) { 16372 PermissionState permissionState = runtimePermStates.get(i); 16373 if (!usedPermissions.contains(permissionState.getName())) { 16374 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16375 if (bp != null) { 16376 permissionsState.revokeRuntimePermission(bp, userId); 16377 permissionsState.updatePermissionFlags(bp, userId, 16378 PackageManager.MASK_PERMISSION_FLAGS, 0); 16379 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16380 runtimePermissionChangedUserIds, userId); 16381 } 16382 } 16383 } 16384 } 16385 16386 return runtimePermissionChangedUserIds; 16387 } 16388 16389 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16390 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16391 // Update the parent package setting 16392 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16393 res, user, installReason); 16394 // Update the child packages setting 16395 final int childCount = (newPackage.childPackages != null) 16396 ? newPackage.childPackages.size() : 0; 16397 for (int i = 0; i < childCount; i++) { 16398 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16399 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16400 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16401 childRes.origUsers, childRes, user, installReason); 16402 } 16403 } 16404 16405 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16406 String installerPackageName, int[] allUsers, int[] installedForUsers, 16407 PackageInstalledInfo res, UserHandle user, int installReason) { 16408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16409 16410 String pkgName = newPackage.packageName; 16411 synchronized (mPackages) { 16412 //write settings. the installStatus will be incomplete at this stage. 16413 //note that the new package setting would have already been 16414 //added to mPackages. It hasn't been persisted yet. 16415 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16416 // TODO: Remove this write? It's also written at the end of this method 16417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16418 mSettings.writeLPr(); 16419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16420 } 16421 16422 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16423 synchronized (mPackages) { 16424 updatePermissionsLPw(newPackage.packageName, newPackage, 16425 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16426 ? UPDATE_PERMISSIONS_ALL : 0)); 16427 // For system-bundled packages, we assume that installing an upgraded version 16428 // of the package implies that the user actually wants to run that new code, 16429 // so we enable the package. 16430 PackageSetting ps = mSettings.mPackages.get(pkgName); 16431 final int userId = user.getIdentifier(); 16432 if (ps != null) { 16433 if (isSystemApp(newPackage)) { 16434 if (DEBUG_INSTALL) { 16435 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16436 } 16437 // Enable system package for requested users 16438 if (res.origUsers != null) { 16439 for (int origUserId : res.origUsers) { 16440 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16441 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16442 origUserId, installerPackageName); 16443 } 16444 } 16445 } 16446 // Also convey the prior install/uninstall state 16447 if (allUsers != null && installedForUsers != null) { 16448 for (int currentUserId : allUsers) { 16449 final boolean installed = ArrayUtils.contains( 16450 installedForUsers, currentUserId); 16451 if (DEBUG_INSTALL) { 16452 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16453 } 16454 ps.setInstalled(installed, currentUserId); 16455 } 16456 // these install state changes will be persisted in the 16457 // upcoming call to mSettings.writeLPr(). 16458 } 16459 } 16460 // It's implied that when a user requests installation, they want the app to be 16461 // installed and enabled. 16462 if (userId != UserHandle.USER_ALL) { 16463 ps.setInstalled(true, userId); 16464 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16465 } 16466 16467 // When replacing an existing package, preserve the original install reason for all 16468 // users that had the package installed before. 16469 final Set<Integer> previousUserIds = new ArraySet<>(); 16470 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16471 final int installReasonCount = res.removedInfo.installReasons.size(); 16472 for (int i = 0; i < installReasonCount; i++) { 16473 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16474 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16475 ps.setInstallReason(previousInstallReason, previousUserId); 16476 previousUserIds.add(previousUserId); 16477 } 16478 } 16479 16480 // Set install reason for users that are having the package newly installed. 16481 if (userId == UserHandle.USER_ALL) { 16482 for (int currentUserId : sUserManager.getUserIds()) { 16483 if (!previousUserIds.contains(currentUserId)) { 16484 ps.setInstallReason(installReason, currentUserId); 16485 } 16486 } 16487 } else if (!previousUserIds.contains(userId)) { 16488 ps.setInstallReason(installReason, userId); 16489 } 16490 mSettings.writeKernelMappingLPr(ps); 16491 } 16492 res.name = pkgName; 16493 res.uid = newPackage.applicationInfo.uid; 16494 res.pkg = newPackage; 16495 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16496 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16497 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16498 //to update install status 16499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16500 mSettings.writeLPr(); 16501 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16502 } 16503 16504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16505 } 16506 16507 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16508 try { 16509 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16510 installPackageLI(args, res); 16511 } finally { 16512 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16513 } 16514 } 16515 16516 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16517 final int installFlags = args.installFlags; 16518 final String installerPackageName = args.installerPackageName; 16519 final String volumeUuid = args.volumeUuid; 16520 final File tmpPackageFile = new File(args.getCodePath()); 16521 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16522 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16523 || (args.volumeUuid != null)); 16524 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16525 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16526 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16527 boolean replace = false; 16528 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16529 if (args.move != null) { 16530 // moving a complete application; perform an initial scan on the new install location 16531 scanFlags |= SCAN_INITIAL; 16532 } 16533 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16534 scanFlags |= SCAN_DONT_KILL_APP; 16535 } 16536 if (instantApp) { 16537 scanFlags |= SCAN_AS_INSTANT_APP; 16538 } 16539 if (fullApp) { 16540 scanFlags |= SCAN_AS_FULL_APP; 16541 } 16542 16543 // Result object to be returned 16544 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16545 16546 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16547 16548 // Sanity check 16549 if (instantApp && (forwardLocked || onExternal)) { 16550 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16551 + " external=" + onExternal); 16552 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16553 return; 16554 } 16555 16556 // Retrieve PackageSettings and parse package 16557 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16558 | PackageParser.PARSE_ENFORCE_CODE 16559 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16560 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16561 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16562 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16563 PackageParser pp = new PackageParser(); 16564 pp.setSeparateProcesses(mSeparateProcesses); 16565 pp.setDisplayMetrics(mMetrics); 16566 pp.setCallback(mPackageParserCallback); 16567 16568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16569 final PackageParser.Package pkg; 16570 try { 16571 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16572 } catch (PackageParserException e) { 16573 res.setError("Failed parse during installPackageLI", e); 16574 return; 16575 } finally { 16576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16577 } 16578 16579 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16580 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16581 Slog.w(TAG, "Instant app package " + pkg.packageName 16582 + " does not target O, this will be a fatal error."); 16583 // STOPSHIP: Make this a fatal error 16584 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16585 } 16586 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16587 Slog.w(TAG, "Instant app package " + pkg.packageName 16588 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16589 // STOPSHIP: Make this a fatal error 16590 pkg.applicationInfo.targetSandboxVersion = 2; 16591 } 16592 16593 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16594 // Static shared libraries have synthetic package names 16595 renameStaticSharedLibraryPackage(pkg); 16596 16597 // No static shared libs on external storage 16598 if (onExternal) { 16599 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16600 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16601 "Packages declaring static-shared libs cannot be updated"); 16602 return; 16603 } 16604 } 16605 16606 // If we are installing a clustered package add results for the children 16607 if (pkg.childPackages != null) { 16608 synchronized (mPackages) { 16609 final int childCount = pkg.childPackages.size(); 16610 for (int i = 0; i < childCount; i++) { 16611 PackageParser.Package childPkg = pkg.childPackages.get(i); 16612 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16613 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16614 childRes.pkg = childPkg; 16615 childRes.name = childPkg.packageName; 16616 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16617 if (childPs != null) { 16618 childRes.origUsers = childPs.queryInstalledUsers( 16619 sUserManager.getUserIds(), true); 16620 } 16621 if ((mPackages.containsKey(childPkg.packageName))) { 16622 childRes.removedInfo = new PackageRemovedInfo(); 16623 childRes.removedInfo.removedPackage = childPkg.packageName; 16624 } 16625 if (res.addedChildPackages == null) { 16626 res.addedChildPackages = new ArrayMap<>(); 16627 } 16628 res.addedChildPackages.put(childPkg.packageName, childRes); 16629 } 16630 } 16631 } 16632 16633 // If package doesn't declare API override, mark that we have an install 16634 // time CPU ABI override. 16635 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16636 pkg.cpuAbiOverride = args.abiOverride; 16637 } 16638 16639 String pkgName = res.name = pkg.packageName; 16640 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16641 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16642 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16643 return; 16644 } 16645 } 16646 16647 try { 16648 // either use what we've been given or parse directly from the APK 16649 if (args.certificates != null) { 16650 try { 16651 PackageParser.populateCertificates(pkg, args.certificates); 16652 } catch (PackageParserException e) { 16653 // there was something wrong with the certificates we were given; 16654 // try to pull them from the APK 16655 PackageParser.collectCertificates(pkg, parseFlags); 16656 } 16657 } else { 16658 PackageParser.collectCertificates(pkg, parseFlags); 16659 } 16660 } catch (PackageParserException e) { 16661 res.setError("Failed collect during installPackageLI", e); 16662 return; 16663 } 16664 16665 // Get rid of all references to package scan path via parser. 16666 pp = null; 16667 String oldCodePath = null; 16668 boolean systemApp = false; 16669 synchronized (mPackages) { 16670 // Check if installing already existing package 16671 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16672 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16673 if (pkg.mOriginalPackages != null 16674 && pkg.mOriginalPackages.contains(oldName) 16675 && mPackages.containsKey(oldName)) { 16676 // This package is derived from an original package, 16677 // and this device has been updating from that original 16678 // name. We must continue using the original name, so 16679 // rename the new package here. 16680 pkg.setPackageName(oldName); 16681 pkgName = pkg.packageName; 16682 replace = true; 16683 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16684 + oldName + " pkgName=" + pkgName); 16685 } else if (mPackages.containsKey(pkgName)) { 16686 // This package, under its official name, already exists 16687 // on the device; we should replace it. 16688 replace = true; 16689 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16690 } 16691 16692 // Child packages are installed through the parent package 16693 if (pkg.parentPackage != null) { 16694 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16695 "Package " + pkg.packageName + " is child of package " 16696 + pkg.parentPackage.parentPackage + ". Child packages " 16697 + "can be updated only through the parent package."); 16698 return; 16699 } 16700 16701 if (replace) { 16702 // Prevent apps opting out from runtime permissions 16703 PackageParser.Package oldPackage = mPackages.get(pkgName); 16704 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16705 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16706 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16707 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16708 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16709 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16710 + " doesn't support runtime permissions but the old" 16711 + " target SDK " + oldTargetSdk + " does."); 16712 return; 16713 } 16714 // Prevent apps from downgrading their targetSandbox. 16715 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16716 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16717 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16718 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16719 "Package " + pkg.packageName + " new target sandbox " 16720 + newTargetSandbox + " is incompatible with the previous value of" 16721 + oldTargetSandbox + "."); 16722 return; 16723 } 16724 16725 // Prevent installing of child packages 16726 if (oldPackage.parentPackage != null) { 16727 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16728 "Package " + pkg.packageName + " is child of package " 16729 + oldPackage.parentPackage + ". Child packages " 16730 + "can be updated only through the parent package."); 16731 return; 16732 } 16733 } 16734 } 16735 16736 PackageSetting ps = mSettings.mPackages.get(pkgName); 16737 if (ps != null) { 16738 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16739 16740 // Static shared libs have same package with different versions where 16741 // we internally use a synthetic package name to allow multiple versions 16742 // of the same package, therefore we need to compare signatures against 16743 // the package setting for the latest library version. 16744 PackageSetting signatureCheckPs = ps; 16745 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16746 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16747 if (libraryEntry != null) { 16748 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16749 } 16750 } 16751 16752 // Quick sanity check that we're signed correctly if updating; 16753 // we'll check this again later when scanning, but we want to 16754 // bail early here before tripping over redefined permissions. 16755 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16756 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16757 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16758 + pkg.packageName + " upgrade keys do not match the " 16759 + "previously installed version"); 16760 return; 16761 } 16762 } else { 16763 try { 16764 verifySignaturesLP(signatureCheckPs, pkg); 16765 } catch (PackageManagerException e) { 16766 res.setError(e.error, e.getMessage()); 16767 return; 16768 } 16769 } 16770 16771 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16772 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16773 systemApp = (ps.pkg.applicationInfo.flags & 16774 ApplicationInfo.FLAG_SYSTEM) != 0; 16775 } 16776 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16777 } 16778 16779 int N = pkg.permissions.size(); 16780 for (int i = N-1; i >= 0; i--) { 16781 PackageParser.Permission perm = pkg.permissions.get(i); 16782 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16783 16784 // Don't allow anyone but the platform to define ephemeral permissions. 16785 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16786 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16787 Slog.w(TAG, "Package " + pkg.packageName 16788 + " attempting to delcare ephemeral permission " 16789 + perm.info.name + "; Removing ephemeral."); 16790 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16791 } 16792 // Check whether the newly-scanned package wants to define an already-defined perm 16793 if (bp != null) { 16794 // If the defining package is signed with our cert, it's okay. This 16795 // also includes the "updating the same package" case, of course. 16796 // "updating same package" could also involve key-rotation. 16797 final boolean sigsOk; 16798 if (bp.sourcePackage.equals(pkg.packageName) 16799 && (bp.packageSetting instanceof PackageSetting) 16800 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16801 scanFlags))) { 16802 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16803 } else { 16804 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16805 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16806 } 16807 if (!sigsOk) { 16808 // If the owning package is the system itself, we log but allow 16809 // install to proceed; we fail the install on all other permission 16810 // redefinitions. 16811 if (!bp.sourcePackage.equals("android")) { 16812 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16813 + pkg.packageName + " attempting to redeclare permission " 16814 + perm.info.name + " already owned by " + bp.sourcePackage); 16815 res.origPermission = perm.info.name; 16816 res.origPackage = bp.sourcePackage; 16817 return; 16818 } else { 16819 Slog.w(TAG, "Package " + pkg.packageName 16820 + " attempting to redeclare system permission " 16821 + perm.info.name + "; ignoring new declaration"); 16822 pkg.permissions.remove(i); 16823 } 16824 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16825 // Prevent apps to change protection level to dangerous from any other 16826 // type as this would allow a privilege escalation where an app adds a 16827 // normal/signature permission in other app's group and later redefines 16828 // it as dangerous leading to the group auto-grant. 16829 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16830 == PermissionInfo.PROTECTION_DANGEROUS) { 16831 if (bp != null && !bp.isRuntime()) { 16832 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16833 + "non-runtime permission " + perm.info.name 16834 + " to runtime; keeping old protection level"); 16835 perm.info.protectionLevel = bp.protectionLevel; 16836 } 16837 } 16838 } 16839 } 16840 } 16841 } 16842 16843 if (systemApp) { 16844 if (onExternal) { 16845 // Abort update; system app can't be replaced with app on sdcard 16846 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16847 "Cannot install updates to system apps on sdcard"); 16848 return; 16849 } else if (instantApp) { 16850 // Abort update; system app can't be replaced with an instant app 16851 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16852 "Cannot update a system app with an instant app"); 16853 return; 16854 } 16855 } 16856 16857 if (args.move != null) { 16858 // We did an in-place move, so dex is ready to roll 16859 scanFlags |= SCAN_NO_DEX; 16860 scanFlags |= SCAN_MOVE; 16861 16862 synchronized (mPackages) { 16863 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16864 if (ps == null) { 16865 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16866 "Missing settings for moved package " + pkgName); 16867 } 16868 16869 // We moved the entire application as-is, so bring over the 16870 // previously derived ABI information. 16871 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16872 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16873 } 16874 16875 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16876 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16877 scanFlags |= SCAN_NO_DEX; 16878 16879 try { 16880 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16881 args.abiOverride : pkg.cpuAbiOverride); 16882 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16883 true /*extractLibs*/, mAppLib32InstallDir); 16884 } catch (PackageManagerException pme) { 16885 Slog.e(TAG, "Error deriving application ABI", pme); 16886 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16887 return; 16888 } 16889 16890 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16891 // Do not run PackageDexOptimizer through the local performDexOpt 16892 // method because `pkg` may not be in `mPackages` yet. 16893 // 16894 // Also, don't fail application installs if the dexopt step fails. 16895 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16896 null /* instructionSets */, false /* checkProfiles */, 16897 getCompilerFilterForReason(REASON_INSTALL), 16898 getOrCreateCompilerPackageStats(pkg), 16899 mDexManager.isUsedByOtherApps(pkg.packageName)); 16900 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16901 16902 // Notify BackgroundDexOptService that the package has been changed. 16903 // If this is an update of a package which used to fail to compile, 16904 // BDOS will remove it from its blacklist. 16905 // TODO: Layering violation 16906 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16907 } 16908 16909 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16910 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16911 return; 16912 } 16913 16914 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16915 16916 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16917 "installPackageLI")) { 16918 if (replace) { 16919 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16920 // Static libs have a synthetic package name containing the version 16921 // and cannot be updated as an update would get a new package name, 16922 // unless this is the exact same version code which is useful for 16923 // development. 16924 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16925 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16926 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16927 + "static-shared libs cannot be updated"); 16928 return; 16929 } 16930 } 16931 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16932 installerPackageName, res, args.installReason); 16933 } else { 16934 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16935 args.user, installerPackageName, volumeUuid, res, args.installReason); 16936 } 16937 } 16938 synchronized (mPackages) { 16939 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16940 if (ps != null) { 16941 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16942 ps.setUpdateAvailable(false /*updateAvailable*/); 16943 } 16944 16945 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16946 for (int i = 0; i < childCount; i++) { 16947 PackageParser.Package childPkg = pkg.childPackages.get(i); 16948 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16949 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16950 if (childPs != null) { 16951 childRes.newUsers = childPs.queryInstalledUsers( 16952 sUserManager.getUserIds(), true); 16953 } 16954 } 16955 16956 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16957 updateSequenceNumberLP(pkgName, res.newUsers); 16958 updateInstantAppInstallerLocked(); 16959 } 16960 } 16961 } 16962 16963 private void startIntentFilterVerifications(int userId, boolean replacing, 16964 PackageParser.Package pkg) { 16965 if (mIntentFilterVerifierComponent == null) { 16966 Slog.w(TAG, "No IntentFilter verification will not be done as " 16967 + "there is no IntentFilterVerifier available!"); 16968 return; 16969 } 16970 16971 final int verifierUid = getPackageUid( 16972 mIntentFilterVerifierComponent.getPackageName(), 16973 MATCH_DEBUG_TRIAGED_MISSING, 16974 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16975 16976 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16977 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16978 mHandler.sendMessage(msg); 16979 16980 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16981 for (int i = 0; i < childCount; i++) { 16982 PackageParser.Package childPkg = pkg.childPackages.get(i); 16983 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16984 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16985 mHandler.sendMessage(msg); 16986 } 16987 } 16988 16989 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16990 PackageParser.Package pkg) { 16991 int size = pkg.activities.size(); 16992 if (size == 0) { 16993 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16994 "No activity, so no need to verify any IntentFilter!"); 16995 return; 16996 } 16997 16998 final boolean hasDomainURLs = hasDomainURLs(pkg); 16999 if (!hasDomainURLs) { 17000 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17001 "No domain URLs, so no need to verify any IntentFilter!"); 17002 return; 17003 } 17004 17005 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17006 + " if any IntentFilter from the " + size 17007 + " Activities needs verification ..."); 17008 17009 int count = 0; 17010 final String packageName = pkg.packageName; 17011 17012 synchronized (mPackages) { 17013 // If this is a new install and we see that we've already run verification for this 17014 // package, we have nothing to do: it means the state was restored from backup. 17015 if (!replacing) { 17016 IntentFilterVerificationInfo ivi = 17017 mSettings.getIntentFilterVerificationLPr(packageName); 17018 if (ivi != null) { 17019 if (DEBUG_DOMAIN_VERIFICATION) { 17020 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17021 + ivi.getStatusString()); 17022 } 17023 return; 17024 } 17025 } 17026 17027 // If any filters need to be verified, then all need to be. 17028 boolean needToVerify = false; 17029 for (PackageParser.Activity a : pkg.activities) { 17030 for (ActivityIntentInfo filter : a.intents) { 17031 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17032 if (DEBUG_DOMAIN_VERIFICATION) { 17033 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17034 } 17035 needToVerify = true; 17036 break; 17037 } 17038 } 17039 } 17040 17041 if (needToVerify) { 17042 final int verificationId = mIntentFilterVerificationToken++; 17043 for (PackageParser.Activity a : pkg.activities) { 17044 for (ActivityIntentInfo filter : a.intents) { 17045 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17046 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17047 "Verification needed for IntentFilter:" + filter.toString()); 17048 mIntentFilterVerifier.addOneIntentFilterVerification( 17049 verifierUid, userId, verificationId, filter, packageName); 17050 count++; 17051 } 17052 } 17053 } 17054 } 17055 } 17056 17057 if (count > 0) { 17058 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17059 + " IntentFilter verification" + (count > 1 ? "s" : "") 17060 + " for userId:" + userId); 17061 mIntentFilterVerifier.startVerifications(userId); 17062 } else { 17063 if (DEBUG_DOMAIN_VERIFICATION) { 17064 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17065 } 17066 } 17067 } 17068 17069 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17070 final ComponentName cn = filter.activity.getComponentName(); 17071 final String packageName = cn.getPackageName(); 17072 17073 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17074 packageName); 17075 if (ivi == null) { 17076 return true; 17077 } 17078 int status = ivi.getStatus(); 17079 switch (status) { 17080 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17081 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17082 return true; 17083 17084 default: 17085 // Nothing to do 17086 return false; 17087 } 17088 } 17089 17090 private static boolean isMultiArch(ApplicationInfo info) { 17091 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17092 } 17093 17094 private static boolean isExternal(PackageParser.Package pkg) { 17095 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17096 } 17097 17098 private static boolean isExternal(PackageSetting ps) { 17099 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17100 } 17101 17102 private static boolean isSystemApp(PackageParser.Package pkg) { 17103 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17104 } 17105 17106 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17107 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17108 } 17109 17110 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17111 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17112 } 17113 17114 private static boolean isSystemApp(PackageSetting ps) { 17115 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17116 } 17117 17118 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17119 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17120 } 17121 17122 private int packageFlagsToInstallFlags(PackageSetting ps) { 17123 int installFlags = 0; 17124 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17125 // This existing package was an external ASEC install when we have 17126 // the external flag without a UUID 17127 installFlags |= PackageManager.INSTALL_EXTERNAL; 17128 } 17129 if (ps.isForwardLocked()) { 17130 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17131 } 17132 return installFlags; 17133 } 17134 17135 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17136 if (isExternal(pkg)) { 17137 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17138 return StorageManager.UUID_PRIMARY_PHYSICAL; 17139 } else { 17140 return pkg.volumeUuid; 17141 } 17142 } else { 17143 return StorageManager.UUID_PRIVATE_INTERNAL; 17144 } 17145 } 17146 17147 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17148 if (isExternal(pkg)) { 17149 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17150 return mSettings.getExternalVersion(); 17151 } else { 17152 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17153 } 17154 } else { 17155 return mSettings.getInternalVersion(); 17156 } 17157 } 17158 17159 private void deleteTempPackageFiles() { 17160 final FilenameFilter filter = new FilenameFilter() { 17161 public boolean accept(File dir, String name) { 17162 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17163 } 17164 }; 17165 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17166 file.delete(); 17167 } 17168 } 17169 17170 @Override 17171 public void deletePackageAsUser(String packageName, int versionCode, 17172 IPackageDeleteObserver observer, int userId, int flags) { 17173 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17174 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17175 } 17176 17177 @Override 17178 public void deletePackageVersioned(VersionedPackage versionedPackage, 17179 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17180 mContext.enforceCallingOrSelfPermission( 17181 android.Manifest.permission.DELETE_PACKAGES, null); 17182 Preconditions.checkNotNull(versionedPackage); 17183 Preconditions.checkNotNull(observer); 17184 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17185 PackageManager.VERSION_CODE_HIGHEST, 17186 Integer.MAX_VALUE, "versionCode must be >= -1"); 17187 17188 final String packageName = versionedPackage.getPackageName(); 17189 // TODO: We will change version code to long, so in the new API it is long 17190 final int versionCode = (int) versionedPackage.getVersionCode(); 17191 final String internalPackageName; 17192 synchronized (mPackages) { 17193 // Normalize package name to handle renamed packages and static libs 17194 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17195 // TODO: We will change version code to long, so in the new API it is long 17196 (int) versionedPackage.getVersionCode()); 17197 } 17198 17199 final int uid = Binder.getCallingUid(); 17200 if (!isOrphaned(internalPackageName) 17201 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17202 try { 17203 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17204 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17205 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17206 observer.onUserActionRequired(intent); 17207 } catch (RemoteException re) { 17208 } 17209 return; 17210 } 17211 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17212 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17213 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17214 mContext.enforceCallingOrSelfPermission( 17215 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17216 "deletePackage for user " + userId); 17217 } 17218 17219 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17220 try { 17221 observer.onPackageDeleted(packageName, 17222 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17223 } catch (RemoteException re) { 17224 } 17225 return; 17226 } 17227 17228 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17229 try { 17230 observer.onPackageDeleted(packageName, 17231 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17232 } catch (RemoteException re) { 17233 } 17234 return; 17235 } 17236 17237 if (DEBUG_REMOVE) { 17238 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17239 + " deleteAllUsers: " + deleteAllUsers + " version=" 17240 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17241 ? "VERSION_CODE_HIGHEST" : versionCode)); 17242 } 17243 // Queue up an async operation since the package deletion may take a little while. 17244 mHandler.post(new Runnable() { 17245 public void run() { 17246 mHandler.removeCallbacks(this); 17247 int returnCode; 17248 if (!deleteAllUsers) { 17249 returnCode = deletePackageX(internalPackageName, versionCode, 17250 userId, deleteFlags); 17251 } else { 17252 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17253 internalPackageName, users); 17254 // If nobody is blocking uninstall, proceed with delete for all users 17255 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17256 returnCode = deletePackageX(internalPackageName, versionCode, 17257 userId, deleteFlags); 17258 } else { 17259 // Otherwise uninstall individually for users with blockUninstalls=false 17260 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17261 for (int userId : users) { 17262 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17263 returnCode = deletePackageX(internalPackageName, versionCode, 17264 userId, userFlags); 17265 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17266 Slog.w(TAG, "Package delete failed for user " + userId 17267 + ", returnCode " + returnCode); 17268 } 17269 } 17270 } 17271 // The app has only been marked uninstalled for certain users. 17272 // We still need to report that delete was blocked 17273 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17274 } 17275 } 17276 try { 17277 observer.onPackageDeleted(packageName, returnCode, null); 17278 } catch (RemoteException e) { 17279 Log.i(TAG, "Observer no longer exists."); 17280 } //end catch 17281 } //end run 17282 }); 17283 } 17284 17285 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17286 if (pkg.staticSharedLibName != null) { 17287 return pkg.manifestPackageName; 17288 } 17289 return pkg.packageName; 17290 } 17291 17292 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17293 // Handle renamed packages 17294 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17295 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17296 17297 // Is this a static library? 17298 SparseArray<SharedLibraryEntry> versionedLib = 17299 mStaticLibsByDeclaringPackage.get(packageName); 17300 if (versionedLib == null || versionedLib.size() <= 0) { 17301 return packageName; 17302 } 17303 17304 // Figure out which lib versions the caller can see 17305 SparseIntArray versionsCallerCanSee = null; 17306 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17307 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17308 && callingAppId != Process.ROOT_UID) { 17309 versionsCallerCanSee = new SparseIntArray(); 17310 String libName = versionedLib.valueAt(0).info.getName(); 17311 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17312 if (uidPackages != null) { 17313 for (String uidPackage : uidPackages) { 17314 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17315 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17316 if (libIdx >= 0) { 17317 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17318 versionsCallerCanSee.append(libVersion, libVersion); 17319 } 17320 } 17321 } 17322 } 17323 17324 // Caller can see nothing - done 17325 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17326 return packageName; 17327 } 17328 17329 // Find the version the caller can see and the app version code 17330 SharedLibraryEntry highestVersion = null; 17331 final int versionCount = versionedLib.size(); 17332 for (int i = 0; i < versionCount; i++) { 17333 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17334 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17335 libEntry.info.getVersion()) < 0) { 17336 continue; 17337 } 17338 // TODO: We will change version code to long, so in the new API it is long 17339 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17340 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17341 if (libVersionCode == versionCode) { 17342 return libEntry.apk; 17343 } 17344 } else if (highestVersion == null) { 17345 highestVersion = libEntry; 17346 } else if (libVersionCode > highestVersion.info 17347 .getDeclaringPackage().getVersionCode()) { 17348 highestVersion = libEntry; 17349 } 17350 } 17351 17352 if (highestVersion != null) { 17353 return highestVersion.apk; 17354 } 17355 17356 return packageName; 17357 } 17358 17359 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17360 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17361 || callingUid == Process.SYSTEM_UID) { 17362 return true; 17363 } 17364 final int callingUserId = UserHandle.getUserId(callingUid); 17365 // If the caller installed the pkgName, then allow it to silently uninstall. 17366 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17367 return true; 17368 } 17369 17370 // Allow package verifier to silently uninstall. 17371 if (mRequiredVerifierPackage != null && 17372 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17373 return true; 17374 } 17375 17376 // Allow package uninstaller to silently uninstall. 17377 if (mRequiredUninstallerPackage != null && 17378 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17379 return true; 17380 } 17381 17382 // Allow storage manager to silently uninstall. 17383 if (mStorageManagerPackage != null && 17384 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17385 return true; 17386 } 17387 return false; 17388 } 17389 17390 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17391 int[] result = EMPTY_INT_ARRAY; 17392 for (int userId : userIds) { 17393 if (getBlockUninstallForUser(packageName, userId)) { 17394 result = ArrayUtils.appendInt(result, userId); 17395 } 17396 } 17397 return result; 17398 } 17399 17400 @Override 17401 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17402 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17403 } 17404 17405 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17406 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17407 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17408 try { 17409 if (dpm != null) { 17410 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17411 /* callingUserOnly =*/ false); 17412 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17413 : deviceOwnerComponentName.getPackageName(); 17414 // Does the package contains the device owner? 17415 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17416 // this check is probably not needed, since DO should be registered as a device 17417 // admin on some user too. (Original bug for this: b/17657954) 17418 if (packageName.equals(deviceOwnerPackageName)) { 17419 return true; 17420 } 17421 // Does it contain a device admin for any user? 17422 int[] users; 17423 if (userId == UserHandle.USER_ALL) { 17424 users = sUserManager.getUserIds(); 17425 } else { 17426 users = new int[]{userId}; 17427 } 17428 for (int i = 0; i < users.length; ++i) { 17429 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17430 return true; 17431 } 17432 } 17433 } 17434 } catch (RemoteException e) { 17435 } 17436 return false; 17437 } 17438 17439 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17440 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17441 } 17442 17443 /** 17444 * This method is an internal method that could be get invoked either 17445 * to delete an installed package or to clean up a failed installation. 17446 * After deleting an installed package, a broadcast is sent to notify any 17447 * listeners that the package has been removed. For cleaning up a failed 17448 * installation, the broadcast is not necessary since the package's 17449 * installation wouldn't have sent the initial broadcast either 17450 * The key steps in deleting a package are 17451 * deleting the package information in internal structures like mPackages, 17452 * deleting the packages base directories through installd 17453 * updating mSettings to reflect current status 17454 * persisting settings for later use 17455 * sending a broadcast if necessary 17456 */ 17457 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17458 final PackageRemovedInfo info = new PackageRemovedInfo(); 17459 final boolean res; 17460 17461 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17462 ? UserHandle.USER_ALL : userId; 17463 17464 if (isPackageDeviceAdmin(packageName, removeUser)) { 17465 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17466 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17467 } 17468 17469 PackageSetting uninstalledPs = null; 17470 PackageParser.Package pkg = null; 17471 17472 // for the uninstall-updates case and restricted profiles, remember the per- 17473 // user handle installed state 17474 int[] allUsers; 17475 synchronized (mPackages) { 17476 uninstalledPs = mSettings.mPackages.get(packageName); 17477 if (uninstalledPs == null) { 17478 Slog.w(TAG, "Not removing non-existent package " + packageName); 17479 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17480 } 17481 17482 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17483 && uninstalledPs.versionCode != versionCode) { 17484 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17485 + uninstalledPs.versionCode + " != " + versionCode); 17486 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17487 } 17488 17489 // Static shared libs can be declared by any package, so let us not 17490 // allow removing a package if it provides a lib others depend on. 17491 pkg = mPackages.get(packageName); 17492 if (pkg != null && pkg.staticSharedLibName != null) { 17493 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17494 pkg.staticSharedLibVersion); 17495 if (libEntry != null) { 17496 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17497 libEntry.info, 0, userId); 17498 if (!ArrayUtils.isEmpty(libClientPackages)) { 17499 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17500 + " hosting lib " + libEntry.info.getName() + " version " 17501 + libEntry.info.getVersion() + " used by " + libClientPackages); 17502 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17503 } 17504 } 17505 } 17506 17507 allUsers = sUserManager.getUserIds(); 17508 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17509 } 17510 17511 final int freezeUser; 17512 if (isUpdatedSystemApp(uninstalledPs) 17513 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17514 // We're downgrading a system app, which will apply to all users, so 17515 // freeze them all during the downgrade 17516 freezeUser = UserHandle.USER_ALL; 17517 } else { 17518 freezeUser = removeUser; 17519 } 17520 17521 synchronized (mInstallLock) { 17522 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17523 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17524 deleteFlags, "deletePackageX")) { 17525 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17526 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17527 } 17528 synchronized (mPackages) { 17529 if (res) { 17530 if (pkg != null) { 17531 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17532 } 17533 updateSequenceNumberLP(packageName, info.removedUsers); 17534 updateInstantAppInstallerLocked(); 17535 } 17536 } 17537 } 17538 17539 if (res) { 17540 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17541 info.sendPackageRemovedBroadcasts(killApp); 17542 info.sendSystemPackageUpdatedBroadcasts(); 17543 info.sendSystemPackageAppearedBroadcasts(); 17544 } 17545 // Force a gc here. 17546 Runtime.getRuntime().gc(); 17547 // Delete the resources here after sending the broadcast to let 17548 // other processes clean up before deleting resources. 17549 if (info.args != null) { 17550 synchronized (mInstallLock) { 17551 info.args.doPostDeleteLI(true); 17552 } 17553 } 17554 17555 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17556 } 17557 17558 class PackageRemovedInfo { 17559 String removedPackage; 17560 int uid = -1; 17561 int removedAppId = -1; 17562 int[] origUsers; 17563 int[] removedUsers = null; 17564 SparseArray<Integer> installReasons; 17565 boolean isRemovedPackageSystemUpdate = false; 17566 boolean isUpdate; 17567 boolean dataRemoved; 17568 boolean removedForAllUsers; 17569 boolean isStaticSharedLib; 17570 // Clean up resources deleted packages. 17571 InstallArgs args = null; 17572 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17573 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17574 17575 void sendPackageRemovedBroadcasts(boolean killApp) { 17576 sendPackageRemovedBroadcastInternal(killApp); 17577 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17578 for (int i = 0; i < childCount; i++) { 17579 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17580 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17581 } 17582 } 17583 17584 void sendSystemPackageUpdatedBroadcasts() { 17585 if (isRemovedPackageSystemUpdate) { 17586 sendSystemPackageUpdatedBroadcastsInternal(); 17587 final int childCount = (removedChildPackages != null) 17588 ? removedChildPackages.size() : 0; 17589 for (int i = 0; i < childCount; i++) { 17590 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17591 if (childInfo.isRemovedPackageSystemUpdate) { 17592 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17593 } 17594 } 17595 } 17596 } 17597 17598 void sendSystemPackageAppearedBroadcasts() { 17599 final int packageCount = (appearedChildPackages != null) 17600 ? appearedChildPackages.size() : 0; 17601 for (int i = 0; i < packageCount; i++) { 17602 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17603 sendPackageAddedForNewUsers(installedInfo.name, true, 17604 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17605 } 17606 } 17607 17608 private void sendSystemPackageUpdatedBroadcastsInternal() { 17609 Bundle extras = new Bundle(2); 17610 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17611 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17612 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17613 extras, 0, null, null, null); 17614 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17615 extras, 0, null, null, null); 17616 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17617 null, 0, removedPackage, null, null); 17618 } 17619 17620 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17621 // Don't send static shared library removal broadcasts as these 17622 // libs are visible only the the apps that depend on them an one 17623 // cannot remove the library if it has a dependency. 17624 if (isStaticSharedLib) { 17625 return; 17626 } 17627 Bundle extras = new Bundle(2); 17628 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17629 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17630 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17631 if (isUpdate || isRemovedPackageSystemUpdate) { 17632 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17633 } 17634 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17635 if (removedPackage != null) { 17636 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17637 extras, 0, null, null, removedUsers); 17638 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17639 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17640 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17641 null, null, removedUsers); 17642 } 17643 } 17644 if (removedAppId >= 0) { 17645 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17646 removedUsers); 17647 } 17648 } 17649 } 17650 17651 /* 17652 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17653 * flag is not set, the data directory is removed as well. 17654 * make sure this flag is set for partially installed apps. If not its meaningless to 17655 * delete a partially installed application. 17656 */ 17657 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17658 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17659 String packageName = ps.name; 17660 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17661 // Retrieve object to delete permissions for shared user later on 17662 final PackageParser.Package deletedPkg; 17663 final PackageSetting deletedPs; 17664 // reader 17665 synchronized (mPackages) { 17666 deletedPkg = mPackages.get(packageName); 17667 deletedPs = mSettings.mPackages.get(packageName); 17668 if (outInfo != null) { 17669 outInfo.removedPackage = packageName; 17670 outInfo.isStaticSharedLib = deletedPkg != null 17671 && deletedPkg.staticSharedLibName != null; 17672 outInfo.removedUsers = deletedPs != null 17673 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17674 : null; 17675 } 17676 } 17677 17678 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17679 17680 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17681 final PackageParser.Package resolvedPkg; 17682 if (deletedPkg != null) { 17683 resolvedPkg = deletedPkg; 17684 } else { 17685 // We don't have a parsed package when it lives on an ejected 17686 // adopted storage device, so fake something together 17687 resolvedPkg = new PackageParser.Package(ps.name); 17688 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17689 } 17690 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17691 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17692 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17693 if (outInfo != null) { 17694 outInfo.dataRemoved = true; 17695 } 17696 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17697 } 17698 17699 int removedAppId = -1; 17700 17701 // writer 17702 synchronized (mPackages) { 17703 boolean installedStateChanged = false; 17704 if (deletedPs != null) { 17705 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17706 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17707 clearDefaultBrowserIfNeeded(packageName); 17708 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17709 removedAppId = mSettings.removePackageLPw(packageName); 17710 if (outInfo != null) { 17711 outInfo.removedAppId = removedAppId; 17712 } 17713 updatePermissionsLPw(deletedPs.name, null, 0); 17714 if (deletedPs.sharedUser != null) { 17715 // Remove permissions associated with package. Since runtime 17716 // permissions are per user we have to kill the removed package 17717 // or packages running under the shared user of the removed 17718 // package if revoking the permissions requested only by the removed 17719 // package is successful and this causes a change in gids. 17720 for (int userId : UserManagerService.getInstance().getUserIds()) { 17721 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17722 userId); 17723 if (userIdToKill == UserHandle.USER_ALL 17724 || userIdToKill >= UserHandle.USER_SYSTEM) { 17725 // If gids changed for this user, kill all affected packages. 17726 mHandler.post(new Runnable() { 17727 @Override 17728 public void run() { 17729 // This has to happen with no lock held. 17730 killApplication(deletedPs.name, deletedPs.appId, 17731 KILL_APP_REASON_GIDS_CHANGED); 17732 } 17733 }); 17734 break; 17735 } 17736 } 17737 } 17738 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17739 } 17740 // make sure to preserve per-user disabled state if this removal was just 17741 // a downgrade of a system app to the factory package 17742 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17743 if (DEBUG_REMOVE) { 17744 Slog.d(TAG, "Propagating install state across downgrade"); 17745 } 17746 for (int userId : allUserHandles) { 17747 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17748 if (DEBUG_REMOVE) { 17749 Slog.d(TAG, " user " + userId + " => " + installed); 17750 } 17751 if (installed != ps.getInstalled(userId)) { 17752 installedStateChanged = true; 17753 } 17754 ps.setInstalled(installed, userId); 17755 } 17756 } 17757 } 17758 // can downgrade to reader 17759 if (writeSettings) { 17760 // Save settings now 17761 mSettings.writeLPr(); 17762 } 17763 if (installedStateChanged) { 17764 mSettings.writeKernelMappingLPr(ps); 17765 } 17766 } 17767 if (removedAppId != -1) { 17768 // A user ID was deleted here. Go through all users and remove it 17769 // from KeyStore. 17770 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17771 } 17772 } 17773 17774 static boolean locationIsPrivileged(File path) { 17775 try { 17776 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17777 .getCanonicalPath(); 17778 return path.getCanonicalPath().startsWith(privilegedAppDir); 17779 } catch (IOException e) { 17780 Slog.e(TAG, "Unable to access code path " + path); 17781 } 17782 return false; 17783 } 17784 17785 /* 17786 * Tries to delete system package. 17787 */ 17788 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17789 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17790 boolean writeSettings) { 17791 if (deletedPs.parentPackageName != null) { 17792 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17793 return false; 17794 } 17795 17796 final boolean applyUserRestrictions 17797 = (allUserHandles != null) && (outInfo.origUsers != null); 17798 final PackageSetting disabledPs; 17799 // Confirm if the system package has been updated 17800 // An updated system app can be deleted. This will also have to restore 17801 // the system pkg from system partition 17802 // reader 17803 synchronized (mPackages) { 17804 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17805 } 17806 17807 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17808 + " disabledPs=" + disabledPs); 17809 17810 if (disabledPs == null) { 17811 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17812 return false; 17813 } else if (DEBUG_REMOVE) { 17814 Slog.d(TAG, "Deleting system pkg from data partition"); 17815 } 17816 17817 if (DEBUG_REMOVE) { 17818 if (applyUserRestrictions) { 17819 Slog.d(TAG, "Remembering install states:"); 17820 for (int userId : allUserHandles) { 17821 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17822 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17823 } 17824 } 17825 } 17826 17827 // Delete the updated package 17828 outInfo.isRemovedPackageSystemUpdate = true; 17829 if (outInfo.removedChildPackages != null) { 17830 final int childCount = (deletedPs.childPackageNames != null) 17831 ? deletedPs.childPackageNames.size() : 0; 17832 for (int i = 0; i < childCount; i++) { 17833 String childPackageName = deletedPs.childPackageNames.get(i); 17834 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17835 .contains(childPackageName)) { 17836 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17837 childPackageName); 17838 if (childInfo != null) { 17839 childInfo.isRemovedPackageSystemUpdate = true; 17840 } 17841 } 17842 } 17843 } 17844 17845 if (disabledPs.versionCode < deletedPs.versionCode) { 17846 // Delete data for downgrades 17847 flags &= ~PackageManager.DELETE_KEEP_DATA; 17848 } else { 17849 // Preserve data by setting flag 17850 flags |= PackageManager.DELETE_KEEP_DATA; 17851 } 17852 17853 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17854 outInfo, writeSettings, disabledPs.pkg); 17855 if (!ret) { 17856 return false; 17857 } 17858 17859 // writer 17860 synchronized (mPackages) { 17861 // Reinstate the old system package 17862 enableSystemPackageLPw(disabledPs.pkg); 17863 // Remove any native libraries from the upgraded package. 17864 removeNativeBinariesLI(deletedPs); 17865 } 17866 17867 // Install the system package 17868 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17869 int parseFlags = mDefParseFlags 17870 | PackageParser.PARSE_MUST_BE_APK 17871 | PackageParser.PARSE_IS_SYSTEM 17872 | PackageParser.PARSE_IS_SYSTEM_DIR; 17873 if (locationIsPrivileged(disabledPs.codePath)) { 17874 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17875 } 17876 17877 final PackageParser.Package newPkg; 17878 try { 17879 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17880 0 /* currentTime */, null); 17881 } catch (PackageManagerException e) { 17882 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17883 + e.getMessage()); 17884 return false; 17885 } 17886 17887 try { 17888 // update shared libraries for the newly re-installed system package 17889 updateSharedLibrariesLPr(newPkg, null); 17890 } catch (PackageManagerException e) { 17891 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17892 } 17893 17894 prepareAppDataAfterInstallLIF(newPkg); 17895 17896 // writer 17897 synchronized (mPackages) { 17898 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17899 17900 // Propagate the permissions state as we do not want to drop on the floor 17901 // runtime permissions. The update permissions method below will take 17902 // care of removing obsolete permissions and grant install permissions. 17903 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17904 updatePermissionsLPw(newPkg.packageName, newPkg, 17905 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17906 17907 if (applyUserRestrictions) { 17908 boolean installedStateChanged = false; 17909 if (DEBUG_REMOVE) { 17910 Slog.d(TAG, "Propagating install state across reinstall"); 17911 } 17912 for (int userId : allUserHandles) { 17913 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17914 if (DEBUG_REMOVE) { 17915 Slog.d(TAG, " user " + userId + " => " + installed); 17916 } 17917 if (installed != ps.getInstalled(userId)) { 17918 installedStateChanged = true; 17919 } 17920 ps.setInstalled(installed, userId); 17921 17922 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17923 } 17924 // Regardless of writeSettings we need to ensure that this restriction 17925 // state propagation is persisted 17926 mSettings.writeAllUsersPackageRestrictionsLPr(); 17927 if (installedStateChanged) { 17928 mSettings.writeKernelMappingLPr(ps); 17929 } 17930 } 17931 // can downgrade to reader here 17932 if (writeSettings) { 17933 mSettings.writeLPr(); 17934 } 17935 } 17936 return true; 17937 } 17938 17939 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17940 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17941 PackageRemovedInfo outInfo, boolean writeSettings, 17942 PackageParser.Package replacingPackage) { 17943 synchronized (mPackages) { 17944 if (outInfo != null) { 17945 outInfo.uid = ps.appId; 17946 } 17947 17948 if (outInfo != null && outInfo.removedChildPackages != null) { 17949 final int childCount = (ps.childPackageNames != null) 17950 ? ps.childPackageNames.size() : 0; 17951 for (int i = 0; i < childCount; i++) { 17952 String childPackageName = ps.childPackageNames.get(i); 17953 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17954 if (childPs == null) { 17955 return false; 17956 } 17957 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17958 childPackageName); 17959 if (childInfo != null) { 17960 childInfo.uid = childPs.appId; 17961 } 17962 } 17963 } 17964 } 17965 17966 // Delete package data from internal structures and also remove data if flag is set 17967 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17968 17969 // Delete the child packages data 17970 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17971 for (int i = 0; i < childCount; i++) { 17972 PackageSetting childPs; 17973 synchronized (mPackages) { 17974 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17975 } 17976 if (childPs != null) { 17977 PackageRemovedInfo childOutInfo = (outInfo != null 17978 && outInfo.removedChildPackages != null) 17979 ? outInfo.removedChildPackages.get(childPs.name) : null; 17980 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17981 && (replacingPackage != null 17982 && !replacingPackage.hasChildPackage(childPs.name)) 17983 ? flags & ~DELETE_KEEP_DATA : flags; 17984 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17985 deleteFlags, writeSettings); 17986 } 17987 } 17988 17989 // Delete application code and resources only for parent packages 17990 if (ps.parentPackageName == null) { 17991 if (deleteCodeAndResources && (outInfo != null)) { 17992 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17993 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17994 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17995 } 17996 } 17997 17998 return true; 17999 } 18000 18001 @Override 18002 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18003 int userId) { 18004 mContext.enforceCallingOrSelfPermission( 18005 android.Manifest.permission.DELETE_PACKAGES, null); 18006 synchronized (mPackages) { 18007 PackageSetting ps = mSettings.mPackages.get(packageName); 18008 if (ps == null) { 18009 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18010 return false; 18011 } 18012 // Cannot block uninstall of static shared libs as they are 18013 // considered a part of the using app (emulating static linking). 18014 // Also static libs are installed always on internal storage. 18015 PackageParser.Package pkg = mPackages.get(packageName); 18016 if (pkg != null && pkg.staticSharedLibName != null) { 18017 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18018 + " providing static shared library: " + pkg.staticSharedLibName); 18019 return false; 18020 } 18021 if (!ps.getInstalled(userId)) { 18022 // Can't block uninstall for an app that is not installed or enabled. 18023 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18024 return false; 18025 } 18026 ps.setBlockUninstall(blockUninstall, userId); 18027 mSettings.writePackageRestrictionsLPr(userId); 18028 } 18029 return true; 18030 } 18031 18032 @Override 18033 public boolean getBlockUninstallForUser(String packageName, int userId) { 18034 synchronized (mPackages) { 18035 PackageSetting ps = mSettings.mPackages.get(packageName); 18036 if (ps == null) { 18037 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18038 return false; 18039 } 18040 return ps.getBlockUninstall(userId); 18041 } 18042 } 18043 18044 @Override 18045 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18046 int callingUid = Binder.getCallingUid(); 18047 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18048 throw new SecurityException( 18049 "setRequiredForSystemUser can only be run by the system or root"); 18050 } 18051 synchronized (mPackages) { 18052 PackageSetting ps = mSettings.mPackages.get(packageName); 18053 if (ps == null) { 18054 Log.w(TAG, "Package doesn't exist: " + packageName); 18055 return false; 18056 } 18057 if (systemUserApp) { 18058 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18059 } else { 18060 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18061 } 18062 mSettings.writeLPr(); 18063 } 18064 return true; 18065 } 18066 18067 /* 18068 * This method handles package deletion in general 18069 */ 18070 private boolean deletePackageLIF(String packageName, UserHandle user, 18071 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18072 PackageRemovedInfo outInfo, boolean writeSettings, 18073 PackageParser.Package replacingPackage) { 18074 if (packageName == null) { 18075 Slog.w(TAG, "Attempt to delete null packageName."); 18076 return false; 18077 } 18078 18079 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18080 18081 PackageSetting ps; 18082 synchronized (mPackages) { 18083 ps = mSettings.mPackages.get(packageName); 18084 if (ps == null) { 18085 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18086 return false; 18087 } 18088 18089 if (ps.parentPackageName != null && (!isSystemApp(ps) 18090 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18091 if (DEBUG_REMOVE) { 18092 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18093 + ((user == null) ? UserHandle.USER_ALL : user)); 18094 } 18095 final int removedUserId = (user != null) ? user.getIdentifier() 18096 : UserHandle.USER_ALL; 18097 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18098 return false; 18099 } 18100 markPackageUninstalledForUserLPw(ps, user); 18101 scheduleWritePackageRestrictionsLocked(user); 18102 return true; 18103 } 18104 } 18105 18106 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18107 && user.getIdentifier() != UserHandle.USER_ALL)) { 18108 // The caller is asking that the package only be deleted for a single 18109 // user. To do this, we just mark its uninstalled state and delete 18110 // its data. If this is a system app, we only allow this to happen if 18111 // they have set the special DELETE_SYSTEM_APP which requests different 18112 // semantics than normal for uninstalling system apps. 18113 markPackageUninstalledForUserLPw(ps, user); 18114 18115 if (!isSystemApp(ps)) { 18116 // Do not uninstall the APK if an app should be cached 18117 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18118 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18119 // Other user still have this package installed, so all 18120 // we need to do is clear this user's data and save that 18121 // it is uninstalled. 18122 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18123 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18124 return false; 18125 } 18126 scheduleWritePackageRestrictionsLocked(user); 18127 return true; 18128 } else { 18129 // We need to set it back to 'installed' so the uninstall 18130 // broadcasts will be sent correctly. 18131 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18132 ps.setInstalled(true, user.getIdentifier()); 18133 mSettings.writeKernelMappingLPr(ps); 18134 } 18135 } else { 18136 // This is a system app, so we assume that the 18137 // other users still have this package installed, so all 18138 // we need to do is clear this user's data and save that 18139 // it is uninstalled. 18140 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18141 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18142 return false; 18143 } 18144 scheduleWritePackageRestrictionsLocked(user); 18145 return true; 18146 } 18147 } 18148 18149 // If we are deleting a composite package for all users, keep track 18150 // of result for each child. 18151 if (ps.childPackageNames != null && outInfo != null) { 18152 synchronized (mPackages) { 18153 final int childCount = ps.childPackageNames.size(); 18154 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18155 for (int i = 0; i < childCount; i++) { 18156 String childPackageName = ps.childPackageNames.get(i); 18157 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18158 childInfo.removedPackage = childPackageName; 18159 outInfo.removedChildPackages.put(childPackageName, childInfo); 18160 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18161 if (childPs != null) { 18162 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18163 } 18164 } 18165 } 18166 } 18167 18168 boolean ret = false; 18169 if (isSystemApp(ps)) { 18170 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18171 // When an updated system application is deleted we delete the existing resources 18172 // as well and fall back to existing code in system partition 18173 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18174 } else { 18175 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18176 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18177 outInfo, writeSettings, replacingPackage); 18178 } 18179 18180 // Take a note whether we deleted the package for all users 18181 if (outInfo != null) { 18182 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18183 if (outInfo.removedChildPackages != null) { 18184 synchronized (mPackages) { 18185 final int childCount = outInfo.removedChildPackages.size(); 18186 for (int i = 0; i < childCount; i++) { 18187 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18188 if (childInfo != null) { 18189 childInfo.removedForAllUsers = mPackages.get( 18190 childInfo.removedPackage) == null; 18191 } 18192 } 18193 } 18194 } 18195 // If we uninstalled an update to a system app there may be some 18196 // child packages that appeared as they are declared in the system 18197 // app but were not declared in the update. 18198 if (isSystemApp(ps)) { 18199 synchronized (mPackages) { 18200 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18201 final int childCount = (updatedPs.childPackageNames != null) 18202 ? updatedPs.childPackageNames.size() : 0; 18203 for (int i = 0; i < childCount; i++) { 18204 String childPackageName = updatedPs.childPackageNames.get(i); 18205 if (outInfo.removedChildPackages == null 18206 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18207 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18208 if (childPs == null) { 18209 continue; 18210 } 18211 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18212 installRes.name = childPackageName; 18213 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18214 installRes.pkg = mPackages.get(childPackageName); 18215 installRes.uid = childPs.pkg.applicationInfo.uid; 18216 if (outInfo.appearedChildPackages == null) { 18217 outInfo.appearedChildPackages = new ArrayMap<>(); 18218 } 18219 outInfo.appearedChildPackages.put(childPackageName, installRes); 18220 } 18221 } 18222 } 18223 } 18224 } 18225 18226 return ret; 18227 } 18228 18229 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18230 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18231 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18232 for (int nextUserId : userIds) { 18233 if (DEBUG_REMOVE) { 18234 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18235 } 18236 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18237 false /*installed*/, 18238 true /*stopped*/, 18239 true /*notLaunched*/, 18240 false /*hidden*/, 18241 false /*suspended*/, 18242 false /*instantApp*/, 18243 null /*lastDisableAppCaller*/, 18244 null /*enabledComponents*/, 18245 null /*disabledComponents*/, 18246 false /*blockUninstall*/, 18247 ps.readUserState(nextUserId).domainVerificationStatus, 18248 0, PackageManager.INSTALL_REASON_UNKNOWN); 18249 } 18250 mSettings.writeKernelMappingLPr(ps); 18251 } 18252 18253 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18254 PackageRemovedInfo outInfo) { 18255 final PackageParser.Package pkg; 18256 synchronized (mPackages) { 18257 pkg = mPackages.get(ps.name); 18258 } 18259 18260 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18261 : new int[] {userId}; 18262 for (int nextUserId : userIds) { 18263 if (DEBUG_REMOVE) { 18264 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18265 + nextUserId); 18266 } 18267 18268 destroyAppDataLIF(pkg, userId, 18269 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18270 destroyAppProfilesLIF(pkg, userId); 18271 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18272 schedulePackageCleaning(ps.name, nextUserId, false); 18273 synchronized (mPackages) { 18274 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18275 scheduleWritePackageRestrictionsLocked(nextUserId); 18276 } 18277 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18278 } 18279 } 18280 18281 if (outInfo != null) { 18282 outInfo.removedPackage = ps.name; 18283 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18284 outInfo.removedAppId = ps.appId; 18285 outInfo.removedUsers = userIds; 18286 } 18287 18288 return true; 18289 } 18290 18291 private final class ClearStorageConnection implements ServiceConnection { 18292 IMediaContainerService mContainerService; 18293 18294 @Override 18295 public void onServiceConnected(ComponentName name, IBinder service) { 18296 synchronized (this) { 18297 mContainerService = IMediaContainerService.Stub 18298 .asInterface(Binder.allowBlocking(service)); 18299 notifyAll(); 18300 } 18301 } 18302 18303 @Override 18304 public void onServiceDisconnected(ComponentName name) { 18305 } 18306 } 18307 18308 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18309 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18310 18311 final boolean mounted; 18312 if (Environment.isExternalStorageEmulated()) { 18313 mounted = true; 18314 } else { 18315 final String status = Environment.getExternalStorageState(); 18316 18317 mounted = status.equals(Environment.MEDIA_MOUNTED) 18318 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18319 } 18320 18321 if (!mounted) { 18322 return; 18323 } 18324 18325 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18326 int[] users; 18327 if (userId == UserHandle.USER_ALL) { 18328 users = sUserManager.getUserIds(); 18329 } else { 18330 users = new int[] { userId }; 18331 } 18332 final ClearStorageConnection conn = new ClearStorageConnection(); 18333 if (mContext.bindServiceAsUser( 18334 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18335 try { 18336 for (int curUser : users) { 18337 long timeout = SystemClock.uptimeMillis() + 5000; 18338 synchronized (conn) { 18339 long now; 18340 while (conn.mContainerService == null && 18341 (now = SystemClock.uptimeMillis()) < timeout) { 18342 try { 18343 conn.wait(timeout - now); 18344 } catch (InterruptedException e) { 18345 } 18346 } 18347 } 18348 if (conn.mContainerService == null) { 18349 return; 18350 } 18351 18352 final UserEnvironment userEnv = new UserEnvironment(curUser); 18353 clearDirectory(conn.mContainerService, 18354 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18355 if (allData) { 18356 clearDirectory(conn.mContainerService, 18357 userEnv.buildExternalStorageAppDataDirs(packageName)); 18358 clearDirectory(conn.mContainerService, 18359 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18360 } 18361 } 18362 } finally { 18363 mContext.unbindService(conn); 18364 } 18365 } 18366 } 18367 18368 @Override 18369 public void clearApplicationProfileData(String packageName) { 18370 enforceSystemOrRoot("Only the system can clear all profile data"); 18371 18372 final PackageParser.Package pkg; 18373 synchronized (mPackages) { 18374 pkg = mPackages.get(packageName); 18375 } 18376 18377 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18378 synchronized (mInstallLock) { 18379 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18380 } 18381 } 18382 } 18383 18384 @Override 18385 public void clearApplicationUserData(final String packageName, 18386 final IPackageDataObserver observer, final int userId) { 18387 mContext.enforceCallingOrSelfPermission( 18388 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18389 18390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18391 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18392 18393 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18394 throw new SecurityException("Cannot clear data for a protected package: " 18395 + packageName); 18396 } 18397 // Queue up an async operation since the package deletion may take a little while. 18398 mHandler.post(new Runnable() { 18399 public void run() { 18400 mHandler.removeCallbacks(this); 18401 final boolean succeeded; 18402 try (PackageFreezer freezer = freezePackage(packageName, 18403 "clearApplicationUserData")) { 18404 synchronized (mInstallLock) { 18405 succeeded = clearApplicationUserDataLIF(packageName, userId); 18406 } 18407 clearExternalStorageDataSync(packageName, userId, true); 18408 synchronized (mPackages) { 18409 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18410 packageName, userId); 18411 } 18412 } 18413 if (succeeded) { 18414 // invoke DeviceStorageMonitor's update method to clear any notifications 18415 DeviceStorageMonitorInternal dsm = LocalServices 18416 .getService(DeviceStorageMonitorInternal.class); 18417 if (dsm != null) { 18418 dsm.checkMemory(); 18419 } 18420 } 18421 if(observer != null) { 18422 try { 18423 observer.onRemoveCompleted(packageName, succeeded); 18424 } catch (RemoteException e) { 18425 Log.i(TAG, "Observer no longer exists."); 18426 } 18427 } //end if observer 18428 } //end run 18429 }); 18430 } 18431 18432 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18433 if (packageName == null) { 18434 Slog.w(TAG, "Attempt to delete null packageName."); 18435 return false; 18436 } 18437 18438 // Try finding details about the requested package 18439 PackageParser.Package pkg; 18440 synchronized (mPackages) { 18441 pkg = mPackages.get(packageName); 18442 if (pkg == null) { 18443 final PackageSetting ps = mSettings.mPackages.get(packageName); 18444 if (ps != null) { 18445 pkg = ps.pkg; 18446 } 18447 } 18448 18449 if (pkg == null) { 18450 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18451 return false; 18452 } 18453 18454 PackageSetting ps = (PackageSetting) pkg.mExtras; 18455 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18456 } 18457 18458 clearAppDataLIF(pkg, userId, 18459 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18460 18461 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18462 removeKeystoreDataIfNeeded(userId, appId); 18463 18464 UserManagerInternal umInternal = getUserManagerInternal(); 18465 final int flags; 18466 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18467 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18468 } else if (umInternal.isUserRunning(userId)) { 18469 flags = StorageManager.FLAG_STORAGE_DE; 18470 } else { 18471 flags = 0; 18472 } 18473 prepareAppDataContentsLIF(pkg, userId, flags); 18474 18475 return true; 18476 } 18477 18478 /** 18479 * Reverts user permission state changes (permissions and flags) in 18480 * all packages for a given user. 18481 * 18482 * @param userId The device user for which to do a reset. 18483 */ 18484 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18485 final int packageCount = mPackages.size(); 18486 for (int i = 0; i < packageCount; i++) { 18487 PackageParser.Package pkg = mPackages.valueAt(i); 18488 PackageSetting ps = (PackageSetting) pkg.mExtras; 18489 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18490 } 18491 } 18492 18493 private void resetNetworkPolicies(int userId) { 18494 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18495 } 18496 18497 /** 18498 * Reverts user permission state changes (permissions and flags). 18499 * 18500 * @param ps The package for which to reset. 18501 * @param userId The device user for which to do a reset. 18502 */ 18503 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18504 final PackageSetting ps, final int userId) { 18505 if (ps.pkg == null) { 18506 return; 18507 } 18508 18509 // These are flags that can change base on user actions. 18510 final int userSettableMask = FLAG_PERMISSION_USER_SET 18511 | FLAG_PERMISSION_USER_FIXED 18512 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18513 | FLAG_PERMISSION_REVIEW_REQUIRED; 18514 18515 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18516 | FLAG_PERMISSION_POLICY_FIXED; 18517 18518 boolean writeInstallPermissions = false; 18519 boolean writeRuntimePermissions = false; 18520 18521 final int permissionCount = ps.pkg.requestedPermissions.size(); 18522 for (int i = 0; i < permissionCount; i++) { 18523 String permission = ps.pkg.requestedPermissions.get(i); 18524 18525 BasePermission bp = mSettings.mPermissions.get(permission); 18526 if (bp == null) { 18527 continue; 18528 } 18529 18530 // If shared user we just reset the state to which only this app contributed. 18531 if (ps.sharedUser != null) { 18532 boolean used = false; 18533 final int packageCount = ps.sharedUser.packages.size(); 18534 for (int j = 0; j < packageCount; j++) { 18535 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18536 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18537 && pkg.pkg.requestedPermissions.contains(permission)) { 18538 used = true; 18539 break; 18540 } 18541 } 18542 if (used) { 18543 continue; 18544 } 18545 } 18546 18547 PermissionsState permissionsState = ps.getPermissionsState(); 18548 18549 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18550 18551 // Always clear the user settable flags. 18552 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18553 bp.name) != null; 18554 // If permission review is enabled and this is a legacy app, mark the 18555 // permission as requiring a review as this is the initial state. 18556 int flags = 0; 18557 if (mPermissionReviewRequired 18558 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18559 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18560 } 18561 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18562 if (hasInstallState) { 18563 writeInstallPermissions = true; 18564 } else { 18565 writeRuntimePermissions = true; 18566 } 18567 } 18568 18569 // Below is only runtime permission handling. 18570 if (!bp.isRuntime()) { 18571 continue; 18572 } 18573 18574 // Never clobber system or policy. 18575 if ((oldFlags & policyOrSystemFlags) != 0) { 18576 continue; 18577 } 18578 18579 // If this permission was granted by default, make sure it is. 18580 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18581 if (permissionsState.grantRuntimePermission(bp, userId) 18582 != PERMISSION_OPERATION_FAILURE) { 18583 writeRuntimePermissions = true; 18584 } 18585 // If permission review is enabled the permissions for a legacy apps 18586 // are represented as constantly granted runtime ones, so don't revoke. 18587 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18588 // Otherwise, reset the permission. 18589 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18590 switch (revokeResult) { 18591 case PERMISSION_OPERATION_SUCCESS: 18592 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18593 writeRuntimePermissions = true; 18594 final int appId = ps.appId; 18595 mHandler.post(new Runnable() { 18596 @Override 18597 public void run() { 18598 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18599 } 18600 }); 18601 } break; 18602 } 18603 } 18604 } 18605 18606 // Synchronously write as we are taking permissions away. 18607 if (writeRuntimePermissions) { 18608 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18609 } 18610 18611 // Synchronously write as we are taking permissions away. 18612 if (writeInstallPermissions) { 18613 mSettings.writeLPr(); 18614 } 18615 } 18616 18617 /** 18618 * Remove entries from the keystore daemon. Will only remove it if the 18619 * {@code appId} is valid. 18620 */ 18621 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18622 if (appId < 0) { 18623 return; 18624 } 18625 18626 final KeyStore keyStore = KeyStore.getInstance(); 18627 if (keyStore != null) { 18628 if (userId == UserHandle.USER_ALL) { 18629 for (final int individual : sUserManager.getUserIds()) { 18630 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18631 } 18632 } else { 18633 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18634 } 18635 } else { 18636 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18637 } 18638 } 18639 18640 @Override 18641 public void deleteApplicationCacheFiles(final String packageName, 18642 final IPackageDataObserver observer) { 18643 final int userId = UserHandle.getCallingUserId(); 18644 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18645 } 18646 18647 @Override 18648 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18649 final IPackageDataObserver observer) { 18650 mContext.enforceCallingOrSelfPermission( 18651 android.Manifest.permission.DELETE_CACHE_FILES, null); 18652 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18653 /* requireFullPermission= */ true, /* checkShell= */ false, 18654 "delete application cache files"); 18655 18656 final PackageParser.Package pkg; 18657 synchronized (mPackages) { 18658 pkg = mPackages.get(packageName); 18659 } 18660 18661 // Queue up an async operation since the package deletion may take a little while. 18662 mHandler.post(new Runnable() { 18663 public void run() { 18664 synchronized (mInstallLock) { 18665 final int flags = StorageManager.FLAG_STORAGE_DE 18666 | StorageManager.FLAG_STORAGE_CE; 18667 // We're only clearing cache files, so we don't care if the 18668 // app is unfrozen and still able to run 18669 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18670 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18671 } 18672 clearExternalStorageDataSync(packageName, userId, false); 18673 if (observer != null) { 18674 try { 18675 observer.onRemoveCompleted(packageName, true); 18676 } catch (RemoteException e) { 18677 Log.i(TAG, "Observer no longer exists."); 18678 } 18679 } 18680 } 18681 }); 18682 } 18683 18684 @Override 18685 public void getPackageSizeInfo(final String packageName, int userHandle, 18686 final IPackageStatsObserver observer) { 18687 throw new UnsupportedOperationException( 18688 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18689 } 18690 18691 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18692 final PackageSetting ps; 18693 synchronized (mPackages) { 18694 ps = mSettings.mPackages.get(packageName); 18695 if (ps == null) { 18696 Slog.w(TAG, "Failed to find settings for " + packageName); 18697 return false; 18698 } 18699 } 18700 18701 final String[] packageNames = { packageName }; 18702 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18703 final String[] codePaths = { ps.codePathString }; 18704 18705 try { 18706 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18707 ps.appId, ceDataInodes, codePaths, stats); 18708 18709 // For now, ignore code size of packages on system partition 18710 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18711 stats.codeSize = 0; 18712 } 18713 18714 // External clients expect these to be tracked separately 18715 stats.dataSize -= stats.cacheSize; 18716 18717 } catch (InstallerException e) { 18718 Slog.w(TAG, String.valueOf(e)); 18719 return false; 18720 } 18721 18722 return true; 18723 } 18724 18725 private int getUidTargetSdkVersionLockedLPr(int uid) { 18726 Object obj = mSettings.getUserIdLPr(uid); 18727 if (obj instanceof SharedUserSetting) { 18728 final SharedUserSetting sus = (SharedUserSetting) obj; 18729 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18730 final Iterator<PackageSetting> it = sus.packages.iterator(); 18731 while (it.hasNext()) { 18732 final PackageSetting ps = it.next(); 18733 if (ps.pkg != null) { 18734 int v = ps.pkg.applicationInfo.targetSdkVersion; 18735 if (v < vers) vers = v; 18736 } 18737 } 18738 return vers; 18739 } else if (obj instanceof PackageSetting) { 18740 final PackageSetting ps = (PackageSetting) obj; 18741 if (ps.pkg != null) { 18742 return ps.pkg.applicationInfo.targetSdkVersion; 18743 } 18744 } 18745 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18746 } 18747 18748 @Override 18749 public void addPreferredActivity(IntentFilter filter, int match, 18750 ComponentName[] set, ComponentName activity, int userId) { 18751 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18752 "Adding preferred"); 18753 } 18754 18755 private void addPreferredActivityInternal(IntentFilter filter, int match, 18756 ComponentName[] set, ComponentName activity, boolean always, int userId, 18757 String opname) { 18758 // writer 18759 int callingUid = Binder.getCallingUid(); 18760 enforceCrossUserPermission(callingUid, userId, 18761 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18762 if (filter.countActions() == 0) { 18763 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18764 return; 18765 } 18766 synchronized (mPackages) { 18767 if (mContext.checkCallingOrSelfPermission( 18768 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18769 != PackageManager.PERMISSION_GRANTED) { 18770 if (getUidTargetSdkVersionLockedLPr(callingUid) 18771 < Build.VERSION_CODES.FROYO) { 18772 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18773 + callingUid); 18774 return; 18775 } 18776 mContext.enforceCallingOrSelfPermission( 18777 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18778 } 18779 18780 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18781 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18782 + userId + ":"); 18783 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18784 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18785 scheduleWritePackageRestrictionsLocked(userId); 18786 postPreferredActivityChangedBroadcast(userId); 18787 } 18788 } 18789 18790 private void postPreferredActivityChangedBroadcast(int userId) { 18791 mHandler.post(() -> { 18792 final IActivityManager am = ActivityManager.getService(); 18793 if (am == null) { 18794 return; 18795 } 18796 18797 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18798 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18799 try { 18800 am.broadcastIntent(null, intent, null, null, 18801 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18802 null, false, false, userId); 18803 } catch (RemoteException e) { 18804 } 18805 }); 18806 } 18807 18808 @Override 18809 public void replacePreferredActivity(IntentFilter filter, int match, 18810 ComponentName[] set, ComponentName activity, int userId) { 18811 if (filter.countActions() != 1) { 18812 throw new IllegalArgumentException( 18813 "replacePreferredActivity expects filter to have only 1 action."); 18814 } 18815 if (filter.countDataAuthorities() != 0 18816 || filter.countDataPaths() != 0 18817 || filter.countDataSchemes() > 1 18818 || filter.countDataTypes() != 0) { 18819 throw new IllegalArgumentException( 18820 "replacePreferredActivity expects filter to have no data authorities, " + 18821 "paths, or types; and at most one scheme."); 18822 } 18823 18824 final int callingUid = Binder.getCallingUid(); 18825 enforceCrossUserPermission(callingUid, userId, 18826 true /* requireFullPermission */, false /* checkShell */, 18827 "replace preferred activity"); 18828 synchronized (mPackages) { 18829 if (mContext.checkCallingOrSelfPermission( 18830 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18831 != PackageManager.PERMISSION_GRANTED) { 18832 if (getUidTargetSdkVersionLockedLPr(callingUid) 18833 < Build.VERSION_CODES.FROYO) { 18834 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18835 + Binder.getCallingUid()); 18836 return; 18837 } 18838 mContext.enforceCallingOrSelfPermission( 18839 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18840 } 18841 18842 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18843 if (pir != null) { 18844 // Get all of the existing entries that exactly match this filter. 18845 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18846 if (existing != null && existing.size() == 1) { 18847 PreferredActivity cur = existing.get(0); 18848 if (DEBUG_PREFERRED) { 18849 Slog.i(TAG, "Checking replace of preferred:"); 18850 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18851 if (!cur.mPref.mAlways) { 18852 Slog.i(TAG, " -- CUR; not mAlways!"); 18853 } else { 18854 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18855 Slog.i(TAG, " -- CUR: mSet=" 18856 + Arrays.toString(cur.mPref.mSetComponents)); 18857 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18858 Slog.i(TAG, " -- NEW: mMatch=" 18859 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18860 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18861 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18862 } 18863 } 18864 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18865 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18866 && cur.mPref.sameSet(set)) { 18867 // Setting the preferred activity to what it happens to be already 18868 if (DEBUG_PREFERRED) { 18869 Slog.i(TAG, "Replacing with same preferred activity " 18870 + cur.mPref.mShortComponent + " for user " 18871 + userId + ":"); 18872 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18873 } 18874 return; 18875 } 18876 } 18877 18878 if (existing != null) { 18879 if (DEBUG_PREFERRED) { 18880 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18881 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18882 } 18883 for (int i = 0; i < existing.size(); i++) { 18884 PreferredActivity pa = existing.get(i); 18885 if (DEBUG_PREFERRED) { 18886 Slog.i(TAG, "Removing existing preferred activity " 18887 + pa.mPref.mComponent + ":"); 18888 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18889 } 18890 pir.removeFilter(pa); 18891 } 18892 } 18893 } 18894 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18895 "Replacing preferred"); 18896 } 18897 } 18898 18899 @Override 18900 public void clearPackagePreferredActivities(String packageName) { 18901 final int uid = Binder.getCallingUid(); 18902 // writer 18903 synchronized (mPackages) { 18904 PackageParser.Package pkg = mPackages.get(packageName); 18905 if (pkg == null || pkg.applicationInfo.uid != uid) { 18906 if (mContext.checkCallingOrSelfPermission( 18907 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18908 != PackageManager.PERMISSION_GRANTED) { 18909 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18910 < Build.VERSION_CODES.FROYO) { 18911 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18912 + Binder.getCallingUid()); 18913 return; 18914 } 18915 mContext.enforceCallingOrSelfPermission( 18916 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18917 } 18918 } 18919 18920 int user = UserHandle.getCallingUserId(); 18921 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18922 scheduleWritePackageRestrictionsLocked(user); 18923 } 18924 } 18925 } 18926 18927 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18928 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18929 ArrayList<PreferredActivity> removed = null; 18930 boolean changed = false; 18931 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18932 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18933 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18934 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18935 continue; 18936 } 18937 Iterator<PreferredActivity> it = pir.filterIterator(); 18938 while (it.hasNext()) { 18939 PreferredActivity pa = it.next(); 18940 // Mark entry for removal only if it matches the package name 18941 // and the entry is of type "always". 18942 if (packageName == null || 18943 (pa.mPref.mComponent.getPackageName().equals(packageName) 18944 && pa.mPref.mAlways)) { 18945 if (removed == null) { 18946 removed = new ArrayList<PreferredActivity>(); 18947 } 18948 removed.add(pa); 18949 } 18950 } 18951 if (removed != null) { 18952 for (int j=0; j<removed.size(); j++) { 18953 PreferredActivity pa = removed.get(j); 18954 pir.removeFilter(pa); 18955 } 18956 changed = true; 18957 } 18958 } 18959 if (changed) { 18960 postPreferredActivityChangedBroadcast(userId); 18961 } 18962 return changed; 18963 } 18964 18965 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18966 private void clearIntentFilterVerificationsLPw(int userId) { 18967 final int packageCount = mPackages.size(); 18968 for (int i = 0; i < packageCount; i++) { 18969 PackageParser.Package pkg = mPackages.valueAt(i); 18970 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18971 } 18972 } 18973 18974 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18975 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18976 if (userId == UserHandle.USER_ALL) { 18977 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18978 sUserManager.getUserIds())) { 18979 for (int oneUserId : sUserManager.getUserIds()) { 18980 scheduleWritePackageRestrictionsLocked(oneUserId); 18981 } 18982 } 18983 } else { 18984 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18985 scheduleWritePackageRestrictionsLocked(userId); 18986 } 18987 } 18988 } 18989 18990 void clearDefaultBrowserIfNeeded(String packageName) { 18991 for (int oneUserId : sUserManager.getUserIds()) { 18992 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18993 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18994 if (packageName.equals(defaultBrowserPackageName)) { 18995 setDefaultBrowserPackageName(null, oneUserId); 18996 } 18997 } 18998 } 18999 19000 @Override 19001 public void resetApplicationPreferences(int userId) { 19002 mContext.enforceCallingOrSelfPermission( 19003 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19004 final long identity = Binder.clearCallingIdentity(); 19005 // writer 19006 try { 19007 synchronized (mPackages) { 19008 clearPackagePreferredActivitiesLPw(null, userId); 19009 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19010 // TODO: We have to reset the default SMS and Phone. This requires 19011 // significant refactoring to keep all default apps in the package 19012 // manager (cleaner but more work) or have the services provide 19013 // callbacks to the package manager to request a default app reset. 19014 applyFactoryDefaultBrowserLPw(userId); 19015 clearIntentFilterVerificationsLPw(userId); 19016 primeDomainVerificationsLPw(userId); 19017 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19018 scheduleWritePackageRestrictionsLocked(userId); 19019 } 19020 resetNetworkPolicies(userId); 19021 } finally { 19022 Binder.restoreCallingIdentity(identity); 19023 } 19024 } 19025 19026 @Override 19027 public int getPreferredActivities(List<IntentFilter> outFilters, 19028 List<ComponentName> outActivities, String packageName) { 19029 19030 int num = 0; 19031 final int userId = UserHandle.getCallingUserId(); 19032 // reader 19033 synchronized (mPackages) { 19034 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19035 if (pir != null) { 19036 final Iterator<PreferredActivity> it = pir.filterIterator(); 19037 while (it.hasNext()) { 19038 final PreferredActivity pa = it.next(); 19039 if (packageName == null 19040 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19041 && pa.mPref.mAlways)) { 19042 if (outFilters != null) { 19043 outFilters.add(new IntentFilter(pa)); 19044 } 19045 if (outActivities != null) { 19046 outActivities.add(pa.mPref.mComponent); 19047 } 19048 } 19049 } 19050 } 19051 } 19052 19053 return num; 19054 } 19055 19056 @Override 19057 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19058 int userId) { 19059 int callingUid = Binder.getCallingUid(); 19060 if (callingUid != Process.SYSTEM_UID) { 19061 throw new SecurityException( 19062 "addPersistentPreferredActivity can only be run by the system"); 19063 } 19064 if (filter.countActions() == 0) { 19065 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19066 return; 19067 } 19068 synchronized (mPackages) { 19069 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19070 ":"); 19071 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19072 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19073 new PersistentPreferredActivity(filter, activity)); 19074 scheduleWritePackageRestrictionsLocked(userId); 19075 postPreferredActivityChangedBroadcast(userId); 19076 } 19077 } 19078 19079 @Override 19080 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19081 int callingUid = Binder.getCallingUid(); 19082 if (callingUid != Process.SYSTEM_UID) { 19083 throw new SecurityException( 19084 "clearPackagePersistentPreferredActivities can only be run by the system"); 19085 } 19086 ArrayList<PersistentPreferredActivity> removed = null; 19087 boolean changed = false; 19088 synchronized (mPackages) { 19089 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19090 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19091 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19092 .valueAt(i); 19093 if (userId != thisUserId) { 19094 continue; 19095 } 19096 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19097 while (it.hasNext()) { 19098 PersistentPreferredActivity ppa = it.next(); 19099 // Mark entry for removal only if it matches the package name. 19100 if (ppa.mComponent.getPackageName().equals(packageName)) { 19101 if (removed == null) { 19102 removed = new ArrayList<PersistentPreferredActivity>(); 19103 } 19104 removed.add(ppa); 19105 } 19106 } 19107 if (removed != null) { 19108 for (int j=0; j<removed.size(); j++) { 19109 PersistentPreferredActivity ppa = removed.get(j); 19110 ppir.removeFilter(ppa); 19111 } 19112 changed = true; 19113 } 19114 } 19115 19116 if (changed) { 19117 scheduleWritePackageRestrictionsLocked(userId); 19118 postPreferredActivityChangedBroadcast(userId); 19119 } 19120 } 19121 } 19122 19123 /** 19124 * Common machinery for picking apart a restored XML blob and passing 19125 * it to a caller-supplied functor to be applied to the running system. 19126 */ 19127 private void restoreFromXml(XmlPullParser parser, int userId, 19128 String expectedStartTag, BlobXmlRestorer functor) 19129 throws IOException, XmlPullParserException { 19130 int type; 19131 while ((type = parser.next()) != XmlPullParser.START_TAG 19132 && type != XmlPullParser.END_DOCUMENT) { 19133 } 19134 if (type != XmlPullParser.START_TAG) { 19135 // oops didn't find a start tag?! 19136 if (DEBUG_BACKUP) { 19137 Slog.e(TAG, "Didn't find start tag during restore"); 19138 } 19139 return; 19140 } 19141Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19142 // this is supposed to be TAG_PREFERRED_BACKUP 19143 if (!expectedStartTag.equals(parser.getName())) { 19144 if (DEBUG_BACKUP) { 19145 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19146 } 19147 return; 19148 } 19149 19150 // skip interfering stuff, then we're aligned with the backing implementation 19151 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19152Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19153 functor.apply(parser, userId); 19154 } 19155 19156 private interface BlobXmlRestorer { 19157 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19158 } 19159 19160 /** 19161 * Non-Binder method, support for the backup/restore mechanism: write the 19162 * full set of preferred activities in its canonical XML format. Returns the 19163 * XML output as a byte array, or null if there is none. 19164 */ 19165 @Override 19166 public byte[] getPreferredActivityBackup(int userId) { 19167 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19168 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19169 } 19170 19171 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19172 try { 19173 final XmlSerializer serializer = new FastXmlSerializer(); 19174 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19175 serializer.startDocument(null, true); 19176 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19177 19178 synchronized (mPackages) { 19179 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19180 } 19181 19182 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19183 serializer.endDocument(); 19184 serializer.flush(); 19185 } catch (Exception e) { 19186 if (DEBUG_BACKUP) { 19187 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19188 } 19189 return null; 19190 } 19191 19192 return dataStream.toByteArray(); 19193 } 19194 19195 @Override 19196 public void restorePreferredActivities(byte[] backup, int userId) { 19197 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19198 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19199 } 19200 19201 try { 19202 final XmlPullParser parser = Xml.newPullParser(); 19203 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19204 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19205 new BlobXmlRestorer() { 19206 @Override 19207 public void apply(XmlPullParser parser, int userId) 19208 throws XmlPullParserException, IOException { 19209 synchronized (mPackages) { 19210 mSettings.readPreferredActivitiesLPw(parser, userId); 19211 } 19212 } 19213 } ); 19214 } catch (Exception e) { 19215 if (DEBUG_BACKUP) { 19216 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19217 } 19218 } 19219 } 19220 19221 /** 19222 * Non-Binder method, support for the backup/restore mechanism: write the 19223 * default browser (etc) settings in its canonical XML format. Returns the default 19224 * browser XML representation as a byte array, or null if there is none. 19225 */ 19226 @Override 19227 public byte[] getDefaultAppsBackup(int userId) { 19228 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19229 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19230 } 19231 19232 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19233 try { 19234 final XmlSerializer serializer = new FastXmlSerializer(); 19235 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19236 serializer.startDocument(null, true); 19237 serializer.startTag(null, TAG_DEFAULT_APPS); 19238 19239 synchronized (mPackages) { 19240 mSettings.writeDefaultAppsLPr(serializer, userId); 19241 } 19242 19243 serializer.endTag(null, TAG_DEFAULT_APPS); 19244 serializer.endDocument(); 19245 serializer.flush(); 19246 } catch (Exception e) { 19247 if (DEBUG_BACKUP) { 19248 Slog.e(TAG, "Unable to write default apps for backup", e); 19249 } 19250 return null; 19251 } 19252 19253 return dataStream.toByteArray(); 19254 } 19255 19256 @Override 19257 public void restoreDefaultApps(byte[] backup, int userId) { 19258 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19259 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19260 } 19261 19262 try { 19263 final XmlPullParser parser = Xml.newPullParser(); 19264 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19265 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19266 new BlobXmlRestorer() { 19267 @Override 19268 public void apply(XmlPullParser parser, int userId) 19269 throws XmlPullParserException, IOException { 19270 synchronized (mPackages) { 19271 mSettings.readDefaultAppsLPw(parser, userId); 19272 } 19273 } 19274 } ); 19275 } catch (Exception e) { 19276 if (DEBUG_BACKUP) { 19277 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19278 } 19279 } 19280 } 19281 19282 @Override 19283 public byte[] getIntentFilterVerificationBackup(int userId) { 19284 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19285 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19286 } 19287 19288 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19289 try { 19290 final XmlSerializer serializer = new FastXmlSerializer(); 19291 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19292 serializer.startDocument(null, true); 19293 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19294 19295 synchronized (mPackages) { 19296 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19297 } 19298 19299 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19300 serializer.endDocument(); 19301 serializer.flush(); 19302 } catch (Exception e) { 19303 if (DEBUG_BACKUP) { 19304 Slog.e(TAG, "Unable to write default apps for backup", e); 19305 } 19306 return null; 19307 } 19308 19309 return dataStream.toByteArray(); 19310 } 19311 19312 @Override 19313 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19314 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19315 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19316 } 19317 19318 try { 19319 final XmlPullParser parser = Xml.newPullParser(); 19320 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19321 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19322 new BlobXmlRestorer() { 19323 @Override 19324 public void apply(XmlPullParser parser, int userId) 19325 throws XmlPullParserException, IOException { 19326 synchronized (mPackages) { 19327 mSettings.readAllDomainVerificationsLPr(parser, userId); 19328 mSettings.writeLPr(); 19329 } 19330 } 19331 } ); 19332 } catch (Exception e) { 19333 if (DEBUG_BACKUP) { 19334 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19335 } 19336 } 19337 } 19338 19339 @Override 19340 public byte[] getPermissionGrantBackup(int userId) { 19341 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19342 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19343 } 19344 19345 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19346 try { 19347 final XmlSerializer serializer = new FastXmlSerializer(); 19348 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19349 serializer.startDocument(null, true); 19350 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19351 19352 synchronized (mPackages) { 19353 serializeRuntimePermissionGrantsLPr(serializer, userId); 19354 } 19355 19356 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19357 serializer.endDocument(); 19358 serializer.flush(); 19359 } catch (Exception e) { 19360 if (DEBUG_BACKUP) { 19361 Slog.e(TAG, "Unable to write default apps for backup", e); 19362 } 19363 return null; 19364 } 19365 19366 return dataStream.toByteArray(); 19367 } 19368 19369 @Override 19370 public void restorePermissionGrants(byte[] backup, int userId) { 19371 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19372 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19373 } 19374 19375 try { 19376 final XmlPullParser parser = Xml.newPullParser(); 19377 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19378 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19379 new BlobXmlRestorer() { 19380 @Override 19381 public void apply(XmlPullParser parser, int userId) 19382 throws XmlPullParserException, IOException { 19383 synchronized (mPackages) { 19384 processRestoredPermissionGrantsLPr(parser, userId); 19385 } 19386 } 19387 } ); 19388 } catch (Exception e) { 19389 if (DEBUG_BACKUP) { 19390 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19391 } 19392 } 19393 } 19394 19395 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19396 throws IOException { 19397 serializer.startTag(null, TAG_ALL_GRANTS); 19398 19399 final int N = mSettings.mPackages.size(); 19400 for (int i = 0; i < N; i++) { 19401 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19402 boolean pkgGrantsKnown = false; 19403 19404 PermissionsState packagePerms = ps.getPermissionsState(); 19405 19406 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19407 final int grantFlags = state.getFlags(); 19408 // only look at grants that are not system/policy fixed 19409 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19410 final boolean isGranted = state.isGranted(); 19411 // And only back up the user-twiddled state bits 19412 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19413 final String packageName = mSettings.mPackages.keyAt(i); 19414 if (!pkgGrantsKnown) { 19415 serializer.startTag(null, TAG_GRANT); 19416 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19417 pkgGrantsKnown = true; 19418 } 19419 19420 final boolean userSet = 19421 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19422 final boolean userFixed = 19423 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19424 final boolean revoke = 19425 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19426 19427 serializer.startTag(null, TAG_PERMISSION); 19428 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19429 if (isGranted) { 19430 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19431 } 19432 if (userSet) { 19433 serializer.attribute(null, ATTR_USER_SET, "true"); 19434 } 19435 if (userFixed) { 19436 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19437 } 19438 if (revoke) { 19439 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19440 } 19441 serializer.endTag(null, TAG_PERMISSION); 19442 } 19443 } 19444 } 19445 19446 if (pkgGrantsKnown) { 19447 serializer.endTag(null, TAG_GRANT); 19448 } 19449 } 19450 19451 serializer.endTag(null, TAG_ALL_GRANTS); 19452 } 19453 19454 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19455 throws XmlPullParserException, IOException { 19456 String pkgName = null; 19457 int outerDepth = parser.getDepth(); 19458 int type; 19459 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19460 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19461 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19462 continue; 19463 } 19464 19465 final String tagName = parser.getName(); 19466 if (tagName.equals(TAG_GRANT)) { 19467 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19468 if (DEBUG_BACKUP) { 19469 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19470 } 19471 } else if (tagName.equals(TAG_PERMISSION)) { 19472 19473 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19474 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19475 19476 int newFlagSet = 0; 19477 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19478 newFlagSet |= FLAG_PERMISSION_USER_SET; 19479 } 19480 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19481 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19482 } 19483 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19484 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19485 } 19486 if (DEBUG_BACKUP) { 19487 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19488 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19489 } 19490 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19491 if (ps != null) { 19492 // Already installed so we apply the grant immediately 19493 if (DEBUG_BACKUP) { 19494 Slog.v(TAG, " + already installed; applying"); 19495 } 19496 PermissionsState perms = ps.getPermissionsState(); 19497 BasePermission bp = mSettings.mPermissions.get(permName); 19498 if (bp != null) { 19499 if (isGranted) { 19500 perms.grantRuntimePermission(bp, userId); 19501 } 19502 if (newFlagSet != 0) { 19503 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19504 } 19505 } 19506 } else { 19507 // Need to wait for post-restore install to apply the grant 19508 if (DEBUG_BACKUP) { 19509 Slog.v(TAG, " - not yet installed; saving for later"); 19510 } 19511 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19512 isGranted, newFlagSet, userId); 19513 } 19514 } else { 19515 PackageManagerService.reportSettingsProblem(Log.WARN, 19516 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19517 XmlUtils.skipCurrentTag(parser); 19518 } 19519 } 19520 19521 scheduleWriteSettingsLocked(); 19522 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19523 } 19524 19525 @Override 19526 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19527 int sourceUserId, int targetUserId, int flags) { 19528 mContext.enforceCallingOrSelfPermission( 19529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19530 int callingUid = Binder.getCallingUid(); 19531 enforceOwnerRights(ownerPackage, callingUid); 19532 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19533 if (intentFilter.countActions() == 0) { 19534 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19535 return; 19536 } 19537 synchronized (mPackages) { 19538 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19539 ownerPackage, targetUserId, flags); 19540 CrossProfileIntentResolver resolver = 19541 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19542 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19543 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19544 if (existing != null) { 19545 int size = existing.size(); 19546 for (int i = 0; i < size; i++) { 19547 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19548 return; 19549 } 19550 } 19551 } 19552 resolver.addFilter(newFilter); 19553 scheduleWritePackageRestrictionsLocked(sourceUserId); 19554 } 19555 } 19556 19557 @Override 19558 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19559 mContext.enforceCallingOrSelfPermission( 19560 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19561 int callingUid = Binder.getCallingUid(); 19562 enforceOwnerRights(ownerPackage, callingUid); 19563 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19564 synchronized (mPackages) { 19565 CrossProfileIntentResolver resolver = 19566 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19567 ArraySet<CrossProfileIntentFilter> set = 19568 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19569 for (CrossProfileIntentFilter filter : set) { 19570 if (filter.getOwnerPackage().equals(ownerPackage)) { 19571 resolver.removeFilter(filter); 19572 } 19573 } 19574 scheduleWritePackageRestrictionsLocked(sourceUserId); 19575 } 19576 } 19577 19578 // Enforcing that callingUid is owning pkg on userId 19579 private void enforceOwnerRights(String pkg, int callingUid) { 19580 // The system owns everything. 19581 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19582 return; 19583 } 19584 int callingUserId = UserHandle.getUserId(callingUid); 19585 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19586 if (pi == null) { 19587 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19588 + callingUserId); 19589 } 19590 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19591 throw new SecurityException("Calling uid " + callingUid 19592 + " does not own package " + pkg); 19593 } 19594 } 19595 19596 @Override 19597 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19598 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19599 } 19600 19601 /** 19602 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19603 * then reports the most likely home activity or null if there are more than one. 19604 */ 19605 public ComponentName getDefaultHomeActivity(int userId) { 19606 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19607 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19608 if (cn != null) { 19609 return cn; 19610 } 19611 19612 // Find the launcher with the highest priority and return that component if there are no 19613 // other home activity with the same priority. 19614 int lastPriority = Integer.MIN_VALUE; 19615 ComponentName lastComponent = null; 19616 final int size = allHomeCandidates.size(); 19617 for (int i = 0; i < size; i++) { 19618 final ResolveInfo ri = allHomeCandidates.get(i); 19619 if (ri.priority > lastPriority) { 19620 lastComponent = ri.activityInfo.getComponentName(); 19621 lastPriority = ri.priority; 19622 } else if (ri.priority == lastPriority) { 19623 // Two components found with same priority. 19624 lastComponent = null; 19625 } 19626 } 19627 return lastComponent; 19628 } 19629 19630 private Intent getHomeIntent() { 19631 Intent intent = new Intent(Intent.ACTION_MAIN); 19632 intent.addCategory(Intent.CATEGORY_HOME); 19633 intent.addCategory(Intent.CATEGORY_DEFAULT); 19634 return intent; 19635 } 19636 19637 private IntentFilter getHomeFilter() { 19638 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19639 filter.addCategory(Intent.CATEGORY_HOME); 19640 filter.addCategory(Intent.CATEGORY_DEFAULT); 19641 return filter; 19642 } 19643 19644 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19645 int userId) { 19646 Intent intent = getHomeIntent(); 19647 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19648 PackageManager.GET_META_DATA, userId); 19649 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19650 true, false, false, userId); 19651 19652 allHomeCandidates.clear(); 19653 if (list != null) { 19654 for (ResolveInfo ri : list) { 19655 allHomeCandidates.add(ri); 19656 } 19657 } 19658 return (preferred == null || preferred.activityInfo == null) 19659 ? null 19660 : new ComponentName(preferred.activityInfo.packageName, 19661 preferred.activityInfo.name); 19662 } 19663 19664 @Override 19665 public void setHomeActivity(ComponentName comp, int userId) { 19666 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19667 getHomeActivitiesAsUser(homeActivities, userId); 19668 19669 boolean found = false; 19670 19671 final int size = homeActivities.size(); 19672 final ComponentName[] set = new ComponentName[size]; 19673 for (int i = 0; i < size; i++) { 19674 final ResolveInfo candidate = homeActivities.get(i); 19675 final ActivityInfo info = candidate.activityInfo; 19676 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19677 set[i] = activityName; 19678 if (!found && activityName.equals(comp)) { 19679 found = true; 19680 } 19681 } 19682 if (!found) { 19683 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19684 + userId); 19685 } 19686 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19687 set, comp, userId); 19688 } 19689 19690 private @Nullable String getSetupWizardPackageName() { 19691 final Intent intent = new Intent(Intent.ACTION_MAIN); 19692 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19693 19694 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19695 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19696 | MATCH_DISABLED_COMPONENTS, 19697 UserHandle.myUserId()); 19698 if (matches.size() == 1) { 19699 return matches.get(0).getComponentInfo().packageName; 19700 } else { 19701 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19702 + ": matches=" + matches); 19703 return null; 19704 } 19705 } 19706 19707 private @Nullable String getStorageManagerPackageName() { 19708 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19709 19710 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19711 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19712 | MATCH_DISABLED_COMPONENTS, 19713 UserHandle.myUserId()); 19714 if (matches.size() == 1) { 19715 return matches.get(0).getComponentInfo().packageName; 19716 } else { 19717 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19718 + matches.size() + ": matches=" + matches); 19719 return null; 19720 } 19721 } 19722 19723 @Override 19724 public void setApplicationEnabledSetting(String appPackageName, 19725 int newState, int flags, int userId, String callingPackage) { 19726 if (!sUserManager.exists(userId)) return; 19727 if (callingPackage == null) { 19728 callingPackage = Integer.toString(Binder.getCallingUid()); 19729 } 19730 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19731 } 19732 19733 @Override 19734 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19735 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19736 synchronized (mPackages) { 19737 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19738 if (pkgSetting != null) { 19739 pkgSetting.setUpdateAvailable(updateAvailable); 19740 } 19741 } 19742 } 19743 19744 @Override 19745 public void setComponentEnabledSetting(ComponentName componentName, 19746 int newState, int flags, int userId) { 19747 if (!sUserManager.exists(userId)) return; 19748 setEnabledSetting(componentName.getPackageName(), 19749 componentName.getClassName(), newState, flags, userId, null); 19750 } 19751 19752 private void setEnabledSetting(final String packageName, String className, int newState, 19753 final int flags, int userId, String callingPackage) { 19754 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19755 || newState == COMPONENT_ENABLED_STATE_ENABLED 19756 || newState == COMPONENT_ENABLED_STATE_DISABLED 19757 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19758 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19759 throw new IllegalArgumentException("Invalid new component state: " 19760 + newState); 19761 } 19762 PackageSetting pkgSetting; 19763 final int uid = Binder.getCallingUid(); 19764 final int permission; 19765 if (uid == Process.SYSTEM_UID) { 19766 permission = PackageManager.PERMISSION_GRANTED; 19767 } else { 19768 permission = mContext.checkCallingOrSelfPermission( 19769 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19770 } 19771 enforceCrossUserPermission(uid, userId, 19772 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19773 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19774 boolean sendNow = false; 19775 boolean isApp = (className == null); 19776 String componentName = isApp ? packageName : className; 19777 int packageUid = -1; 19778 ArrayList<String> components; 19779 19780 // writer 19781 synchronized (mPackages) { 19782 pkgSetting = mSettings.mPackages.get(packageName); 19783 if (pkgSetting == null) { 19784 if (className == null) { 19785 throw new IllegalArgumentException("Unknown package: " + packageName); 19786 } 19787 throw new IllegalArgumentException( 19788 "Unknown component: " + packageName + "/" + className); 19789 } 19790 } 19791 19792 // Limit who can change which apps 19793 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19794 // Don't allow apps that don't have permission to modify other apps 19795 if (!allowedByPermission) { 19796 throw new SecurityException( 19797 "Permission Denial: attempt to change component state from pid=" 19798 + Binder.getCallingPid() 19799 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19800 } 19801 // Don't allow changing protected packages. 19802 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19803 throw new SecurityException("Cannot disable a protected package: " + packageName); 19804 } 19805 } 19806 19807 synchronized (mPackages) { 19808 if (uid == Process.SHELL_UID 19809 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19810 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19811 // unless it is a test package. 19812 int oldState = pkgSetting.getEnabled(userId); 19813 if (className == null 19814 && 19815 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19816 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19817 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19818 && 19819 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19820 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19821 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19822 // ok 19823 } else { 19824 throw new SecurityException( 19825 "Shell cannot change component state for " + packageName + "/" 19826 + className + " to " + newState); 19827 } 19828 } 19829 if (className == null) { 19830 // We're dealing with an application/package level state change 19831 if (pkgSetting.getEnabled(userId) == newState) { 19832 // Nothing to do 19833 return; 19834 } 19835 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19836 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19837 // Don't care about who enables an app. 19838 callingPackage = null; 19839 } 19840 pkgSetting.setEnabled(newState, userId, callingPackage); 19841 // pkgSetting.pkg.mSetEnabled = newState; 19842 } else { 19843 // We're dealing with a component level state change 19844 // First, verify that this is a valid class name. 19845 PackageParser.Package pkg = pkgSetting.pkg; 19846 if (pkg == null || !pkg.hasComponentClassName(className)) { 19847 if (pkg != null && 19848 pkg.applicationInfo.targetSdkVersion >= 19849 Build.VERSION_CODES.JELLY_BEAN) { 19850 throw new IllegalArgumentException("Component class " + className 19851 + " does not exist in " + packageName); 19852 } else { 19853 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19854 + className + " does not exist in " + packageName); 19855 } 19856 } 19857 switch (newState) { 19858 case COMPONENT_ENABLED_STATE_ENABLED: 19859 if (!pkgSetting.enableComponentLPw(className, userId)) { 19860 return; 19861 } 19862 break; 19863 case COMPONENT_ENABLED_STATE_DISABLED: 19864 if (!pkgSetting.disableComponentLPw(className, userId)) { 19865 return; 19866 } 19867 break; 19868 case COMPONENT_ENABLED_STATE_DEFAULT: 19869 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19870 return; 19871 } 19872 break; 19873 default: 19874 Slog.e(TAG, "Invalid new component state: " + newState); 19875 return; 19876 } 19877 } 19878 scheduleWritePackageRestrictionsLocked(userId); 19879 updateSequenceNumberLP(packageName, new int[] { userId }); 19880 final long callingId = Binder.clearCallingIdentity(); 19881 try { 19882 updateInstantAppInstallerLocked(); 19883 } finally { 19884 Binder.restoreCallingIdentity(callingId); 19885 } 19886 components = mPendingBroadcasts.get(userId, packageName); 19887 final boolean newPackage = components == null; 19888 if (newPackage) { 19889 components = new ArrayList<String>(); 19890 } 19891 if (!components.contains(componentName)) { 19892 components.add(componentName); 19893 } 19894 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19895 sendNow = true; 19896 // Purge entry from pending broadcast list if another one exists already 19897 // since we are sending one right away. 19898 mPendingBroadcasts.remove(userId, packageName); 19899 } else { 19900 if (newPackage) { 19901 mPendingBroadcasts.put(userId, packageName, components); 19902 } 19903 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19904 // Schedule a message 19905 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19906 } 19907 } 19908 } 19909 19910 long callingId = Binder.clearCallingIdentity(); 19911 try { 19912 if (sendNow) { 19913 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19914 sendPackageChangedBroadcast(packageName, 19915 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19916 } 19917 } finally { 19918 Binder.restoreCallingIdentity(callingId); 19919 } 19920 } 19921 19922 @Override 19923 public void flushPackageRestrictionsAsUser(int userId) { 19924 if (!sUserManager.exists(userId)) { 19925 return; 19926 } 19927 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19928 false /* checkShell */, "flushPackageRestrictions"); 19929 synchronized (mPackages) { 19930 mSettings.writePackageRestrictionsLPr(userId); 19931 mDirtyUsers.remove(userId); 19932 if (mDirtyUsers.isEmpty()) { 19933 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19934 } 19935 } 19936 } 19937 19938 private void sendPackageChangedBroadcast(String packageName, 19939 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19940 if (DEBUG_INSTALL) 19941 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19942 + componentNames); 19943 Bundle extras = new Bundle(4); 19944 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19945 String nameList[] = new String[componentNames.size()]; 19946 componentNames.toArray(nameList); 19947 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19948 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19949 extras.putInt(Intent.EXTRA_UID, packageUid); 19950 // If this is not reporting a change of the overall package, then only send it 19951 // to registered receivers. We don't want to launch a swath of apps for every 19952 // little component state change. 19953 final int flags = !componentNames.contains(packageName) 19954 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19955 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19956 new int[] {UserHandle.getUserId(packageUid)}); 19957 } 19958 19959 @Override 19960 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19961 if (!sUserManager.exists(userId)) return; 19962 final int uid = Binder.getCallingUid(); 19963 final int permission = mContext.checkCallingOrSelfPermission( 19964 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19965 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19966 enforceCrossUserPermission(uid, userId, 19967 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19968 // writer 19969 synchronized (mPackages) { 19970 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19971 allowedByPermission, uid, userId)) { 19972 scheduleWritePackageRestrictionsLocked(userId); 19973 } 19974 } 19975 } 19976 19977 @Override 19978 public String getInstallerPackageName(String packageName) { 19979 // reader 19980 synchronized (mPackages) { 19981 return mSettings.getInstallerPackageNameLPr(packageName); 19982 } 19983 } 19984 19985 public boolean isOrphaned(String packageName) { 19986 // reader 19987 synchronized (mPackages) { 19988 return mSettings.isOrphaned(packageName); 19989 } 19990 } 19991 19992 @Override 19993 public int getApplicationEnabledSetting(String packageName, int userId) { 19994 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19995 int uid = Binder.getCallingUid(); 19996 enforceCrossUserPermission(uid, userId, 19997 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19998 // reader 19999 synchronized (mPackages) { 20000 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20001 } 20002 } 20003 20004 @Override 20005 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20006 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20007 int uid = Binder.getCallingUid(); 20008 enforceCrossUserPermission(uid, userId, 20009 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20010 // reader 20011 synchronized (mPackages) { 20012 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20013 } 20014 } 20015 20016 @Override 20017 public void enterSafeMode() { 20018 enforceSystemOrRoot("Only the system can request entering safe mode"); 20019 20020 if (!mSystemReady) { 20021 mSafeMode = true; 20022 } 20023 } 20024 20025 @Override 20026 public void systemReady() { 20027 mSystemReady = true; 20028 20029 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20030 // disabled after already being started. 20031 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20032 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20033 20034 // Read the compatibilty setting when the system is ready. 20035 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20036 mContext.getContentResolver(), 20037 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20038 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20039 if (DEBUG_SETTINGS) { 20040 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20041 } 20042 20043 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20044 20045 synchronized (mPackages) { 20046 // Verify that all of the preferred activity components actually 20047 // exist. It is possible for applications to be updated and at 20048 // that point remove a previously declared activity component that 20049 // had been set as a preferred activity. We try to clean this up 20050 // the next time we encounter that preferred activity, but it is 20051 // possible for the user flow to never be able to return to that 20052 // situation so here we do a sanity check to make sure we haven't 20053 // left any junk around. 20054 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20055 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20056 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20057 removed.clear(); 20058 for (PreferredActivity pa : pir.filterSet()) { 20059 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20060 removed.add(pa); 20061 } 20062 } 20063 if (removed.size() > 0) { 20064 for (int r=0; r<removed.size(); r++) { 20065 PreferredActivity pa = removed.get(r); 20066 Slog.w(TAG, "Removing dangling preferred activity: " 20067 + pa.mPref.mComponent); 20068 pir.removeFilter(pa); 20069 } 20070 mSettings.writePackageRestrictionsLPr( 20071 mSettings.mPreferredActivities.keyAt(i)); 20072 } 20073 } 20074 20075 for (int userId : UserManagerService.getInstance().getUserIds()) { 20076 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20077 grantPermissionsUserIds = ArrayUtils.appendInt( 20078 grantPermissionsUserIds, userId); 20079 } 20080 } 20081 } 20082 sUserManager.systemReady(); 20083 20084 // If we upgraded grant all default permissions before kicking off. 20085 for (int userId : grantPermissionsUserIds) { 20086 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20087 } 20088 20089 // If we did not grant default permissions, we preload from this the 20090 // default permission exceptions lazily to ensure we don't hit the 20091 // disk on a new user creation. 20092 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20093 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20094 } 20095 20096 // Kick off any messages waiting for system ready 20097 if (mPostSystemReadyMessages != null) { 20098 for (Message msg : mPostSystemReadyMessages) { 20099 msg.sendToTarget(); 20100 } 20101 mPostSystemReadyMessages = null; 20102 } 20103 20104 // Watch for external volumes that come and go over time 20105 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20106 storage.registerListener(mStorageListener); 20107 20108 mInstallerService.systemReady(); 20109 mPackageDexOptimizer.systemReady(); 20110 20111 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20112 StorageManagerInternal.class); 20113 StorageManagerInternal.addExternalStoragePolicy( 20114 new StorageManagerInternal.ExternalStorageMountPolicy() { 20115 @Override 20116 public int getMountMode(int uid, String packageName) { 20117 if (Process.isIsolated(uid)) { 20118 return Zygote.MOUNT_EXTERNAL_NONE; 20119 } 20120 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20121 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20122 } 20123 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20124 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20125 } 20126 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20127 return Zygote.MOUNT_EXTERNAL_READ; 20128 } 20129 return Zygote.MOUNT_EXTERNAL_WRITE; 20130 } 20131 20132 @Override 20133 public boolean hasExternalStorage(int uid, String packageName) { 20134 return true; 20135 } 20136 }); 20137 20138 // Now that we're mostly running, clean up stale users and apps 20139 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20140 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20141 20142 if (mPrivappPermissionsViolations != null) { 20143 Slog.wtf(TAG,"Signature|privileged permissions not in " 20144 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20145 mPrivappPermissionsViolations = null; 20146 } 20147 } 20148 20149 public void waitForAppDataPrepared() { 20150 if (mPrepareAppDataFuture == null) { 20151 return; 20152 } 20153 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20154 mPrepareAppDataFuture = null; 20155 } 20156 20157 @Override 20158 public boolean isSafeMode() { 20159 return mSafeMode; 20160 } 20161 20162 @Override 20163 public boolean hasSystemUidErrors() { 20164 return mHasSystemUidErrors; 20165 } 20166 20167 static String arrayToString(int[] array) { 20168 StringBuffer buf = new StringBuffer(128); 20169 buf.append('['); 20170 if (array != null) { 20171 for (int i=0; i<array.length; i++) { 20172 if (i > 0) buf.append(", "); 20173 buf.append(array[i]); 20174 } 20175 } 20176 buf.append(']'); 20177 return buf.toString(); 20178 } 20179 20180 static class DumpState { 20181 public static final int DUMP_LIBS = 1 << 0; 20182 public static final int DUMP_FEATURES = 1 << 1; 20183 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20184 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20185 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20186 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20187 public static final int DUMP_PERMISSIONS = 1 << 6; 20188 public static final int DUMP_PACKAGES = 1 << 7; 20189 public static final int DUMP_SHARED_USERS = 1 << 8; 20190 public static final int DUMP_MESSAGES = 1 << 9; 20191 public static final int DUMP_PROVIDERS = 1 << 10; 20192 public static final int DUMP_VERIFIERS = 1 << 11; 20193 public static final int DUMP_PREFERRED = 1 << 12; 20194 public static final int DUMP_PREFERRED_XML = 1 << 13; 20195 public static final int DUMP_KEYSETS = 1 << 14; 20196 public static final int DUMP_VERSION = 1 << 15; 20197 public static final int DUMP_INSTALLS = 1 << 16; 20198 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20199 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20200 public static final int DUMP_FROZEN = 1 << 19; 20201 public static final int DUMP_DEXOPT = 1 << 20; 20202 public static final int DUMP_COMPILER_STATS = 1 << 21; 20203 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20204 20205 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20206 20207 private int mTypes; 20208 20209 private int mOptions; 20210 20211 private boolean mTitlePrinted; 20212 20213 private SharedUserSetting mSharedUser; 20214 20215 public boolean isDumping(int type) { 20216 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20217 return true; 20218 } 20219 20220 return (mTypes & type) != 0; 20221 } 20222 20223 public void setDump(int type) { 20224 mTypes |= type; 20225 } 20226 20227 public boolean isOptionEnabled(int option) { 20228 return (mOptions & option) != 0; 20229 } 20230 20231 public void setOptionEnabled(int option) { 20232 mOptions |= option; 20233 } 20234 20235 public boolean onTitlePrinted() { 20236 final boolean printed = mTitlePrinted; 20237 mTitlePrinted = true; 20238 return printed; 20239 } 20240 20241 public boolean getTitlePrinted() { 20242 return mTitlePrinted; 20243 } 20244 20245 public void setTitlePrinted(boolean enabled) { 20246 mTitlePrinted = enabled; 20247 } 20248 20249 public SharedUserSetting getSharedUser() { 20250 return mSharedUser; 20251 } 20252 20253 public void setSharedUser(SharedUserSetting user) { 20254 mSharedUser = user; 20255 } 20256 } 20257 20258 @Override 20259 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20260 FileDescriptor err, String[] args, ShellCallback callback, 20261 ResultReceiver resultReceiver) { 20262 (new PackageManagerShellCommand(this)).exec( 20263 this, in, out, err, args, callback, resultReceiver); 20264 } 20265 20266 @Override 20267 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20268 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20269 != PackageManager.PERMISSION_GRANTED) { 20270 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20271 + Binder.getCallingPid() 20272 + ", uid=" + Binder.getCallingUid() 20273 + " without permission " 20274 + android.Manifest.permission.DUMP); 20275 return; 20276 } 20277 20278 DumpState dumpState = new DumpState(); 20279 boolean fullPreferred = false; 20280 boolean checkin = false; 20281 20282 String packageName = null; 20283 ArraySet<String> permissionNames = null; 20284 20285 int opti = 0; 20286 while (opti < args.length) { 20287 String opt = args[opti]; 20288 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20289 break; 20290 } 20291 opti++; 20292 20293 if ("-a".equals(opt)) { 20294 // Right now we only know how to print all. 20295 } else if ("-h".equals(opt)) { 20296 pw.println("Package manager dump options:"); 20297 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20298 pw.println(" --checkin: dump for a checkin"); 20299 pw.println(" -f: print details of intent filters"); 20300 pw.println(" -h: print this help"); 20301 pw.println(" cmd may be one of:"); 20302 pw.println(" l[ibraries]: list known shared libraries"); 20303 pw.println(" f[eatures]: list device features"); 20304 pw.println(" k[eysets]: print known keysets"); 20305 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20306 pw.println(" perm[issions]: dump permissions"); 20307 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20308 pw.println(" pref[erred]: print preferred package settings"); 20309 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20310 pw.println(" prov[iders]: dump content providers"); 20311 pw.println(" p[ackages]: dump installed packages"); 20312 pw.println(" s[hared-users]: dump shared user IDs"); 20313 pw.println(" m[essages]: print collected runtime messages"); 20314 pw.println(" v[erifiers]: print package verifier info"); 20315 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20316 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20317 pw.println(" version: print database version info"); 20318 pw.println(" write: write current settings now"); 20319 pw.println(" installs: details about install sessions"); 20320 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20321 pw.println(" dexopt: dump dexopt state"); 20322 pw.println(" compiler-stats: dump compiler statistics"); 20323 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20324 pw.println(" <package.name>: info about given package"); 20325 return; 20326 } else if ("--checkin".equals(opt)) { 20327 checkin = true; 20328 } else if ("-f".equals(opt)) { 20329 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20330 } else if ("--proto".equals(opt)) { 20331 dumpProto(fd); 20332 return; 20333 } else { 20334 pw.println("Unknown argument: " + opt + "; use -h for help"); 20335 } 20336 } 20337 20338 // Is the caller requesting to dump a particular piece of data? 20339 if (opti < args.length) { 20340 String cmd = args[opti]; 20341 opti++; 20342 // Is this a package name? 20343 if ("android".equals(cmd) || cmd.contains(".")) { 20344 packageName = cmd; 20345 // When dumping a single package, we always dump all of its 20346 // filter information since the amount of data will be reasonable. 20347 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20348 } else if ("check-permission".equals(cmd)) { 20349 if (opti >= args.length) { 20350 pw.println("Error: check-permission missing permission argument"); 20351 return; 20352 } 20353 String perm = args[opti]; 20354 opti++; 20355 if (opti >= args.length) { 20356 pw.println("Error: check-permission missing package argument"); 20357 return; 20358 } 20359 20360 String pkg = args[opti]; 20361 opti++; 20362 int user = UserHandle.getUserId(Binder.getCallingUid()); 20363 if (opti < args.length) { 20364 try { 20365 user = Integer.parseInt(args[opti]); 20366 } catch (NumberFormatException e) { 20367 pw.println("Error: check-permission user argument is not a number: " 20368 + args[opti]); 20369 return; 20370 } 20371 } 20372 20373 // Normalize package name to handle renamed packages and static libs 20374 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20375 20376 pw.println(checkPermission(perm, pkg, user)); 20377 return; 20378 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20379 dumpState.setDump(DumpState.DUMP_LIBS); 20380 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20381 dumpState.setDump(DumpState.DUMP_FEATURES); 20382 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20383 if (opti >= args.length) { 20384 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20385 | DumpState.DUMP_SERVICE_RESOLVERS 20386 | DumpState.DUMP_RECEIVER_RESOLVERS 20387 | DumpState.DUMP_CONTENT_RESOLVERS); 20388 } else { 20389 while (opti < args.length) { 20390 String name = args[opti]; 20391 if ("a".equals(name) || "activity".equals(name)) { 20392 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20393 } else if ("s".equals(name) || "service".equals(name)) { 20394 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20395 } else if ("r".equals(name) || "receiver".equals(name)) { 20396 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20397 } else if ("c".equals(name) || "content".equals(name)) { 20398 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20399 } else { 20400 pw.println("Error: unknown resolver table type: " + name); 20401 return; 20402 } 20403 opti++; 20404 } 20405 } 20406 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20407 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20408 } else if ("permission".equals(cmd)) { 20409 if (opti >= args.length) { 20410 pw.println("Error: permission requires permission name"); 20411 return; 20412 } 20413 permissionNames = new ArraySet<>(); 20414 while (opti < args.length) { 20415 permissionNames.add(args[opti]); 20416 opti++; 20417 } 20418 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20419 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20420 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20421 dumpState.setDump(DumpState.DUMP_PREFERRED); 20422 } else if ("preferred-xml".equals(cmd)) { 20423 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20424 if (opti < args.length && "--full".equals(args[opti])) { 20425 fullPreferred = true; 20426 opti++; 20427 } 20428 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20429 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20430 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20431 dumpState.setDump(DumpState.DUMP_PACKAGES); 20432 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20433 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20434 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20435 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20436 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20437 dumpState.setDump(DumpState.DUMP_MESSAGES); 20438 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20439 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20440 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20441 || "intent-filter-verifiers".equals(cmd)) { 20442 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20443 } else if ("version".equals(cmd)) { 20444 dumpState.setDump(DumpState.DUMP_VERSION); 20445 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20446 dumpState.setDump(DumpState.DUMP_KEYSETS); 20447 } else if ("installs".equals(cmd)) { 20448 dumpState.setDump(DumpState.DUMP_INSTALLS); 20449 } else if ("frozen".equals(cmd)) { 20450 dumpState.setDump(DumpState.DUMP_FROZEN); 20451 } else if ("dexopt".equals(cmd)) { 20452 dumpState.setDump(DumpState.DUMP_DEXOPT); 20453 } else if ("compiler-stats".equals(cmd)) { 20454 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20455 } else if ("enabled-overlays".equals(cmd)) { 20456 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20457 } else if ("write".equals(cmd)) { 20458 synchronized (mPackages) { 20459 mSettings.writeLPr(); 20460 pw.println("Settings written."); 20461 return; 20462 } 20463 } 20464 } 20465 20466 if (checkin) { 20467 pw.println("vers,1"); 20468 } 20469 20470 // reader 20471 synchronized (mPackages) { 20472 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20473 if (!checkin) { 20474 if (dumpState.onTitlePrinted()) 20475 pw.println(); 20476 pw.println("Database versions:"); 20477 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20478 } 20479 } 20480 20481 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20482 if (!checkin) { 20483 if (dumpState.onTitlePrinted()) 20484 pw.println(); 20485 pw.println("Verifiers:"); 20486 pw.print(" Required: "); 20487 pw.print(mRequiredVerifierPackage); 20488 pw.print(" (uid="); 20489 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20490 UserHandle.USER_SYSTEM)); 20491 pw.println(")"); 20492 } else if (mRequiredVerifierPackage != null) { 20493 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20494 pw.print(","); 20495 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20496 UserHandle.USER_SYSTEM)); 20497 } 20498 } 20499 20500 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20501 packageName == null) { 20502 if (mIntentFilterVerifierComponent != null) { 20503 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20504 if (!checkin) { 20505 if (dumpState.onTitlePrinted()) 20506 pw.println(); 20507 pw.println("Intent Filter Verifier:"); 20508 pw.print(" Using: "); 20509 pw.print(verifierPackageName); 20510 pw.print(" (uid="); 20511 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20512 UserHandle.USER_SYSTEM)); 20513 pw.println(")"); 20514 } else if (verifierPackageName != null) { 20515 pw.print("ifv,"); pw.print(verifierPackageName); 20516 pw.print(","); 20517 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20518 UserHandle.USER_SYSTEM)); 20519 } 20520 } else { 20521 pw.println(); 20522 pw.println("No Intent Filter Verifier available!"); 20523 } 20524 } 20525 20526 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20527 boolean printedHeader = false; 20528 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20529 while (it.hasNext()) { 20530 String libName = it.next(); 20531 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20532 if (versionedLib == null) { 20533 continue; 20534 } 20535 final int versionCount = versionedLib.size(); 20536 for (int i = 0; i < versionCount; i++) { 20537 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20538 if (!checkin) { 20539 if (!printedHeader) { 20540 if (dumpState.onTitlePrinted()) 20541 pw.println(); 20542 pw.println("Libraries:"); 20543 printedHeader = true; 20544 } 20545 pw.print(" "); 20546 } else { 20547 pw.print("lib,"); 20548 } 20549 pw.print(libEntry.info.getName()); 20550 if (libEntry.info.isStatic()) { 20551 pw.print(" version=" + libEntry.info.getVersion()); 20552 } 20553 if (!checkin) { 20554 pw.print(" -> "); 20555 } 20556 if (libEntry.path != null) { 20557 pw.print(" (jar) "); 20558 pw.print(libEntry.path); 20559 } else { 20560 pw.print(" (apk) "); 20561 pw.print(libEntry.apk); 20562 } 20563 pw.println(); 20564 } 20565 } 20566 } 20567 20568 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20569 if (dumpState.onTitlePrinted()) 20570 pw.println(); 20571 if (!checkin) { 20572 pw.println("Features:"); 20573 } 20574 20575 synchronized (mAvailableFeatures) { 20576 for (FeatureInfo feat : mAvailableFeatures.values()) { 20577 if (checkin) { 20578 pw.print("feat,"); 20579 pw.print(feat.name); 20580 pw.print(","); 20581 pw.println(feat.version); 20582 } else { 20583 pw.print(" "); 20584 pw.print(feat.name); 20585 if (feat.version > 0) { 20586 pw.print(" version="); 20587 pw.print(feat.version); 20588 } 20589 pw.println(); 20590 } 20591 } 20592 } 20593 } 20594 20595 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20596 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20597 : "Activity Resolver Table:", " ", packageName, 20598 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20599 dumpState.setTitlePrinted(true); 20600 } 20601 } 20602 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20603 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20604 : "Receiver Resolver Table:", " ", packageName, 20605 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20606 dumpState.setTitlePrinted(true); 20607 } 20608 } 20609 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20610 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20611 : "Service Resolver Table:", " ", packageName, 20612 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20613 dumpState.setTitlePrinted(true); 20614 } 20615 } 20616 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20617 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20618 : "Provider Resolver Table:", " ", packageName, 20619 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20620 dumpState.setTitlePrinted(true); 20621 } 20622 } 20623 20624 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20625 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20626 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20627 int user = mSettings.mPreferredActivities.keyAt(i); 20628 if (pir.dump(pw, 20629 dumpState.getTitlePrinted() 20630 ? "\nPreferred Activities User " + user + ":" 20631 : "Preferred Activities User " + user + ":", " ", 20632 packageName, true, false)) { 20633 dumpState.setTitlePrinted(true); 20634 } 20635 } 20636 } 20637 20638 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20639 pw.flush(); 20640 FileOutputStream fout = new FileOutputStream(fd); 20641 BufferedOutputStream str = new BufferedOutputStream(fout); 20642 XmlSerializer serializer = new FastXmlSerializer(); 20643 try { 20644 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20645 serializer.startDocument(null, true); 20646 serializer.setFeature( 20647 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20648 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20649 serializer.endDocument(); 20650 serializer.flush(); 20651 } catch (IllegalArgumentException e) { 20652 pw.println("Failed writing: " + e); 20653 } catch (IllegalStateException e) { 20654 pw.println("Failed writing: " + e); 20655 } catch (IOException e) { 20656 pw.println("Failed writing: " + e); 20657 } 20658 } 20659 20660 if (!checkin 20661 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20662 && packageName == null) { 20663 pw.println(); 20664 int count = mSettings.mPackages.size(); 20665 if (count == 0) { 20666 pw.println("No applications!"); 20667 pw.println(); 20668 } else { 20669 final String prefix = " "; 20670 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20671 if (allPackageSettings.size() == 0) { 20672 pw.println("No domain preferred apps!"); 20673 pw.println(); 20674 } else { 20675 pw.println("App verification status:"); 20676 pw.println(); 20677 count = 0; 20678 for (PackageSetting ps : allPackageSettings) { 20679 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20680 if (ivi == null || ivi.getPackageName() == null) continue; 20681 pw.println(prefix + "Package: " + ivi.getPackageName()); 20682 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20683 pw.println(prefix + "Status: " + ivi.getStatusString()); 20684 pw.println(); 20685 count++; 20686 } 20687 if (count == 0) { 20688 pw.println(prefix + "No app verification established."); 20689 pw.println(); 20690 } 20691 for (int userId : sUserManager.getUserIds()) { 20692 pw.println("App linkages for user " + userId + ":"); 20693 pw.println(); 20694 count = 0; 20695 for (PackageSetting ps : allPackageSettings) { 20696 final long status = ps.getDomainVerificationStatusForUser(userId); 20697 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20698 && !DEBUG_DOMAIN_VERIFICATION) { 20699 continue; 20700 } 20701 pw.println(prefix + "Package: " + ps.name); 20702 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20703 String statusStr = IntentFilterVerificationInfo. 20704 getStatusStringFromValue(status); 20705 pw.println(prefix + "Status: " + statusStr); 20706 pw.println(); 20707 count++; 20708 } 20709 if (count == 0) { 20710 pw.println(prefix + "No configured app linkages."); 20711 pw.println(); 20712 } 20713 } 20714 } 20715 } 20716 } 20717 20718 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20719 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20720 if (packageName == null && permissionNames == null) { 20721 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20722 if (iperm == 0) { 20723 if (dumpState.onTitlePrinted()) 20724 pw.println(); 20725 pw.println("AppOp Permissions:"); 20726 } 20727 pw.print(" AppOp Permission "); 20728 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20729 pw.println(":"); 20730 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20731 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20732 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20733 } 20734 } 20735 } 20736 } 20737 20738 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20739 boolean printedSomething = false; 20740 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20741 if (packageName != null && !packageName.equals(p.info.packageName)) { 20742 continue; 20743 } 20744 if (!printedSomething) { 20745 if (dumpState.onTitlePrinted()) 20746 pw.println(); 20747 pw.println("Registered ContentProviders:"); 20748 printedSomething = true; 20749 } 20750 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20751 pw.print(" "); pw.println(p.toString()); 20752 } 20753 printedSomething = false; 20754 for (Map.Entry<String, PackageParser.Provider> entry : 20755 mProvidersByAuthority.entrySet()) { 20756 PackageParser.Provider p = entry.getValue(); 20757 if (packageName != null && !packageName.equals(p.info.packageName)) { 20758 continue; 20759 } 20760 if (!printedSomething) { 20761 if (dumpState.onTitlePrinted()) 20762 pw.println(); 20763 pw.println("ContentProvider Authorities:"); 20764 printedSomething = true; 20765 } 20766 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20767 pw.print(" "); pw.println(p.toString()); 20768 if (p.info != null && p.info.applicationInfo != null) { 20769 final String appInfo = p.info.applicationInfo.toString(); 20770 pw.print(" applicationInfo="); pw.println(appInfo); 20771 } 20772 } 20773 } 20774 20775 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20776 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20777 } 20778 20779 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20780 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20781 } 20782 20783 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20784 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20785 } 20786 20787 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20788 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20789 } 20790 20791 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20792 // XXX should handle packageName != null by dumping only install data that 20793 // the given package is involved with. 20794 if (dumpState.onTitlePrinted()) pw.println(); 20795 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20796 } 20797 20798 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20799 // XXX should handle packageName != null by dumping only install data that 20800 // the given package is involved with. 20801 if (dumpState.onTitlePrinted()) pw.println(); 20802 20803 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20804 ipw.println(); 20805 ipw.println("Frozen packages:"); 20806 ipw.increaseIndent(); 20807 if (mFrozenPackages.size() == 0) { 20808 ipw.println("(none)"); 20809 } else { 20810 for (int i = 0; i < mFrozenPackages.size(); i++) { 20811 ipw.println(mFrozenPackages.valueAt(i)); 20812 } 20813 } 20814 ipw.decreaseIndent(); 20815 } 20816 20817 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20818 if (dumpState.onTitlePrinted()) pw.println(); 20819 dumpDexoptStateLPr(pw, packageName); 20820 } 20821 20822 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20823 if (dumpState.onTitlePrinted()) pw.println(); 20824 dumpCompilerStatsLPr(pw, packageName); 20825 } 20826 20827 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20828 if (dumpState.onTitlePrinted()) pw.println(); 20829 dumpEnabledOverlaysLPr(pw); 20830 } 20831 20832 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20833 if (dumpState.onTitlePrinted()) pw.println(); 20834 mSettings.dumpReadMessagesLPr(pw, dumpState); 20835 20836 pw.println(); 20837 pw.println("Package warning messages:"); 20838 BufferedReader in = null; 20839 String line = null; 20840 try { 20841 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20842 while ((line = in.readLine()) != null) { 20843 if (line.contains("ignored: updated version")) continue; 20844 pw.println(line); 20845 } 20846 } catch (IOException ignored) { 20847 } finally { 20848 IoUtils.closeQuietly(in); 20849 } 20850 } 20851 20852 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20853 BufferedReader in = null; 20854 String line = null; 20855 try { 20856 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20857 while ((line = in.readLine()) != null) { 20858 if (line.contains("ignored: updated version")) continue; 20859 pw.print("msg,"); 20860 pw.println(line); 20861 } 20862 } catch (IOException ignored) { 20863 } finally { 20864 IoUtils.closeQuietly(in); 20865 } 20866 } 20867 } 20868 } 20869 20870 private void dumpProto(FileDescriptor fd) { 20871 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20872 20873 synchronized (mPackages) { 20874 final long requiredVerifierPackageToken = 20875 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20876 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20877 proto.write( 20878 PackageServiceDumpProto.PackageShortProto.UID, 20879 getPackageUid( 20880 mRequiredVerifierPackage, 20881 MATCH_DEBUG_TRIAGED_MISSING, 20882 UserHandle.USER_SYSTEM)); 20883 proto.end(requiredVerifierPackageToken); 20884 20885 if (mIntentFilterVerifierComponent != null) { 20886 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20887 final long verifierPackageToken = 20888 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20889 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20890 proto.write( 20891 PackageServiceDumpProto.PackageShortProto.UID, 20892 getPackageUid( 20893 verifierPackageName, 20894 MATCH_DEBUG_TRIAGED_MISSING, 20895 UserHandle.USER_SYSTEM)); 20896 proto.end(verifierPackageToken); 20897 } 20898 20899 dumpSharedLibrariesProto(proto); 20900 dumpFeaturesProto(proto); 20901 mSettings.dumpPackagesProto(proto); 20902 mSettings.dumpSharedUsersProto(proto); 20903 dumpMessagesProto(proto); 20904 } 20905 proto.flush(); 20906 } 20907 20908 private void dumpMessagesProto(ProtoOutputStream proto) { 20909 BufferedReader in = null; 20910 String line = null; 20911 try { 20912 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20913 while ((line = in.readLine()) != null) { 20914 if (line.contains("ignored: updated version")) continue; 20915 proto.write(PackageServiceDumpProto.MESSAGES, line); 20916 } 20917 } catch (IOException ignored) { 20918 } finally { 20919 IoUtils.closeQuietly(in); 20920 } 20921 } 20922 20923 private void dumpFeaturesProto(ProtoOutputStream proto) { 20924 synchronized (mAvailableFeatures) { 20925 final int count = mAvailableFeatures.size(); 20926 for (int i = 0; i < count; i++) { 20927 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20928 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20929 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20930 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20931 proto.end(featureToken); 20932 } 20933 } 20934 } 20935 20936 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20937 final int count = mSharedLibraries.size(); 20938 for (int i = 0; i < count; i++) { 20939 final String libName = mSharedLibraries.keyAt(i); 20940 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20941 if (versionedLib == null) { 20942 continue; 20943 } 20944 final int versionCount = versionedLib.size(); 20945 for (int j = 0; j < versionCount; j++) { 20946 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20947 final long sharedLibraryToken = 20948 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20949 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20950 final boolean isJar = (libEntry.path != null); 20951 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20952 if (isJar) { 20953 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20954 } else { 20955 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20956 } 20957 proto.end(sharedLibraryToken); 20958 } 20959 } 20960 } 20961 20962 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20963 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20964 ipw.println(); 20965 ipw.println("Dexopt state:"); 20966 ipw.increaseIndent(); 20967 Collection<PackageParser.Package> packages = null; 20968 if (packageName != null) { 20969 PackageParser.Package targetPackage = mPackages.get(packageName); 20970 if (targetPackage != null) { 20971 packages = Collections.singletonList(targetPackage); 20972 } else { 20973 ipw.println("Unable to find package: " + packageName); 20974 return; 20975 } 20976 } else { 20977 packages = mPackages.values(); 20978 } 20979 20980 for (PackageParser.Package pkg : packages) { 20981 ipw.println("[" + pkg.packageName + "]"); 20982 ipw.increaseIndent(); 20983 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20984 ipw.decreaseIndent(); 20985 } 20986 } 20987 20988 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20989 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20990 ipw.println(); 20991 ipw.println("Compiler stats:"); 20992 ipw.increaseIndent(); 20993 Collection<PackageParser.Package> packages = null; 20994 if (packageName != null) { 20995 PackageParser.Package targetPackage = mPackages.get(packageName); 20996 if (targetPackage != null) { 20997 packages = Collections.singletonList(targetPackage); 20998 } else { 20999 ipw.println("Unable to find package: " + packageName); 21000 return; 21001 } 21002 } else { 21003 packages = mPackages.values(); 21004 } 21005 21006 for (PackageParser.Package pkg : packages) { 21007 ipw.println("[" + pkg.packageName + "]"); 21008 ipw.increaseIndent(); 21009 21010 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21011 if (stats == null) { 21012 ipw.println("(No recorded stats)"); 21013 } else { 21014 stats.dump(ipw); 21015 } 21016 ipw.decreaseIndent(); 21017 } 21018 } 21019 21020 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21021 pw.println("Enabled overlay paths:"); 21022 final int N = mEnabledOverlayPaths.size(); 21023 for (int i = 0; i < N; i++) { 21024 final int userId = mEnabledOverlayPaths.keyAt(i); 21025 pw.println(String.format(" User %d:", userId)); 21026 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21027 mEnabledOverlayPaths.valueAt(i); 21028 final int M = userSpecificOverlays.size(); 21029 for (int j = 0; j < M; j++) { 21030 final String targetPackageName = userSpecificOverlays.keyAt(j); 21031 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21032 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21033 } 21034 } 21035 } 21036 21037 private String dumpDomainString(String packageName) { 21038 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21039 .getList(); 21040 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21041 21042 ArraySet<String> result = new ArraySet<>(); 21043 if (iviList.size() > 0) { 21044 for (IntentFilterVerificationInfo ivi : iviList) { 21045 for (String host : ivi.getDomains()) { 21046 result.add(host); 21047 } 21048 } 21049 } 21050 if (filters != null && filters.size() > 0) { 21051 for (IntentFilter filter : filters) { 21052 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21053 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21054 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21055 result.addAll(filter.getHostsList()); 21056 } 21057 } 21058 } 21059 21060 StringBuilder sb = new StringBuilder(result.size() * 16); 21061 for (String domain : result) { 21062 if (sb.length() > 0) sb.append(" "); 21063 sb.append(domain); 21064 } 21065 return sb.toString(); 21066 } 21067 21068 // ------- apps on sdcard specific code ------- 21069 static final boolean DEBUG_SD_INSTALL = false; 21070 21071 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21072 21073 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21074 21075 private boolean mMediaMounted = false; 21076 21077 static String getEncryptKey() { 21078 try { 21079 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21080 SD_ENCRYPTION_KEYSTORE_NAME); 21081 if (sdEncKey == null) { 21082 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21083 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21084 if (sdEncKey == null) { 21085 Slog.e(TAG, "Failed to create encryption keys"); 21086 return null; 21087 } 21088 } 21089 return sdEncKey; 21090 } catch (NoSuchAlgorithmException nsae) { 21091 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21092 return null; 21093 } catch (IOException ioe) { 21094 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21095 return null; 21096 } 21097 } 21098 21099 /* 21100 * Update media status on PackageManager. 21101 */ 21102 @Override 21103 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21104 int callingUid = Binder.getCallingUid(); 21105 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21106 throw new SecurityException("Media status can only be updated by the system"); 21107 } 21108 // reader; this apparently protects mMediaMounted, but should probably 21109 // be a different lock in that case. 21110 synchronized (mPackages) { 21111 Log.i(TAG, "Updating external media status from " 21112 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21113 + (mediaStatus ? "mounted" : "unmounted")); 21114 if (DEBUG_SD_INSTALL) 21115 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21116 + ", mMediaMounted=" + mMediaMounted); 21117 if (mediaStatus == mMediaMounted) { 21118 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21119 : 0, -1); 21120 mHandler.sendMessage(msg); 21121 return; 21122 } 21123 mMediaMounted = mediaStatus; 21124 } 21125 // Queue up an async operation since the package installation may take a 21126 // little while. 21127 mHandler.post(new Runnable() { 21128 public void run() { 21129 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21130 } 21131 }); 21132 } 21133 21134 /** 21135 * Called by StorageManagerService when the initial ASECs to scan are available. 21136 * Should block until all the ASEC containers are finished being scanned. 21137 */ 21138 public void scanAvailableAsecs() { 21139 updateExternalMediaStatusInner(true, false, false); 21140 } 21141 21142 /* 21143 * Collect information of applications on external media, map them against 21144 * existing containers and update information based on current mount status. 21145 * Please note that we always have to report status if reportStatus has been 21146 * set to true especially when unloading packages. 21147 */ 21148 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21149 boolean externalStorage) { 21150 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21151 int[] uidArr = EmptyArray.INT; 21152 21153 final String[] list = PackageHelper.getSecureContainerList(); 21154 if (ArrayUtils.isEmpty(list)) { 21155 Log.i(TAG, "No secure containers found"); 21156 } else { 21157 // Process list of secure containers and categorize them 21158 // as active or stale based on their package internal state. 21159 21160 // reader 21161 synchronized (mPackages) { 21162 for (String cid : list) { 21163 // Leave stages untouched for now; installer service owns them 21164 if (PackageInstallerService.isStageName(cid)) continue; 21165 21166 if (DEBUG_SD_INSTALL) 21167 Log.i(TAG, "Processing container " + cid); 21168 String pkgName = getAsecPackageName(cid); 21169 if (pkgName == null) { 21170 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21171 continue; 21172 } 21173 if (DEBUG_SD_INSTALL) 21174 Log.i(TAG, "Looking for pkg : " + pkgName); 21175 21176 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21177 if (ps == null) { 21178 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21179 continue; 21180 } 21181 21182 /* 21183 * Skip packages that are not external if we're unmounting 21184 * external storage. 21185 */ 21186 if (externalStorage && !isMounted && !isExternal(ps)) { 21187 continue; 21188 } 21189 21190 final AsecInstallArgs args = new AsecInstallArgs(cid, 21191 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21192 // The package status is changed only if the code path 21193 // matches between settings and the container id. 21194 if (ps.codePathString != null 21195 && ps.codePathString.startsWith(args.getCodePath())) { 21196 if (DEBUG_SD_INSTALL) { 21197 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21198 + " at code path: " + ps.codePathString); 21199 } 21200 21201 // We do have a valid package installed on sdcard 21202 processCids.put(args, ps.codePathString); 21203 final int uid = ps.appId; 21204 if (uid != -1) { 21205 uidArr = ArrayUtils.appendInt(uidArr, uid); 21206 } 21207 } else { 21208 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21209 + ps.codePathString); 21210 } 21211 } 21212 } 21213 21214 Arrays.sort(uidArr); 21215 } 21216 21217 // Process packages with valid entries. 21218 if (isMounted) { 21219 if (DEBUG_SD_INSTALL) 21220 Log.i(TAG, "Loading packages"); 21221 loadMediaPackages(processCids, uidArr, externalStorage); 21222 startCleaningPackages(); 21223 mInstallerService.onSecureContainersAvailable(); 21224 } else { 21225 if (DEBUG_SD_INSTALL) 21226 Log.i(TAG, "Unloading packages"); 21227 unloadMediaPackages(processCids, uidArr, reportStatus); 21228 } 21229 } 21230 21231 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21232 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21233 final int size = infos.size(); 21234 final String[] packageNames = new String[size]; 21235 final int[] packageUids = new int[size]; 21236 for (int i = 0; i < size; i++) { 21237 final ApplicationInfo info = infos.get(i); 21238 packageNames[i] = info.packageName; 21239 packageUids[i] = info.uid; 21240 } 21241 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21242 finishedReceiver); 21243 } 21244 21245 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21246 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21247 sendResourcesChangedBroadcast(mediaStatus, replacing, 21248 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21249 } 21250 21251 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21252 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21253 int size = pkgList.length; 21254 if (size > 0) { 21255 // Send broadcasts here 21256 Bundle extras = new Bundle(); 21257 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21258 if (uidArr != null) { 21259 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21260 } 21261 if (replacing) { 21262 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21263 } 21264 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21265 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21266 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21267 } 21268 } 21269 21270 /* 21271 * Look at potentially valid container ids from processCids If package 21272 * information doesn't match the one on record or package scanning fails, 21273 * the cid is added to list of removeCids. We currently don't delete stale 21274 * containers. 21275 */ 21276 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21277 boolean externalStorage) { 21278 ArrayList<String> pkgList = new ArrayList<String>(); 21279 Set<AsecInstallArgs> keys = processCids.keySet(); 21280 21281 for (AsecInstallArgs args : keys) { 21282 String codePath = processCids.get(args); 21283 if (DEBUG_SD_INSTALL) 21284 Log.i(TAG, "Loading container : " + args.cid); 21285 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21286 try { 21287 // Make sure there are no container errors first. 21288 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21289 Slog.e(TAG, "Failed to mount cid : " + args.cid 21290 + " when installing from sdcard"); 21291 continue; 21292 } 21293 // Check code path here. 21294 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21295 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21296 + " does not match one in settings " + codePath); 21297 continue; 21298 } 21299 // Parse package 21300 int parseFlags = mDefParseFlags; 21301 if (args.isExternalAsec()) { 21302 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21303 } 21304 if (args.isFwdLocked()) { 21305 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21306 } 21307 21308 synchronized (mInstallLock) { 21309 PackageParser.Package pkg = null; 21310 try { 21311 // Sadly we don't know the package name yet to freeze it 21312 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21313 SCAN_IGNORE_FROZEN, 0, null); 21314 } catch (PackageManagerException e) { 21315 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21316 } 21317 // Scan the package 21318 if (pkg != null) { 21319 /* 21320 * TODO why is the lock being held? doPostInstall is 21321 * called in other places without the lock. This needs 21322 * to be straightened out. 21323 */ 21324 // writer 21325 synchronized (mPackages) { 21326 retCode = PackageManager.INSTALL_SUCCEEDED; 21327 pkgList.add(pkg.packageName); 21328 // Post process args 21329 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21330 pkg.applicationInfo.uid); 21331 } 21332 } else { 21333 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21334 } 21335 } 21336 21337 } finally { 21338 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21339 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21340 } 21341 } 21342 } 21343 // writer 21344 synchronized (mPackages) { 21345 // If the platform SDK has changed since the last time we booted, 21346 // we need to re-grant app permission to catch any new ones that 21347 // appear. This is really a hack, and means that apps can in some 21348 // cases get permissions that the user didn't initially explicitly 21349 // allow... it would be nice to have some better way to handle 21350 // this situation. 21351 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21352 : mSettings.getInternalVersion(); 21353 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21354 : StorageManager.UUID_PRIVATE_INTERNAL; 21355 21356 int updateFlags = UPDATE_PERMISSIONS_ALL; 21357 if (ver.sdkVersion != mSdkVersion) { 21358 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21359 + mSdkVersion + "; regranting permissions for external"); 21360 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21361 } 21362 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21363 21364 // Yay, everything is now upgraded 21365 ver.forceCurrent(); 21366 21367 // can downgrade to reader 21368 // Persist settings 21369 mSettings.writeLPr(); 21370 } 21371 // Send a broadcast to let everyone know we are done processing 21372 if (pkgList.size() > 0) { 21373 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21374 } 21375 } 21376 21377 /* 21378 * Utility method to unload a list of specified containers 21379 */ 21380 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21381 // Just unmount all valid containers. 21382 for (AsecInstallArgs arg : cidArgs) { 21383 synchronized (mInstallLock) { 21384 arg.doPostDeleteLI(false); 21385 } 21386 } 21387 } 21388 21389 /* 21390 * Unload packages mounted on external media. This involves deleting package 21391 * data from internal structures, sending broadcasts about disabled packages, 21392 * gc'ing to free up references, unmounting all secure containers 21393 * corresponding to packages on external media, and posting a 21394 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21395 * that we always have to post this message if status has been requested no 21396 * matter what. 21397 */ 21398 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21399 final boolean reportStatus) { 21400 if (DEBUG_SD_INSTALL) 21401 Log.i(TAG, "unloading media packages"); 21402 ArrayList<String> pkgList = new ArrayList<String>(); 21403 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21404 final Set<AsecInstallArgs> keys = processCids.keySet(); 21405 for (AsecInstallArgs args : keys) { 21406 String pkgName = args.getPackageName(); 21407 if (DEBUG_SD_INSTALL) 21408 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21409 // Delete package internally 21410 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21411 synchronized (mInstallLock) { 21412 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21413 final boolean res; 21414 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21415 "unloadMediaPackages")) { 21416 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21417 null); 21418 } 21419 if (res) { 21420 pkgList.add(pkgName); 21421 } else { 21422 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21423 failedList.add(args); 21424 } 21425 } 21426 } 21427 21428 // reader 21429 synchronized (mPackages) { 21430 // We didn't update the settings after removing each package; 21431 // write them now for all packages. 21432 mSettings.writeLPr(); 21433 } 21434 21435 // We have to absolutely send UPDATED_MEDIA_STATUS only 21436 // after confirming that all the receivers processed the ordered 21437 // broadcast when packages get disabled, force a gc to clean things up. 21438 // and unload all the containers. 21439 if (pkgList.size() > 0) { 21440 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21441 new IIntentReceiver.Stub() { 21442 public void performReceive(Intent intent, int resultCode, String data, 21443 Bundle extras, boolean ordered, boolean sticky, 21444 int sendingUser) throws RemoteException { 21445 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21446 reportStatus ? 1 : 0, 1, keys); 21447 mHandler.sendMessage(msg); 21448 } 21449 }); 21450 } else { 21451 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21452 keys); 21453 mHandler.sendMessage(msg); 21454 } 21455 } 21456 21457 private void loadPrivatePackages(final VolumeInfo vol) { 21458 mHandler.post(new Runnable() { 21459 @Override 21460 public void run() { 21461 loadPrivatePackagesInner(vol); 21462 } 21463 }); 21464 } 21465 21466 private void loadPrivatePackagesInner(VolumeInfo vol) { 21467 final String volumeUuid = vol.fsUuid; 21468 if (TextUtils.isEmpty(volumeUuid)) { 21469 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21470 return; 21471 } 21472 21473 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21474 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21475 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21476 21477 final VersionInfo ver; 21478 final List<PackageSetting> packages; 21479 synchronized (mPackages) { 21480 ver = mSettings.findOrCreateVersion(volumeUuid); 21481 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21482 } 21483 21484 for (PackageSetting ps : packages) { 21485 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21486 synchronized (mInstallLock) { 21487 final PackageParser.Package pkg; 21488 try { 21489 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21490 loaded.add(pkg.applicationInfo); 21491 21492 } catch (PackageManagerException e) { 21493 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21494 } 21495 21496 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21497 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21498 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21499 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21500 } 21501 } 21502 } 21503 21504 // Reconcile app data for all started/unlocked users 21505 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21506 final UserManager um = mContext.getSystemService(UserManager.class); 21507 UserManagerInternal umInternal = getUserManagerInternal(); 21508 for (UserInfo user : um.getUsers()) { 21509 final int flags; 21510 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21511 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21512 } else if (umInternal.isUserRunning(user.id)) { 21513 flags = StorageManager.FLAG_STORAGE_DE; 21514 } else { 21515 continue; 21516 } 21517 21518 try { 21519 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21520 synchronized (mInstallLock) { 21521 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21522 } 21523 } catch (IllegalStateException e) { 21524 // Device was probably ejected, and we'll process that event momentarily 21525 Slog.w(TAG, "Failed to prepare storage: " + e); 21526 } 21527 } 21528 21529 synchronized (mPackages) { 21530 int updateFlags = UPDATE_PERMISSIONS_ALL; 21531 if (ver.sdkVersion != mSdkVersion) { 21532 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21533 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21534 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21535 } 21536 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21537 21538 // Yay, everything is now upgraded 21539 ver.forceCurrent(); 21540 21541 mSettings.writeLPr(); 21542 } 21543 21544 for (PackageFreezer freezer : freezers) { 21545 freezer.close(); 21546 } 21547 21548 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21549 sendResourcesChangedBroadcast(true, false, loaded, null); 21550 } 21551 21552 private void unloadPrivatePackages(final VolumeInfo vol) { 21553 mHandler.post(new Runnable() { 21554 @Override 21555 public void run() { 21556 unloadPrivatePackagesInner(vol); 21557 } 21558 }); 21559 } 21560 21561 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21562 final String volumeUuid = vol.fsUuid; 21563 if (TextUtils.isEmpty(volumeUuid)) { 21564 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21565 return; 21566 } 21567 21568 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21569 synchronized (mInstallLock) { 21570 synchronized (mPackages) { 21571 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21572 for (PackageSetting ps : packages) { 21573 if (ps.pkg == null) continue; 21574 21575 final ApplicationInfo info = ps.pkg.applicationInfo; 21576 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21577 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21578 21579 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21580 "unloadPrivatePackagesInner")) { 21581 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21582 false, null)) { 21583 unloaded.add(info); 21584 } else { 21585 Slog.w(TAG, "Failed to unload " + ps.codePath); 21586 } 21587 } 21588 21589 // Try very hard to release any references to this package 21590 // so we don't risk the system server being killed due to 21591 // open FDs 21592 AttributeCache.instance().removePackage(ps.name); 21593 } 21594 21595 mSettings.writeLPr(); 21596 } 21597 } 21598 21599 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21600 sendResourcesChangedBroadcast(false, false, unloaded, null); 21601 21602 // Try very hard to release any references to this path so we don't risk 21603 // the system server being killed due to open FDs 21604 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21605 21606 for (int i = 0; i < 3; i++) { 21607 System.gc(); 21608 System.runFinalization(); 21609 } 21610 } 21611 21612 private void assertPackageKnown(String volumeUuid, String packageName) 21613 throws PackageManagerException { 21614 synchronized (mPackages) { 21615 // Normalize package name to handle renamed packages 21616 packageName = normalizePackageNameLPr(packageName); 21617 21618 final PackageSetting ps = mSettings.mPackages.get(packageName); 21619 if (ps == null) { 21620 throw new PackageManagerException("Package " + packageName + " is unknown"); 21621 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21622 throw new PackageManagerException( 21623 "Package " + packageName + " found on unknown volume " + volumeUuid 21624 + "; expected volume " + ps.volumeUuid); 21625 } 21626 } 21627 } 21628 21629 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21630 throws PackageManagerException { 21631 synchronized (mPackages) { 21632 // Normalize package name to handle renamed packages 21633 packageName = normalizePackageNameLPr(packageName); 21634 21635 final PackageSetting ps = mSettings.mPackages.get(packageName); 21636 if (ps == null) { 21637 throw new PackageManagerException("Package " + packageName + " is unknown"); 21638 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21639 throw new PackageManagerException( 21640 "Package " + packageName + " found on unknown volume " + volumeUuid 21641 + "; expected volume " + ps.volumeUuid); 21642 } else if (!ps.getInstalled(userId)) { 21643 throw new PackageManagerException( 21644 "Package " + packageName + " not installed for user " + userId); 21645 } 21646 } 21647 } 21648 21649 private List<String> collectAbsoluteCodePaths() { 21650 synchronized (mPackages) { 21651 List<String> codePaths = new ArrayList<>(); 21652 final int packageCount = mSettings.mPackages.size(); 21653 for (int i = 0; i < packageCount; i++) { 21654 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21655 codePaths.add(ps.codePath.getAbsolutePath()); 21656 } 21657 return codePaths; 21658 } 21659 } 21660 21661 /** 21662 * Examine all apps present on given mounted volume, and destroy apps that 21663 * aren't expected, either due to uninstallation or reinstallation on 21664 * another volume. 21665 */ 21666 private void reconcileApps(String volumeUuid) { 21667 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21668 List<File> filesToDelete = null; 21669 21670 final File[] files = FileUtils.listFilesOrEmpty( 21671 Environment.getDataAppDirectory(volumeUuid)); 21672 for (File file : files) { 21673 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21674 && !PackageInstallerService.isStageName(file.getName()); 21675 if (!isPackage) { 21676 // Ignore entries which are not packages 21677 continue; 21678 } 21679 21680 String absolutePath = file.getAbsolutePath(); 21681 21682 boolean pathValid = false; 21683 final int absoluteCodePathCount = absoluteCodePaths.size(); 21684 for (int i = 0; i < absoluteCodePathCount; i++) { 21685 String absoluteCodePath = absoluteCodePaths.get(i); 21686 if (absolutePath.startsWith(absoluteCodePath)) { 21687 pathValid = true; 21688 break; 21689 } 21690 } 21691 21692 if (!pathValid) { 21693 if (filesToDelete == null) { 21694 filesToDelete = new ArrayList<>(); 21695 } 21696 filesToDelete.add(file); 21697 } 21698 } 21699 21700 if (filesToDelete != null) { 21701 final int fileToDeleteCount = filesToDelete.size(); 21702 for (int i = 0; i < fileToDeleteCount; i++) { 21703 File fileToDelete = filesToDelete.get(i); 21704 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21705 synchronized (mInstallLock) { 21706 removeCodePathLI(fileToDelete); 21707 } 21708 } 21709 } 21710 } 21711 21712 /** 21713 * Reconcile all app data for the given user. 21714 * <p> 21715 * Verifies that directories exist and that ownership and labeling is 21716 * correct for all installed apps on all mounted volumes. 21717 */ 21718 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21719 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21720 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21721 final String volumeUuid = vol.getFsUuid(); 21722 synchronized (mInstallLock) { 21723 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21724 } 21725 } 21726 } 21727 21728 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21729 boolean migrateAppData) { 21730 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21731 } 21732 21733 /** 21734 * Reconcile all app data on given mounted volume. 21735 * <p> 21736 * Destroys app data that isn't expected, either due to uninstallation or 21737 * reinstallation on another volume. 21738 * <p> 21739 * Verifies that directories exist and that ownership and labeling is 21740 * correct for all installed apps. 21741 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21742 */ 21743 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21744 boolean migrateAppData, boolean onlyCoreApps) { 21745 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21746 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21747 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21748 21749 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21750 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21751 21752 // First look for stale data that doesn't belong, and check if things 21753 // have changed since we did our last restorecon 21754 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21755 if (StorageManager.isFileEncryptedNativeOrEmulated() 21756 && !StorageManager.isUserKeyUnlocked(userId)) { 21757 throw new RuntimeException( 21758 "Yikes, someone asked us to reconcile CE storage while " + userId 21759 + " was still locked; this would have caused massive data loss!"); 21760 } 21761 21762 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21763 for (File file : files) { 21764 final String packageName = file.getName(); 21765 try { 21766 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21767 } catch (PackageManagerException e) { 21768 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21769 try { 21770 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21771 StorageManager.FLAG_STORAGE_CE, 0); 21772 } catch (InstallerException e2) { 21773 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21774 } 21775 } 21776 } 21777 } 21778 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21779 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21780 for (File file : files) { 21781 final String packageName = file.getName(); 21782 try { 21783 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21784 } catch (PackageManagerException e) { 21785 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21786 try { 21787 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21788 StorageManager.FLAG_STORAGE_DE, 0); 21789 } catch (InstallerException e2) { 21790 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21791 } 21792 } 21793 } 21794 } 21795 21796 // Ensure that data directories are ready to roll for all packages 21797 // installed for this volume and user 21798 final List<PackageSetting> packages; 21799 synchronized (mPackages) { 21800 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21801 } 21802 int preparedCount = 0; 21803 for (PackageSetting ps : packages) { 21804 final String packageName = ps.name; 21805 if (ps.pkg == null) { 21806 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21807 // TODO: might be due to legacy ASEC apps; we should circle back 21808 // and reconcile again once they're scanned 21809 continue; 21810 } 21811 // Skip non-core apps if requested 21812 if (onlyCoreApps && !ps.pkg.coreApp) { 21813 result.add(packageName); 21814 continue; 21815 } 21816 21817 if (ps.getInstalled(userId)) { 21818 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21819 preparedCount++; 21820 } 21821 } 21822 21823 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21824 return result; 21825 } 21826 21827 /** 21828 * Prepare app data for the given app just after it was installed or 21829 * upgraded. This method carefully only touches users that it's installed 21830 * for, and it forces a restorecon to handle any seinfo changes. 21831 * <p> 21832 * Verifies that directories exist and that ownership and labeling is 21833 * correct for all installed apps. If there is an ownership mismatch, it 21834 * will try recovering system apps by wiping data; third-party app data is 21835 * left intact. 21836 * <p> 21837 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21838 */ 21839 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21840 final PackageSetting ps; 21841 synchronized (mPackages) { 21842 ps = mSettings.mPackages.get(pkg.packageName); 21843 mSettings.writeKernelMappingLPr(ps); 21844 } 21845 21846 final UserManager um = mContext.getSystemService(UserManager.class); 21847 UserManagerInternal umInternal = getUserManagerInternal(); 21848 for (UserInfo user : um.getUsers()) { 21849 final int flags; 21850 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21851 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21852 } else if (umInternal.isUserRunning(user.id)) { 21853 flags = StorageManager.FLAG_STORAGE_DE; 21854 } else { 21855 continue; 21856 } 21857 21858 if (ps.getInstalled(user.id)) { 21859 // TODO: when user data is locked, mark that we're still dirty 21860 prepareAppDataLIF(pkg, user.id, flags); 21861 } 21862 } 21863 } 21864 21865 /** 21866 * Prepare app data for the given app. 21867 * <p> 21868 * Verifies that directories exist and that ownership and labeling is 21869 * correct for all installed apps. If there is an ownership mismatch, this 21870 * will try recovering system apps by wiping data; third-party app data is 21871 * left intact. 21872 */ 21873 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21874 if (pkg == null) { 21875 Slog.wtf(TAG, "Package was null!", new Throwable()); 21876 return; 21877 } 21878 prepareAppDataLeafLIF(pkg, userId, flags); 21879 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21880 for (int i = 0; i < childCount; i++) { 21881 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21882 } 21883 } 21884 21885 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21886 boolean maybeMigrateAppData) { 21887 prepareAppDataLIF(pkg, userId, flags); 21888 21889 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21890 // We may have just shuffled around app data directories, so 21891 // prepare them one more time 21892 prepareAppDataLIF(pkg, userId, flags); 21893 } 21894 } 21895 21896 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21897 if (DEBUG_APP_DATA) { 21898 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21899 + Integer.toHexString(flags)); 21900 } 21901 21902 final String volumeUuid = pkg.volumeUuid; 21903 final String packageName = pkg.packageName; 21904 final ApplicationInfo app = pkg.applicationInfo; 21905 final int appId = UserHandle.getAppId(app.uid); 21906 21907 Preconditions.checkNotNull(app.seInfo); 21908 21909 long ceDataInode = -1; 21910 try { 21911 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21912 appId, app.seInfo, app.targetSdkVersion); 21913 } catch (InstallerException e) { 21914 if (app.isSystemApp()) { 21915 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21916 + ", but trying to recover: " + e); 21917 destroyAppDataLeafLIF(pkg, userId, flags); 21918 try { 21919 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21920 appId, app.seInfo, app.targetSdkVersion); 21921 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21922 } catch (InstallerException e2) { 21923 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21924 } 21925 } else { 21926 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21927 } 21928 } 21929 21930 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21931 // TODO: mark this structure as dirty so we persist it! 21932 synchronized (mPackages) { 21933 final PackageSetting ps = mSettings.mPackages.get(packageName); 21934 if (ps != null) { 21935 ps.setCeDataInode(ceDataInode, userId); 21936 } 21937 } 21938 } 21939 21940 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21941 } 21942 21943 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21944 if (pkg == null) { 21945 Slog.wtf(TAG, "Package was null!", new Throwable()); 21946 return; 21947 } 21948 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21949 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21950 for (int i = 0; i < childCount; i++) { 21951 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21952 } 21953 } 21954 21955 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21956 final String volumeUuid = pkg.volumeUuid; 21957 final String packageName = pkg.packageName; 21958 final ApplicationInfo app = pkg.applicationInfo; 21959 21960 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21961 // Create a native library symlink only if we have native libraries 21962 // and if the native libraries are 32 bit libraries. We do not provide 21963 // this symlink for 64 bit libraries. 21964 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21965 final String nativeLibPath = app.nativeLibraryDir; 21966 try { 21967 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21968 nativeLibPath, userId); 21969 } catch (InstallerException e) { 21970 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21971 } 21972 } 21973 } 21974 } 21975 21976 /** 21977 * For system apps on non-FBE devices, this method migrates any existing 21978 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21979 * requested by the app. 21980 */ 21981 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21982 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21983 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21984 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21985 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21986 try { 21987 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21988 storageTarget); 21989 } catch (InstallerException e) { 21990 logCriticalInfo(Log.WARN, 21991 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21992 } 21993 return true; 21994 } else { 21995 return false; 21996 } 21997 } 21998 21999 public PackageFreezer freezePackage(String packageName, String killReason) { 22000 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22001 } 22002 22003 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22004 return new PackageFreezer(packageName, userId, killReason); 22005 } 22006 22007 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22008 String killReason) { 22009 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22010 } 22011 22012 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22013 String killReason) { 22014 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22015 return new PackageFreezer(); 22016 } else { 22017 return freezePackage(packageName, userId, killReason); 22018 } 22019 } 22020 22021 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22022 String killReason) { 22023 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22024 } 22025 22026 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22027 String killReason) { 22028 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22029 return new PackageFreezer(); 22030 } else { 22031 return freezePackage(packageName, userId, killReason); 22032 } 22033 } 22034 22035 /** 22036 * Class that freezes and kills the given package upon creation, and 22037 * unfreezes it upon closing. This is typically used when doing surgery on 22038 * app code/data to prevent the app from running while you're working. 22039 */ 22040 private class PackageFreezer implements AutoCloseable { 22041 private final String mPackageName; 22042 private final PackageFreezer[] mChildren; 22043 22044 private final boolean mWeFroze; 22045 22046 private final AtomicBoolean mClosed = new AtomicBoolean(); 22047 private final CloseGuard mCloseGuard = CloseGuard.get(); 22048 22049 /** 22050 * Create and return a stub freezer that doesn't actually do anything, 22051 * typically used when someone requested 22052 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22053 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22054 */ 22055 public PackageFreezer() { 22056 mPackageName = null; 22057 mChildren = null; 22058 mWeFroze = false; 22059 mCloseGuard.open("close"); 22060 } 22061 22062 public PackageFreezer(String packageName, int userId, String killReason) { 22063 synchronized (mPackages) { 22064 mPackageName = packageName; 22065 mWeFroze = mFrozenPackages.add(mPackageName); 22066 22067 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22068 if (ps != null) { 22069 killApplication(ps.name, ps.appId, userId, killReason); 22070 } 22071 22072 final PackageParser.Package p = mPackages.get(packageName); 22073 if (p != null && p.childPackages != null) { 22074 final int N = p.childPackages.size(); 22075 mChildren = new PackageFreezer[N]; 22076 for (int i = 0; i < N; i++) { 22077 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22078 userId, killReason); 22079 } 22080 } else { 22081 mChildren = null; 22082 } 22083 } 22084 mCloseGuard.open("close"); 22085 } 22086 22087 @Override 22088 protected void finalize() throws Throwable { 22089 try { 22090 mCloseGuard.warnIfOpen(); 22091 close(); 22092 } finally { 22093 super.finalize(); 22094 } 22095 } 22096 22097 @Override 22098 public void close() { 22099 mCloseGuard.close(); 22100 if (mClosed.compareAndSet(false, true)) { 22101 synchronized (mPackages) { 22102 if (mWeFroze) { 22103 mFrozenPackages.remove(mPackageName); 22104 } 22105 22106 if (mChildren != null) { 22107 for (PackageFreezer freezer : mChildren) { 22108 freezer.close(); 22109 } 22110 } 22111 } 22112 } 22113 } 22114 } 22115 22116 /** 22117 * Verify that given package is currently frozen. 22118 */ 22119 private void checkPackageFrozen(String packageName) { 22120 synchronized (mPackages) { 22121 if (!mFrozenPackages.contains(packageName)) { 22122 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22123 } 22124 } 22125 } 22126 22127 @Override 22128 public int movePackage(final String packageName, final String volumeUuid) { 22129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22130 22131 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22132 final int moveId = mNextMoveId.getAndIncrement(); 22133 mHandler.post(new Runnable() { 22134 @Override 22135 public void run() { 22136 try { 22137 movePackageInternal(packageName, volumeUuid, moveId, user); 22138 } catch (PackageManagerException e) { 22139 Slog.w(TAG, "Failed to move " + packageName, e); 22140 mMoveCallbacks.notifyStatusChanged(moveId, 22141 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22142 } 22143 } 22144 }); 22145 return moveId; 22146 } 22147 22148 private void movePackageInternal(final String packageName, final String volumeUuid, 22149 final int moveId, UserHandle user) throws PackageManagerException { 22150 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22151 final PackageManager pm = mContext.getPackageManager(); 22152 22153 final boolean currentAsec; 22154 final String currentVolumeUuid; 22155 final File codeFile; 22156 final String installerPackageName; 22157 final String packageAbiOverride; 22158 final int appId; 22159 final String seinfo; 22160 final String label; 22161 final int targetSdkVersion; 22162 final PackageFreezer freezer; 22163 final int[] installedUserIds; 22164 22165 // reader 22166 synchronized (mPackages) { 22167 final PackageParser.Package pkg = mPackages.get(packageName); 22168 final PackageSetting ps = mSettings.mPackages.get(packageName); 22169 if (pkg == null || ps == null) { 22170 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22171 } 22172 22173 if (pkg.applicationInfo.isSystemApp()) { 22174 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22175 "Cannot move system application"); 22176 } 22177 22178 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22179 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22180 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22181 if (isInternalStorage && !allow3rdPartyOnInternal) { 22182 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22183 "3rd party apps are not allowed on internal storage"); 22184 } 22185 22186 if (pkg.applicationInfo.isExternalAsec()) { 22187 currentAsec = true; 22188 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22189 } else if (pkg.applicationInfo.isForwardLocked()) { 22190 currentAsec = true; 22191 currentVolumeUuid = "forward_locked"; 22192 } else { 22193 currentAsec = false; 22194 currentVolumeUuid = ps.volumeUuid; 22195 22196 final File probe = new File(pkg.codePath); 22197 final File probeOat = new File(probe, "oat"); 22198 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22199 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22200 "Move only supported for modern cluster style installs"); 22201 } 22202 } 22203 22204 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22205 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22206 "Package already moved to " + volumeUuid); 22207 } 22208 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22209 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22210 "Device admin cannot be moved"); 22211 } 22212 22213 if (mFrozenPackages.contains(packageName)) { 22214 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22215 "Failed to move already frozen package"); 22216 } 22217 22218 codeFile = new File(pkg.codePath); 22219 installerPackageName = ps.installerPackageName; 22220 packageAbiOverride = ps.cpuAbiOverrideString; 22221 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22222 seinfo = pkg.applicationInfo.seInfo; 22223 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22224 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22225 freezer = freezePackage(packageName, "movePackageInternal"); 22226 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22227 } 22228 22229 final Bundle extras = new Bundle(); 22230 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22231 extras.putString(Intent.EXTRA_TITLE, label); 22232 mMoveCallbacks.notifyCreated(moveId, extras); 22233 22234 int installFlags; 22235 final boolean moveCompleteApp; 22236 final File measurePath; 22237 22238 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22239 installFlags = INSTALL_INTERNAL; 22240 moveCompleteApp = !currentAsec; 22241 measurePath = Environment.getDataAppDirectory(volumeUuid); 22242 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22243 installFlags = INSTALL_EXTERNAL; 22244 moveCompleteApp = false; 22245 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22246 } else { 22247 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22248 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22249 || !volume.isMountedWritable()) { 22250 freezer.close(); 22251 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22252 "Move location not mounted private volume"); 22253 } 22254 22255 Preconditions.checkState(!currentAsec); 22256 22257 installFlags = INSTALL_INTERNAL; 22258 moveCompleteApp = true; 22259 measurePath = Environment.getDataAppDirectory(volumeUuid); 22260 } 22261 22262 final PackageStats stats = new PackageStats(null, -1); 22263 synchronized (mInstaller) { 22264 for (int userId : installedUserIds) { 22265 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22266 freezer.close(); 22267 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22268 "Failed to measure package size"); 22269 } 22270 } 22271 } 22272 22273 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22274 + stats.dataSize); 22275 22276 final long startFreeBytes = measurePath.getFreeSpace(); 22277 final long sizeBytes; 22278 if (moveCompleteApp) { 22279 sizeBytes = stats.codeSize + stats.dataSize; 22280 } else { 22281 sizeBytes = stats.codeSize; 22282 } 22283 22284 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22285 freezer.close(); 22286 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22287 "Not enough free space to move"); 22288 } 22289 22290 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22291 22292 final CountDownLatch installedLatch = new CountDownLatch(1); 22293 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22294 @Override 22295 public void onUserActionRequired(Intent intent) throws RemoteException { 22296 throw new IllegalStateException(); 22297 } 22298 22299 @Override 22300 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22301 Bundle extras) throws RemoteException { 22302 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22303 + PackageManager.installStatusToString(returnCode, msg)); 22304 22305 installedLatch.countDown(); 22306 freezer.close(); 22307 22308 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22309 switch (status) { 22310 case PackageInstaller.STATUS_SUCCESS: 22311 mMoveCallbacks.notifyStatusChanged(moveId, 22312 PackageManager.MOVE_SUCCEEDED); 22313 break; 22314 case PackageInstaller.STATUS_FAILURE_STORAGE: 22315 mMoveCallbacks.notifyStatusChanged(moveId, 22316 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22317 break; 22318 default: 22319 mMoveCallbacks.notifyStatusChanged(moveId, 22320 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22321 break; 22322 } 22323 } 22324 }; 22325 22326 final MoveInfo move; 22327 if (moveCompleteApp) { 22328 // Kick off a thread to report progress estimates 22329 new Thread() { 22330 @Override 22331 public void run() { 22332 while (true) { 22333 try { 22334 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22335 break; 22336 } 22337 } catch (InterruptedException ignored) { 22338 } 22339 22340 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22341 final int progress = 10 + (int) MathUtils.constrain( 22342 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22343 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22344 } 22345 } 22346 }.start(); 22347 22348 final String dataAppName = codeFile.getName(); 22349 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22350 dataAppName, appId, seinfo, targetSdkVersion); 22351 } else { 22352 move = null; 22353 } 22354 22355 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22356 22357 final Message msg = mHandler.obtainMessage(INIT_COPY); 22358 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22359 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22360 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22361 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22362 PackageManager.INSTALL_REASON_UNKNOWN); 22363 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22364 msg.obj = params; 22365 22366 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22367 System.identityHashCode(msg.obj)); 22368 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22369 System.identityHashCode(msg.obj)); 22370 22371 mHandler.sendMessage(msg); 22372 } 22373 22374 @Override 22375 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22376 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22377 22378 final int realMoveId = mNextMoveId.getAndIncrement(); 22379 final Bundle extras = new Bundle(); 22380 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22381 mMoveCallbacks.notifyCreated(realMoveId, extras); 22382 22383 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22384 @Override 22385 public void onCreated(int moveId, Bundle extras) { 22386 // Ignored 22387 } 22388 22389 @Override 22390 public void onStatusChanged(int moveId, int status, long estMillis) { 22391 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22392 } 22393 }; 22394 22395 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22396 storage.setPrimaryStorageUuid(volumeUuid, callback); 22397 return realMoveId; 22398 } 22399 22400 @Override 22401 public int getMoveStatus(int moveId) { 22402 mContext.enforceCallingOrSelfPermission( 22403 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22404 return mMoveCallbacks.mLastStatus.get(moveId); 22405 } 22406 22407 @Override 22408 public void registerMoveCallback(IPackageMoveObserver callback) { 22409 mContext.enforceCallingOrSelfPermission( 22410 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22411 mMoveCallbacks.register(callback); 22412 } 22413 22414 @Override 22415 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22416 mContext.enforceCallingOrSelfPermission( 22417 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22418 mMoveCallbacks.unregister(callback); 22419 } 22420 22421 @Override 22422 public boolean setInstallLocation(int loc) { 22423 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22424 null); 22425 if (getInstallLocation() == loc) { 22426 return true; 22427 } 22428 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22429 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22430 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22431 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22432 return true; 22433 } 22434 return false; 22435 } 22436 22437 @Override 22438 public int getInstallLocation() { 22439 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22440 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22441 PackageHelper.APP_INSTALL_AUTO); 22442 } 22443 22444 /** Called by UserManagerService */ 22445 void cleanUpUser(UserManagerService userManager, int userHandle) { 22446 synchronized (mPackages) { 22447 mDirtyUsers.remove(userHandle); 22448 mUserNeedsBadging.delete(userHandle); 22449 mSettings.removeUserLPw(userHandle); 22450 mPendingBroadcasts.remove(userHandle); 22451 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22452 removeUnusedPackagesLPw(userManager, userHandle); 22453 } 22454 } 22455 22456 /** 22457 * We're removing userHandle and would like to remove any downloaded packages 22458 * that are no longer in use by any other user. 22459 * @param userHandle the user being removed 22460 */ 22461 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22462 final boolean DEBUG_CLEAN_APKS = false; 22463 int [] users = userManager.getUserIds(); 22464 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22465 while (psit.hasNext()) { 22466 PackageSetting ps = psit.next(); 22467 if (ps.pkg == null) { 22468 continue; 22469 } 22470 final String packageName = ps.pkg.packageName; 22471 // Skip over if system app 22472 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22473 continue; 22474 } 22475 if (DEBUG_CLEAN_APKS) { 22476 Slog.i(TAG, "Checking package " + packageName); 22477 } 22478 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22479 if (keep) { 22480 if (DEBUG_CLEAN_APKS) { 22481 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22482 } 22483 } else { 22484 for (int i = 0; i < users.length; i++) { 22485 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22486 keep = true; 22487 if (DEBUG_CLEAN_APKS) { 22488 Slog.i(TAG, " Keeping package " + packageName + " for user " 22489 + users[i]); 22490 } 22491 break; 22492 } 22493 } 22494 } 22495 if (!keep) { 22496 if (DEBUG_CLEAN_APKS) { 22497 Slog.i(TAG, " Removing package " + packageName); 22498 } 22499 mHandler.post(new Runnable() { 22500 public void run() { 22501 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22502 userHandle, 0); 22503 } //end run 22504 }); 22505 } 22506 } 22507 } 22508 22509 /** Called by UserManagerService */ 22510 void createNewUser(int userId, String[] disallowedPackages) { 22511 synchronized (mInstallLock) { 22512 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22513 } 22514 synchronized (mPackages) { 22515 scheduleWritePackageRestrictionsLocked(userId); 22516 scheduleWritePackageListLocked(userId); 22517 applyFactoryDefaultBrowserLPw(userId); 22518 primeDomainVerificationsLPw(userId); 22519 } 22520 } 22521 22522 void onNewUserCreated(final int userId) { 22523 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22524 // If permission review for legacy apps is required, we represent 22525 // dagerous permissions for such apps as always granted runtime 22526 // permissions to keep per user flag state whether review is needed. 22527 // Hence, if a new user is added we have to propagate dangerous 22528 // permission grants for these legacy apps. 22529 if (mPermissionReviewRequired) { 22530 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22531 | UPDATE_PERMISSIONS_REPLACE_ALL); 22532 } 22533 } 22534 22535 @Override 22536 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22537 mContext.enforceCallingOrSelfPermission( 22538 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22539 "Only package verification agents can read the verifier device identity"); 22540 22541 synchronized (mPackages) { 22542 return mSettings.getVerifierDeviceIdentityLPw(); 22543 } 22544 } 22545 22546 @Override 22547 public void setPermissionEnforced(String permission, boolean enforced) { 22548 // TODO: Now that we no longer change GID for storage, this should to away. 22549 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22550 "setPermissionEnforced"); 22551 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22552 synchronized (mPackages) { 22553 if (mSettings.mReadExternalStorageEnforced == null 22554 || mSettings.mReadExternalStorageEnforced != enforced) { 22555 mSettings.mReadExternalStorageEnforced = enforced; 22556 mSettings.writeLPr(); 22557 } 22558 } 22559 // kill any non-foreground processes so we restart them and 22560 // grant/revoke the GID. 22561 final IActivityManager am = ActivityManager.getService(); 22562 if (am != null) { 22563 final long token = Binder.clearCallingIdentity(); 22564 try { 22565 am.killProcessesBelowForeground("setPermissionEnforcement"); 22566 } catch (RemoteException e) { 22567 } finally { 22568 Binder.restoreCallingIdentity(token); 22569 } 22570 } 22571 } else { 22572 throw new IllegalArgumentException("No selective enforcement for " + permission); 22573 } 22574 } 22575 22576 @Override 22577 @Deprecated 22578 public boolean isPermissionEnforced(String permission) { 22579 return true; 22580 } 22581 22582 @Override 22583 public boolean isStorageLow() { 22584 final long token = Binder.clearCallingIdentity(); 22585 try { 22586 final DeviceStorageMonitorInternal 22587 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22588 if (dsm != null) { 22589 return dsm.isMemoryLow(); 22590 } else { 22591 return false; 22592 } 22593 } finally { 22594 Binder.restoreCallingIdentity(token); 22595 } 22596 } 22597 22598 @Override 22599 public IPackageInstaller getPackageInstaller() { 22600 return mInstallerService; 22601 } 22602 22603 private boolean userNeedsBadging(int userId) { 22604 int index = mUserNeedsBadging.indexOfKey(userId); 22605 if (index < 0) { 22606 final UserInfo userInfo; 22607 final long token = Binder.clearCallingIdentity(); 22608 try { 22609 userInfo = sUserManager.getUserInfo(userId); 22610 } finally { 22611 Binder.restoreCallingIdentity(token); 22612 } 22613 final boolean b; 22614 if (userInfo != null && userInfo.isManagedProfile()) { 22615 b = true; 22616 } else { 22617 b = false; 22618 } 22619 mUserNeedsBadging.put(userId, b); 22620 return b; 22621 } 22622 return mUserNeedsBadging.valueAt(index); 22623 } 22624 22625 @Override 22626 public KeySet getKeySetByAlias(String packageName, String alias) { 22627 if (packageName == null || alias == null) { 22628 return null; 22629 } 22630 synchronized(mPackages) { 22631 final PackageParser.Package pkg = mPackages.get(packageName); 22632 if (pkg == null) { 22633 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22634 throw new IllegalArgumentException("Unknown package: " + packageName); 22635 } 22636 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22637 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22638 } 22639 } 22640 22641 @Override 22642 public KeySet getSigningKeySet(String packageName) { 22643 if (packageName == null) { 22644 return null; 22645 } 22646 synchronized(mPackages) { 22647 final PackageParser.Package pkg = mPackages.get(packageName); 22648 if (pkg == null) { 22649 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22650 throw new IllegalArgumentException("Unknown package: " + packageName); 22651 } 22652 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22653 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22654 throw new SecurityException("May not access signing KeySet of other apps."); 22655 } 22656 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22657 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22658 } 22659 } 22660 22661 @Override 22662 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22663 if (packageName == null || ks == null) { 22664 return false; 22665 } 22666 synchronized(mPackages) { 22667 final PackageParser.Package pkg = mPackages.get(packageName); 22668 if (pkg == null) { 22669 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22670 throw new IllegalArgumentException("Unknown package: " + packageName); 22671 } 22672 IBinder ksh = ks.getToken(); 22673 if (ksh instanceof KeySetHandle) { 22674 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22675 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22676 } 22677 return false; 22678 } 22679 } 22680 22681 @Override 22682 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22683 if (packageName == null || ks == null) { 22684 return false; 22685 } 22686 synchronized(mPackages) { 22687 final PackageParser.Package pkg = mPackages.get(packageName); 22688 if (pkg == null) { 22689 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22690 throw new IllegalArgumentException("Unknown package: " + packageName); 22691 } 22692 IBinder ksh = ks.getToken(); 22693 if (ksh instanceof KeySetHandle) { 22694 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22695 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22696 } 22697 return false; 22698 } 22699 } 22700 22701 private void deletePackageIfUnusedLPr(final String packageName) { 22702 PackageSetting ps = mSettings.mPackages.get(packageName); 22703 if (ps == null) { 22704 return; 22705 } 22706 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22707 // TODO Implement atomic delete if package is unused 22708 // It is currently possible that the package will be deleted even if it is installed 22709 // after this method returns. 22710 mHandler.post(new Runnable() { 22711 public void run() { 22712 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22713 0, PackageManager.DELETE_ALL_USERS); 22714 } 22715 }); 22716 } 22717 } 22718 22719 /** 22720 * Check and throw if the given before/after packages would be considered a 22721 * downgrade. 22722 */ 22723 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22724 throws PackageManagerException { 22725 if (after.versionCode < before.mVersionCode) { 22726 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22727 "Update version code " + after.versionCode + " is older than current " 22728 + before.mVersionCode); 22729 } else if (after.versionCode == before.mVersionCode) { 22730 if (after.baseRevisionCode < before.baseRevisionCode) { 22731 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22732 "Update base revision code " + after.baseRevisionCode 22733 + " is older than current " + before.baseRevisionCode); 22734 } 22735 22736 if (!ArrayUtils.isEmpty(after.splitNames)) { 22737 for (int i = 0; i < after.splitNames.length; i++) { 22738 final String splitName = after.splitNames[i]; 22739 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22740 if (j != -1) { 22741 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22742 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22743 "Update split " + splitName + " revision code " 22744 + after.splitRevisionCodes[i] + " is older than current " 22745 + before.splitRevisionCodes[j]); 22746 } 22747 } 22748 } 22749 } 22750 } 22751 } 22752 22753 private static class MoveCallbacks extends Handler { 22754 private static final int MSG_CREATED = 1; 22755 private static final int MSG_STATUS_CHANGED = 2; 22756 22757 private final RemoteCallbackList<IPackageMoveObserver> 22758 mCallbacks = new RemoteCallbackList<>(); 22759 22760 private final SparseIntArray mLastStatus = new SparseIntArray(); 22761 22762 public MoveCallbacks(Looper looper) { 22763 super(looper); 22764 } 22765 22766 public void register(IPackageMoveObserver callback) { 22767 mCallbacks.register(callback); 22768 } 22769 22770 public void unregister(IPackageMoveObserver callback) { 22771 mCallbacks.unregister(callback); 22772 } 22773 22774 @Override 22775 public void handleMessage(Message msg) { 22776 final SomeArgs args = (SomeArgs) msg.obj; 22777 final int n = mCallbacks.beginBroadcast(); 22778 for (int i = 0; i < n; i++) { 22779 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22780 try { 22781 invokeCallback(callback, msg.what, args); 22782 } catch (RemoteException ignored) { 22783 } 22784 } 22785 mCallbacks.finishBroadcast(); 22786 args.recycle(); 22787 } 22788 22789 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22790 throws RemoteException { 22791 switch (what) { 22792 case MSG_CREATED: { 22793 callback.onCreated(args.argi1, (Bundle) args.arg2); 22794 break; 22795 } 22796 case MSG_STATUS_CHANGED: { 22797 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22798 break; 22799 } 22800 } 22801 } 22802 22803 private void notifyCreated(int moveId, Bundle extras) { 22804 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22805 22806 final SomeArgs args = SomeArgs.obtain(); 22807 args.argi1 = moveId; 22808 args.arg2 = extras; 22809 obtainMessage(MSG_CREATED, args).sendToTarget(); 22810 } 22811 22812 private void notifyStatusChanged(int moveId, int status) { 22813 notifyStatusChanged(moveId, status, -1); 22814 } 22815 22816 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22817 Slog.v(TAG, "Move " + moveId + " status " + status); 22818 22819 final SomeArgs args = SomeArgs.obtain(); 22820 args.argi1 = moveId; 22821 args.argi2 = status; 22822 args.arg3 = estMillis; 22823 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22824 22825 synchronized (mLastStatus) { 22826 mLastStatus.put(moveId, status); 22827 } 22828 } 22829 } 22830 22831 private final static class OnPermissionChangeListeners extends Handler { 22832 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22833 22834 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22835 new RemoteCallbackList<>(); 22836 22837 public OnPermissionChangeListeners(Looper looper) { 22838 super(looper); 22839 } 22840 22841 @Override 22842 public void handleMessage(Message msg) { 22843 switch (msg.what) { 22844 case MSG_ON_PERMISSIONS_CHANGED: { 22845 final int uid = msg.arg1; 22846 handleOnPermissionsChanged(uid); 22847 } break; 22848 } 22849 } 22850 22851 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22852 mPermissionListeners.register(listener); 22853 22854 } 22855 22856 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22857 mPermissionListeners.unregister(listener); 22858 } 22859 22860 public void onPermissionsChanged(int uid) { 22861 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22862 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22863 } 22864 } 22865 22866 private void handleOnPermissionsChanged(int uid) { 22867 final int count = mPermissionListeners.beginBroadcast(); 22868 try { 22869 for (int i = 0; i < count; i++) { 22870 IOnPermissionsChangeListener callback = mPermissionListeners 22871 .getBroadcastItem(i); 22872 try { 22873 callback.onPermissionsChanged(uid); 22874 } catch (RemoteException e) { 22875 Log.e(TAG, "Permission listener is dead", e); 22876 } 22877 } 22878 } finally { 22879 mPermissionListeners.finishBroadcast(); 22880 } 22881 } 22882 } 22883 22884 private class PackageManagerInternalImpl extends PackageManagerInternal { 22885 @Override 22886 public void setLocationPackagesProvider(PackagesProvider provider) { 22887 synchronized (mPackages) { 22888 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22889 } 22890 } 22891 22892 @Override 22893 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22894 synchronized (mPackages) { 22895 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22896 } 22897 } 22898 22899 @Override 22900 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22901 synchronized (mPackages) { 22902 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22903 } 22904 } 22905 22906 @Override 22907 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22908 synchronized (mPackages) { 22909 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22910 } 22911 } 22912 22913 @Override 22914 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22915 synchronized (mPackages) { 22916 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22917 } 22918 } 22919 22920 @Override 22921 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22922 synchronized (mPackages) { 22923 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22924 } 22925 } 22926 22927 @Override 22928 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22929 synchronized (mPackages) { 22930 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22931 packageName, userId); 22932 } 22933 } 22934 22935 @Override 22936 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22937 synchronized (mPackages) { 22938 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22939 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22940 packageName, userId); 22941 } 22942 } 22943 22944 @Override 22945 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22946 synchronized (mPackages) { 22947 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22948 packageName, userId); 22949 } 22950 } 22951 22952 @Override 22953 public void setKeepUninstalledPackages(final List<String> packageList) { 22954 Preconditions.checkNotNull(packageList); 22955 List<String> removedFromList = null; 22956 synchronized (mPackages) { 22957 if (mKeepUninstalledPackages != null) { 22958 final int packagesCount = mKeepUninstalledPackages.size(); 22959 for (int i = 0; i < packagesCount; i++) { 22960 String oldPackage = mKeepUninstalledPackages.get(i); 22961 if (packageList != null && packageList.contains(oldPackage)) { 22962 continue; 22963 } 22964 if (removedFromList == null) { 22965 removedFromList = new ArrayList<>(); 22966 } 22967 removedFromList.add(oldPackage); 22968 } 22969 } 22970 mKeepUninstalledPackages = new ArrayList<>(packageList); 22971 if (removedFromList != null) { 22972 final int removedCount = removedFromList.size(); 22973 for (int i = 0; i < removedCount; i++) { 22974 deletePackageIfUnusedLPr(removedFromList.get(i)); 22975 } 22976 } 22977 } 22978 } 22979 22980 @Override 22981 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22982 synchronized (mPackages) { 22983 // If we do not support permission review, done. 22984 if (!mPermissionReviewRequired) { 22985 return false; 22986 } 22987 22988 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22989 if (packageSetting == null) { 22990 return false; 22991 } 22992 22993 // Permission review applies only to apps not supporting the new permission model. 22994 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22995 return false; 22996 } 22997 22998 // Legacy apps have the permission and get user consent on launch. 22999 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23000 return permissionsState.isPermissionReviewRequired(userId); 23001 } 23002 } 23003 23004 @Override 23005 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23006 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23007 } 23008 23009 @Override 23010 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23011 int userId) { 23012 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23013 } 23014 23015 @Override 23016 public void setDeviceAndProfileOwnerPackages( 23017 int deviceOwnerUserId, String deviceOwnerPackage, 23018 SparseArray<String> profileOwnerPackages) { 23019 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23020 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23021 } 23022 23023 @Override 23024 public boolean isPackageDataProtected(int userId, String packageName) { 23025 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23026 } 23027 23028 @Override 23029 public boolean isPackageEphemeral(int userId, String packageName) { 23030 synchronized (mPackages) { 23031 final PackageSetting ps = mSettings.mPackages.get(packageName); 23032 return ps != null ? ps.getInstantApp(userId) : false; 23033 } 23034 } 23035 23036 @Override 23037 public boolean wasPackageEverLaunched(String packageName, int userId) { 23038 synchronized (mPackages) { 23039 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23040 } 23041 } 23042 23043 @Override 23044 public void grantRuntimePermission(String packageName, String name, int userId, 23045 boolean overridePolicy) { 23046 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23047 overridePolicy); 23048 } 23049 23050 @Override 23051 public void revokeRuntimePermission(String packageName, String name, int userId, 23052 boolean overridePolicy) { 23053 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23054 overridePolicy); 23055 } 23056 23057 @Override 23058 public String getNameForUid(int uid) { 23059 return PackageManagerService.this.getNameForUid(uid); 23060 } 23061 23062 @Override 23063 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23064 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23065 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23066 responseObj, origIntent, resolvedType, callingPackage, userId); 23067 } 23068 23069 @Override 23070 public void grantEphemeralAccess(int userId, Intent intent, 23071 int targetAppId, int ephemeralAppId) { 23072 synchronized (mPackages) { 23073 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23074 targetAppId, ephemeralAppId); 23075 } 23076 } 23077 23078 @Override 23079 public boolean isInstantAppInstallerComponent(ComponentName component) { 23080 synchronized (mPackages) { 23081 return component != null && component.equals(mInstantAppInstallerComponent); 23082 } 23083 } 23084 23085 @Override 23086 public void pruneInstantApps() { 23087 synchronized (mPackages) { 23088 mInstantAppRegistry.pruneInstantAppsLPw(); 23089 } 23090 } 23091 23092 @Override 23093 public String getSetupWizardPackageName() { 23094 return mSetupWizardPackage; 23095 } 23096 23097 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23098 if (policy != null) { 23099 mExternalSourcesPolicy = policy; 23100 } 23101 } 23102 23103 @Override 23104 public boolean isPackagePersistent(String packageName) { 23105 synchronized (mPackages) { 23106 PackageParser.Package pkg = mPackages.get(packageName); 23107 return pkg != null 23108 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23109 | ApplicationInfo.FLAG_PERSISTENT)) == 23110 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23111 : false; 23112 } 23113 } 23114 23115 @Override 23116 public List<PackageInfo> getOverlayPackages(int userId) { 23117 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23118 synchronized (mPackages) { 23119 for (PackageParser.Package p : mPackages.values()) { 23120 if (p.mOverlayTarget != null) { 23121 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23122 if (pkg != null) { 23123 overlayPackages.add(pkg); 23124 } 23125 } 23126 } 23127 } 23128 return overlayPackages; 23129 } 23130 23131 @Override 23132 public List<String> getTargetPackageNames(int userId) { 23133 List<String> targetPackages = new ArrayList<>(); 23134 synchronized (mPackages) { 23135 for (PackageParser.Package p : mPackages.values()) { 23136 if (p.mOverlayTarget == null) { 23137 targetPackages.add(p.packageName); 23138 } 23139 } 23140 } 23141 return targetPackages; 23142 } 23143 23144 @Override 23145 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23146 @Nullable List<String> overlayPackageNames) { 23147 synchronized (mPackages) { 23148 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23149 Slog.e(TAG, "failed to find package " + targetPackageName); 23150 return false; 23151 } 23152 23153 ArrayList<String> paths = null; 23154 if (overlayPackageNames != null) { 23155 final int N = overlayPackageNames.size(); 23156 paths = new ArrayList<>(N); 23157 for (int i = 0; i < N; i++) { 23158 final String packageName = overlayPackageNames.get(i); 23159 final PackageParser.Package pkg = mPackages.get(packageName); 23160 if (pkg == null) { 23161 Slog.e(TAG, "failed to find package " + packageName); 23162 return false; 23163 } 23164 paths.add(pkg.baseCodePath); 23165 } 23166 } 23167 23168 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23169 mEnabledOverlayPaths.get(userId); 23170 if (userSpecificOverlays == null) { 23171 userSpecificOverlays = new ArrayMap<>(); 23172 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23173 } 23174 23175 if (paths != null && paths.size() > 0) { 23176 userSpecificOverlays.put(targetPackageName, paths); 23177 } else { 23178 userSpecificOverlays.remove(targetPackageName); 23179 } 23180 return true; 23181 } 23182 } 23183 23184 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23185 int flags, int userId) { 23186 return resolveIntentInternal( 23187 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23188 } 23189 } 23190 23191 @Override 23192 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23193 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23194 synchronized (mPackages) { 23195 final long identity = Binder.clearCallingIdentity(); 23196 try { 23197 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23198 packageNames, userId); 23199 } finally { 23200 Binder.restoreCallingIdentity(identity); 23201 } 23202 } 23203 } 23204 23205 @Override 23206 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23207 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23208 synchronized (mPackages) { 23209 final long identity = Binder.clearCallingIdentity(); 23210 try { 23211 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23212 packageNames, userId); 23213 } finally { 23214 Binder.restoreCallingIdentity(identity); 23215 } 23216 } 23217 } 23218 23219 private static void enforceSystemOrPhoneCaller(String tag) { 23220 int callingUid = Binder.getCallingUid(); 23221 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23222 throw new SecurityException( 23223 "Cannot call " + tag + " from UID " + callingUid); 23224 } 23225 } 23226 23227 boolean isHistoricalPackageUsageAvailable() { 23228 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23229 } 23230 23231 /** 23232 * Return a <b>copy</b> of the collection of packages known to the package manager. 23233 * @return A copy of the values of mPackages. 23234 */ 23235 Collection<PackageParser.Package> getPackages() { 23236 synchronized (mPackages) { 23237 return new ArrayList<>(mPackages.values()); 23238 } 23239 } 23240 23241 /** 23242 * Logs process start information (including base APK hash) to the security log. 23243 * @hide 23244 */ 23245 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23246 String apkFile, int pid) { 23247 if (!SecurityLog.isLoggingEnabled()) { 23248 return; 23249 } 23250 Bundle data = new Bundle(); 23251 data.putLong("startTimestamp", System.currentTimeMillis()); 23252 data.putString("processName", processName); 23253 data.putInt("uid", uid); 23254 data.putString("seinfo", seinfo); 23255 data.putString("apkFile", apkFile); 23256 data.putInt("pid", pid); 23257 Message msg = mProcessLoggingHandler.obtainMessage( 23258 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23259 msg.setData(data); 23260 mProcessLoggingHandler.sendMessage(msg); 23261 } 23262 23263 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23264 return mCompilerStats.getPackageStats(pkgName); 23265 } 23266 23267 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23268 return getOrCreateCompilerPackageStats(pkg.packageName); 23269 } 23270 23271 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23272 return mCompilerStats.getOrCreatePackageStats(pkgName); 23273 } 23274 23275 public void deleteCompilerPackageStats(String pkgName) { 23276 mCompilerStats.deletePackageStats(pkgName); 23277 } 23278 23279 @Override 23280 public int getInstallReason(String packageName, int userId) { 23281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23282 true /* requireFullPermission */, false /* checkShell */, 23283 "get install reason"); 23284 synchronized (mPackages) { 23285 final PackageSetting ps = mSettings.mPackages.get(packageName); 23286 if (ps != null) { 23287 return ps.getInstallReason(userId); 23288 } 23289 } 23290 return PackageManager.INSTALL_REASON_UNKNOWN; 23291 } 23292 23293 @Override 23294 public boolean canRequestPackageInstalls(String packageName, int userId) { 23295 int callingUid = Binder.getCallingUid(); 23296 int uid = getPackageUid(packageName, 0, userId); 23297 if (callingUid != uid && callingUid != Process.ROOT_UID 23298 && callingUid != Process.SYSTEM_UID) { 23299 throw new SecurityException( 23300 "Caller uid " + callingUid + " does not own package " + packageName); 23301 } 23302 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23303 if (info == null) { 23304 return false; 23305 } 23306 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23307 throw new UnsupportedOperationException( 23308 "Operation only supported on apps targeting Android O or higher"); 23309 } 23310 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23311 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23312 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23313 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23314 } 23315 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23316 return false; 23317 } 23318 if (mExternalSourcesPolicy != null) { 23319 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23320 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23321 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23322 } 23323 } 23324 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23325 } 23326} 23327