PackageManagerService.java revision 910a19a535760df574371534bec030f9335bc351
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_EPHEMERAL_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.ComponentInfo; 130import android.content.pm.EphemeralApplicationInfo; 131import android.content.pm.EphemeralRequest; 132import android.content.pm.EphemeralResolveInfo; 133import android.content.pm.EphemeralResponse; 134import android.content.pm.FallbackCategoryProvider; 135import android.content.pm.FeatureInfo; 136import android.content.pm.IOnPermissionsChangeListener; 137import android.content.pm.IPackageDataObserver; 138import android.content.pm.IPackageDeleteObserver; 139import android.content.pm.IPackageDeleteObserver2; 140import android.content.pm.IPackageInstallObserver2; 141import android.content.pm.IPackageInstaller; 142import android.content.pm.IPackageManager; 143import android.content.pm.IPackageMoveObserver; 144import android.content.pm.IPackageStatsObserver; 145import android.content.pm.InstrumentationInfo; 146import android.content.pm.IntentFilterVerificationInfo; 147import android.content.pm.KeySet; 148import android.content.pm.PackageCleanItem; 149import android.content.pm.PackageInfo; 150import android.content.pm.PackageInfoLite; 151import android.content.pm.PackageInstaller; 152import android.content.pm.PackageManager; 153import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 154import android.content.pm.PackageManagerInternal; 155import android.content.pm.PackageParser; 156import android.content.pm.PackageParser.ActivityIntentInfo; 157import android.content.pm.PackageParser.PackageLite; 158import android.content.pm.PackageParser.PackageParserException; 159import android.content.pm.PackageStats; 160import android.content.pm.PackageUserState; 161import android.content.pm.ParceledListSlice; 162import android.content.pm.PermissionGroupInfo; 163import android.content.pm.PermissionInfo; 164import android.content.pm.ProviderInfo; 165import android.content.pm.ResolveInfo; 166import android.content.pm.ServiceInfo; 167import android.content.pm.SharedLibraryInfo; 168import android.content.pm.Signature; 169import android.content.pm.UserInfo; 170import android.content.pm.VerifierDeviceIdentity; 171import android.content.pm.VerifierInfo; 172import android.content.pm.VersionedPackage; 173import android.content.res.Resources; 174import android.graphics.Bitmap; 175import android.hardware.display.DisplayManager; 176import android.net.Uri; 177import android.os.Binder; 178import android.os.Build; 179import android.os.Bundle; 180import android.os.Debug; 181import android.os.Environment; 182import android.os.Environment.UserEnvironment; 183import android.os.FileUtils; 184import android.os.Handler; 185import android.os.IBinder; 186import android.os.Looper; 187import android.os.Message; 188import android.os.Parcel; 189import android.os.ParcelFileDescriptor; 190import android.os.PatternMatcher; 191import android.os.Process; 192import android.os.RemoteCallbackList; 193import android.os.RemoteException; 194import android.os.ResultReceiver; 195import android.os.SELinux; 196import android.os.ServiceManager; 197import android.os.ShellCallback; 198import android.os.SystemClock; 199import android.os.SystemProperties; 200import android.os.Trace; 201import android.os.UserHandle; 202import android.os.UserManager; 203import android.os.UserManagerInternal; 204import android.os.storage.IStorageManager; 205import android.os.storage.StorageManagerInternal; 206import android.os.storage.StorageEventListener; 207import android.os.storage.StorageManager; 208import android.os.storage.VolumeInfo; 209import android.os.storage.VolumeRecord; 210import android.provider.Settings.Global; 211import android.provider.Settings.Secure; 212import android.security.KeyStore; 213import android.security.SystemKeyStore; 214import android.system.ErrnoException; 215import android.system.Os; 216import android.text.TextUtils; 217import android.text.format.DateUtils; 218import android.util.ArrayMap; 219import android.util.ArraySet; 220import android.util.Base64; 221import android.util.DisplayMetrics; 222import android.util.EventLog; 223import android.util.ExceptionUtils; 224import android.util.Log; 225import android.util.LogPrinter; 226import android.util.MathUtils; 227import android.util.PackageUtils; 228import android.util.Pair; 229import android.util.PrintStreamPrinter; 230import android.util.Slog; 231import android.util.SparseArray; 232import android.util.SparseBooleanArray; 233import android.util.SparseIntArray; 234import android.util.Xml; 235import android.util.jar.StrictJarFile; 236import android.view.Display; 237 238import com.android.internal.R; 239import com.android.internal.annotations.GuardedBy; 240import com.android.internal.app.IMediaContainerService; 241import com.android.internal.app.ResolverActivity; 242import com.android.internal.content.NativeLibraryHelper; 243import com.android.internal.content.PackageHelper; 244import com.android.internal.logging.MetricsLogger; 245import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 246import com.android.internal.os.IParcelFileDescriptorFactory; 247import com.android.internal.os.RoSystemProperties; 248import com.android.internal.os.SomeArgs; 249import com.android.internal.os.Zygote; 250import com.android.internal.telephony.CarrierAppUtils; 251import com.android.internal.util.ArrayUtils; 252import com.android.internal.util.FastPrintWriter; 253import com.android.internal.util.FastXmlSerializer; 254import com.android.internal.util.IndentingPrintWriter; 255import com.android.internal.util.Preconditions; 256import com.android.internal.util.XmlUtils; 257import com.android.server.AttributeCache; 258import com.android.server.EventLogTags; 259import com.android.server.FgThread; 260import com.android.server.IntentResolver; 261import com.android.server.LocalServices; 262import com.android.server.ServiceThread; 263import com.android.server.SystemConfig; 264import com.android.server.Watchdog; 265import com.android.server.net.NetworkPolicyManagerInternal; 266import com.android.server.pm.Installer.InstallerException; 267import com.android.server.pm.PermissionsState.PermissionState; 268import com.android.server.pm.Settings.DatabaseVersion; 269import com.android.server.pm.Settings.VersionInfo; 270import com.android.server.pm.dex.DexManager; 271import com.android.server.storage.DeviceStorageMonitorInternal; 272 273import dalvik.system.CloseGuard; 274import dalvik.system.DexFile; 275import dalvik.system.VMRuntime; 276 277import libcore.io.IoUtils; 278import libcore.util.EmptyArray; 279 280import org.xmlpull.v1.XmlPullParser; 281import org.xmlpull.v1.XmlPullParserException; 282import org.xmlpull.v1.XmlSerializer; 283 284import java.io.BufferedOutputStream; 285import java.io.BufferedReader; 286import java.io.ByteArrayInputStream; 287import java.io.ByteArrayOutputStream; 288import java.io.File; 289import java.io.FileDescriptor; 290import java.io.FileInputStream; 291import java.io.FileNotFoundException; 292import java.io.FileOutputStream; 293import java.io.FileReader; 294import java.io.FilenameFilter; 295import java.io.IOException; 296import java.io.PrintWriter; 297import java.nio.charset.StandardCharsets; 298import java.security.DigestInputStream; 299import java.security.MessageDigest; 300import java.security.NoSuchAlgorithmException; 301import java.security.PublicKey; 302import java.security.SecureRandom; 303import java.security.cert.Certificate; 304import java.security.cert.CertificateEncodingException; 305import java.security.cert.CertificateException; 306import java.text.SimpleDateFormat; 307import java.util.ArrayList; 308import java.util.Arrays; 309import java.util.Collection; 310import java.util.Collections; 311import java.util.Comparator; 312import java.util.Date; 313import java.util.HashSet; 314import java.util.HashMap; 315import java.util.Iterator; 316import java.util.List; 317import java.util.Map; 318import java.util.Objects; 319import java.util.Set; 320import java.util.concurrent.CountDownLatch; 321import java.util.concurrent.TimeUnit; 322import java.util.concurrent.atomic.AtomicBoolean; 323import java.util.concurrent.atomic.AtomicInteger; 324 325/** 326 * Keep track of all those APKs everywhere. 327 * <p> 328 * Internally there are two important locks: 329 * <ul> 330 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 331 * and other related state. It is a fine-grained lock that should only be held 332 * momentarily, as it's one of the most contended locks in the system. 333 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 334 * operations typically involve heavy lifting of application data on disk. Since 335 * {@code installd} is single-threaded, and it's operations can often be slow, 336 * this lock should never be acquired while already holding {@link #mPackages}. 337 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 338 * holding {@link #mInstallLock}. 339 * </ul> 340 * Many internal methods rely on the caller to hold the appropriate locks, and 341 * this contract is expressed through method name suffixes: 342 * <ul> 343 * <li>fooLI(): the caller must hold {@link #mInstallLock} 344 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 345 * being modified must be frozen 346 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 347 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 348 * </ul> 349 * <p> 350 * Because this class is very central to the platform's security; please run all 351 * CTS and unit tests whenever making modifications: 352 * 353 * <pre> 354 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 355 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 356 * </pre> 357 */ 358public class PackageManagerService extends IPackageManager.Stub { 359 static final String TAG = "PackageManager"; 360 static final boolean DEBUG_SETTINGS = false; 361 static final boolean DEBUG_PREFERRED = false; 362 static final boolean DEBUG_UPGRADE = false; 363 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 364 private static final boolean DEBUG_BACKUP = false; 365 private static final boolean DEBUG_INSTALL = false; 366 private static final boolean DEBUG_REMOVE = false; 367 private static final boolean DEBUG_BROADCASTS = false; 368 private static final boolean DEBUG_SHOW_INFO = false; 369 private static final boolean DEBUG_PACKAGE_INFO = false; 370 private static final boolean DEBUG_INTENT_MATCHING = false; 371 private static final boolean DEBUG_PACKAGE_SCANNING = false; 372 private static final boolean DEBUG_VERIFY = false; 373 private static final boolean DEBUG_FILTERS = false; 374 375 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 376 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 377 // user, but by default initialize to this. 378 static final boolean DEBUG_DEXOPT = false; 379 380 private static final boolean DEBUG_ABI_SELECTION = false; 381 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 382 private static final boolean DEBUG_TRIAGED_MISSING = false; 383 private static final boolean DEBUG_APP_DATA = false; 384 385 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 386 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 387 388 private static final boolean DISABLE_EPHEMERAL_APPS = false; 389 private static final boolean HIDE_EPHEMERAL_APIS = true; 390 391 private static final boolean ENABLE_QUOTA = 392 SystemProperties.getBoolean("persist.fw.quota", false); 393 394 private static final int RADIO_UID = Process.PHONE_UID; 395 private static final int LOG_UID = Process.LOG_UID; 396 private static final int NFC_UID = Process.NFC_UID; 397 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 398 private static final int SHELL_UID = Process.SHELL_UID; 399 400 // Cap the size of permission trees that 3rd party apps can define 401 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 402 403 // Suffix used during package installation when copying/moving 404 // package apks to install directory. 405 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 406 407 static final int SCAN_NO_DEX = 1<<1; 408 static final int SCAN_FORCE_DEX = 1<<2; 409 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 410 static final int SCAN_NEW_INSTALL = 1<<4; 411 static final int SCAN_UPDATE_TIME = 1<<5; 412 static final int SCAN_BOOTING = 1<<6; 413 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 414 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 415 static final int SCAN_REPLACING = 1<<9; 416 static final int SCAN_REQUIRE_KNOWN = 1<<10; 417 static final int SCAN_MOVE = 1<<11; 418 static final int SCAN_INITIAL = 1<<12; 419 static final int SCAN_CHECK_ONLY = 1<<13; 420 static final int SCAN_DONT_KILL_APP = 1<<14; 421 static final int SCAN_IGNORE_FROZEN = 1<<15; 422 static final int REMOVE_CHATTY = 1<<16; 423 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 424 425 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 426 427 private static final int[] EMPTY_INT_ARRAY = new int[0]; 428 429 /** 430 * Timeout (in milliseconds) after which the watchdog should declare that 431 * our handler thread is wedged. The usual default for such things is one 432 * minute but we sometimes do very lengthy I/O operations on this thread, 433 * such as installing multi-gigabyte applications, so ours needs to be longer. 434 */ 435 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 436 437 /** 438 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 439 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 440 * settings entry if available, otherwise we use the hardcoded default. If it's been 441 * more than this long since the last fstrim, we force one during the boot sequence. 442 * 443 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 444 * one gets run at the next available charging+idle time. This final mandatory 445 * no-fstrim check kicks in only of the other scheduling criteria is never met. 446 */ 447 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 448 449 /** 450 * Whether verification is enabled by default. 451 */ 452 private static final boolean DEFAULT_VERIFY_ENABLE = true; 453 454 /** 455 * The default maximum time to wait for the verification agent to return in 456 * milliseconds. 457 */ 458 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 459 460 /** 461 * The default response for package verification timeout. 462 * 463 * This can be either PackageManager.VERIFICATION_ALLOW or 464 * PackageManager.VERIFICATION_REJECT. 465 */ 466 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 467 468 static final String PLATFORM_PACKAGE_NAME = "android"; 469 470 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 471 472 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 473 DEFAULT_CONTAINER_PACKAGE, 474 "com.android.defcontainer.DefaultContainerService"); 475 476 private static final String KILL_APP_REASON_GIDS_CHANGED = 477 "permission grant or revoke changed gids"; 478 479 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 480 "permissions revoked"; 481 482 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 483 484 private static final String PACKAGE_SCHEME = "package"; 485 486 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 487 /** 488 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 489 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 490 * VENDOR_OVERLAY_DIR. 491 */ 492 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 493 /** 494 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 495 * is in VENDOR_OVERLAY_THEME_PROPERTY. 496 */ 497 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 498 = "persist.vendor.overlay.theme"; 499 500 /** Permission grant: not grant the permission. */ 501 private static final int GRANT_DENIED = 1; 502 503 /** Permission grant: grant the permission as an install permission. */ 504 private static final int GRANT_INSTALL = 2; 505 506 /** Permission grant: grant the permission as a runtime one. */ 507 private static final int GRANT_RUNTIME = 3; 508 509 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 510 private static final int GRANT_UPGRADE = 4; 511 512 /** Canonical intent used to identify what counts as a "web browser" app */ 513 private static final Intent sBrowserIntent; 514 static { 515 sBrowserIntent = new Intent(); 516 sBrowserIntent.setAction(Intent.ACTION_VIEW); 517 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 518 sBrowserIntent.setData(Uri.parse("http:")); 519 } 520 521 /** 522 * The set of all protected actions [i.e. those actions for which a high priority 523 * intent filter is disallowed]. 524 */ 525 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 526 static { 527 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 528 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 530 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 531 } 532 533 // Compilation reasons. 534 public static final int REASON_FIRST_BOOT = 0; 535 public static final int REASON_BOOT = 1; 536 public static final int REASON_INSTALL = 2; 537 public static final int REASON_BACKGROUND_DEXOPT = 3; 538 public static final int REASON_AB_OTA = 4; 539 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 540 public static final int REASON_SHARED_APK = 6; 541 public static final int REASON_FORCED_DEXOPT = 7; 542 public static final int REASON_CORE_APP = 8; 543 544 public static final int REASON_LAST = REASON_CORE_APP; 545 546 /** Special library name that skips shared libraries check during compilation. */ 547 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 548 549 /** All dangerous permission names in the same order as the events in MetricsEvent */ 550 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 551 Manifest.permission.READ_CALENDAR, 552 Manifest.permission.WRITE_CALENDAR, 553 Manifest.permission.CAMERA, 554 Manifest.permission.READ_CONTACTS, 555 Manifest.permission.WRITE_CONTACTS, 556 Manifest.permission.GET_ACCOUNTS, 557 Manifest.permission.ACCESS_FINE_LOCATION, 558 Manifest.permission.ACCESS_COARSE_LOCATION, 559 Manifest.permission.RECORD_AUDIO, 560 Manifest.permission.READ_PHONE_STATE, 561 Manifest.permission.CALL_PHONE, 562 Manifest.permission.READ_CALL_LOG, 563 Manifest.permission.WRITE_CALL_LOG, 564 Manifest.permission.ADD_VOICEMAIL, 565 Manifest.permission.USE_SIP, 566 Manifest.permission.PROCESS_OUTGOING_CALLS, 567 Manifest.permission.READ_CELL_BROADCASTS, 568 Manifest.permission.BODY_SENSORS, 569 Manifest.permission.SEND_SMS, 570 Manifest.permission.RECEIVE_SMS, 571 Manifest.permission.READ_SMS, 572 Manifest.permission.RECEIVE_WAP_PUSH, 573 Manifest.permission.RECEIVE_MMS, 574 Manifest.permission.READ_EXTERNAL_STORAGE, 575 Manifest.permission.WRITE_EXTERNAL_STORAGE, 576 Manifest.permission.READ_PHONE_NUMBER); 577 578 579 /** 580 * Version number for the package parser cache. Increment this whenever the format or 581 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 582 */ 583 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 584 585 /** 586 * Whether the package parser cache is enabled. 587 */ 588 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 589 590 final ServiceThread mHandlerThread; 591 592 final PackageHandler mHandler; 593 594 private final ProcessLoggingHandler mProcessLoggingHandler; 595 596 /** 597 * Messages for {@link #mHandler} that need to wait for system ready before 598 * being dispatched. 599 */ 600 private ArrayList<Message> mPostSystemReadyMessages; 601 602 final int mSdkVersion = Build.VERSION.SDK_INT; 603 604 final Context mContext; 605 final boolean mFactoryTest; 606 final boolean mOnlyCore; 607 final DisplayMetrics mMetrics; 608 final int mDefParseFlags; 609 final String[] mSeparateProcesses; 610 final boolean mIsUpgrade; 611 final boolean mIsPreNUpgrade; 612 final boolean mIsPreNMR1Upgrade; 613 614 @GuardedBy("mPackages") 615 private boolean mDexOptDialogShown; 616 617 /** The location for ASEC container files on internal storage. */ 618 final String mAsecInternalPath; 619 620 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 621 // LOCK HELD. Can be called with mInstallLock held. 622 @GuardedBy("mInstallLock") 623 final Installer mInstaller; 624 625 /** Directory where installed third-party apps stored */ 626 final File mAppInstallDir; 627 final File mEphemeralInstallDir; 628 629 /** 630 * Directory to which applications installed internally have their 631 * 32 bit native libraries copied. 632 */ 633 private File mAppLib32InstallDir; 634 635 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 636 // apps. 637 final File mDrmAppPrivateInstallDir; 638 639 // ---------------------------------------------------------------- 640 641 // Lock for state used when installing and doing other long running 642 // operations. Methods that must be called with this lock held have 643 // the suffix "LI". 644 final Object mInstallLock = new Object(); 645 646 // ---------------------------------------------------------------- 647 648 // Keys are String (package name), values are Package. This also serves 649 // as the lock for the global state. Methods that must be called with 650 // this lock held have the prefix "LP". 651 @GuardedBy("mPackages") 652 final ArrayMap<String, PackageParser.Package> mPackages = 653 new ArrayMap<String, PackageParser.Package>(); 654 655 final ArrayMap<String, Set<String>> mKnownCodebase = 656 new ArrayMap<String, Set<String>>(); 657 658 // Tracks available target package names -> overlay package paths. 659 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 660 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 661 662 /** 663 * Tracks new system packages [received in an OTA] that we expect to 664 * find updated user-installed versions. Keys are package name, values 665 * are package location. 666 */ 667 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 668 /** 669 * Tracks high priority intent filters for protected actions. During boot, certain 670 * filter actions are protected and should never be allowed to have a high priority 671 * intent filter for them. However, there is one, and only one exception -- the 672 * setup wizard. It must be able to define a high priority intent filter for these 673 * actions to ensure there are no escapes from the wizard. We need to delay processing 674 * of these during boot as we need to look at all of the system packages in order 675 * to know which component is the setup wizard. 676 */ 677 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 678 /** 679 * Whether or not processing protected filters should be deferred. 680 */ 681 private boolean mDeferProtectedFilters = true; 682 683 /** 684 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 685 */ 686 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 687 /** 688 * Whether or not system app permissions should be promoted from install to runtime. 689 */ 690 boolean mPromoteSystemApps; 691 692 @GuardedBy("mPackages") 693 final Settings mSettings; 694 695 /** 696 * Set of package names that are currently "frozen", which means active 697 * surgery is being done on the code/data for that package. The platform 698 * will refuse to launch frozen packages to avoid race conditions. 699 * 700 * @see PackageFreezer 701 */ 702 @GuardedBy("mPackages") 703 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 704 705 final ProtectedPackages mProtectedPackages; 706 707 boolean mFirstBoot; 708 709 // System configuration read by SystemConfig. 710 final int[] mGlobalGids; 711 final SparseArray<ArraySet<String>> mSystemPermissions; 712 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 713 714 // If mac_permissions.xml was found for seinfo labeling. 715 boolean mFoundPolicyFile; 716 717 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 718 719 public static final class SharedLibraryEntry { 720 public final String path; 721 public final String apk; 722 public final SharedLibraryInfo info; 723 724 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 725 String declaringPackageName, int declaringPackageVersionCode) { 726 path = _path; 727 apk = _apk; 728 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 729 declaringPackageName, declaringPackageVersionCode), null); 730 } 731 } 732 733 // Currently known shared libraries. 734 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 735 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 736 new ArrayMap<>(); 737 738 // All available activities, for your resolving pleasure. 739 final ActivityIntentResolver mActivities = 740 new ActivityIntentResolver(); 741 742 // All available receivers, for your resolving pleasure. 743 final ActivityIntentResolver mReceivers = 744 new ActivityIntentResolver(); 745 746 // All available services, for your resolving pleasure. 747 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 748 749 // All available providers, for your resolving pleasure. 750 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 751 752 // Mapping from provider base names (first directory in content URI codePath) 753 // to the provider information. 754 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 755 new ArrayMap<String, PackageParser.Provider>(); 756 757 // Mapping from instrumentation class names to info about them. 758 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 759 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 760 761 // Mapping from permission names to info about them. 762 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 763 new ArrayMap<String, PackageParser.PermissionGroup>(); 764 765 // Packages whose data we have transfered into another package, thus 766 // should no longer exist. 767 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 768 769 // Broadcast actions that are only available to the system. 770 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 771 772 /** List of packages waiting for verification. */ 773 final SparseArray<PackageVerificationState> mPendingVerification 774 = new SparseArray<PackageVerificationState>(); 775 776 /** Set of packages associated with each app op permission. */ 777 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 778 779 final PackageInstallerService mInstallerService; 780 781 private final PackageDexOptimizer mPackageDexOptimizer; 782 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 783 // is used by other apps). 784 private final DexManager mDexManager; 785 786 private AtomicInteger mNextMoveId = new AtomicInteger(); 787 private final MoveCallbacks mMoveCallbacks; 788 789 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 790 791 // Cache of users who need badging. 792 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 793 794 /** Token for keys in mPendingVerification. */ 795 private int mPendingVerificationToken = 0; 796 797 volatile boolean mSystemReady; 798 volatile boolean mSafeMode; 799 volatile boolean mHasSystemUidErrors; 800 801 ApplicationInfo mAndroidApplication; 802 final ActivityInfo mResolveActivity = new ActivityInfo(); 803 final ResolveInfo mResolveInfo = new ResolveInfo(); 804 ComponentName mResolveComponentName; 805 PackageParser.Package mPlatformPackage; 806 ComponentName mCustomResolverComponentName; 807 808 boolean mResolverReplaced = false; 809 810 private final @Nullable ComponentName mIntentFilterVerifierComponent; 811 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 812 813 private int mIntentFilterVerificationToken = 0; 814 815 /** The service connection to the ephemeral resolver */ 816 final EphemeralResolverConnection mEphemeralResolverConnection; 817 818 /** Component used to install ephemeral applications */ 819 ComponentName mEphemeralInstallerComponent; 820 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 821 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 822 823 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 824 = new SparseArray<IntentFilterVerificationState>(); 825 826 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 827 828 // List of packages names to keep cached, even if they are uninstalled for all users 829 private List<String> mKeepUninstalledPackages; 830 831 private UserManagerInternal mUserManagerInternal; 832 833 private File mCacheDir; 834 835 private static class IFVerificationParams { 836 PackageParser.Package pkg; 837 boolean replacing; 838 int userId; 839 int verifierUid; 840 841 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 842 int _userId, int _verifierUid) { 843 pkg = _pkg; 844 replacing = _replacing; 845 userId = _userId; 846 replacing = _replacing; 847 verifierUid = _verifierUid; 848 } 849 } 850 851 private interface IntentFilterVerifier<T extends IntentFilter> { 852 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 853 T filter, String packageName); 854 void startVerifications(int userId); 855 void receiveVerificationResponse(int verificationId); 856 } 857 858 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 859 private Context mContext; 860 private ComponentName mIntentFilterVerifierComponent; 861 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 862 863 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 864 mContext = context; 865 mIntentFilterVerifierComponent = verifierComponent; 866 } 867 868 private String getDefaultScheme() { 869 return IntentFilter.SCHEME_HTTPS; 870 } 871 872 @Override 873 public void startVerifications(int userId) { 874 // Launch verifications requests 875 int count = mCurrentIntentFilterVerifications.size(); 876 for (int n=0; n<count; n++) { 877 int verificationId = mCurrentIntentFilterVerifications.get(n); 878 final IntentFilterVerificationState ivs = 879 mIntentFilterVerificationStates.get(verificationId); 880 881 String packageName = ivs.getPackageName(); 882 883 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 884 final int filterCount = filters.size(); 885 ArraySet<String> domainsSet = new ArraySet<>(); 886 for (int m=0; m<filterCount; m++) { 887 PackageParser.ActivityIntentInfo filter = filters.get(m); 888 domainsSet.addAll(filter.getHostsList()); 889 } 890 synchronized (mPackages) { 891 if (mSettings.createIntentFilterVerificationIfNeededLPw( 892 packageName, domainsSet) != null) { 893 scheduleWriteSettingsLocked(); 894 } 895 } 896 sendVerificationRequest(userId, verificationId, ivs); 897 } 898 mCurrentIntentFilterVerifications.clear(); 899 } 900 901 private void sendVerificationRequest(int userId, int verificationId, 902 IntentFilterVerificationState ivs) { 903 904 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 905 verificationIntent.putExtra( 906 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 907 verificationId); 908 verificationIntent.putExtra( 909 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 910 getDefaultScheme()); 911 verificationIntent.putExtra( 912 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 913 ivs.getHostsString()); 914 verificationIntent.putExtra( 915 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 916 ivs.getPackageName()); 917 verificationIntent.setComponent(mIntentFilterVerifierComponent); 918 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 919 920 UserHandle user = new UserHandle(userId); 921 mContext.sendBroadcastAsUser(verificationIntent, user); 922 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 923 "Sending IntentFilter verification broadcast"); 924 } 925 926 public void receiveVerificationResponse(int verificationId) { 927 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 928 929 final boolean verified = ivs.isVerified(); 930 931 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 932 final int count = filters.size(); 933 if (DEBUG_DOMAIN_VERIFICATION) { 934 Slog.i(TAG, "Received verification response " + verificationId 935 + " for " + count + " filters, verified=" + verified); 936 } 937 for (int n=0; n<count; n++) { 938 PackageParser.ActivityIntentInfo filter = filters.get(n); 939 filter.setVerified(verified); 940 941 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 942 + " verified with result:" + verified + " and hosts:" 943 + ivs.getHostsString()); 944 } 945 946 mIntentFilterVerificationStates.remove(verificationId); 947 948 final String packageName = ivs.getPackageName(); 949 IntentFilterVerificationInfo ivi = null; 950 951 synchronized (mPackages) { 952 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 953 } 954 if (ivi == null) { 955 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 956 + verificationId + " packageName:" + packageName); 957 return; 958 } 959 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 960 "Updating IntentFilterVerificationInfo for package " + packageName 961 +" verificationId:" + verificationId); 962 963 synchronized (mPackages) { 964 if (verified) { 965 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 966 } else { 967 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 968 } 969 scheduleWriteSettingsLocked(); 970 971 final int userId = ivs.getUserId(); 972 if (userId != UserHandle.USER_ALL) { 973 final int userStatus = 974 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 975 976 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 977 boolean needUpdate = false; 978 979 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 980 // already been set by the User thru the Disambiguation dialog 981 switch (userStatus) { 982 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 983 if (verified) { 984 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 985 } else { 986 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 987 } 988 needUpdate = true; 989 break; 990 991 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 992 if (verified) { 993 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 994 needUpdate = true; 995 } 996 break; 997 998 default: 999 // Nothing to do 1000 } 1001 1002 if (needUpdate) { 1003 mSettings.updateIntentFilterVerificationStatusLPw( 1004 packageName, updatedStatus, userId); 1005 scheduleWritePackageRestrictionsLocked(userId); 1006 } 1007 } 1008 } 1009 } 1010 1011 @Override 1012 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1013 ActivityIntentInfo filter, String packageName) { 1014 if (!hasValidDomains(filter)) { 1015 return false; 1016 } 1017 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1018 if (ivs == null) { 1019 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1020 packageName); 1021 } 1022 if (DEBUG_DOMAIN_VERIFICATION) { 1023 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1024 } 1025 ivs.addFilter(filter); 1026 return true; 1027 } 1028 1029 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1030 int userId, int verificationId, String packageName) { 1031 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1032 verifierUid, userId, packageName); 1033 ivs.setPendingState(); 1034 synchronized (mPackages) { 1035 mIntentFilterVerificationStates.append(verificationId, ivs); 1036 mCurrentIntentFilterVerifications.add(verificationId); 1037 } 1038 return ivs; 1039 } 1040 } 1041 1042 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1043 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1044 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1045 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1046 } 1047 1048 // Set of pending broadcasts for aggregating enable/disable of components. 1049 static class PendingPackageBroadcasts { 1050 // for each user id, a map of <package name -> components within that package> 1051 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1052 1053 public PendingPackageBroadcasts() { 1054 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1055 } 1056 1057 public ArrayList<String> get(int userId, String packageName) { 1058 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1059 return packages.get(packageName); 1060 } 1061 1062 public void put(int userId, String packageName, ArrayList<String> components) { 1063 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1064 packages.put(packageName, components); 1065 } 1066 1067 public void remove(int userId, String packageName) { 1068 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1069 if (packages != null) { 1070 packages.remove(packageName); 1071 } 1072 } 1073 1074 public void remove(int userId) { 1075 mUidMap.remove(userId); 1076 } 1077 1078 public int userIdCount() { 1079 return mUidMap.size(); 1080 } 1081 1082 public int userIdAt(int n) { 1083 return mUidMap.keyAt(n); 1084 } 1085 1086 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1087 return mUidMap.get(userId); 1088 } 1089 1090 public int size() { 1091 // total number of pending broadcast entries across all userIds 1092 int num = 0; 1093 for (int i = 0; i< mUidMap.size(); i++) { 1094 num += mUidMap.valueAt(i).size(); 1095 } 1096 return num; 1097 } 1098 1099 public void clear() { 1100 mUidMap.clear(); 1101 } 1102 1103 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1104 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1105 if (map == null) { 1106 map = new ArrayMap<String, ArrayList<String>>(); 1107 mUidMap.put(userId, map); 1108 } 1109 return map; 1110 } 1111 } 1112 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1113 1114 // Service Connection to remote media container service to copy 1115 // package uri's from external media onto secure containers 1116 // or internal storage. 1117 private IMediaContainerService mContainerService = null; 1118 1119 static final int SEND_PENDING_BROADCAST = 1; 1120 static final int MCS_BOUND = 3; 1121 static final int END_COPY = 4; 1122 static final int INIT_COPY = 5; 1123 static final int MCS_UNBIND = 6; 1124 static final int START_CLEANING_PACKAGE = 7; 1125 static final int FIND_INSTALL_LOC = 8; 1126 static final int POST_INSTALL = 9; 1127 static final int MCS_RECONNECT = 10; 1128 static final int MCS_GIVE_UP = 11; 1129 static final int UPDATED_MEDIA_STATUS = 12; 1130 static final int WRITE_SETTINGS = 13; 1131 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1132 static final int PACKAGE_VERIFIED = 15; 1133 static final int CHECK_PENDING_VERIFICATION = 16; 1134 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1135 static final int INTENT_FILTER_VERIFIED = 18; 1136 static final int WRITE_PACKAGE_LIST = 19; 1137 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1138 1139 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1140 1141 // Delay time in millisecs 1142 static final int BROADCAST_DELAY = 10 * 1000; 1143 1144 static UserManagerService sUserManager; 1145 1146 // Stores a list of users whose package restrictions file needs to be updated 1147 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1148 1149 final private DefaultContainerConnection mDefContainerConn = 1150 new DefaultContainerConnection(); 1151 class DefaultContainerConnection implements ServiceConnection { 1152 public void onServiceConnected(ComponentName name, IBinder service) { 1153 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1154 final IMediaContainerService imcs = IMediaContainerService.Stub 1155 .asInterface(Binder.allowBlocking(service)); 1156 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1157 } 1158 1159 public void onServiceDisconnected(ComponentName name) { 1160 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1161 } 1162 } 1163 1164 // Recordkeeping of restore-after-install operations that are currently in flight 1165 // between the Package Manager and the Backup Manager 1166 static class PostInstallData { 1167 public InstallArgs args; 1168 public PackageInstalledInfo res; 1169 1170 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1171 args = _a; 1172 res = _r; 1173 } 1174 } 1175 1176 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1177 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1178 1179 // XML tags for backup/restore of various bits of state 1180 private static final String TAG_PREFERRED_BACKUP = "pa"; 1181 private static final String TAG_DEFAULT_APPS = "da"; 1182 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1183 1184 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1185 private static final String TAG_ALL_GRANTS = "rt-grants"; 1186 private static final String TAG_GRANT = "grant"; 1187 private static final String ATTR_PACKAGE_NAME = "pkg"; 1188 1189 private static final String TAG_PERMISSION = "perm"; 1190 private static final String ATTR_PERMISSION_NAME = "name"; 1191 private static final String ATTR_IS_GRANTED = "g"; 1192 private static final String ATTR_USER_SET = "set"; 1193 private static final String ATTR_USER_FIXED = "fixed"; 1194 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1195 1196 // System/policy permission grants are not backed up 1197 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1198 FLAG_PERMISSION_POLICY_FIXED 1199 | FLAG_PERMISSION_SYSTEM_FIXED 1200 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1201 1202 // And we back up these user-adjusted states 1203 private static final int USER_RUNTIME_GRANT_MASK = 1204 FLAG_PERMISSION_USER_SET 1205 | FLAG_PERMISSION_USER_FIXED 1206 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1207 1208 final @Nullable String mRequiredVerifierPackage; 1209 final @NonNull String mRequiredInstallerPackage; 1210 final @NonNull String mRequiredUninstallerPackage; 1211 final @Nullable String mSetupWizardPackage; 1212 final @Nullable String mStorageManagerPackage; 1213 final @NonNull String mServicesSystemSharedLibraryPackageName; 1214 final @NonNull String mSharedSystemSharedLibraryPackageName; 1215 1216 final boolean mPermissionReviewRequired; 1217 1218 private final PackageUsage mPackageUsage = new PackageUsage(); 1219 private final CompilerStats mCompilerStats = new CompilerStats(); 1220 1221 class PackageHandler extends Handler { 1222 private boolean mBound = false; 1223 final ArrayList<HandlerParams> mPendingInstalls = 1224 new ArrayList<HandlerParams>(); 1225 1226 private boolean connectToService() { 1227 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1228 " DefaultContainerService"); 1229 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1231 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1232 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1234 mBound = true; 1235 return true; 1236 } 1237 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1238 return false; 1239 } 1240 1241 private void disconnectService() { 1242 mContainerService = null; 1243 mBound = false; 1244 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1245 mContext.unbindService(mDefContainerConn); 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 } 1248 1249 PackageHandler(Looper looper) { 1250 super(looper); 1251 } 1252 1253 public void handleMessage(Message msg) { 1254 try { 1255 doHandleMessage(msg); 1256 } finally { 1257 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1258 } 1259 } 1260 1261 void doHandleMessage(Message msg) { 1262 switch (msg.what) { 1263 case INIT_COPY: { 1264 HandlerParams params = (HandlerParams) msg.obj; 1265 int idx = mPendingInstalls.size(); 1266 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1267 // If a bind was already initiated we dont really 1268 // need to do anything. The pending install 1269 // will be processed later on. 1270 if (!mBound) { 1271 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1272 System.identityHashCode(mHandler)); 1273 // If this is the only one pending we might 1274 // have to bind to the service again. 1275 if (!connectToService()) { 1276 Slog.e(TAG, "Failed to bind to media container service"); 1277 params.serviceError(); 1278 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1279 System.identityHashCode(mHandler)); 1280 if (params.traceMethod != null) { 1281 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1282 params.traceCookie); 1283 } 1284 return; 1285 } else { 1286 // Once we bind to the service, the first 1287 // pending request will be processed. 1288 mPendingInstalls.add(idx, params); 1289 } 1290 } else { 1291 mPendingInstalls.add(idx, params); 1292 // Already bound to the service. Just make 1293 // sure we trigger off processing the first request. 1294 if (idx == 0) { 1295 mHandler.sendEmptyMessage(MCS_BOUND); 1296 } 1297 } 1298 break; 1299 } 1300 case MCS_BOUND: { 1301 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1302 if (msg.obj != null) { 1303 mContainerService = (IMediaContainerService) msg.obj; 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 } 1307 if (mContainerService == null) { 1308 if (!mBound) { 1309 // Something seriously wrong since we are not bound and we are not 1310 // waiting for connection. Bail out. 1311 Slog.e(TAG, "Cannot bind to media container service"); 1312 for (HandlerParams params : mPendingInstalls) { 1313 // Indicate service bind error 1314 params.serviceError(); 1315 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1316 System.identityHashCode(params)); 1317 if (params.traceMethod != null) { 1318 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1319 params.traceMethod, params.traceCookie); 1320 } 1321 return; 1322 } 1323 mPendingInstalls.clear(); 1324 } else { 1325 Slog.w(TAG, "Waiting to connect to media container service"); 1326 } 1327 } else if (mPendingInstalls.size() > 0) { 1328 HandlerParams params = mPendingInstalls.get(0); 1329 if (params != null) { 1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1331 System.identityHashCode(params)); 1332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1333 if (params.startCopy()) { 1334 // We are done... look for more work or to 1335 // go idle. 1336 if (DEBUG_SD_INSTALL) Log.i(TAG, 1337 "Checking for more work or unbind..."); 1338 // Delete pending install 1339 if (mPendingInstalls.size() > 0) { 1340 mPendingInstalls.remove(0); 1341 } 1342 if (mPendingInstalls.size() == 0) { 1343 if (mBound) { 1344 if (DEBUG_SD_INSTALL) Log.i(TAG, 1345 "Posting delayed MCS_UNBIND"); 1346 removeMessages(MCS_UNBIND); 1347 Message ubmsg = obtainMessage(MCS_UNBIND); 1348 // Unbind after a little delay, to avoid 1349 // continual thrashing. 1350 sendMessageDelayed(ubmsg, 10000); 1351 } 1352 } else { 1353 // There are more pending requests in queue. 1354 // Just post MCS_BOUND message to trigger processing 1355 // of next pending install. 1356 if (DEBUG_SD_INSTALL) Log.i(TAG, 1357 "Posting MCS_BOUND for next work"); 1358 mHandler.sendEmptyMessage(MCS_BOUND); 1359 } 1360 } 1361 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1362 } 1363 } else { 1364 // Should never happen ideally. 1365 Slog.w(TAG, "Empty queue"); 1366 } 1367 break; 1368 } 1369 case MCS_RECONNECT: { 1370 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1371 if (mPendingInstalls.size() > 0) { 1372 if (mBound) { 1373 disconnectService(); 1374 } 1375 if (!connectToService()) { 1376 Slog.e(TAG, "Failed to bind to media container service"); 1377 for (HandlerParams params : mPendingInstalls) { 1378 // Indicate service bind error 1379 params.serviceError(); 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1381 System.identityHashCode(params)); 1382 } 1383 mPendingInstalls.clear(); 1384 } 1385 } 1386 break; 1387 } 1388 case MCS_UNBIND: { 1389 // If there is no actual work left, then time to unbind. 1390 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1391 1392 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1393 if (mBound) { 1394 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1395 1396 disconnectService(); 1397 } 1398 } else if (mPendingInstalls.size() > 0) { 1399 // There are more pending requests in queue. 1400 // Just post MCS_BOUND message to trigger processing 1401 // of next pending install. 1402 mHandler.sendEmptyMessage(MCS_BOUND); 1403 } 1404 1405 break; 1406 } 1407 case MCS_GIVE_UP: { 1408 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1409 HandlerParams params = mPendingInstalls.remove(0); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 break; 1413 } 1414 case SEND_PENDING_BROADCAST: { 1415 String packages[]; 1416 ArrayList<String> components[]; 1417 int size = 0; 1418 int uids[]; 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1420 synchronized (mPackages) { 1421 if (mPendingBroadcasts == null) { 1422 return; 1423 } 1424 size = mPendingBroadcasts.size(); 1425 if (size <= 0) { 1426 // Nothing to be done. Just return 1427 return; 1428 } 1429 packages = new String[size]; 1430 components = new ArrayList[size]; 1431 uids = new int[size]; 1432 int i = 0; // filling out the above arrays 1433 1434 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1435 int packageUserId = mPendingBroadcasts.userIdAt(n); 1436 Iterator<Map.Entry<String, ArrayList<String>>> it 1437 = mPendingBroadcasts.packagesForUserId(packageUserId) 1438 .entrySet().iterator(); 1439 while (it.hasNext() && i < size) { 1440 Map.Entry<String, ArrayList<String>> ent = it.next(); 1441 packages[i] = ent.getKey(); 1442 components[i] = ent.getValue(); 1443 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1444 uids[i] = (ps != null) 1445 ? UserHandle.getUid(packageUserId, ps.appId) 1446 : -1; 1447 i++; 1448 } 1449 } 1450 size = i; 1451 mPendingBroadcasts.clear(); 1452 } 1453 // Send broadcasts 1454 for (int i = 0; i < size; i++) { 1455 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1456 } 1457 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1458 break; 1459 } 1460 case START_CLEANING_PACKAGE: { 1461 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1462 final String packageName = (String)msg.obj; 1463 final int userId = msg.arg1; 1464 final boolean andCode = msg.arg2 != 0; 1465 synchronized (mPackages) { 1466 if (userId == UserHandle.USER_ALL) { 1467 int[] users = sUserManager.getUserIds(); 1468 for (int user : users) { 1469 mSettings.addPackageToCleanLPw( 1470 new PackageCleanItem(user, packageName, andCode)); 1471 } 1472 } else { 1473 mSettings.addPackageToCleanLPw( 1474 new PackageCleanItem(userId, packageName, andCode)); 1475 } 1476 } 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1478 startCleaningPackages(); 1479 } break; 1480 case POST_INSTALL: { 1481 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1482 1483 PostInstallData data = mRunningInstalls.get(msg.arg1); 1484 final boolean didRestore = (msg.arg2 != 0); 1485 mRunningInstalls.delete(msg.arg1); 1486 1487 if (data != null) { 1488 InstallArgs args = data.args; 1489 PackageInstalledInfo parentRes = data.res; 1490 1491 final boolean grantPermissions = (args.installFlags 1492 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1493 final boolean killApp = (args.installFlags 1494 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1495 final String[] grantedPermissions = args.installGrantPermissions; 1496 1497 // Handle the parent package 1498 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1499 grantedPermissions, didRestore, args.installerPackageName, 1500 args.observer); 1501 1502 // Handle the child packages 1503 final int childCount = (parentRes.addedChildPackages != null) 1504 ? parentRes.addedChildPackages.size() : 0; 1505 for (int i = 0; i < childCount; i++) { 1506 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1507 handlePackagePostInstall(childRes, grantPermissions, killApp, 1508 grantedPermissions, false, args.installerPackageName, 1509 args.observer); 1510 } 1511 1512 // Log tracing if needed 1513 if (args.traceMethod != null) { 1514 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1515 args.traceCookie); 1516 } 1517 } else { 1518 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1519 } 1520 1521 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1522 } break; 1523 case UPDATED_MEDIA_STATUS: { 1524 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1525 boolean reportStatus = msg.arg1 == 1; 1526 boolean doGc = msg.arg2 == 1; 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1528 if (doGc) { 1529 // Force a gc to clear up stale containers. 1530 Runtime.getRuntime().gc(); 1531 } 1532 if (msg.obj != null) { 1533 @SuppressWarnings("unchecked") 1534 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1536 // Unload containers 1537 unloadAllContainers(args); 1538 } 1539 if (reportStatus) { 1540 try { 1541 if (DEBUG_SD_INSTALL) Log.i(TAG, 1542 "Invoking StorageManagerService call back"); 1543 PackageHelper.getStorageManager().finishMediaUpdate(); 1544 } catch (RemoteException e) { 1545 Log.e(TAG, "StorageManagerService not running?"); 1546 } 1547 } 1548 } break; 1549 case WRITE_SETTINGS: { 1550 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1551 synchronized (mPackages) { 1552 removeMessages(WRITE_SETTINGS); 1553 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1554 mSettings.writeLPr(); 1555 mDirtyUsers.clear(); 1556 } 1557 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1558 } break; 1559 case WRITE_PACKAGE_RESTRICTIONS: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 synchronized (mPackages) { 1562 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1563 for (int userId : mDirtyUsers) { 1564 mSettings.writePackageRestrictionsLPr(userId); 1565 } 1566 mDirtyUsers.clear(); 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 } break; 1570 case WRITE_PACKAGE_LIST: { 1571 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1572 synchronized (mPackages) { 1573 removeMessages(WRITE_PACKAGE_LIST); 1574 mSettings.writePackageListLPr(msg.arg1); 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 } break; 1578 case CHECK_PENDING_VERIFICATION: { 1579 final int verificationId = msg.arg1; 1580 final PackageVerificationState state = mPendingVerification.get(verificationId); 1581 1582 if ((state != null) && !state.timeoutExtended()) { 1583 final InstallArgs args = state.getInstallArgs(); 1584 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1585 1586 Slog.i(TAG, "Verification timed out for " + originUri); 1587 mPendingVerification.remove(verificationId); 1588 1589 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1590 1591 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1592 Slog.i(TAG, "Continuing with installation of " + originUri); 1593 state.setVerifierResponse(Binder.getCallingUid(), 1594 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1595 broadcastPackageVerified(verificationId, originUri, 1596 PackageManager.VERIFICATION_ALLOW, 1597 state.getInstallArgs().getUser()); 1598 try { 1599 ret = args.copyApk(mContainerService, true); 1600 } catch (RemoteException e) { 1601 Slog.e(TAG, "Could not contact the ContainerService"); 1602 } 1603 } else { 1604 broadcastPackageVerified(verificationId, originUri, 1605 PackageManager.VERIFICATION_REJECT, 1606 state.getInstallArgs().getUser()); 1607 } 1608 1609 Trace.asyncTraceEnd( 1610 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1611 1612 processPendingInstall(args, ret); 1613 mHandler.sendEmptyMessage(MCS_UNBIND); 1614 } 1615 break; 1616 } 1617 case PACKAGE_VERIFIED: { 1618 final int verificationId = msg.arg1; 1619 1620 final PackageVerificationState state = mPendingVerification.get(verificationId); 1621 if (state == null) { 1622 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1623 break; 1624 } 1625 1626 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1627 1628 state.setVerifierResponse(response.callerUid, response.code); 1629 1630 if (state.isVerificationComplete()) { 1631 mPendingVerification.remove(verificationId); 1632 1633 final InstallArgs args = state.getInstallArgs(); 1634 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1635 1636 int ret; 1637 if (state.isInstallAllowed()) { 1638 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1639 broadcastPackageVerified(verificationId, originUri, 1640 response.code, state.getInstallArgs().getUser()); 1641 try { 1642 ret = args.copyApk(mContainerService, true); 1643 } catch (RemoteException e) { 1644 Slog.e(TAG, "Could not contact the ContainerService"); 1645 } 1646 } else { 1647 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1648 } 1649 1650 Trace.asyncTraceEnd( 1651 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1652 1653 processPendingInstall(args, ret); 1654 mHandler.sendEmptyMessage(MCS_UNBIND); 1655 } 1656 1657 break; 1658 } 1659 case START_INTENT_FILTER_VERIFICATIONS: { 1660 IFVerificationParams params = (IFVerificationParams) msg.obj; 1661 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1662 params.replacing, params.pkg); 1663 break; 1664 } 1665 case INTENT_FILTER_VERIFIED: { 1666 final int verificationId = msg.arg1; 1667 1668 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1669 verificationId); 1670 if (state == null) { 1671 Slog.w(TAG, "Invalid IntentFilter verification token " 1672 + verificationId + " received"); 1673 break; 1674 } 1675 1676 final int userId = state.getUserId(); 1677 1678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1679 "Processing IntentFilter verification with token:" 1680 + verificationId + " and userId:" + userId); 1681 1682 final IntentFilterVerificationResponse response = 1683 (IntentFilterVerificationResponse) msg.obj; 1684 1685 state.setVerifierResponse(response.callerUid, response.code); 1686 1687 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1688 "IntentFilter verification with token:" + verificationId 1689 + " and userId:" + userId 1690 + " is settings verifier response with response code:" 1691 + response.code); 1692 1693 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1695 + response.getFailedDomainsString()); 1696 } 1697 1698 if (state.isVerificationComplete()) { 1699 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1700 } else { 1701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1702 "IntentFilter verification with token:" + verificationId 1703 + " was not said to be complete"); 1704 } 1705 1706 break; 1707 } 1708 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1709 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1710 mEphemeralResolverConnection, 1711 (EphemeralRequest) msg.obj, 1712 mEphemeralInstallerActivity, 1713 mHandler); 1714 } 1715 } 1716 } 1717 } 1718 1719 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1720 boolean killApp, String[] grantedPermissions, 1721 boolean launchedForRestore, String installerPackage, 1722 IPackageInstallObserver2 installObserver) { 1723 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1724 // Send the removed broadcasts 1725 if (res.removedInfo != null) { 1726 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1727 } 1728 1729 // Now that we successfully installed the package, grant runtime 1730 // permissions if requested before broadcasting the install. Also 1731 // for legacy apps in permission review mode we clear the permission 1732 // review flag which is used to emulate runtime permissions for 1733 // legacy apps. 1734 if (grantPermissions) { 1735 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1736 } 1737 1738 final boolean update = res.removedInfo != null 1739 && res.removedInfo.removedPackage != null; 1740 1741 // If this is the first time we have child packages for a disabled privileged 1742 // app that had no children, we grant requested runtime permissions to the new 1743 // children if the parent on the system image had them already granted. 1744 if (res.pkg.parentPackage != null) { 1745 synchronized (mPackages) { 1746 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1747 } 1748 } 1749 1750 synchronized (mPackages) { 1751 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1752 } 1753 1754 final String packageName = res.pkg.applicationInfo.packageName; 1755 1756 // Determine the set of users who are adding this package for 1757 // the first time vs. those who are seeing an update. 1758 int[] firstUsers = EMPTY_INT_ARRAY; 1759 int[] updateUsers = EMPTY_INT_ARRAY; 1760 if (res.origUsers == null || res.origUsers.length == 0) { 1761 firstUsers = res.newUsers; 1762 } else { 1763 for (int newUser : res.newUsers) { 1764 boolean isNew = true; 1765 for (int origUser : res.origUsers) { 1766 if (origUser == newUser) { 1767 isNew = false; 1768 break; 1769 } 1770 } 1771 if (isNew) { 1772 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1773 } else { 1774 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1775 } 1776 } 1777 } 1778 1779 // Send installed broadcasts if the install/update is not ephemeral 1780 // and the package is not a static shared lib. 1781 if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) { 1782 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1783 1784 // Send added for users that see the package for the first time 1785 // sendPackageAddedForNewUsers also deals with system apps 1786 int appId = UserHandle.getAppId(res.uid); 1787 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1788 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1789 1790 // Send added for users that don't see the package for the first time 1791 Bundle extras = new Bundle(1); 1792 extras.putInt(Intent.EXTRA_UID, res.uid); 1793 if (update) { 1794 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1795 } 1796 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1797 extras, 0 /*flags*/, null /*targetPackage*/, 1798 null /*finishedReceiver*/, updateUsers); 1799 1800 // Send replaced for users that don't see the package for the first time 1801 if (update) { 1802 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1803 packageName, extras, 0 /*flags*/, 1804 null /*targetPackage*/, null /*finishedReceiver*/, 1805 updateUsers); 1806 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1807 null /*package*/, null /*extras*/, 0 /*flags*/, 1808 packageName /*targetPackage*/, 1809 null /*finishedReceiver*/, updateUsers); 1810 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1811 // First-install and we did a restore, so we're responsible for the 1812 // first-launch broadcast. 1813 if (DEBUG_BACKUP) { 1814 Slog.i(TAG, "Post-restore of " + packageName 1815 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1816 } 1817 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1818 } 1819 1820 // Send broadcast package appeared if forward locked/external for all users 1821 // treat asec-hosted packages like removable media on upgrade 1822 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1823 if (DEBUG_INSTALL) { 1824 Slog.i(TAG, "upgrading pkg " + res.pkg 1825 + " is ASEC-hosted -> AVAILABLE"); 1826 } 1827 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1828 ArrayList<String> pkgList = new ArrayList<>(1); 1829 pkgList.add(packageName); 1830 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1831 } 1832 } 1833 1834 // Work that needs to happen on first install within each user 1835 if (firstUsers != null && firstUsers.length > 0) { 1836 synchronized (mPackages) { 1837 for (int userId : firstUsers) { 1838 // If this app is a browser and it's newly-installed for some 1839 // users, clear any default-browser state in those users. The 1840 // app's nature doesn't depend on the user, so we can just check 1841 // its browser nature in any user and generalize. 1842 if (packageIsBrowser(packageName, userId)) { 1843 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1844 } 1845 1846 // We may also need to apply pending (restored) runtime 1847 // permission grants within these users. 1848 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1849 } 1850 } 1851 } 1852 1853 // Log current value of "unknown sources" setting 1854 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1855 getUnknownSourcesSettings()); 1856 1857 // Force a gc to clear up things 1858 Runtime.getRuntime().gc(); 1859 1860 // Remove the replaced package's older resources safely now 1861 // We delete after a gc for applications on sdcard. 1862 if (res.removedInfo != null && res.removedInfo.args != null) { 1863 synchronized (mInstallLock) { 1864 res.removedInfo.args.doPostDeleteLI(true); 1865 } 1866 } 1867 } 1868 1869 // If someone is watching installs - notify them 1870 if (installObserver != null) { 1871 try { 1872 Bundle extras = extrasForInstallResult(res); 1873 installObserver.onPackageInstalled(res.name, res.returnCode, 1874 res.returnMsg, extras); 1875 } catch (RemoteException e) { 1876 Slog.i(TAG, "Observer no longer exists."); 1877 } 1878 } 1879 } 1880 1881 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1882 PackageParser.Package pkg) { 1883 if (pkg.parentPackage == null) { 1884 return; 1885 } 1886 if (pkg.requestedPermissions == null) { 1887 return; 1888 } 1889 final PackageSetting disabledSysParentPs = mSettings 1890 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1891 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1892 || !disabledSysParentPs.isPrivileged() 1893 || (disabledSysParentPs.childPackageNames != null 1894 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1895 return; 1896 } 1897 final int[] allUserIds = sUserManager.getUserIds(); 1898 final int permCount = pkg.requestedPermissions.size(); 1899 for (int i = 0; i < permCount; i++) { 1900 String permission = pkg.requestedPermissions.get(i); 1901 BasePermission bp = mSettings.mPermissions.get(permission); 1902 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1903 continue; 1904 } 1905 for (int userId : allUserIds) { 1906 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1907 permission, userId)) { 1908 grantRuntimePermission(pkg.packageName, permission, userId); 1909 } 1910 } 1911 } 1912 } 1913 1914 private StorageEventListener mStorageListener = new StorageEventListener() { 1915 @Override 1916 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1917 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1918 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1919 final String volumeUuid = vol.getFsUuid(); 1920 1921 // Clean up any users or apps that were removed or recreated 1922 // while this volume was missing 1923 reconcileUsers(volumeUuid); 1924 reconcileApps(volumeUuid); 1925 1926 // Clean up any install sessions that expired or were 1927 // cancelled while this volume was missing 1928 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1929 1930 loadPrivatePackages(vol); 1931 1932 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1933 unloadPrivatePackages(vol); 1934 } 1935 } 1936 1937 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1938 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1939 updateExternalMediaStatus(true, false); 1940 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1941 updateExternalMediaStatus(false, false); 1942 } 1943 } 1944 } 1945 1946 @Override 1947 public void onVolumeForgotten(String fsUuid) { 1948 if (TextUtils.isEmpty(fsUuid)) { 1949 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1950 return; 1951 } 1952 1953 // Remove any apps installed on the forgotten volume 1954 synchronized (mPackages) { 1955 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1956 for (PackageSetting ps : packages) { 1957 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1958 deletePackageVersioned(new VersionedPackage(ps.name, 1959 PackageManager.VERSION_CODE_HIGHEST), 1960 new LegacyPackageDeleteObserver(null).getBinder(), 1961 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1962 // Try very hard to release any references to this package 1963 // so we don't risk the system server being killed due to 1964 // open FDs 1965 AttributeCache.instance().removePackage(ps.name); 1966 } 1967 1968 mSettings.onVolumeForgotten(fsUuid); 1969 mSettings.writeLPr(); 1970 } 1971 } 1972 }; 1973 1974 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1975 String[] grantedPermissions) { 1976 for (int userId : userIds) { 1977 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1978 } 1979 } 1980 1981 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1982 String[] grantedPermissions) { 1983 SettingBase sb = (SettingBase) pkg.mExtras; 1984 if (sb == null) { 1985 return; 1986 } 1987 1988 PermissionsState permissionsState = sb.getPermissionsState(); 1989 1990 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1991 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1992 1993 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 1994 >= Build.VERSION_CODES.M; 1995 1996 for (String permission : pkg.requestedPermissions) { 1997 final BasePermission bp; 1998 synchronized (mPackages) { 1999 bp = mSettings.mPermissions.get(permission); 2000 } 2001 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2002 && (grantedPermissions == null 2003 || ArrayUtils.contains(grantedPermissions, permission))) { 2004 final int flags = permissionsState.getPermissionFlags(permission, userId); 2005 if (supportsRuntimePermissions) { 2006 // Installer cannot change immutable permissions. 2007 if ((flags & immutableFlags) == 0) { 2008 grantRuntimePermission(pkg.packageName, permission, userId); 2009 } 2010 } else if (mPermissionReviewRequired) { 2011 // In permission review mode we clear the review flag when we 2012 // are asked to install the app with all permissions granted. 2013 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2014 updatePermissionFlags(permission, pkg.packageName, 2015 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2016 } 2017 } 2018 } 2019 } 2020 } 2021 2022 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2023 Bundle extras = null; 2024 switch (res.returnCode) { 2025 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2026 extras = new Bundle(); 2027 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2028 res.origPermission); 2029 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2030 res.origPackage); 2031 break; 2032 } 2033 case PackageManager.INSTALL_SUCCEEDED: { 2034 extras = new Bundle(); 2035 extras.putBoolean(Intent.EXTRA_REPLACING, 2036 res.removedInfo != null && res.removedInfo.removedPackage != null); 2037 break; 2038 } 2039 } 2040 return extras; 2041 } 2042 2043 void scheduleWriteSettingsLocked() { 2044 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2045 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2046 } 2047 } 2048 2049 void scheduleWritePackageListLocked(int userId) { 2050 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2051 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2052 msg.arg1 = userId; 2053 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2054 } 2055 } 2056 2057 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2058 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2059 scheduleWritePackageRestrictionsLocked(userId); 2060 } 2061 2062 void scheduleWritePackageRestrictionsLocked(int userId) { 2063 final int[] userIds = (userId == UserHandle.USER_ALL) 2064 ? sUserManager.getUserIds() : new int[]{userId}; 2065 for (int nextUserId : userIds) { 2066 if (!sUserManager.exists(nextUserId)) return; 2067 mDirtyUsers.add(nextUserId); 2068 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2069 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2070 } 2071 } 2072 } 2073 2074 public static PackageManagerService main(Context context, Installer installer, 2075 boolean factoryTest, boolean onlyCore) { 2076 // Self-check for initial settings. 2077 PackageManagerServiceCompilerMapping.checkProperties(); 2078 2079 PackageManagerService m = new PackageManagerService(context, installer, 2080 factoryTest, onlyCore); 2081 m.enableSystemUserPackages(); 2082 ServiceManager.addService("package", m); 2083 return m; 2084 } 2085 2086 private void enableSystemUserPackages() { 2087 if (!UserManager.isSplitSystemUser()) { 2088 return; 2089 } 2090 // For system user, enable apps based on the following conditions: 2091 // - app is whitelisted or belong to one of these groups: 2092 // -- system app which has no launcher icons 2093 // -- system app which has INTERACT_ACROSS_USERS permission 2094 // -- system IME app 2095 // - app is not in the blacklist 2096 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2097 Set<String> enableApps = new ArraySet<>(); 2098 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2099 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2100 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2101 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2102 enableApps.addAll(wlApps); 2103 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2104 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2105 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2106 enableApps.removeAll(blApps); 2107 Log.i(TAG, "Applications installed for system user: " + enableApps); 2108 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2109 UserHandle.SYSTEM); 2110 final int allAppsSize = allAps.size(); 2111 synchronized (mPackages) { 2112 for (int i = 0; i < allAppsSize; i++) { 2113 String pName = allAps.get(i); 2114 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2115 // Should not happen, but we shouldn't be failing if it does 2116 if (pkgSetting == null) { 2117 continue; 2118 } 2119 boolean install = enableApps.contains(pName); 2120 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2121 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2122 + " for system user"); 2123 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2124 } 2125 } 2126 } 2127 } 2128 2129 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2130 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2131 Context.DISPLAY_SERVICE); 2132 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2133 } 2134 2135 /** 2136 * Requests that files preopted on a secondary system partition be copied to the data partition 2137 * if possible. Note that the actual copying of the files is accomplished by init for security 2138 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2139 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2140 */ 2141 private static void requestCopyPreoptedFiles() { 2142 final int WAIT_TIME_MS = 100; 2143 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2144 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2145 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2146 // We will wait for up to 100 seconds. 2147 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2148 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2149 try { 2150 Thread.sleep(WAIT_TIME_MS); 2151 } catch (InterruptedException e) { 2152 // Do nothing 2153 } 2154 if (SystemClock.uptimeMillis() > timeEnd) { 2155 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2156 Slog.wtf(TAG, "cppreopt did not finish!"); 2157 break; 2158 } 2159 } 2160 } 2161 } 2162 2163 public PackageManagerService(Context context, Installer installer, 2164 boolean factoryTest, boolean onlyCore) { 2165 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2166 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2167 SystemClock.uptimeMillis()); 2168 2169 if (mSdkVersion <= 0) { 2170 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2171 } 2172 2173 mContext = context; 2174 2175 mPermissionReviewRequired = context.getResources().getBoolean( 2176 R.bool.config_permissionReviewRequired); 2177 2178 mFactoryTest = factoryTest; 2179 mOnlyCore = onlyCore; 2180 mMetrics = new DisplayMetrics(); 2181 mSettings = new Settings(mPackages); 2182 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2183 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2184 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2185 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2186 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2187 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2188 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2189 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2190 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2191 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2192 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2193 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2194 2195 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2196 if (separateProcesses != null && separateProcesses.length() > 0) { 2197 if ("*".equals(separateProcesses)) { 2198 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2199 mSeparateProcesses = null; 2200 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2201 } else { 2202 mDefParseFlags = 0; 2203 mSeparateProcesses = separateProcesses.split(","); 2204 Slog.w(TAG, "Running with debug.separate_processes: " 2205 + separateProcesses); 2206 } 2207 } else { 2208 mDefParseFlags = 0; 2209 mSeparateProcesses = null; 2210 } 2211 2212 mInstaller = installer; 2213 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2214 "*dexopt*"); 2215 mDexManager = new DexManager(); 2216 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2217 2218 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2219 FgThread.get().getLooper()); 2220 2221 getDefaultDisplayMetrics(context, mMetrics); 2222 2223 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2224 SystemConfig systemConfig = SystemConfig.getInstance(); 2225 mGlobalGids = systemConfig.getGlobalGids(); 2226 mSystemPermissions = systemConfig.getSystemPermissions(); 2227 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2228 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2229 2230 mProtectedPackages = new ProtectedPackages(mContext); 2231 2232 synchronized (mInstallLock) { 2233 // writer 2234 synchronized (mPackages) { 2235 mHandlerThread = new ServiceThread(TAG, 2236 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2237 mHandlerThread.start(); 2238 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2239 mProcessLoggingHandler = new ProcessLoggingHandler(); 2240 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2241 2242 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2243 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2244 2245 File dataDir = Environment.getDataDirectory(); 2246 mAppInstallDir = new File(dataDir, "app"); 2247 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2248 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2249 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2250 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2251 2252 sUserManager = new UserManagerService(context, this, mPackages); 2253 2254 // Propagate permission configuration in to package manager. 2255 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2256 = systemConfig.getPermissions(); 2257 for (int i=0; i<permConfig.size(); i++) { 2258 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2259 BasePermission bp = mSettings.mPermissions.get(perm.name); 2260 if (bp == null) { 2261 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2262 mSettings.mPermissions.put(perm.name, bp); 2263 } 2264 if (perm.gids != null) { 2265 bp.setGids(perm.gids, perm.perUser); 2266 } 2267 } 2268 2269 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2270 final int builtInLibCount = libConfig.size(); 2271 for (int i = 0; i < builtInLibCount; i++) { 2272 String name = libConfig.keyAt(i); 2273 String path = libConfig.valueAt(i); 2274 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2275 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2276 } 2277 2278 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2279 2280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2281 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2282 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2283 2284 // Clean up orphaned packages for which the code path doesn't exist 2285 // and they are an update to a system app - caused by bug/32321269 2286 final int packageSettingCount = mSettings.mPackages.size(); 2287 for (int i = packageSettingCount - 1; i >= 0; i--) { 2288 PackageSetting ps = mSettings.mPackages.valueAt(i); 2289 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2290 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2291 mSettings.mPackages.removeAt(i); 2292 mSettings.enableSystemPackageLPw(ps.name); 2293 } 2294 } 2295 2296 if (mFirstBoot) { 2297 requestCopyPreoptedFiles(); 2298 } 2299 2300 String customResolverActivity = Resources.getSystem().getString( 2301 R.string.config_customResolverActivity); 2302 if (TextUtils.isEmpty(customResolverActivity)) { 2303 customResolverActivity = null; 2304 } else { 2305 mCustomResolverComponentName = ComponentName.unflattenFromString( 2306 customResolverActivity); 2307 } 2308 2309 long startTime = SystemClock.uptimeMillis(); 2310 2311 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2312 startTime); 2313 2314 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2315 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2316 2317 if (bootClassPath == null) { 2318 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2319 } 2320 2321 if (systemServerClassPath == null) { 2322 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2323 } 2324 2325 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2326 final String[] dexCodeInstructionSets = 2327 getDexCodeInstructionSets( 2328 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2329 2330 /** 2331 * Ensure all external libraries have had dexopt run on them. 2332 */ 2333 if (mSharedLibraries.size() > 0) { 2334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2335 // NOTE: For now, we're compiling these system "shared libraries" 2336 // (and framework jars) into all available architectures. It's possible 2337 // to compile them only when we come across an app that uses them (there's 2338 // already logic for that in scanPackageLI) but that adds some complexity. 2339 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2340 final int libCount = mSharedLibraries.size(); 2341 for (int i = 0; i < libCount; i++) { 2342 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2343 final int versionCount = versionedLib.size(); 2344 for (int j = 0; j < versionCount; j++) { 2345 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2346 final String libPath = libEntry.path != null 2347 ? libEntry.path : libEntry.apk; 2348 if (libPath == null) { 2349 continue; 2350 } 2351 try { 2352 // Shared libraries do not have profiles so we perform a full 2353 // AOT compilation (if needed). 2354 int dexoptNeeded = DexFile.getDexOptNeeded( 2355 libPath, dexCodeInstructionSet, 2356 getCompilerFilterForReason(REASON_SHARED_APK), 2357 false /* newProfile */); 2358 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2359 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2360 dexCodeInstructionSet, dexoptNeeded, null, 2361 DEXOPT_PUBLIC, 2362 getCompilerFilterForReason(REASON_SHARED_APK), 2363 StorageManager.UUID_PRIVATE_INTERNAL, 2364 SKIP_SHARED_LIBRARY_CHECK); 2365 } 2366 } catch (FileNotFoundException e) { 2367 Slog.w(TAG, "Library not found: " + libPath); 2368 } catch (IOException | InstallerException e) { 2369 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2370 + e.getMessage()); 2371 } 2372 } 2373 } 2374 } 2375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2376 } 2377 2378 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2379 2380 final VersionInfo ver = mSettings.getInternalVersion(); 2381 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2382 2383 // when upgrading from pre-M, promote system app permissions from install to runtime 2384 mPromoteSystemApps = 2385 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2386 2387 // When upgrading from pre-N, we need to handle package extraction like first boot, 2388 // as there is no profiling data available. 2389 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2390 2391 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2392 2393 // save off the names of pre-existing system packages prior to scanning; we don't 2394 // want to automatically grant runtime permissions for new system apps 2395 if (mPromoteSystemApps) { 2396 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2397 while (pkgSettingIter.hasNext()) { 2398 PackageSetting ps = pkgSettingIter.next(); 2399 if (isSystemApp(ps)) { 2400 mExistingSystemPackages.add(ps.name); 2401 } 2402 } 2403 } 2404 2405 mCacheDir = preparePackageParserCache(mIsUpgrade); 2406 2407 // Set flag to monitor and not change apk file paths when 2408 // scanning install directories. 2409 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2410 2411 if (mIsUpgrade || mFirstBoot) { 2412 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2413 } 2414 2415 // Collect vendor overlay packages. (Do this before scanning any apps.) 2416 // For security and version matching reason, only consider 2417 // overlay packages if they reside in the right directory. 2418 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2419 if (overlayThemeDir.isEmpty()) { 2420 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2421 } 2422 if (!overlayThemeDir.isEmpty()) { 2423 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2424 | PackageParser.PARSE_IS_SYSTEM 2425 | PackageParser.PARSE_IS_SYSTEM_DIR 2426 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2427 } 2428 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2432 2433 // Find base frameworks (resource packages without code). 2434 scanDirTracedLI(frameworkDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED, 2438 scanFlags | SCAN_NO_DEX, 0); 2439 2440 // Collected privileged system packages. 2441 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2442 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR 2445 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2446 2447 // Collect ordinary system packages. 2448 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2449 scanDirTracedLI(systemAppDir, mDefParseFlags 2450 | PackageParser.PARSE_IS_SYSTEM 2451 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2452 2453 // Collect all vendor packages. 2454 File vendorAppDir = new File("/vendor/app"); 2455 try { 2456 vendorAppDir = vendorAppDir.getCanonicalFile(); 2457 } catch (IOException e) { 2458 // failed to look up canonical path, continue with original one 2459 } 2460 scanDirTracedLI(vendorAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Collect all OEM packages. 2465 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2466 scanDirTracedLI(oemAppDir, mDefParseFlags 2467 | PackageParser.PARSE_IS_SYSTEM 2468 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2469 2470 // Prune any system packages that no longer exist. 2471 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2472 if (!mOnlyCore) { 2473 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2474 while (psit.hasNext()) { 2475 PackageSetting ps = psit.next(); 2476 2477 /* 2478 * If this is not a system app, it can't be a 2479 * disable system app. 2480 */ 2481 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2482 continue; 2483 } 2484 2485 /* 2486 * If the package is scanned, it's not erased. 2487 */ 2488 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2489 if (scannedPkg != null) { 2490 /* 2491 * If the system app is both scanned and in the 2492 * disabled packages list, then it must have been 2493 * added via OTA. Remove it from the currently 2494 * scanned package so the previously user-installed 2495 * application can be scanned. 2496 */ 2497 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2498 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2499 + ps.name + "; removing system app. Last known codePath=" 2500 + ps.codePathString + ", installStatus=" + ps.installStatus 2501 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2502 + scannedPkg.mVersionCode); 2503 removePackageLI(scannedPkg, true); 2504 mExpectingBetter.put(ps.name, ps.codePath); 2505 } 2506 2507 continue; 2508 } 2509 2510 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2511 psit.remove(); 2512 logCriticalInfo(Log.WARN, "System package " + ps.name 2513 + " no longer exists; it's data will be wiped"); 2514 // Actual deletion of code and data will be handled by later 2515 // reconciliation step 2516 } else { 2517 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2518 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2519 possiblyDeletedUpdatedSystemApps.add(ps.name); 2520 } 2521 } 2522 } 2523 } 2524 2525 //look for any incomplete package installations 2526 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2527 for (int i = 0; i < deletePkgsList.size(); i++) { 2528 // Actual deletion of code and data will be handled by later 2529 // reconciliation step 2530 final String packageName = deletePkgsList.get(i).name; 2531 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2532 synchronized (mPackages) { 2533 mSettings.removePackageLPw(packageName); 2534 } 2535 } 2536 2537 //delete tmp files 2538 deleteTempPackageFiles(); 2539 2540 // Remove any shared userIDs that have no associated packages 2541 mSettings.pruneSharedUsersLPw(); 2542 2543 if (!mOnlyCore) { 2544 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2545 SystemClock.uptimeMillis()); 2546 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2549 | PackageParser.PARSE_FORWARD_LOCK, 2550 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2551 2552 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2553 | PackageParser.PARSE_IS_EPHEMERAL, 2554 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2555 2556 /** 2557 * Remove disable package settings for any updated system 2558 * apps that were removed via an OTA. If they're not a 2559 * previously-updated app, remove them completely. 2560 * Otherwise, just revoke their system-level permissions. 2561 */ 2562 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2563 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2564 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2565 2566 String msg; 2567 if (deletedPkg == null) { 2568 msg = "Updated system package " + deletedAppName 2569 + " no longer exists; it's data will be wiped"; 2570 // Actual deletion of code and data will be handled by later 2571 // reconciliation step 2572 } else { 2573 msg = "Updated system app + " + deletedAppName 2574 + " no longer present; removing system privileges for " 2575 + deletedAppName; 2576 2577 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2578 2579 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2580 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2581 } 2582 logCriticalInfo(Log.WARN, msg); 2583 } 2584 2585 /** 2586 * Make sure all system apps that we expected to appear on 2587 * the userdata partition actually showed up. If they never 2588 * appeared, crawl back and revive the system version. 2589 */ 2590 for (int i = 0; i < mExpectingBetter.size(); i++) { 2591 final String packageName = mExpectingBetter.keyAt(i); 2592 if (!mPackages.containsKey(packageName)) { 2593 final File scanFile = mExpectingBetter.valueAt(i); 2594 2595 logCriticalInfo(Log.WARN, "Expected better " + packageName 2596 + " but never showed up; reverting to system"); 2597 2598 int reparseFlags = mDefParseFlags; 2599 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2600 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2601 | PackageParser.PARSE_IS_SYSTEM_DIR 2602 | PackageParser.PARSE_IS_PRIVILEGED; 2603 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR; 2606 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2607 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2608 | PackageParser.PARSE_IS_SYSTEM_DIR; 2609 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2610 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2611 | PackageParser.PARSE_IS_SYSTEM_DIR; 2612 } else { 2613 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2614 continue; 2615 } 2616 2617 mSettings.enableSystemPackageLPw(packageName); 2618 2619 try { 2620 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2621 } catch (PackageManagerException e) { 2622 Slog.e(TAG, "Failed to parse original system package: " 2623 + e.getMessage()); 2624 } 2625 } 2626 } 2627 } 2628 mExpectingBetter.clear(); 2629 2630 // Resolve the storage manager. 2631 mStorageManagerPackage = getStorageManagerPackageName(); 2632 2633 // Resolve protected action filters. Only the setup wizard is allowed to 2634 // have a high priority filter for these actions. 2635 mSetupWizardPackage = getSetupWizardPackageName(); 2636 if (mProtectedFilters.size() > 0) { 2637 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2638 Slog.i(TAG, "No setup wizard;" 2639 + " All protected intents capped to priority 0"); 2640 } 2641 for (ActivityIntentInfo filter : mProtectedFilters) { 2642 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2643 if (DEBUG_FILTERS) { 2644 Slog.i(TAG, "Found setup wizard;" 2645 + " allow priority " + filter.getPriority() + ";" 2646 + " package: " + filter.activity.info.packageName 2647 + " activity: " + filter.activity.className 2648 + " priority: " + filter.getPriority()); 2649 } 2650 // skip setup wizard; allow it to keep the high priority filter 2651 continue; 2652 } 2653 Slog.w(TAG, "Protected action; cap priority to 0;" 2654 + " package: " + filter.activity.info.packageName 2655 + " activity: " + filter.activity.className 2656 + " origPrio: " + filter.getPriority()); 2657 filter.setPriority(0); 2658 } 2659 } 2660 mDeferProtectedFilters = false; 2661 mProtectedFilters.clear(); 2662 2663 // Now that we know all of the shared libraries, update all clients to have 2664 // the correct library paths. 2665 updateAllSharedLibrariesLPw(null); 2666 2667 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2668 // NOTE: We ignore potential failures here during a system scan (like 2669 // the rest of the commands above) because there's precious little we 2670 // can do about it. A settings error is reported, though. 2671 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2672 } 2673 2674 // Now that we know all the packages we are keeping, 2675 // read and update their last usage times. 2676 mPackageUsage.read(mPackages); 2677 mCompilerStats.read(); 2678 2679 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2680 SystemClock.uptimeMillis()); 2681 Slog.i(TAG, "Time to scan packages: " 2682 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2683 + " seconds"); 2684 2685 // If the platform SDK has changed since the last time we booted, 2686 // we need to re-grant app permission to catch any new ones that 2687 // appear. This is really a hack, and means that apps can in some 2688 // cases get permissions that the user didn't initially explicitly 2689 // allow... it would be nice to have some better way to handle 2690 // this situation. 2691 int updateFlags = UPDATE_PERMISSIONS_ALL; 2692 if (ver.sdkVersion != mSdkVersion) { 2693 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2694 + mSdkVersion + "; regranting permissions for internal storage"); 2695 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2696 } 2697 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2698 ver.sdkVersion = mSdkVersion; 2699 2700 // If this is the first boot or an update from pre-M, and it is a normal 2701 // boot, then we need to initialize the default preferred apps across 2702 // all defined users. 2703 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2704 for (UserInfo user : sUserManager.getUsers(true)) { 2705 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2706 applyFactoryDefaultBrowserLPw(user.id); 2707 primeDomainVerificationsLPw(user.id); 2708 } 2709 } 2710 2711 // Prepare storage for system user really early during boot, 2712 // since core system apps like SettingsProvider and SystemUI 2713 // can't wait for user to start 2714 final int storageFlags; 2715 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2716 storageFlags = StorageManager.FLAG_STORAGE_DE; 2717 } else { 2718 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2719 } 2720 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2721 storageFlags, true /* migrateAppData */); 2722 2723 // If this is first boot after an OTA, and a normal boot, then 2724 // we need to clear code cache directories. 2725 // Note that we do *not* clear the application profiles. These remain valid 2726 // across OTAs and are used to drive profile verification (post OTA) and 2727 // profile compilation (without waiting to collect a fresh set of profiles). 2728 if (mIsUpgrade && !onlyCore) { 2729 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2730 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2731 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2732 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2733 // No apps are running this early, so no need to freeze 2734 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2735 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2736 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2737 } 2738 } 2739 ver.fingerprint = Build.FINGERPRINT; 2740 } 2741 2742 checkDefaultBrowser(); 2743 2744 // clear only after permissions and other defaults have been updated 2745 mExistingSystemPackages.clear(); 2746 mPromoteSystemApps = false; 2747 2748 // All the changes are done during package scanning. 2749 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2750 2751 // can downgrade to reader 2752 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2753 mSettings.writeLPr(); 2754 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2755 2756 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2757 // early on (before the package manager declares itself as early) because other 2758 // components in the system server might ask for package contexts for these apps. 2759 // 2760 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2761 // (i.e, that the data partition is unavailable). 2762 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2763 long start = System.nanoTime(); 2764 List<PackageParser.Package> coreApps = new ArrayList<>(); 2765 for (PackageParser.Package pkg : mPackages.values()) { 2766 if (pkg.coreApp) { 2767 coreApps.add(pkg); 2768 } 2769 } 2770 2771 int[] stats = performDexOptUpgrade(coreApps, false, 2772 getCompilerFilterForReason(REASON_CORE_APP)); 2773 2774 final int elapsedTimeSeconds = 2775 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2776 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2777 2778 if (DEBUG_DEXOPT) { 2779 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2780 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2781 } 2782 2783 2784 // TODO: Should we log these stats to tron too ? 2785 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2786 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2787 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2788 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2789 } 2790 2791 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2792 SystemClock.uptimeMillis()); 2793 2794 if (!mOnlyCore) { 2795 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2796 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2797 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2798 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2799 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2800 mIntentFilterVerifierComponent); 2801 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2802 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2803 SharedLibraryInfo.VERSION_UNDEFINED); 2804 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2805 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2806 SharedLibraryInfo.VERSION_UNDEFINED); 2807 } else { 2808 mRequiredVerifierPackage = null; 2809 mRequiredInstallerPackage = null; 2810 mRequiredUninstallerPackage = null; 2811 mIntentFilterVerifierComponent = null; 2812 mIntentFilterVerifier = null; 2813 mServicesSystemSharedLibraryPackageName = null; 2814 mSharedSystemSharedLibraryPackageName = null; 2815 } 2816 2817 mInstallerService = new PackageInstallerService(context, this); 2818 2819 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2820 if (ephemeralResolverComponent != null) { 2821 if (DEBUG_EPHEMERAL) { 2822 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2823 } 2824 mEphemeralResolverConnection = 2825 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2826 } else { 2827 mEphemeralResolverConnection = null; 2828 } 2829 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2830 if (mEphemeralInstallerComponent != null) { 2831 if (DEBUG_EPHEMERAL) { 2832 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2833 } 2834 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2835 } 2836 2837 // Read and update the usage of dex files. 2838 // Do this at the end of PM init so that all the packages have their 2839 // data directory reconciled. 2840 // At this point we know the code paths of the packages, so we can validate 2841 // the disk file and build the internal cache. 2842 // The usage file is expected to be small so loading and verifying it 2843 // should take a fairly small time compare to the other activities (e.g. package 2844 // scanning). 2845 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2846 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2847 for (int userId : currentUserIds) { 2848 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2849 } 2850 mDexManager.load(userPackages); 2851 } // synchronized (mPackages) 2852 } // synchronized (mInstallLock) 2853 2854 // Now after opening every single application zip, make sure they 2855 // are all flushed. Not really needed, but keeps things nice and 2856 // tidy. 2857 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2858 Runtime.getRuntime().gc(); 2859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2860 2861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2862 FallbackCategoryProvider.loadFallbacks(); 2863 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2864 2865 // The initial scanning above does many calls into installd while 2866 // holding the mPackages lock, but we're mostly interested in yelling 2867 // once we have a booted system. 2868 mInstaller.setWarnIfHeld(mPackages); 2869 2870 // Expose private service for system components to use. 2871 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2872 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2873 } 2874 2875 private static File preparePackageParserCache(boolean isUpgrade) { 2876 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2877 return null; 2878 } 2879 2880 // Disable package parsing on eng builds to allow for faster incremental development. 2881 if ("eng".equals(Build.TYPE)) { 2882 return null; 2883 } 2884 2885 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2886 Slog.i(TAG, "Disabling package parser cache due to system property."); 2887 return null; 2888 } 2889 2890 // The base directory for the package parser cache lives under /data/system/. 2891 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2892 "package_cache"); 2893 if (cacheBaseDir == null) { 2894 return null; 2895 } 2896 2897 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2898 // This also serves to "GC" unused entries when the package cache version changes (which 2899 // can only happen during upgrades). 2900 if (isUpgrade) { 2901 FileUtils.deleteContents(cacheBaseDir); 2902 } 2903 2904 2905 // Return the versioned package cache directory. This is something like 2906 // "/data/system/package_cache/1" 2907 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2908 2909 // The following is a workaround to aid development on non-numbered userdebug 2910 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2911 // the system partition is newer. 2912 // 2913 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2914 // that starts with "eng." to signify that this is an engineering build and not 2915 // destined for release. 2916 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2917 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2918 2919 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2920 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2921 // in general and should not be used for production changes. In this specific case, 2922 // we know that they will work. 2923 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2924 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2925 FileUtils.deleteContents(cacheBaseDir); 2926 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2927 } 2928 } 2929 2930 return cacheDir; 2931 } 2932 2933 @Override 2934 public boolean isFirstBoot() { 2935 return mFirstBoot; 2936 } 2937 2938 @Override 2939 public boolean isOnlyCoreApps() { 2940 return mOnlyCore; 2941 } 2942 2943 @Override 2944 public boolean isUpgrade() { 2945 return mIsUpgrade; 2946 } 2947 2948 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2949 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2950 2951 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2952 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2953 UserHandle.USER_SYSTEM); 2954 if (matches.size() == 1) { 2955 return matches.get(0).getComponentInfo().packageName; 2956 } else if (matches.size() == 0) { 2957 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2958 return null; 2959 } 2960 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2961 } 2962 2963 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2964 synchronized (mPackages) { 2965 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2966 if (libraryEntry == null) { 2967 throw new IllegalStateException("Missing required shared library:" + name); 2968 } 2969 return libraryEntry.apk; 2970 } 2971 } 2972 2973 private @NonNull String getRequiredInstallerLPr() { 2974 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2975 intent.addCategory(Intent.CATEGORY_DEFAULT); 2976 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2977 2978 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2979 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2980 UserHandle.USER_SYSTEM); 2981 if (matches.size() == 1) { 2982 ResolveInfo resolveInfo = matches.get(0); 2983 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2984 throw new RuntimeException("The installer must be a privileged app"); 2985 } 2986 return matches.get(0).getComponentInfo().packageName; 2987 } else { 2988 throw new RuntimeException("There must be exactly one installer; found " + matches); 2989 } 2990 } 2991 2992 private @NonNull String getRequiredUninstallerLPr() { 2993 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2994 intent.addCategory(Intent.CATEGORY_DEFAULT); 2995 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2996 2997 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2998 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2999 UserHandle.USER_SYSTEM); 3000 if (resolveInfo == null || 3001 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3002 throw new RuntimeException("There must be exactly one uninstaller; found " 3003 + resolveInfo); 3004 } 3005 return resolveInfo.getComponentInfo().packageName; 3006 } 3007 3008 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3009 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3010 3011 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3012 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3013 UserHandle.USER_SYSTEM); 3014 ResolveInfo best = null; 3015 final int N = matches.size(); 3016 for (int i = 0; i < N; i++) { 3017 final ResolveInfo cur = matches.get(i); 3018 final String packageName = cur.getComponentInfo().packageName; 3019 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3020 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3021 continue; 3022 } 3023 3024 if (best == null || cur.priority > best.priority) { 3025 best = cur; 3026 } 3027 } 3028 3029 if (best != null) { 3030 return best.getComponentInfo().getComponentName(); 3031 } else { 3032 throw new RuntimeException("There must be at least one intent filter verifier"); 3033 } 3034 } 3035 3036 private @Nullable ComponentName getEphemeralResolverLPr() { 3037 final String[] packageArray = 3038 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3039 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3040 if (DEBUG_EPHEMERAL) { 3041 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3042 } 3043 return null; 3044 } 3045 3046 final int resolveFlags = 3047 MATCH_DIRECT_BOOT_AWARE 3048 | MATCH_DIRECT_BOOT_UNAWARE 3049 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3050 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3051 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3052 resolveFlags, UserHandle.USER_SYSTEM); 3053 3054 final int N = resolvers.size(); 3055 if (N == 0) { 3056 if (DEBUG_EPHEMERAL) { 3057 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3058 } 3059 return null; 3060 } 3061 3062 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3063 for (int i = 0; i < N; i++) { 3064 final ResolveInfo info = resolvers.get(i); 3065 3066 if (info.serviceInfo == null) { 3067 continue; 3068 } 3069 3070 final String packageName = info.serviceInfo.packageName; 3071 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3072 if (DEBUG_EPHEMERAL) { 3073 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3074 + " pkg: " + packageName + ", info:" + info); 3075 } 3076 continue; 3077 } 3078 3079 if (DEBUG_EPHEMERAL) { 3080 Slog.v(TAG, "Ephemeral resolver found;" 3081 + " pkg: " + packageName + ", info:" + info); 3082 } 3083 return new ComponentName(packageName, info.serviceInfo.name); 3084 } 3085 if (DEBUG_EPHEMERAL) { 3086 Slog.v(TAG, "Ephemeral resolver NOT found"); 3087 } 3088 return null; 3089 } 3090 3091 private @Nullable ComponentName getEphemeralInstallerLPr() { 3092 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3093 intent.addCategory(Intent.CATEGORY_DEFAULT); 3094 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3095 3096 final int resolveFlags = 3097 MATCH_DIRECT_BOOT_AWARE 3098 | MATCH_DIRECT_BOOT_UNAWARE 3099 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3100 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3101 resolveFlags, UserHandle.USER_SYSTEM); 3102 Iterator<ResolveInfo> iter = matches.iterator(); 3103 while (iter.hasNext()) { 3104 final ResolveInfo rInfo = iter.next(); 3105 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3106 if (ps != null) { 3107 final PermissionsState permissionsState = ps.getPermissionsState(); 3108 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3109 continue; 3110 } 3111 } 3112 iter.remove(); 3113 } 3114 if (matches.size() == 0) { 3115 return null; 3116 } else if (matches.size() == 1) { 3117 return matches.get(0).getComponentInfo().getComponentName(); 3118 } else { 3119 throw new RuntimeException( 3120 "There must be at most one ephemeral installer; found " + matches); 3121 } 3122 } 3123 3124 private void primeDomainVerificationsLPw(int userId) { 3125 if (DEBUG_DOMAIN_VERIFICATION) { 3126 Slog.d(TAG, "Priming domain verifications in user " + userId); 3127 } 3128 3129 SystemConfig systemConfig = SystemConfig.getInstance(); 3130 ArraySet<String> packages = systemConfig.getLinkedApps(); 3131 3132 for (String packageName : packages) { 3133 PackageParser.Package pkg = mPackages.get(packageName); 3134 if (pkg != null) { 3135 if (!pkg.isSystemApp()) { 3136 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3137 continue; 3138 } 3139 3140 ArraySet<String> domains = null; 3141 for (PackageParser.Activity a : pkg.activities) { 3142 for (ActivityIntentInfo filter : a.intents) { 3143 if (hasValidDomains(filter)) { 3144 if (domains == null) { 3145 domains = new ArraySet<String>(); 3146 } 3147 domains.addAll(filter.getHostsList()); 3148 } 3149 } 3150 } 3151 3152 if (domains != null && domains.size() > 0) { 3153 if (DEBUG_DOMAIN_VERIFICATION) { 3154 Slog.v(TAG, " + " + packageName); 3155 } 3156 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3157 // state w.r.t. the formal app-linkage "no verification attempted" state; 3158 // and then 'always' in the per-user state actually used for intent resolution. 3159 final IntentFilterVerificationInfo ivi; 3160 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3161 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3162 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3163 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3164 } else { 3165 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3166 + "' does not handle web links"); 3167 } 3168 } else { 3169 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3170 } 3171 } 3172 3173 scheduleWritePackageRestrictionsLocked(userId); 3174 scheduleWriteSettingsLocked(); 3175 } 3176 3177 private void applyFactoryDefaultBrowserLPw(int userId) { 3178 // The default browser app's package name is stored in a string resource, 3179 // with a product-specific overlay used for vendor customization. 3180 String browserPkg = mContext.getResources().getString( 3181 com.android.internal.R.string.default_browser); 3182 if (!TextUtils.isEmpty(browserPkg)) { 3183 // non-empty string => required to be a known package 3184 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3185 if (ps == null) { 3186 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3187 browserPkg = null; 3188 } else { 3189 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3190 } 3191 } 3192 3193 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3194 // default. If there's more than one, just leave everything alone. 3195 if (browserPkg == null) { 3196 calculateDefaultBrowserLPw(userId); 3197 } 3198 } 3199 3200 private void calculateDefaultBrowserLPw(int userId) { 3201 List<String> allBrowsers = resolveAllBrowserApps(userId); 3202 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3203 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3204 } 3205 3206 private List<String> resolveAllBrowserApps(int userId) { 3207 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3208 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3209 PackageManager.MATCH_ALL, userId); 3210 3211 final int count = list.size(); 3212 List<String> result = new ArrayList<String>(count); 3213 for (int i=0; i<count; i++) { 3214 ResolveInfo info = list.get(i); 3215 if (info.activityInfo == null 3216 || !info.handleAllWebDataURI 3217 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3218 || result.contains(info.activityInfo.packageName)) { 3219 continue; 3220 } 3221 result.add(info.activityInfo.packageName); 3222 } 3223 3224 return result; 3225 } 3226 3227 private boolean packageIsBrowser(String packageName, int userId) { 3228 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3229 PackageManager.MATCH_ALL, userId); 3230 final int N = list.size(); 3231 for (int i = 0; i < N; i++) { 3232 ResolveInfo info = list.get(i); 3233 if (packageName.equals(info.activityInfo.packageName)) { 3234 return true; 3235 } 3236 } 3237 return false; 3238 } 3239 3240 private void checkDefaultBrowser() { 3241 final int myUserId = UserHandle.myUserId(); 3242 final String packageName = getDefaultBrowserPackageName(myUserId); 3243 if (packageName != null) { 3244 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3245 if (info == null) { 3246 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3247 synchronized (mPackages) { 3248 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3249 } 3250 } 3251 } 3252 } 3253 3254 @Override 3255 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3256 throws RemoteException { 3257 try { 3258 return super.onTransact(code, data, reply, flags); 3259 } catch (RuntimeException e) { 3260 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3261 Slog.wtf(TAG, "Package Manager Crash", e); 3262 } 3263 throw e; 3264 } 3265 } 3266 3267 static int[] appendInts(int[] cur, int[] add) { 3268 if (add == null) return cur; 3269 if (cur == null) return add; 3270 final int N = add.length; 3271 for (int i=0; i<N; i++) { 3272 cur = appendInt(cur, add[i]); 3273 } 3274 return cur; 3275 } 3276 3277 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3278 if (!sUserManager.exists(userId)) return null; 3279 if (ps == null) { 3280 return null; 3281 } 3282 final PackageParser.Package p = ps.pkg; 3283 if (p == null) { 3284 return null; 3285 } 3286 // Filter out ephemeral app metadata: 3287 // * The system/shell/root can see metadata for any app 3288 // * An installed app can see metadata for 1) other installed apps 3289 // and 2) ephemeral apps that have explicitly interacted with it 3290 // * Ephemeral apps can only see their own metadata 3291 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3292 if (callingAppId != Process.SYSTEM_UID 3293 && callingAppId != Process.SHELL_UID 3294 && callingAppId != Process.ROOT_UID) { 3295 final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid()); 3296 if (ephemeralPackageName != null) { 3297 // ephemeral apps can only get information on themselves 3298 if (!ephemeralPackageName.equals(p.packageName)) { 3299 return null; 3300 } 3301 } else { 3302 if (p.applicationInfo.isEphemeralApp()) { 3303 // only get access to the ephemeral app if we've been granted access 3304 if (!mEphemeralApplicationRegistry.isEphemeralAccessGranted( 3305 userId, callingAppId, ps.appId)) { 3306 return null; 3307 } 3308 } 3309 } 3310 } 3311 3312 final PermissionsState permissionsState = ps.getPermissionsState(); 3313 3314 // Compute GIDs only if requested 3315 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3316 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3317 // Compute granted permissions only if package has requested permissions 3318 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3319 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3320 final PackageUserState state = ps.readUserState(userId); 3321 3322 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3323 && ps.isSystem()) { 3324 flags |= MATCH_ANY_USER; 3325 } 3326 3327 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3328 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3329 3330 if (packageInfo == null) { 3331 return null; 3332 } 3333 3334 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3335 resolveExternalPackageNameLPr(p); 3336 3337 return packageInfo; 3338 } 3339 3340 @Override 3341 public void checkPackageStartable(String packageName, int userId) { 3342 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3343 3344 synchronized (mPackages) { 3345 final PackageSetting ps = mSettings.mPackages.get(packageName); 3346 if (ps == null) { 3347 throw new SecurityException("Package " + packageName + " was not found!"); 3348 } 3349 3350 if (!ps.getInstalled(userId)) { 3351 throw new SecurityException( 3352 "Package " + packageName + " was not installed for user " + userId + "!"); 3353 } 3354 3355 if (mSafeMode && !ps.isSystem()) { 3356 throw new SecurityException("Package " + packageName + " not a system app!"); 3357 } 3358 3359 if (mFrozenPackages.contains(packageName)) { 3360 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3361 } 3362 3363 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3364 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3365 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3366 } 3367 } 3368 } 3369 3370 @Override 3371 public boolean isPackageAvailable(String packageName, int userId) { 3372 if (!sUserManager.exists(userId)) return false; 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3374 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3375 synchronized (mPackages) { 3376 PackageParser.Package p = mPackages.get(packageName); 3377 if (p != null) { 3378 final PackageSetting ps = (PackageSetting) p.mExtras; 3379 if (ps != null) { 3380 final PackageUserState state = ps.readUserState(userId); 3381 if (state != null) { 3382 return PackageParser.isAvailable(state); 3383 } 3384 } 3385 } 3386 } 3387 return false; 3388 } 3389 3390 @Override 3391 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3392 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3393 flags, userId); 3394 } 3395 3396 @Override 3397 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3398 int flags, int userId) { 3399 return getPackageInfoInternal(versionedPackage.getPackageName(), 3400 // TODO: We will change version code to long, so in the new API it is long 3401 (int) versionedPackage.getVersionCode(), flags, userId); 3402 } 3403 3404 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3405 int flags, int userId) { 3406 if (!sUserManager.exists(userId)) return null; 3407 flags = updateFlagsForPackage(flags, userId, packageName); 3408 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3409 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3410 3411 // reader 3412 synchronized (mPackages) { 3413 // Normalize package name to handle renamed packages and static libs 3414 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3415 3416 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3417 if (matchFactoryOnly) { 3418 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3419 if (ps != null) { 3420 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3421 return null; 3422 } 3423 return generatePackageInfo(ps, flags, userId); 3424 } 3425 } 3426 3427 PackageParser.Package p = mPackages.get(packageName); 3428 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3429 return null; 3430 } 3431 if (DEBUG_PACKAGE_INFO) 3432 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3433 if (p != null) { 3434 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3435 Binder.getCallingUid(), userId)) { 3436 return null; 3437 } 3438 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3439 } 3440 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3441 final PackageSetting ps = mSettings.mPackages.get(packageName); 3442 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3443 return null; 3444 } 3445 return generatePackageInfo(ps, flags, userId); 3446 } 3447 } 3448 return null; 3449 } 3450 3451 3452 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3453 // System/shell/root get to see all static libs 3454 final int appId = UserHandle.getAppId(uid); 3455 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3456 || appId == Process.ROOT_UID) { 3457 return false; 3458 } 3459 3460 // No package means no static lib as it is always on internal storage 3461 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3462 return false; 3463 } 3464 3465 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3466 ps.pkg.staticSharedLibVersion); 3467 if (libEntry == null) { 3468 return false; 3469 } 3470 3471 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3472 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3473 if (uidPackageNames == null) { 3474 return true; 3475 } 3476 3477 for (String uidPackageName : uidPackageNames) { 3478 if (ps.name.equals(uidPackageName)) { 3479 return false; 3480 } 3481 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3482 if (uidPs != null) { 3483 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3484 libEntry.info.getName()); 3485 if (index < 0) { 3486 continue; 3487 } 3488 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3489 return false; 3490 } 3491 } 3492 } 3493 return true; 3494 } 3495 3496 @Override 3497 public String[] currentToCanonicalPackageNames(String[] names) { 3498 String[] out = new String[names.length]; 3499 // reader 3500 synchronized (mPackages) { 3501 for (int i=names.length-1; i>=0; i--) { 3502 PackageSetting ps = mSettings.mPackages.get(names[i]); 3503 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3504 } 3505 } 3506 return out; 3507 } 3508 3509 @Override 3510 public String[] canonicalToCurrentPackageNames(String[] names) { 3511 String[] out = new String[names.length]; 3512 // reader 3513 synchronized (mPackages) { 3514 for (int i=names.length-1; i>=0; i--) { 3515 String cur = mSettings.getRenamedPackageLPr(names[i]); 3516 out[i] = cur != null ? cur : names[i]; 3517 } 3518 } 3519 return out; 3520 } 3521 3522 @Override 3523 public int getPackageUid(String packageName, int flags, int userId) { 3524 if (!sUserManager.exists(userId)) return -1; 3525 flags = updateFlagsForPackage(flags, userId, packageName); 3526 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3527 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3528 3529 // reader 3530 synchronized (mPackages) { 3531 final PackageParser.Package p = mPackages.get(packageName); 3532 if (p != null && p.isMatch(flags)) { 3533 return UserHandle.getUid(userId, p.applicationInfo.uid); 3534 } 3535 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3536 final PackageSetting ps = mSettings.mPackages.get(packageName); 3537 if (ps != null && ps.isMatch(flags)) { 3538 return UserHandle.getUid(userId, ps.appId); 3539 } 3540 } 3541 } 3542 3543 return -1; 3544 } 3545 3546 @Override 3547 public int[] getPackageGids(String packageName, int flags, int userId) { 3548 if (!sUserManager.exists(userId)) return null; 3549 flags = updateFlagsForPackage(flags, userId, packageName); 3550 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3551 false /* requireFullPermission */, false /* checkShell */, 3552 "getPackageGids"); 3553 3554 // reader 3555 synchronized (mPackages) { 3556 final PackageParser.Package p = mPackages.get(packageName); 3557 if (p != null && p.isMatch(flags)) { 3558 PackageSetting ps = (PackageSetting) p.mExtras; 3559 // TODO: Shouldn't this be checking for package installed state for userId and 3560 // return null? 3561 return ps.getPermissionsState().computeGids(userId); 3562 } 3563 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3564 final PackageSetting ps = mSettings.mPackages.get(packageName); 3565 if (ps != null && ps.isMatch(flags)) { 3566 return ps.getPermissionsState().computeGids(userId); 3567 } 3568 } 3569 } 3570 3571 return null; 3572 } 3573 3574 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3575 if (bp.perm != null) { 3576 return PackageParser.generatePermissionInfo(bp.perm, flags); 3577 } 3578 PermissionInfo pi = new PermissionInfo(); 3579 pi.name = bp.name; 3580 pi.packageName = bp.sourcePackage; 3581 pi.nonLocalizedLabel = bp.name; 3582 pi.protectionLevel = bp.protectionLevel; 3583 return pi; 3584 } 3585 3586 @Override 3587 public PermissionInfo getPermissionInfo(String name, int flags) { 3588 // reader 3589 synchronized (mPackages) { 3590 final BasePermission p = mSettings.mPermissions.get(name); 3591 if (p != null) { 3592 return generatePermissionInfo(p, flags); 3593 } 3594 return null; 3595 } 3596 } 3597 3598 @Override 3599 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3600 int flags) { 3601 // reader 3602 synchronized (mPackages) { 3603 if (group != null && !mPermissionGroups.containsKey(group)) { 3604 // This is thrown as NameNotFoundException 3605 return null; 3606 } 3607 3608 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3609 for (BasePermission p : mSettings.mPermissions.values()) { 3610 if (group == null) { 3611 if (p.perm == null || p.perm.info.group == null) { 3612 out.add(generatePermissionInfo(p, flags)); 3613 } 3614 } else { 3615 if (p.perm != null && group.equals(p.perm.info.group)) { 3616 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3617 } 3618 } 3619 } 3620 return new ParceledListSlice<>(out); 3621 } 3622 } 3623 3624 @Override 3625 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3626 // reader 3627 synchronized (mPackages) { 3628 return PackageParser.generatePermissionGroupInfo( 3629 mPermissionGroups.get(name), flags); 3630 } 3631 } 3632 3633 @Override 3634 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3635 // reader 3636 synchronized (mPackages) { 3637 final int N = mPermissionGroups.size(); 3638 ArrayList<PermissionGroupInfo> out 3639 = new ArrayList<PermissionGroupInfo>(N); 3640 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3641 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3642 } 3643 return new ParceledListSlice<>(out); 3644 } 3645 } 3646 3647 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3648 int uid, int userId) { 3649 if (!sUserManager.exists(userId)) return null; 3650 PackageSetting ps = mSettings.mPackages.get(packageName); 3651 if (ps != null) { 3652 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3653 return null; 3654 } 3655 if (ps.pkg == null) { 3656 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3657 if (pInfo != null) { 3658 return pInfo.applicationInfo; 3659 } 3660 return null; 3661 } 3662 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3663 ps.readUserState(userId), userId); 3664 if (ai != null) { 3665 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3666 } 3667 return ai; 3668 } 3669 return null; 3670 } 3671 3672 @Override 3673 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3674 if (!sUserManager.exists(userId)) return null; 3675 flags = updateFlagsForApplication(flags, userId, packageName); 3676 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3677 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3678 3679 // writer 3680 synchronized (mPackages) { 3681 // Normalize package name to handle renamed packages and static libs 3682 packageName = resolveInternalPackageNameLPr(packageName, 3683 PackageManager.VERSION_CODE_HIGHEST); 3684 3685 PackageParser.Package p = mPackages.get(packageName); 3686 if (DEBUG_PACKAGE_INFO) Log.v( 3687 TAG, "getApplicationInfo " + packageName 3688 + ": " + p); 3689 if (p != null) { 3690 PackageSetting ps = mSettings.mPackages.get(packageName); 3691 if (ps == null) return null; 3692 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3693 return null; 3694 } 3695 // Note: isEnabledLP() does not apply here - always return info 3696 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3697 p, flags, ps.readUserState(userId), userId); 3698 if (ai != null) { 3699 ai.packageName = resolveExternalPackageNameLPr(p); 3700 } 3701 return ai; 3702 } 3703 if ("android".equals(packageName)||"system".equals(packageName)) { 3704 return mAndroidApplication; 3705 } 3706 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3707 // Already generates the external package name 3708 return generateApplicationInfoFromSettingsLPw(packageName, 3709 Binder.getCallingUid(), flags, userId); 3710 } 3711 } 3712 return null; 3713 } 3714 3715 private String normalizePackageNameLPr(String packageName) { 3716 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3717 return normalizedPackageName != null ? normalizedPackageName : packageName; 3718 } 3719 3720 @Override 3721 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3722 final IPackageDataObserver observer) { 3723 mContext.enforceCallingOrSelfPermission( 3724 android.Manifest.permission.CLEAR_APP_CACHE, null); 3725 // Queue up an async operation since clearing cache may take a little while. 3726 mHandler.post(new Runnable() { 3727 public void run() { 3728 mHandler.removeCallbacks(this); 3729 boolean success = true; 3730 synchronized (mInstallLock) { 3731 try { 3732 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3733 } catch (InstallerException e) { 3734 Slog.w(TAG, "Couldn't clear application caches: " + e); 3735 success = false; 3736 } 3737 } 3738 if (observer != null) { 3739 try { 3740 observer.onRemoveCompleted(null, success); 3741 } catch (RemoteException e) { 3742 Slog.w(TAG, "RemoveException when invoking call back"); 3743 } 3744 } 3745 } 3746 }); 3747 } 3748 3749 @Override 3750 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3751 final IntentSender pi) { 3752 mContext.enforceCallingOrSelfPermission( 3753 android.Manifest.permission.CLEAR_APP_CACHE, null); 3754 // Queue up an async operation since clearing cache may take a little while. 3755 mHandler.post(new Runnable() { 3756 public void run() { 3757 mHandler.removeCallbacks(this); 3758 boolean success = true; 3759 synchronized (mInstallLock) { 3760 try { 3761 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3762 } catch (InstallerException e) { 3763 Slog.w(TAG, "Couldn't clear application caches: " + e); 3764 success = false; 3765 } 3766 } 3767 if(pi != null) { 3768 try { 3769 // Callback via pending intent 3770 int code = success ? 1 : 0; 3771 pi.sendIntent(null, code, null, 3772 null, null); 3773 } catch (SendIntentException e1) { 3774 Slog.i(TAG, "Failed to send pending intent"); 3775 } 3776 } 3777 } 3778 }); 3779 } 3780 3781 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3782 synchronized (mInstallLock) { 3783 try { 3784 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3785 } catch (InstallerException e) { 3786 throw new IOException("Failed to free enough space", e); 3787 } 3788 } 3789 } 3790 3791 /** 3792 * Update given flags based on encryption status of current user. 3793 */ 3794 private int updateFlags(int flags, int userId) { 3795 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3796 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3797 // Caller expressed an explicit opinion about what encryption 3798 // aware/unaware components they want to see, so fall through and 3799 // give them what they want 3800 } else { 3801 // Caller expressed no opinion, so match based on user state 3802 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3803 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3804 } else { 3805 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3806 } 3807 } 3808 return flags; 3809 } 3810 3811 private UserManagerInternal getUserManagerInternal() { 3812 if (mUserManagerInternal == null) { 3813 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3814 } 3815 return mUserManagerInternal; 3816 } 3817 3818 /** 3819 * Update given flags when being used to request {@link PackageInfo}. 3820 */ 3821 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3822 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3823 boolean triaged = true; 3824 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3825 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3826 // Caller is asking for component details, so they'd better be 3827 // asking for specific encryption matching behavior, or be triaged 3828 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3829 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3830 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3831 triaged = false; 3832 } 3833 } 3834 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3835 | PackageManager.MATCH_SYSTEM_ONLY 3836 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3837 triaged = false; 3838 } 3839 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3840 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3841 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3842 + Debug.getCallers(5)); 3843 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3844 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3845 // If the caller wants all packages and has a restricted profile associated with it, 3846 // then match all users. This is to make sure that launchers that need to access work 3847 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3848 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3849 flags |= PackageManager.MATCH_ANY_USER; 3850 } 3851 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3852 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3853 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3854 } 3855 return updateFlags(flags, userId); 3856 } 3857 3858 /** 3859 * Update given flags when being used to request {@link ApplicationInfo}. 3860 */ 3861 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3862 return updateFlagsForPackage(flags, userId, cookie); 3863 } 3864 3865 /** 3866 * Update given flags when being used to request {@link ComponentInfo}. 3867 */ 3868 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3869 if (cookie instanceof Intent) { 3870 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3871 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3872 } 3873 } 3874 3875 boolean triaged = true; 3876 // Caller is asking for component details, so they'd better be 3877 // asking for specific encryption matching behavior, or be triaged 3878 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3879 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3880 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3881 triaged = false; 3882 } 3883 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3884 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3885 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3886 } 3887 3888 return updateFlags(flags, userId); 3889 } 3890 3891 /** 3892 * Update given intent when being used to request {@link ResolveInfo}. 3893 */ 3894 private Intent updateIntentForResolve(Intent intent) { 3895 if (intent.getSelector() != null) { 3896 intent = intent.getSelector(); 3897 } 3898 if (DEBUG_PREFERRED) { 3899 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3900 } 3901 return intent; 3902 } 3903 3904 /** 3905 * Update given flags when being used to request {@link ResolveInfo}. 3906 */ 3907 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3908 // Safe mode means we shouldn't match any third-party components 3909 if (mSafeMode) { 3910 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3911 } 3912 final int callingUid = Binder.getCallingUid(); 3913 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3914 // The system sees all components 3915 flags |= PackageManager.MATCH_EPHEMERAL; 3916 } else if (getEphemeralPackageName(callingUid) != null) { 3917 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3918 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3919 flags |= PackageManager.MATCH_EPHEMERAL; 3920 } else { 3921 // Otherwise, prevent leaking ephemeral components 3922 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3923 flags &= ~PackageManager.MATCH_EPHEMERAL; 3924 } 3925 return updateFlagsForComponent(flags, userId, cookie); 3926 } 3927 3928 @Override 3929 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3930 if (!sUserManager.exists(userId)) return null; 3931 flags = updateFlagsForComponent(flags, userId, component); 3932 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3933 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3934 synchronized (mPackages) { 3935 PackageParser.Activity a = mActivities.mActivities.get(component); 3936 3937 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3938 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3939 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3940 if (ps == null) return null; 3941 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3942 userId); 3943 } 3944 if (mResolveComponentName.equals(component)) { 3945 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3946 new PackageUserState(), userId); 3947 } 3948 } 3949 return null; 3950 } 3951 3952 @Override 3953 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3954 String resolvedType) { 3955 synchronized (mPackages) { 3956 if (component.equals(mResolveComponentName)) { 3957 // The resolver supports EVERYTHING! 3958 return true; 3959 } 3960 PackageParser.Activity a = mActivities.mActivities.get(component); 3961 if (a == null) { 3962 return false; 3963 } 3964 for (int i=0; i<a.intents.size(); i++) { 3965 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3966 intent.getData(), intent.getCategories(), TAG) >= 0) { 3967 return true; 3968 } 3969 } 3970 return false; 3971 } 3972 } 3973 3974 @Override 3975 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3976 if (!sUserManager.exists(userId)) return null; 3977 flags = updateFlagsForComponent(flags, userId, component); 3978 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3979 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3980 synchronized (mPackages) { 3981 PackageParser.Activity a = mReceivers.mActivities.get(component); 3982 if (DEBUG_PACKAGE_INFO) Log.v( 3983 TAG, "getReceiverInfo " + component + ": " + a); 3984 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3985 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3986 if (ps == null) return null; 3987 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3988 userId); 3989 } 3990 } 3991 return null; 3992 } 3993 3994 @Override 3995 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 3996 if (!sUserManager.exists(userId)) return null; 3997 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 3998 3999 flags = updateFlagsForPackage(flags, userId, null); 4000 4001 final boolean canSeeStaticLibraries = 4002 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4003 == PERMISSION_GRANTED 4004 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4005 == PERMISSION_GRANTED 4006 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4007 == PERMISSION_GRANTED 4008 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4009 == PERMISSION_GRANTED; 4010 4011 synchronized (mPackages) { 4012 List<SharedLibraryInfo> result = null; 4013 4014 final int libCount = mSharedLibraries.size(); 4015 for (int i = 0; i < libCount; i++) { 4016 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4017 if (versionedLib == null) { 4018 continue; 4019 } 4020 4021 final int versionCount = versionedLib.size(); 4022 for (int j = 0; j < versionCount; j++) { 4023 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4024 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4025 break; 4026 } 4027 final long identity = Binder.clearCallingIdentity(); 4028 try { 4029 // TODO: We will change version code to long, so in the new API it is long 4030 PackageInfo packageInfo = getPackageInfoVersioned( 4031 libInfo.getDeclaringPackage(), flags, userId); 4032 if (packageInfo == null) { 4033 continue; 4034 } 4035 } finally { 4036 Binder.restoreCallingIdentity(identity); 4037 } 4038 4039 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4040 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4041 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4042 4043 if (result == null) { 4044 result = new ArrayList<>(); 4045 } 4046 result.add(resLibInfo); 4047 } 4048 } 4049 4050 return result != null ? new ParceledListSlice<>(result) : null; 4051 } 4052 } 4053 4054 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4055 SharedLibraryInfo libInfo, int flags, int userId) { 4056 List<VersionedPackage> versionedPackages = null; 4057 final int packageCount = mSettings.mPackages.size(); 4058 for (int i = 0; i < packageCount; i++) { 4059 PackageSetting ps = mSettings.mPackages.valueAt(i); 4060 4061 if (ps == null) { 4062 continue; 4063 } 4064 4065 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4066 continue; 4067 } 4068 4069 final String libName = libInfo.getName(); 4070 if (libInfo.isStatic()) { 4071 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4072 if (libIdx < 0) { 4073 continue; 4074 } 4075 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4076 continue; 4077 } 4078 if (versionedPackages == null) { 4079 versionedPackages = new ArrayList<>(); 4080 } 4081 // If the dependent is a static shared lib, use the public package name 4082 String dependentPackageName = ps.name; 4083 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4084 dependentPackageName = ps.pkg.manifestPackageName; 4085 } 4086 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4087 } else if (ps.pkg != null) { 4088 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4089 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4090 if (versionedPackages == null) { 4091 versionedPackages = new ArrayList<>(); 4092 } 4093 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4094 } 4095 } 4096 } 4097 4098 return versionedPackages; 4099 } 4100 4101 @Override 4102 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4103 if (!sUserManager.exists(userId)) return null; 4104 flags = updateFlagsForComponent(flags, userId, component); 4105 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4106 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4107 synchronized (mPackages) { 4108 PackageParser.Service s = mServices.mServices.get(component); 4109 if (DEBUG_PACKAGE_INFO) Log.v( 4110 TAG, "getServiceInfo " + component + ": " + s); 4111 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4112 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4113 if (ps == null) return null; 4114 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4115 userId); 4116 } 4117 } 4118 return null; 4119 } 4120 4121 @Override 4122 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4123 if (!sUserManager.exists(userId)) return null; 4124 flags = updateFlagsForComponent(flags, userId, component); 4125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4126 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4127 synchronized (mPackages) { 4128 PackageParser.Provider p = mProviders.mProviders.get(component); 4129 if (DEBUG_PACKAGE_INFO) Log.v( 4130 TAG, "getProviderInfo " + component + ": " + p); 4131 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4132 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4133 if (ps == null) return null; 4134 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4135 userId); 4136 } 4137 } 4138 return null; 4139 } 4140 4141 @Override 4142 public String[] getSystemSharedLibraryNames() { 4143 synchronized (mPackages) { 4144 Set<String> libs = null; 4145 final int libCount = mSharedLibraries.size(); 4146 for (int i = 0; i < libCount; i++) { 4147 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4148 if (versionedLib == null) { 4149 continue; 4150 } 4151 final int versionCount = versionedLib.size(); 4152 for (int j = 0; j < versionCount; j++) { 4153 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4154 if (!libEntry.info.isStatic()) { 4155 if (libs == null) { 4156 libs = new ArraySet<>(); 4157 } 4158 libs.add(libEntry.info.getName()); 4159 break; 4160 } 4161 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4162 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4163 UserHandle.getUserId(Binder.getCallingUid()))) { 4164 if (libs == null) { 4165 libs = new ArraySet<>(); 4166 } 4167 libs.add(libEntry.info.getName()); 4168 break; 4169 } 4170 } 4171 } 4172 4173 if (libs != null) { 4174 String[] libsArray = new String[libs.size()]; 4175 libs.toArray(libsArray); 4176 return libsArray; 4177 } 4178 4179 return null; 4180 } 4181 } 4182 4183 @Override 4184 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4185 synchronized (mPackages) { 4186 return mServicesSystemSharedLibraryPackageName; 4187 } 4188 } 4189 4190 @Override 4191 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4192 synchronized (mPackages) { 4193 return mSharedSystemSharedLibraryPackageName; 4194 } 4195 } 4196 4197 @Override 4198 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4199 synchronized (mPackages) { 4200 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 4201 4202 final FeatureInfo fi = new FeatureInfo(); 4203 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4204 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4205 res.add(fi); 4206 4207 return new ParceledListSlice<>(res); 4208 } 4209 } 4210 4211 @Override 4212 public boolean hasSystemFeature(String name, int version) { 4213 synchronized (mPackages) { 4214 final FeatureInfo feat = mAvailableFeatures.get(name); 4215 if (feat == null) { 4216 return false; 4217 } else { 4218 return feat.version >= version; 4219 } 4220 } 4221 } 4222 4223 @Override 4224 public int checkPermission(String permName, String pkgName, int userId) { 4225 if (!sUserManager.exists(userId)) { 4226 return PackageManager.PERMISSION_DENIED; 4227 } 4228 4229 synchronized (mPackages) { 4230 final PackageParser.Package p = mPackages.get(pkgName); 4231 if (p != null && p.mExtras != null) { 4232 final PackageSetting ps = (PackageSetting) p.mExtras; 4233 final PermissionsState permissionsState = ps.getPermissionsState(); 4234 if (permissionsState.hasPermission(permName, userId)) { 4235 return PackageManager.PERMISSION_GRANTED; 4236 } 4237 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4238 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4239 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4240 return PackageManager.PERMISSION_GRANTED; 4241 } 4242 } 4243 } 4244 4245 return PackageManager.PERMISSION_DENIED; 4246 } 4247 4248 @Override 4249 public int checkUidPermission(String permName, int uid) { 4250 final int userId = UserHandle.getUserId(uid); 4251 4252 if (!sUserManager.exists(userId)) { 4253 return PackageManager.PERMISSION_DENIED; 4254 } 4255 4256 synchronized (mPackages) { 4257 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4258 if (obj != null) { 4259 final SettingBase ps = (SettingBase) obj; 4260 final PermissionsState permissionsState = ps.getPermissionsState(); 4261 if (permissionsState.hasPermission(permName, userId)) { 4262 return PackageManager.PERMISSION_GRANTED; 4263 } 4264 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4265 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4266 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4267 return PackageManager.PERMISSION_GRANTED; 4268 } 4269 } else { 4270 ArraySet<String> perms = mSystemPermissions.get(uid); 4271 if (perms != null) { 4272 if (perms.contains(permName)) { 4273 return PackageManager.PERMISSION_GRANTED; 4274 } 4275 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4276 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4277 return PackageManager.PERMISSION_GRANTED; 4278 } 4279 } 4280 } 4281 } 4282 4283 return PackageManager.PERMISSION_DENIED; 4284 } 4285 4286 @Override 4287 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4288 if (UserHandle.getCallingUserId() != userId) { 4289 mContext.enforceCallingPermission( 4290 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4291 "isPermissionRevokedByPolicy for user " + userId); 4292 } 4293 4294 if (checkPermission(permission, packageName, userId) 4295 == PackageManager.PERMISSION_GRANTED) { 4296 return false; 4297 } 4298 4299 final long identity = Binder.clearCallingIdentity(); 4300 try { 4301 final int flags = getPermissionFlags(permission, packageName, userId); 4302 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4303 } finally { 4304 Binder.restoreCallingIdentity(identity); 4305 } 4306 } 4307 4308 @Override 4309 public String getPermissionControllerPackageName() { 4310 synchronized (mPackages) { 4311 return mRequiredInstallerPackage; 4312 } 4313 } 4314 4315 /** 4316 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4317 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4318 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4319 * @param message the message to log on security exception 4320 */ 4321 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4322 boolean checkShell, String message) { 4323 if (userId < 0) { 4324 throw new IllegalArgumentException("Invalid userId " + userId); 4325 } 4326 if (checkShell) { 4327 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4328 } 4329 if (userId == UserHandle.getUserId(callingUid)) return; 4330 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4331 if (requireFullPermission) { 4332 mContext.enforceCallingOrSelfPermission( 4333 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4334 } else { 4335 try { 4336 mContext.enforceCallingOrSelfPermission( 4337 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4338 } catch (SecurityException se) { 4339 mContext.enforceCallingOrSelfPermission( 4340 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4341 } 4342 } 4343 } 4344 } 4345 4346 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4347 if (callingUid == Process.SHELL_UID) { 4348 if (userHandle >= 0 4349 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4350 throw new SecurityException("Shell does not have permission to access user " 4351 + userHandle); 4352 } else if (userHandle < 0) { 4353 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4354 + Debug.getCallers(3)); 4355 } 4356 } 4357 } 4358 4359 private BasePermission findPermissionTreeLP(String permName) { 4360 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4361 if (permName.startsWith(bp.name) && 4362 permName.length() > bp.name.length() && 4363 permName.charAt(bp.name.length()) == '.') { 4364 return bp; 4365 } 4366 } 4367 return null; 4368 } 4369 4370 private BasePermission checkPermissionTreeLP(String permName) { 4371 if (permName != null) { 4372 BasePermission bp = findPermissionTreeLP(permName); 4373 if (bp != null) { 4374 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4375 return bp; 4376 } 4377 throw new SecurityException("Calling uid " 4378 + Binder.getCallingUid() 4379 + " is not allowed to add to permission tree " 4380 + bp.name + " owned by uid " + bp.uid); 4381 } 4382 } 4383 throw new SecurityException("No permission tree found for " + permName); 4384 } 4385 4386 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4387 if (s1 == null) { 4388 return s2 == null; 4389 } 4390 if (s2 == null) { 4391 return false; 4392 } 4393 if (s1.getClass() != s2.getClass()) { 4394 return false; 4395 } 4396 return s1.equals(s2); 4397 } 4398 4399 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4400 if (pi1.icon != pi2.icon) return false; 4401 if (pi1.logo != pi2.logo) return false; 4402 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4403 if (!compareStrings(pi1.name, pi2.name)) return false; 4404 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4405 // We'll take care of setting this one. 4406 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4407 // These are not currently stored in settings. 4408 //if (!compareStrings(pi1.group, pi2.group)) return false; 4409 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4410 //if (pi1.labelRes != pi2.labelRes) return false; 4411 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4412 return true; 4413 } 4414 4415 int permissionInfoFootprint(PermissionInfo info) { 4416 int size = info.name.length(); 4417 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4418 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4419 return size; 4420 } 4421 4422 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4423 int size = 0; 4424 for (BasePermission perm : mSettings.mPermissions.values()) { 4425 if (perm.uid == tree.uid) { 4426 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4427 } 4428 } 4429 return size; 4430 } 4431 4432 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4433 // We calculate the max size of permissions defined by this uid and throw 4434 // if that plus the size of 'info' would exceed our stated maximum. 4435 if (tree.uid != Process.SYSTEM_UID) { 4436 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4437 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4438 throw new SecurityException("Permission tree size cap exceeded"); 4439 } 4440 } 4441 } 4442 4443 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4444 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4445 throw new SecurityException("Label must be specified in permission"); 4446 } 4447 BasePermission tree = checkPermissionTreeLP(info.name); 4448 BasePermission bp = mSettings.mPermissions.get(info.name); 4449 boolean added = bp == null; 4450 boolean changed = true; 4451 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4452 if (added) { 4453 enforcePermissionCapLocked(info, tree); 4454 bp = new BasePermission(info.name, tree.sourcePackage, 4455 BasePermission.TYPE_DYNAMIC); 4456 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4457 throw new SecurityException( 4458 "Not allowed to modify non-dynamic permission " 4459 + info.name); 4460 } else { 4461 if (bp.protectionLevel == fixedLevel 4462 && bp.perm.owner.equals(tree.perm.owner) 4463 && bp.uid == tree.uid 4464 && comparePermissionInfos(bp.perm.info, info)) { 4465 changed = false; 4466 } 4467 } 4468 bp.protectionLevel = fixedLevel; 4469 info = new PermissionInfo(info); 4470 info.protectionLevel = fixedLevel; 4471 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4472 bp.perm.info.packageName = tree.perm.info.packageName; 4473 bp.uid = tree.uid; 4474 if (added) { 4475 mSettings.mPermissions.put(info.name, bp); 4476 } 4477 if (changed) { 4478 if (!async) { 4479 mSettings.writeLPr(); 4480 } else { 4481 scheduleWriteSettingsLocked(); 4482 } 4483 } 4484 return added; 4485 } 4486 4487 @Override 4488 public boolean addPermission(PermissionInfo info) { 4489 synchronized (mPackages) { 4490 return addPermissionLocked(info, false); 4491 } 4492 } 4493 4494 @Override 4495 public boolean addPermissionAsync(PermissionInfo info) { 4496 synchronized (mPackages) { 4497 return addPermissionLocked(info, true); 4498 } 4499 } 4500 4501 @Override 4502 public void removePermission(String name) { 4503 synchronized (mPackages) { 4504 checkPermissionTreeLP(name); 4505 BasePermission bp = mSettings.mPermissions.get(name); 4506 if (bp != null) { 4507 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4508 throw new SecurityException( 4509 "Not allowed to modify non-dynamic permission " 4510 + name); 4511 } 4512 mSettings.mPermissions.remove(name); 4513 mSettings.writeLPr(); 4514 } 4515 } 4516 } 4517 4518 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4519 BasePermission bp) { 4520 int index = pkg.requestedPermissions.indexOf(bp.name); 4521 if (index == -1) { 4522 throw new SecurityException("Package " + pkg.packageName 4523 + " has not requested permission " + bp.name); 4524 } 4525 if (!bp.isRuntime() && !bp.isDevelopment()) { 4526 throw new SecurityException("Permission " + bp.name 4527 + " is not a changeable permission type"); 4528 } 4529 } 4530 4531 @Override 4532 public void grantRuntimePermission(String packageName, String name, final int userId) { 4533 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4534 } 4535 4536 private void grantRuntimePermission(String packageName, String name, final int userId, 4537 boolean overridePolicy) { 4538 if (!sUserManager.exists(userId)) { 4539 Log.e(TAG, "No such user:" + userId); 4540 return; 4541 } 4542 4543 mContext.enforceCallingOrSelfPermission( 4544 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4545 "grantRuntimePermission"); 4546 4547 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4548 true /* requireFullPermission */, true /* checkShell */, 4549 "grantRuntimePermission"); 4550 4551 final int uid; 4552 final SettingBase sb; 4553 4554 synchronized (mPackages) { 4555 final PackageParser.Package pkg = mPackages.get(packageName); 4556 if (pkg == null) { 4557 throw new IllegalArgumentException("Unknown package: " + packageName); 4558 } 4559 4560 final BasePermission bp = mSettings.mPermissions.get(name); 4561 if (bp == null) { 4562 throw new IllegalArgumentException("Unknown permission: " + name); 4563 } 4564 4565 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4566 4567 // If a permission review is required for legacy apps we represent 4568 // their permissions as always granted runtime ones since we need 4569 // to keep the review required permission flag per user while an 4570 // install permission's state is shared across all users. 4571 if (mPermissionReviewRequired 4572 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4573 && bp.isRuntime()) { 4574 return; 4575 } 4576 4577 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4578 sb = (SettingBase) pkg.mExtras; 4579 if (sb == null) { 4580 throw new IllegalArgumentException("Unknown package: " + packageName); 4581 } 4582 4583 final PermissionsState permissionsState = sb.getPermissionsState(); 4584 4585 final int flags = permissionsState.getPermissionFlags(name, userId); 4586 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4587 throw new SecurityException("Cannot grant system fixed permission " 4588 + name + " for package " + packageName); 4589 } 4590 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4591 throw new SecurityException("Cannot grant policy fixed permission " 4592 + name + " for package " + packageName); 4593 } 4594 4595 if (bp.isDevelopment()) { 4596 // Development permissions must be handled specially, since they are not 4597 // normal runtime permissions. For now they apply to all users. 4598 if (permissionsState.grantInstallPermission(bp) != 4599 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4600 scheduleWriteSettingsLocked(); 4601 } 4602 return; 4603 } 4604 4605 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4606 throw new SecurityException("Cannot grant non-ephemeral permission" 4607 + name + " for package " + packageName); 4608 } 4609 4610 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4611 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4612 return; 4613 } 4614 4615 final int result = permissionsState.grantRuntimePermission(bp, userId); 4616 switch (result) { 4617 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4618 return; 4619 } 4620 4621 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4622 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4623 mHandler.post(new Runnable() { 4624 @Override 4625 public void run() { 4626 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4627 } 4628 }); 4629 } 4630 break; 4631 } 4632 4633 if (bp.isRuntime()) { 4634 logPermissionGranted(mContext, name, packageName); 4635 } 4636 4637 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4638 4639 // Not critical if that is lost - app has to request again. 4640 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4641 } 4642 4643 // Only need to do this if user is initialized. Otherwise it's a new user 4644 // and there are no processes running as the user yet and there's no need 4645 // to make an expensive call to remount processes for the changed permissions. 4646 if (READ_EXTERNAL_STORAGE.equals(name) 4647 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4648 final long token = Binder.clearCallingIdentity(); 4649 try { 4650 if (sUserManager.isInitialized(userId)) { 4651 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4652 StorageManagerInternal.class); 4653 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4654 } 4655 } finally { 4656 Binder.restoreCallingIdentity(token); 4657 } 4658 } 4659 } 4660 4661 @Override 4662 public void revokeRuntimePermission(String packageName, String name, int userId) { 4663 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4664 } 4665 4666 private void revokeRuntimePermission(String packageName, String name, int userId, 4667 boolean overridePolicy) { 4668 if (!sUserManager.exists(userId)) { 4669 Log.e(TAG, "No such user:" + userId); 4670 return; 4671 } 4672 4673 mContext.enforceCallingOrSelfPermission( 4674 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4675 "revokeRuntimePermission"); 4676 4677 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4678 true /* requireFullPermission */, true /* checkShell */, 4679 "revokeRuntimePermission"); 4680 4681 final int appId; 4682 4683 synchronized (mPackages) { 4684 final PackageParser.Package pkg = mPackages.get(packageName); 4685 if (pkg == null) { 4686 throw new IllegalArgumentException("Unknown package: " + packageName); 4687 } 4688 4689 final BasePermission bp = mSettings.mPermissions.get(name); 4690 if (bp == null) { 4691 throw new IllegalArgumentException("Unknown permission: " + name); 4692 } 4693 4694 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4695 4696 // If a permission review is required for legacy apps we represent 4697 // their permissions as always granted runtime ones since we need 4698 // to keep the review required permission flag per user while an 4699 // install permission's state is shared across all users. 4700 if (mPermissionReviewRequired 4701 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4702 && bp.isRuntime()) { 4703 return; 4704 } 4705 4706 SettingBase sb = (SettingBase) pkg.mExtras; 4707 if (sb == null) { 4708 throw new IllegalArgumentException("Unknown package: " + packageName); 4709 } 4710 4711 final PermissionsState permissionsState = sb.getPermissionsState(); 4712 4713 final int flags = permissionsState.getPermissionFlags(name, userId); 4714 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4715 throw new SecurityException("Cannot revoke system fixed permission " 4716 + name + " for package " + packageName); 4717 } 4718 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4719 throw new SecurityException("Cannot revoke policy fixed permission " 4720 + name + " for package " + packageName); 4721 } 4722 4723 if (bp.isDevelopment()) { 4724 // Development permissions must be handled specially, since they are not 4725 // normal runtime permissions. For now they apply to all users. 4726 if (permissionsState.revokeInstallPermission(bp) != 4727 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4728 scheduleWriteSettingsLocked(); 4729 } 4730 return; 4731 } 4732 4733 if (permissionsState.revokeRuntimePermission(bp, userId) == 4734 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4735 return; 4736 } 4737 4738 if (bp.isRuntime()) { 4739 logPermissionRevoked(mContext, name, packageName); 4740 } 4741 4742 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4743 4744 // Critical, after this call app should never have the permission. 4745 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4746 4747 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4748 } 4749 4750 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4751 } 4752 4753 /** 4754 * Get the first event id for the permission. 4755 * 4756 * <p>There are four events for each permission: <ul> 4757 * <li>Request permission: first id + 0</li> 4758 * <li>Grant permission: first id + 1</li> 4759 * <li>Request for permission denied: first id + 2</li> 4760 * <li>Revoke permission: first id + 3</li> 4761 * </ul></p> 4762 * 4763 * @param name name of the permission 4764 * 4765 * @return The first event id for the permission 4766 */ 4767 private static int getBaseEventId(@NonNull String name) { 4768 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4769 4770 if (eventIdIndex == -1) { 4771 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4772 || "user".equals(Build.TYPE)) { 4773 Log.i(TAG, "Unknown permission " + name); 4774 4775 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4776 } else { 4777 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4778 // 4779 // Also update 4780 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4781 // - metrics_constants.proto 4782 throw new IllegalStateException("Unknown permission " + name); 4783 } 4784 } 4785 4786 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4787 } 4788 4789 /** 4790 * Log that a permission was revoked. 4791 * 4792 * @param context Context of the caller 4793 * @param name name of the permission 4794 * @param packageName package permission if for 4795 */ 4796 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4797 @NonNull String packageName) { 4798 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4799 } 4800 4801 /** 4802 * Log that a permission request was granted. 4803 * 4804 * @param context Context of the caller 4805 * @param name name of the permission 4806 * @param packageName package permission if for 4807 */ 4808 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4809 @NonNull String packageName) { 4810 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4811 } 4812 4813 @Override 4814 public void resetRuntimePermissions() { 4815 mContext.enforceCallingOrSelfPermission( 4816 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4817 "revokeRuntimePermission"); 4818 4819 int callingUid = Binder.getCallingUid(); 4820 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4821 mContext.enforceCallingOrSelfPermission( 4822 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4823 "resetRuntimePermissions"); 4824 } 4825 4826 synchronized (mPackages) { 4827 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4828 for (int userId : UserManagerService.getInstance().getUserIds()) { 4829 final int packageCount = mPackages.size(); 4830 for (int i = 0; i < packageCount; i++) { 4831 PackageParser.Package pkg = mPackages.valueAt(i); 4832 if (!(pkg.mExtras instanceof PackageSetting)) { 4833 continue; 4834 } 4835 PackageSetting ps = (PackageSetting) pkg.mExtras; 4836 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4837 } 4838 } 4839 } 4840 } 4841 4842 @Override 4843 public int getPermissionFlags(String name, String packageName, int userId) { 4844 if (!sUserManager.exists(userId)) { 4845 return 0; 4846 } 4847 4848 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4849 4850 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4851 true /* requireFullPermission */, false /* checkShell */, 4852 "getPermissionFlags"); 4853 4854 synchronized (mPackages) { 4855 final PackageParser.Package pkg = mPackages.get(packageName); 4856 if (pkg == null) { 4857 return 0; 4858 } 4859 4860 final BasePermission bp = mSettings.mPermissions.get(name); 4861 if (bp == null) { 4862 return 0; 4863 } 4864 4865 SettingBase sb = (SettingBase) pkg.mExtras; 4866 if (sb == null) { 4867 return 0; 4868 } 4869 4870 PermissionsState permissionsState = sb.getPermissionsState(); 4871 return permissionsState.getPermissionFlags(name, userId); 4872 } 4873 } 4874 4875 @Override 4876 public void updatePermissionFlags(String name, String packageName, int flagMask, 4877 int flagValues, int userId) { 4878 if (!sUserManager.exists(userId)) { 4879 return; 4880 } 4881 4882 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4883 4884 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4885 true /* requireFullPermission */, true /* checkShell */, 4886 "updatePermissionFlags"); 4887 4888 // Only the system can change these flags and nothing else. 4889 if (getCallingUid() != Process.SYSTEM_UID) { 4890 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4891 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4892 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4893 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4894 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4895 } 4896 4897 synchronized (mPackages) { 4898 final PackageParser.Package pkg = mPackages.get(packageName); 4899 if (pkg == null) { 4900 throw new IllegalArgumentException("Unknown package: " + packageName); 4901 } 4902 4903 final BasePermission bp = mSettings.mPermissions.get(name); 4904 if (bp == null) { 4905 throw new IllegalArgumentException("Unknown permission: " + name); 4906 } 4907 4908 SettingBase sb = (SettingBase) pkg.mExtras; 4909 if (sb == null) { 4910 throw new IllegalArgumentException("Unknown package: " + packageName); 4911 } 4912 4913 PermissionsState permissionsState = sb.getPermissionsState(); 4914 4915 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4916 4917 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4918 // Install and runtime permissions are stored in different places, 4919 // so figure out what permission changed and persist the change. 4920 if (permissionsState.getInstallPermissionState(name) != null) { 4921 scheduleWriteSettingsLocked(); 4922 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4923 || hadState) { 4924 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4925 } 4926 } 4927 } 4928 } 4929 4930 /** 4931 * Update the permission flags for all packages and runtime permissions of a user in order 4932 * to allow device or profile owner to remove POLICY_FIXED. 4933 */ 4934 @Override 4935 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4936 if (!sUserManager.exists(userId)) { 4937 return; 4938 } 4939 4940 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4941 4942 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4943 true /* requireFullPermission */, true /* checkShell */, 4944 "updatePermissionFlagsForAllApps"); 4945 4946 // Only the system can change system fixed flags. 4947 if (getCallingUid() != Process.SYSTEM_UID) { 4948 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4949 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4950 } 4951 4952 synchronized (mPackages) { 4953 boolean changed = false; 4954 final int packageCount = mPackages.size(); 4955 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4956 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4957 SettingBase sb = (SettingBase) pkg.mExtras; 4958 if (sb == null) { 4959 continue; 4960 } 4961 PermissionsState permissionsState = sb.getPermissionsState(); 4962 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4963 userId, flagMask, flagValues); 4964 } 4965 if (changed) { 4966 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4967 } 4968 } 4969 } 4970 4971 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4972 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4973 != PackageManager.PERMISSION_GRANTED 4974 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4975 != PackageManager.PERMISSION_GRANTED) { 4976 throw new SecurityException(message + " requires " 4977 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4978 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4979 } 4980 } 4981 4982 @Override 4983 public boolean shouldShowRequestPermissionRationale(String permissionName, 4984 String packageName, int userId) { 4985 if (UserHandle.getCallingUserId() != userId) { 4986 mContext.enforceCallingPermission( 4987 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4988 "canShowRequestPermissionRationale for user " + userId); 4989 } 4990 4991 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4992 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4993 return false; 4994 } 4995 4996 if (checkPermission(permissionName, packageName, userId) 4997 == PackageManager.PERMISSION_GRANTED) { 4998 return false; 4999 } 5000 5001 final int flags; 5002 5003 final long identity = Binder.clearCallingIdentity(); 5004 try { 5005 flags = getPermissionFlags(permissionName, 5006 packageName, userId); 5007 } finally { 5008 Binder.restoreCallingIdentity(identity); 5009 } 5010 5011 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5012 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5013 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5014 5015 if ((flags & fixedFlags) != 0) { 5016 return false; 5017 } 5018 5019 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5020 } 5021 5022 @Override 5023 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5024 mContext.enforceCallingOrSelfPermission( 5025 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5026 "addOnPermissionsChangeListener"); 5027 5028 synchronized (mPackages) { 5029 mOnPermissionChangeListeners.addListenerLocked(listener); 5030 } 5031 } 5032 5033 @Override 5034 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5035 synchronized (mPackages) { 5036 mOnPermissionChangeListeners.removeListenerLocked(listener); 5037 } 5038 } 5039 5040 @Override 5041 public boolean isProtectedBroadcast(String actionName) { 5042 synchronized (mPackages) { 5043 if (mProtectedBroadcasts.contains(actionName)) { 5044 return true; 5045 } else if (actionName != null) { 5046 // TODO: remove these terrible hacks 5047 if (actionName.startsWith("android.net.netmon.lingerExpired") 5048 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5049 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5050 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5051 return true; 5052 } 5053 } 5054 } 5055 return false; 5056 } 5057 5058 @Override 5059 public int checkSignatures(String pkg1, String pkg2) { 5060 synchronized (mPackages) { 5061 final PackageParser.Package p1 = mPackages.get(pkg1); 5062 final PackageParser.Package p2 = mPackages.get(pkg2); 5063 if (p1 == null || p1.mExtras == null 5064 || p2 == null || p2.mExtras == null) { 5065 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5066 } 5067 return compareSignatures(p1.mSignatures, p2.mSignatures); 5068 } 5069 } 5070 5071 @Override 5072 public int checkUidSignatures(int uid1, int uid2) { 5073 // Map to base uids. 5074 uid1 = UserHandle.getAppId(uid1); 5075 uid2 = UserHandle.getAppId(uid2); 5076 // reader 5077 synchronized (mPackages) { 5078 Signature[] s1; 5079 Signature[] s2; 5080 Object obj = mSettings.getUserIdLPr(uid1); 5081 if (obj != null) { 5082 if (obj instanceof SharedUserSetting) { 5083 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5084 } else if (obj instanceof PackageSetting) { 5085 s1 = ((PackageSetting)obj).signatures.mSignatures; 5086 } else { 5087 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5088 } 5089 } else { 5090 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5091 } 5092 obj = mSettings.getUserIdLPr(uid2); 5093 if (obj != null) { 5094 if (obj instanceof SharedUserSetting) { 5095 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5096 } else if (obj instanceof PackageSetting) { 5097 s2 = ((PackageSetting)obj).signatures.mSignatures; 5098 } else { 5099 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5100 } 5101 } else { 5102 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5103 } 5104 return compareSignatures(s1, s2); 5105 } 5106 } 5107 5108 /** 5109 * This method should typically only be used when granting or revoking 5110 * permissions, since the app may immediately restart after this call. 5111 * <p> 5112 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5113 * guard your work against the app being relaunched. 5114 */ 5115 private void killUid(int appId, int userId, String reason) { 5116 final long identity = Binder.clearCallingIdentity(); 5117 try { 5118 IActivityManager am = ActivityManager.getService(); 5119 if (am != null) { 5120 try { 5121 am.killUid(appId, userId, reason); 5122 } catch (RemoteException e) { 5123 /* ignore - same process */ 5124 } 5125 } 5126 } finally { 5127 Binder.restoreCallingIdentity(identity); 5128 } 5129 } 5130 5131 /** 5132 * Compares two sets of signatures. Returns: 5133 * <br /> 5134 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5135 * <br /> 5136 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5137 * <br /> 5138 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5139 * <br /> 5140 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5141 * <br /> 5142 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5143 */ 5144 static int compareSignatures(Signature[] s1, Signature[] s2) { 5145 if (s1 == null) { 5146 return s2 == null 5147 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5148 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5149 } 5150 5151 if (s2 == null) { 5152 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5153 } 5154 5155 if (s1.length != s2.length) { 5156 return PackageManager.SIGNATURE_NO_MATCH; 5157 } 5158 5159 // Since both signature sets are of size 1, we can compare without HashSets. 5160 if (s1.length == 1) { 5161 return s1[0].equals(s2[0]) ? 5162 PackageManager.SIGNATURE_MATCH : 5163 PackageManager.SIGNATURE_NO_MATCH; 5164 } 5165 5166 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5167 for (Signature sig : s1) { 5168 set1.add(sig); 5169 } 5170 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5171 for (Signature sig : s2) { 5172 set2.add(sig); 5173 } 5174 // Make sure s2 contains all signatures in s1. 5175 if (set1.equals(set2)) { 5176 return PackageManager.SIGNATURE_MATCH; 5177 } 5178 return PackageManager.SIGNATURE_NO_MATCH; 5179 } 5180 5181 /** 5182 * If the database version for this type of package (internal storage or 5183 * external storage) is less than the version where package signatures 5184 * were updated, return true. 5185 */ 5186 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5187 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5188 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5189 } 5190 5191 /** 5192 * Used for backward compatibility to make sure any packages with 5193 * certificate chains get upgraded to the new style. {@code existingSigs} 5194 * will be in the old format (since they were stored on disk from before the 5195 * system upgrade) and {@code scannedSigs} will be in the newer format. 5196 */ 5197 private int compareSignaturesCompat(PackageSignatures existingSigs, 5198 PackageParser.Package scannedPkg) { 5199 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5200 return PackageManager.SIGNATURE_NO_MATCH; 5201 } 5202 5203 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5204 for (Signature sig : existingSigs.mSignatures) { 5205 existingSet.add(sig); 5206 } 5207 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5208 for (Signature sig : scannedPkg.mSignatures) { 5209 try { 5210 Signature[] chainSignatures = sig.getChainSignatures(); 5211 for (Signature chainSig : chainSignatures) { 5212 scannedCompatSet.add(chainSig); 5213 } 5214 } catch (CertificateEncodingException e) { 5215 scannedCompatSet.add(sig); 5216 } 5217 } 5218 /* 5219 * Make sure the expanded scanned set contains all signatures in the 5220 * existing one. 5221 */ 5222 if (scannedCompatSet.equals(existingSet)) { 5223 // Migrate the old signatures to the new scheme. 5224 existingSigs.assignSignatures(scannedPkg.mSignatures); 5225 // The new KeySets will be re-added later in the scanning process. 5226 synchronized (mPackages) { 5227 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5228 } 5229 return PackageManager.SIGNATURE_MATCH; 5230 } 5231 return PackageManager.SIGNATURE_NO_MATCH; 5232 } 5233 5234 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5235 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5236 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5237 } 5238 5239 private int compareSignaturesRecover(PackageSignatures existingSigs, 5240 PackageParser.Package scannedPkg) { 5241 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5242 return PackageManager.SIGNATURE_NO_MATCH; 5243 } 5244 5245 String msg = null; 5246 try { 5247 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5248 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5249 + scannedPkg.packageName); 5250 return PackageManager.SIGNATURE_MATCH; 5251 } 5252 } catch (CertificateException e) { 5253 msg = e.getMessage(); 5254 } 5255 5256 logCriticalInfo(Log.INFO, 5257 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5258 return PackageManager.SIGNATURE_NO_MATCH; 5259 } 5260 5261 @Override 5262 public List<String> getAllPackages() { 5263 synchronized (mPackages) { 5264 return new ArrayList<String>(mPackages.keySet()); 5265 } 5266 } 5267 5268 @Override 5269 public String[] getPackagesForUid(int uid) { 5270 final int userId = UserHandle.getUserId(uid); 5271 uid = UserHandle.getAppId(uid); 5272 // reader 5273 synchronized (mPackages) { 5274 Object obj = mSettings.getUserIdLPr(uid); 5275 if (obj instanceof SharedUserSetting) { 5276 final SharedUserSetting sus = (SharedUserSetting) obj; 5277 final int N = sus.packages.size(); 5278 String[] res = new String[N]; 5279 final Iterator<PackageSetting> it = sus.packages.iterator(); 5280 int i = 0; 5281 while (it.hasNext()) { 5282 PackageSetting ps = it.next(); 5283 if (ps.getInstalled(userId)) { 5284 res[i++] = ps.name; 5285 } else { 5286 res = ArrayUtils.removeElement(String.class, res, res[i]); 5287 } 5288 } 5289 return res; 5290 } else if (obj instanceof PackageSetting) { 5291 final PackageSetting ps = (PackageSetting) obj; 5292 if (ps.getInstalled(userId)) { 5293 return new String[]{ps.name}; 5294 } 5295 } 5296 } 5297 return null; 5298 } 5299 5300 @Override 5301 public String getNameForUid(int uid) { 5302 // reader 5303 synchronized (mPackages) { 5304 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5305 if (obj instanceof SharedUserSetting) { 5306 final SharedUserSetting sus = (SharedUserSetting) obj; 5307 return sus.name + ":" + sus.userId; 5308 } else if (obj instanceof PackageSetting) { 5309 final PackageSetting ps = (PackageSetting) obj; 5310 return ps.name; 5311 } 5312 } 5313 return null; 5314 } 5315 5316 @Override 5317 public int getUidForSharedUser(String sharedUserName) { 5318 if(sharedUserName == null) { 5319 return -1; 5320 } 5321 // reader 5322 synchronized (mPackages) { 5323 SharedUserSetting suid; 5324 try { 5325 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5326 if (suid != null) { 5327 return suid.userId; 5328 } 5329 } catch (PackageManagerException ignore) { 5330 // can't happen, but, still need to catch it 5331 } 5332 return -1; 5333 } 5334 } 5335 5336 @Override 5337 public int getFlagsForUid(int uid) { 5338 synchronized (mPackages) { 5339 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5340 if (obj instanceof SharedUserSetting) { 5341 final SharedUserSetting sus = (SharedUserSetting) obj; 5342 return sus.pkgFlags; 5343 } else if (obj instanceof PackageSetting) { 5344 final PackageSetting ps = (PackageSetting) obj; 5345 return ps.pkgFlags; 5346 } 5347 } 5348 return 0; 5349 } 5350 5351 @Override 5352 public int getPrivateFlagsForUid(int uid) { 5353 synchronized (mPackages) { 5354 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5355 if (obj instanceof SharedUserSetting) { 5356 final SharedUserSetting sus = (SharedUserSetting) obj; 5357 return sus.pkgPrivateFlags; 5358 } else if (obj instanceof PackageSetting) { 5359 final PackageSetting ps = (PackageSetting) obj; 5360 return ps.pkgPrivateFlags; 5361 } 5362 } 5363 return 0; 5364 } 5365 5366 @Override 5367 public boolean isUidPrivileged(int uid) { 5368 uid = UserHandle.getAppId(uid); 5369 // reader 5370 synchronized (mPackages) { 5371 Object obj = mSettings.getUserIdLPr(uid); 5372 if (obj instanceof SharedUserSetting) { 5373 final SharedUserSetting sus = (SharedUserSetting) obj; 5374 final Iterator<PackageSetting> it = sus.packages.iterator(); 5375 while (it.hasNext()) { 5376 if (it.next().isPrivileged()) { 5377 return true; 5378 } 5379 } 5380 } else if (obj instanceof PackageSetting) { 5381 final PackageSetting ps = (PackageSetting) obj; 5382 return ps.isPrivileged(); 5383 } 5384 } 5385 return false; 5386 } 5387 5388 @Override 5389 public String[] getAppOpPermissionPackages(String permissionName) { 5390 synchronized (mPackages) { 5391 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5392 if (pkgs == null) { 5393 return null; 5394 } 5395 return pkgs.toArray(new String[pkgs.size()]); 5396 } 5397 } 5398 5399 @Override 5400 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5401 int flags, int userId) { 5402 try { 5403 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5404 5405 if (!sUserManager.exists(userId)) return null; 5406 flags = updateFlagsForResolve(flags, userId, intent); 5407 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5408 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5409 5410 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5411 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5412 flags, userId); 5413 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5414 5415 final ResolveInfo bestChoice = 5416 chooseBestActivity(intent, resolvedType, flags, query, userId); 5417 return bestChoice; 5418 } finally { 5419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5420 } 5421 } 5422 5423 @Override 5424 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5425 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5426 throw new SecurityException( 5427 "findPersistentPreferredActivity can only be run by the system"); 5428 } 5429 if (!sUserManager.exists(userId)) { 5430 return null; 5431 } 5432 intent = updateIntentForResolve(intent); 5433 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5434 final int flags = updateFlagsForResolve(0, userId, intent); 5435 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5436 userId); 5437 synchronized (mPackages) { 5438 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5439 userId); 5440 } 5441 } 5442 5443 @Override 5444 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5445 IntentFilter filter, int match, ComponentName activity) { 5446 final int userId = UserHandle.getCallingUserId(); 5447 if (DEBUG_PREFERRED) { 5448 Log.v(TAG, "setLastChosenActivity intent=" + intent 5449 + " resolvedType=" + resolvedType 5450 + " flags=" + flags 5451 + " filter=" + filter 5452 + " match=" + match 5453 + " activity=" + activity); 5454 filter.dump(new PrintStreamPrinter(System.out), " "); 5455 } 5456 intent.setComponent(null); 5457 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5458 userId); 5459 // Find any earlier preferred or last chosen entries and nuke them 5460 findPreferredActivity(intent, resolvedType, 5461 flags, query, 0, false, true, false, userId); 5462 // Add the new activity as the last chosen for this filter 5463 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5464 "Setting last chosen"); 5465 } 5466 5467 @Override 5468 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5469 final int userId = UserHandle.getCallingUserId(); 5470 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5471 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5472 userId); 5473 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5474 false, false, false, userId); 5475 } 5476 5477 private boolean isEphemeralDisabled() { 5478 // ephemeral apps have been disabled across the board 5479 if (DISABLE_EPHEMERAL_APPS) { 5480 return true; 5481 } 5482 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5483 if (!mSystemReady) { 5484 return true; 5485 } 5486 // we can't get a content resolver until the system is ready; these checks must happen last 5487 final ContentResolver resolver = mContext.getContentResolver(); 5488 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5489 return true; 5490 } 5491 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5492 } 5493 5494 private boolean isEphemeralAllowed( 5495 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5496 boolean skipPackageCheck) { 5497 // Short circuit and return early if possible. 5498 if (isEphemeralDisabled()) { 5499 return false; 5500 } 5501 final int callingUser = UserHandle.getCallingUserId(); 5502 if (callingUser != UserHandle.USER_SYSTEM) { 5503 return false; 5504 } 5505 if (mEphemeralResolverConnection == null) { 5506 return false; 5507 } 5508 if (mEphemeralInstallerComponent == null) { 5509 return false; 5510 } 5511 if (intent.getComponent() != null) { 5512 return false; 5513 } 5514 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5515 return false; 5516 } 5517 if (!skipPackageCheck && intent.getPackage() != null) { 5518 return false; 5519 } 5520 final boolean isWebUri = hasWebURI(intent); 5521 if (!isWebUri || intent.getData().getHost() == null) { 5522 return false; 5523 } 5524 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5525 synchronized (mPackages) { 5526 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5527 for (int n = 0; n < count; n++) { 5528 ResolveInfo info = resolvedActivities.get(n); 5529 String packageName = info.activityInfo.packageName; 5530 PackageSetting ps = mSettings.mPackages.get(packageName); 5531 if (ps != null) { 5532 // Try to get the status from User settings first 5533 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5534 int status = (int) (packedStatus >> 32); 5535 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5536 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5537 if (DEBUG_EPHEMERAL) { 5538 Slog.v(TAG, "DENY ephemeral apps;" 5539 + " pkg: " + packageName + ", status: " + status); 5540 } 5541 return false; 5542 } 5543 } 5544 } 5545 } 5546 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5547 return true; 5548 } 5549 5550 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5551 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5552 int userId) { 5553 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5554 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5555 callingPackage, userId)); 5556 mHandler.sendMessage(msg); 5557 } 5558 5559 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5560 int flags, List<ResolveInfo> query, int userId) { 5561 if (query != null) { 5562 final int N = query.size(); 5563 if (N == 1) { 5564 return query.get(0); 5565 } else if (N > 1) { 5566 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5567 // If there is more than one activity with the same priority, 5568 // then let the user decide between them. 5569 ResolveInfo r0 = query.get(0); 5570 ResolveInfo r1 = query.get(1); 5571 if (DEBUG_INTENT_MATCHING || debug) { 5572 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5573 + r1.activityInfo.name + "=" + r1.priority); 5574 } 5575 // If the first activity has a higher priority, or a different 5576 // default, then it is always desirable to pick it. 5577 if (r0.priority != r1.priority 5578 || r0.preferredOrder != r1.preferredOrder 5579 || r0.isDefault != r1.isDefault) { 5580 return query.get(0); 5581 } 5582 // If we have saved a preference for a preferred activity for 5583 // this Intent, use that. 5584 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5585 flags, query, r0.priority, true, false, debug, userId); 5586 if (ri != null) { 5587 return ri; 5588 } 5589 ri = new ResolveInfo(mResolveInfo); 5590 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5591 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5592 // If all of the options come from the same package, show the application's 5593 // label and icon instead of the generic resolver's. 5594 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5595 // and then throw away the ResolveInfo itself, meaning that the caller loses 5596 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5597 // a fallback for this case; we only set the target package's resources on 5598 // the ResolveInfo, not the ActivityInfo. 5599 final String intentPackage = intent.getPackage(); 5600 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5601 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5602 ri.resolvePackageName = intentPackage; 5603 if (userNeedsBadging(userId)) { 5604 ri.noResourceId = true; 5605 } else { 5606 ri.icon = appi.icon; 5607 } 5608 ri.iconResourceId = appi.icon; 5609 ri.labelRes = appi.labelRes; 5610 } 5611 ri.activityInfo.applicationInfo = new ApplicationInfo( 5612 ri.activityInfo.applicationInfo); 5613 if (userId != 0) { 5614 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5615 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5616 } 5617 // Make sure that the resolver is displayable in car mode 5618 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5619 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5620 return ri; 5621 } 5622 } 5623 return null; 5624 } 5625 5626 /** 5627 * Return true if the given list is not empty and all of its contents have 5628 * an activityInfo with the given package name. 5629 */ 5630 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5631 if (ArrayUtils.isEmpty(list)) { 5632 return false; 5633 } 5634 for (int i = 0, N = list.size(); i < N; i++) { 5635 final ResolveInfo ri = list.get(i); 5636 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5637 if (ai == null || !packageName.equals(ai.packageName)) { 5638 return false; 5639 } 5640 } 5641 return true; 5642 } 5643 5644 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5645 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5646 final int N = query.size(); 5647 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5648 .get(userId); 5649 // Get the list of persistent preferred activities that handle the intent 5650 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5651 List<PersistentPreferredActivity> pprefs = ppir != null 5652 ? ppir.queryIntent(intent, resolvedType, 5653 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5654 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5655 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5656 : null; 5657 if (pprefs != null && pprefs.size() > 0) { 5658 final int M = pprefs.size(); 5659 for (int i=0; i<M; i++) { 5660 final PersistentPreferredActivity ppa = pprefs.get(i); 5661 if (DEBUG_PREFERRED || debug) { 5662 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5663 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5664 + "\n component=" + ppa.mComponent); 5665 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5666 } 5667 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5668 flags | MATCH_DISABLED_COMPONENTS, userId); 5669 if (DEBUG_PREFERRED || debug) { 5670 Slog.v(TAG, "Found persistent preferred activity:"); 5671 if (ai != null) { 5672 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5673 } else { 5674 Slog.v(TAG, " null"); 5675 } 5676 } 5677 if (ai == null) { 5678 // This previously registered persistent preferred activity 5679 // component is no longer known. Ignore it and do NOT remove it. 5680 continue; 5681 } 5682 for (int j=0; j<N; j++) { 5683 final ResolveInfo ri = query.get(j); 5684 if (!ri.activityInfo.applicationInfo.packageName 5685 .equals(ai.applicationInfo.packageName)) { 5686 continue; 5687 } 5688 if (!ri.activityInfo.name.equals(ai.name)) { 5689 continue; 5690 } 5691 // Found a persistent preference that can handle the intent. 5692 if (DEBUG_PREFERRED || debug) { 5693 Slog.v(TAG, "Returning persistent preferred activity: " + 5694 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5695 } 5696 return ri; 5697 } 5698 } 5699 } 5700 return null; 5701 } 5702 5703 // TODO: handle preferred activities missing while user has amnesia 5704 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5705 List<ResolveInfo> query, int priority, boolean always, 5706 boolean removeMatches, boolean debug, int userId) { 5707 if (!sUserManager.exists(userId)) return null; 5708 flags = updateFlagsForResolve(flags, userId, intent); 5709 intent = updateIntentForResolve(intent); 5710 // writer 5711 synchronized (mPackages) { 5712 // Try to find a matching persistent preferred activity. 5713 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5714 debug, userId); 5715 5716 // If a persistent preferred activity matched, use it. 5717 if (pri != null) { 5718 return pri; 5719 } 5720 5721 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5722 // Get the list of preferred activities that handle the intent 5723 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5724 List<PreferredActivity> prefs = pir != null 5725 ? pir.queryIntent(intent, resolvedType, 5726 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5727 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5728 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5729 : null; 5730 if (prefs != null && prefs.size() > 0) { 5731 boolean changed = false; 5732 try { 5733 // First figure out how good the original match set is. 5734 // We will only allow preferred activities that came 5735 // from the same match quality. 5736 int match = 0; 5737 5738 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5739 5740 final int N = query.size(); 5741 for (int j=0; j<N; j++) { 5742 final ResolveInfo ri = query.get(j); 5743 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5744 + ": 0x" + Integer.toHexString(match)); 5745 if (ri.match > match) { 5746 match = ri.match; 5747 } 5748 } 5749 5750 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5751 + Integer.toHexString(match)); 5752 5753 match &= IntentFilter.MATCH_CATEGORY_MASK; 5754 final int M = prefs.size(); 5755 for (int i=0; i<M; i++) { 5756 final PreferredActivity pa = prefs.get(i); 5757 if (DEBUG_PREFERRED || debug) { 5758 Slog.v(TAG, "Checking PreferredActivity ds=" 5759 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5760 + "\n component=" + pa.mPref.mComponent); 5761 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5762 } 5763 if (pa.mPref.mMatch != match) { 5764 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5765 + Integer.toHexString(pa.mPref.mMatch)); 5766 continue; 5767 } 5768 // If it's not an "always" type preferred activity and that's what we're 5769 // looking for, skip it. 5770 if (always && !pa.mPref.mAlways) { 5771 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5772 continue; 5773 } 5774 final ActivityInfo ai = getActivityInfo( 5775 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5776 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5777 userId); 5778 if (DEBUG_PREFERRED || debug) { 5779 Slog.v(TAG, "Found preferred activity:"); 5780 if (ai != null) { 5781 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5782 } else { 5783 Slog.v(TAG, " null"); 5784 } 5785 } 5786 if (ai == null) { 5787 // This previously registered preferred activity 5788 // component is no longer known. Most likely an update 5789 // to the app was installed and in the new version this 5790 // component no longer exists. Clean it up by removing 5791 // it from the preferred activities list, and skip it. 5792 Slog.w(TAG, "Removing dangling preferred activity: " 5793 + pa.mPref.mComponent); 5794 pir.removeFilter(pa); 5795 changed = true; 5796 continue; 5797 } 5798 for (int j=0; j<N; j++) { 5799 final ResolveInfo ri = query.get(j); 5800 if (!ri.activityInfo.applicationInfo.packageName 5801 .equals(ai.applicationInfo.packageName)) { 5802 continue; 5803 } 5804 if (!ri.activityInfo.name.equals(ai.name)) { 5805 continue; 5806 } 5807 5808 if (removeMatches) { 5809 pir.removeFilter(pa); 5810 changed = true; 5811 if (DEBUG_PREFERRED) { 5812 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5813 } 5814 break; 5815 } 5816 5817 // Okay we found a previously set preferred or last chosen app. 5818 // If the result set is different from when this 5819 // was created, we need to clear it and re-ask the 5820 // user their preference, if we're looking for an "always" type entry. 5821 if (always && !pa.mPref.sameSet(query)) { 5822 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5823 + intent + " type " + resolvedType); 5824 if (DEBUG_PREFERRED) { 5825 Slog.v(TAG, "Removing preferred activity since set changed " 5826 + pa.mPref.mComponent); 5827 } 5828 pir.removeFilter(pa); 5829 // Re-add the filter as a "last chosen" entry (!always) 5830 PreferredActivity lastChosen = new PreferredActivity( 5831 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5832 pir.addFilter(lastChosen); 5833 changed = true; 5834 return null; 5835 } 5836 5837 // Yay! Either the set matched or we're looking for the last chosen 5838 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5839 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5840 return ri; 5841 } 5842 } 5843 } finally { 5844 if (changed) { 5845 if (DEBUG_PREFERRED) { 5846 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5847 } 5848 scheduleWritePackageRestrictionsLocked(userId); 5849 } 5850 } 5851 } 5852 } 5853 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5854 return null; 5855 } 5856 5857 /* 5858 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5859 */ 5860 @Override 5861 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5862 int targetUserId) { 5863 mContext.enforceCallingOrSelfPermission( 5864 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5865 List<CrossProfileIntentFilter> matches = 5866 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5867 if (matches != null) { 5868 int size = matches.size(); 5869 for (int i = 0; i < size; i++) { 5870 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5871 } 5872 } 5873 if (hasWebURI(intent)) { 5874 // cross-profile app linking works only towards the parent. 5875 final UserInfo parent = getProfileParent(sourceUserId); 5876 synchronized(mPackages) { 5877 int flags = updateFlagsForResolve(0, parent.id, intent); 5878 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5879 intent, resolvedType, flags, sourceUserId, parent.id); 5880 return xpDomainInfo != null; 5881 } 5882 } 5883 return false; 5884 } 5885 5886 private UserInfo getProfileParent(int userId) { 5887 final long identity = Binder.clearCallingIdentity(); 5888 try { 5889 return sUserManager.getProfileParent(userId); 5890 } finally { 5891 Binder.restoreCallingIdentity(identity); 5892 } 5893 } 5894 5895 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5896 String resolvedType, int userId) { 5897 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5898 if (resolver != null) { 5899 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5900 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5901 } 5902 return null; 5903 } 5904 5905 @Override 5906 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5907 String resolvedType, int flags, int userId) { 5908 try { 5909 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5910 5911 return new ParceledListSlice<>( 5912 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5913 } finally { 5914 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5915 } 5916 } 5917 5918 /** 5919 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5920 * ephemeral, returns {@code null}. 5921 */ 5922 private String getEphemeralPackageName(int callingUid) { 5923 final int appId = UserHandle.getAppId(callingUid); 5924 synchronized (mPackages) { 5925 final Object obj = mSettings.getUserIdLPr(appId); 5926 if (obj instanceof PackageSetting) { 5927 final PackageSetting ps = (PackageSetting) obj; 5928 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5929 } 5930 } 5931 return null; 5932 } 5933 5934 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5935 String resolvedType, int flags, int userId) { 5936 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5937 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5938 flags = updateFlagsForResolve(flags, userId, intent); 5939 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5940 false /* requireFullPermission */, false /* checkShell */, 5941 "query intent activities"); 5942 ComponentName comp = intent.getComponent(); 5943 if (comp == null) { 5944 if (intent.getSelector() != null) { 5945 intent = intent.getSelector(); 5946 comp = intent.getComponent(); 5947 } 5948 } 5949 5950 if (comp != null) { 5951 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5952 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5953 if (ai != null) { 5954 // When specifying an explicit component, we prevent the activity from being 5955 // used when either 1) the calling package is normal and the activity is within 5956 // an ephemeral application or 2) the calling package is ephemeral and the 5957 // activity is not visible to ephemeral applications. 5958 boolean matchEphemeral = 5959 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 5960 boolean ephemeralVisibleOnly = 5961 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 5962 boolean blockResolution = 5963 (!matchEphemeral && ephemeralPkgName == null 5964 && (ai.applicationInfo.privateFlags 5965 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5966 || (ephemeralVisibleOnly && ephemeralPkgName != null 5967 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5968 if (!blockResolution) { 5969 final ResolveInfo ri = new ResolveInfo(); 5970 ri.activityInfo = ai; 5971 list.add(ri); 5972 } 5973 } 5974 return list; 5975 } 5976 5977 // reader 5978 boolean sortResult = false; 5979 boolean addEphemeral = false; 5980 List<ResolveInfo> result; 5981 final String pkgName = intent.getPackage(); 5982 synchronized (mPackages) { 5983 if (pkgName == null) { 5984 List<CrossProfileIntentFilter> matchingFilters = 5985 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5986 // Check for results that need to skip the current profile. 5987 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5988 resolvedType, flags, userId); 5989 if (xpResolveInfo != null) { 5990 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5991 xpResult.add(xpResolveInfo); 5992 return filterForEphemeral( 5993 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5994 } 5995 5996 // Check for results in the current profile. 5997 result = filterIfNotSystemUser(mActivities.queryIntent( 5998 intent, resolvedType, flags, userId), userId); 5999 addEphemeral = 6000 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6001 6002 // Check for cross profile results. 6003 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6004 xpResolveInfo = queryCrossProfileIntents( 6005 matchingFilters, intent, resolvedType, flags, userId, 6006 hasNonNegativePriorityResult); 6007 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6008 boolean isVisibleToUser = filterIfNotSystemUser( 6009 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6010 if (isVisibleToUser) { 6011 result.add(xpResolveInfo); 6012 sortResult = true; 6013 } 6014 } 6015 if (hasWebURI(intent)) { 6016 CrossProfileDomainInfo xpDomainInfo = null; 6017 final UserInfo parent = getProfileParent(userId); 6018 if (parent != null) { 6019 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6020 flags, userId, parent.id); 6021 } 6022 if (xpDomainInfo != null) { 6023 if (xpResolveInfo != null) { 6024 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6025 // in the result. 6026 result.remove(xpResolveInfo); 6027 } 6028 if (result.size() == 0 && !addEphemeral) { 6029 // No result in current profile, but found candidate in parent user. 6030 // And we are not going to add emphemeral app, so we can return the 6031 // result straight away. 6032 result.add(xpDomainInfo.resolveInfo); 6033 return filterForEphemeral(result, ephemeralPkgName); 6034 } 6035 } else if (result.size() <= 1 && !addEphemeral) { 6036 // No result in parent user and <= 1 result in current profile, and we 6037 // are not going to add emphemeral app, so we can return the result without 6038 // further processing. 6039 return filterForEphemeral(result, ephemeralPkgName); 6040 } 6041 // We have more than one candidate (combining results from current and parent 6042 // profile), so we need filtering and sorting. 6043 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6044 intent, flags, result, xpDomainInfo, userId); 6045 sortResult = true; 6046 } 6047 } else { 6048 final PackageParser.Package pkg = mPackages.get(pkgName); 6049 if (pkg != null) { 6050 result = filterForEphemeral(filterIfNotSystemUser( 6051 mActivities.queryIntentForPackage( 6052 intent, resolvedType, flags, pkg.activities, userId), 6053 userId), ephemeralPkgName); 6054 } else { 6055 // the caller wants to resolve for a particular package; however, there 6056 // were no installed results, so, try to find an ephemeral result 6057 addEphemeral = isEphemeralAllowed( 6058 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6059 result = new ArrayList<ResolveInfo>(); 6060 } 6061 } 6062 } 6063 if (addEphemeral) { 6064 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6065 final EphemeralRequest requestObject = new EphemeralRequest( 6066 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6067 null /*launchIntent*/, null /*callingPackage*/, userId); 6068 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 6069 mContext, mEphemeralResolverConnection, requestObject); 6070 if (intentInfo != null) { 6071 if (DEBUG_EPHEMERAL) { 6072 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6073 } 6074 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 6075 ephemeralInstaller.ephemeralResponse = intentInfo; 6076 // make sure this resolver is the default 6077 ephemeralInstaller.isDefault = true; 6078 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6079 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6080 // add a non-generic filter 6081 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6082 ephemeralInstaller.filter.addDataPath( 6083 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6084 result.add(ephemeralInstaller); 6085 } 6086 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6087 } 6088 if (sortResult) { 6089 Collections.sort(result, mResolvePrioritySorter); 6090 } 6091 return filterForEphemeral(result, ephemeralPkgName); 6092 } 6093 6094 private static class CrossProfileDomainInfo { 6095 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6096 ResolveInfo resolveInfo; 6097 /* Best domain verification status of the activities found in the other profile */ 6098 int bestDomainVerificationStatus; 6099 } 6100 6101 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6102 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6103 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6104 sourceUserId)) { 6105 return null; 6106 } 6107 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6108 resolvedType, flags, parentUserId); 6109 6110 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6111 return null; 6112 } 6113 CrossProfileDomainInfo result = null; 6114 int size = resultTargetUser.size(); 6115 for (int i = 0; i < size; i++) { 6116 ResolveInfo riTargetUser = resultTargetUser.get(i); 6117 // Intent filter verification is only for filters that specify a host. So don't return 6118 // those that handle all web uris. 6119 if (riTargetUser.handleAllWebDataURI) { 6120 continue; 6121 } 6122 String packageName = riTargetUser.activityInfo.packageName; 6123 PackageSetting ps = mSettings.mPackages.get(packageName); 6124 if (ps == null) { 6125 continue; 6126 } 6127 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6128 int status = (int)(verificationState >> 32); 6129 if (result == null) { 6130 result = new CrossProfileDomainInfo(); 6131 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6132 sourceUserId, parentUserId); 6133 result.bestDomainVerificationStatus = status; 6134 } else { 6135 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6136 result.bestDomainVerificationStatus); 6137 } 6138 } 6139 // Don't consider matches with status NEVER across profiles. 6140 if (result != null && result.bestDomainVerificationStatus 6141 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6142 return null; 6143 } 6144 return result; 6145 } 6146 6147 /** 6148 * Verification statuses are ordered from the worse to the best, except for 6149 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6150 */ 6151 private int bestDomainVerificationStatus(int status1, int status2) { 6152 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6153 return status2; 6154 } 6155 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6156 return status1; 6157 } 6158 return (int) MathUtils.max(status1, status2); 6159 } 6160 6161 private boolean isUserEnabled(int userId) { 6162 long callingId = Binder.clearCallingIdentity(); 6163 try { 6164 UserInfo userInfo = sUserManager.getUserInfo(userId); 6165 return userInfo != null && userInfo.isEnabled(); 6166 } finally { 6167 Binder.restoreCallingIdentity(callingId); 6168 } 6169 } 6170 6171 /** 6172 * Filter out activities with systemUserOnly flag set, when current user is not System. 6173 * 6174 * @return filtered list 6175 */ 6176 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6177 if (userId == UserHandle.USER_SYSTEM) { 6178 return resolveInfos; 6179 } 6180 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6181 ResolveInfo info = resolveInfos.get(i); 6182 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6183 resolveInfos.remove(i); 6184 } 6185 } 6186 return resolveInfos; 6187 } 6188 6189 /** 6190 * Filters out ephemeral activities. 6191 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6192 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6193 * 6194 * @param resolveInfos The pre-filtered list of resolved activities 6195 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6196 * is performed. 6197 * @return A filtered list of resolved activities. 6198 */ 6199 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 6200 String ephemeralPkgName) { 6201 if (ephemeralPkgName == null) { 6202 return resolveInfos; 6203 } 6204 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6205 ResolveInfo info = resolveInfos.get(i); 6206 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 6207 // allow activities that are defined in the provided package 6208 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6209 continue; 6210 } 6211 // allow activities that have been explicitly exposed to ephemeral apps 6212 if (!isEphemeralApp 6213 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6214 continue; 6215 } 6216 resolveInfos.remove(i); 6217 } 6218 return resolveInfos; 6219 } 6220 6221 /** 6222 * @param resolveInfos list of resolve infos in descending priority order 6223 * @return if the list contains a resolve info with non-negative priority 6224 */ 6225 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6226 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6227 } 6228 6229 private static boolean hasWebURI(Intent intent) { 6230 if (intent.getData() == null) { 6231 return false; 6232 } 6233 final String scheme = intent.getScheme(); 6234 if (TextUtils.isEmpty(scheme)) { 6235 return false; 6236 } 6237 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6238 } 6239 6240 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6241 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6242 int userId) { 6243 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6244 6245 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6246 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6247 candidates.size()); 6248 } 6249 6250 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6251 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6252 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6253 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6254 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6255 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6256 6257 synchronized (mPackages) { 6258 final int count = candidates.size(); 6259 // First, try to use linked apps. Partition the candidates into four lists: 6260 // one for the final results, one for the "do not use ever", one for "undefined status" 6261 // and finally one for "browser app type". 6262 for (int n=0; n<count; n++) { 6263 ResolveInfo info = candidates.get(n); 6264 String packageName = info.activityInfo.packageName; 6265 PackageSetting ps = mSettings.mPackages.get(packageName); 6266 if (ps != null) { 6267 // Add to the special match all list (Browser use case) 6268 if (info.handleAllWebDataURI) { 6269 matchAllList.add(info); 6270 continue; 6271 } 6272 // Try to get the status from User settings first 6273 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6274 int status = (int)(packedStatus >> 32); 6275 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6276 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6277 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6278 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6279 + " : linkgen=" + linkGeneration); 6280 } 6281 // Use link-enabled generation as preferredOrder, i.e. 6282 // prefer newly-enabled over earlier-enabled. 6283 info.preferredOrder = linkGeneration; 6284 alwaysList.add(info); 6285 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6286 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6287 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6288 } 6289 neverList.add(info); 6290 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6291 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6292 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6293 } 6294 alwaysAskList.add(info); 6295 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6296 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6297 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6298 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6299 } 6300 undefinedList.add(info); 6301 } 6302 } 6303 } 6304 6305 // We'll want to include browser possibilities in a few cases 6306 boolean includeBrowser = false; 6307 6308 // First try to add the "always" resolution(s) for the current user, if any 6309 if (alwaysList.size() > 0) { 6310 result.addAll(alwaysList); 6311 } else { 6312 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6313 result.addAll(undefinedList); 6314 // Maybe add one for the other profile. 6315 if (xpDomainInfo != null && ( 6316 xpDomainInfo.bestDomainVerificationStatus 6317 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6318 result.add(xpDomainInfo.resolveInfo); 6319 } 6320 includeBrowser = true; 6321 } 6322 6323 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6324 // If there were 'always' entries their preferred order has been set, so we also 6325 // back that off to make the alternatives equivalent 6326 if (alwaysAskList.size() > 0) { 6327 for (ResolveInfo i : result) { 6328 i.preferredOrder = 0; 6329 } 6330 result.addAll(alwaysAskList); 6331 includeBrowser = true; 6332 } 6333 6334 if (includeBrowser) { 6335 // Also add browsers (all of them or only the default one) 6336 if (DEBUG_DOMAIN_VERIFICATION) { 6337 Slog.v(TAG, " ...including browsers in candidate set"); 6338 } 6339 if ((matchFlags & MATCH_ALL) != 0) { 6340 result.addAll(matchAllList); 6341 } else { 6342 // Browser/generic handling case. If there's a default browser, go straight 6343 // to that (but only if there is no other higher-priority match). 6344 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6345 int maxMatchPrio = 0; 6346 ResolveInfo defaultBrowserMatch = null; 6347 final int numCandidates = matchAllList.size(); 6348 for (int n = 0; n < numCandidates; n++) { 6349 ResolveInfo info = matchAllList.get(n); 6350 // track the highest overall match priority... 6351 if (info.priority > maxMatchPrio) { 6352 maxMatchPrio = info.priority; 6353 } 6354 // ...and the highest-priority default browser match 6355 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6356 if (defaultBrowserMatch == null 6357 || (defaultBrowserMatch.priority < info.priority)) { 6358 if (debug) { 6359 Slog.v(TAG, "Considering default browser match " + info); 6360 } 6361 defaultBrowserMatch = info; 6362 } 6363 } 6364 } 6365 if (defaultBrowserMatch != null 6366 && defaultBrowserMatch.priority >= maxMatchPrio 6367 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6368 { 6369 if (debug) { 6370 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6371 } 6372 result.add(defaultBrowserMatch); 6373 } else { 6374 result.addAll(matchAllList); 6375 } 6376 } 6377 6378 // If there is nothing selected, add all candidates and remove the ones that the user 6379 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6380 if (result.size() == 0) { 6381 result.addAll(candidates); 6382 result.removeAll(neverList); 6383 } 6384 } 6385 } 6386 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6387 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6388 result.size()); 6389 for (ResolveInfo info : result) { 6390 Slog.v(TAG, " + " + info.activityInfo); 6391 } 6392 } 6393 return result; 6394 } 6395 6396 // Returns a packed value as a long: 6397 // 6398 // high 'int'-sized word: link status: undefined/ask/never/always. 6399 // low 'int'-sized word: relative priority among 'always' results. 6400 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6401 long result = ps.getDomainVerificationStatusForUser(userId); 6402 // if none available, get the master status 6403 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6404 if (ps.getIntentFilterVerificationInfo() != null) { 6405 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6406 } 6407 } 6408 return result; 6409 } 6410 6411 private ResolveInfo querySkipCurrentProfileIntents( 6412 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6413 int flags, int sourceUserId) { 6414 if (matchingFilters != null) { 6415 int size = matchingFilters.size(); 6416 for (int i = 0; i < size; i ++) { 6417 CrossProfileIntentFilter filter = matchingFilters.get(i); 6418 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6419 // Checking if there are activities in the target user that can handle the 6420 // intent. 6421 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6422 resolvedType, flags, sourceUserId); 6423 if (resolveInfo != null) { 6424 return resolveInfo; 6425 } 6426 } 6427 } 6428 } 6429 return null; 6430 } 6431 6432 // Return matching ResolveInfo in target user if any. 6433 private ResolveInfo queryCrossProfileIntents( 6434 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6435 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6436 if (matchingFilters != null) { 6437 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6438 // match the same intent. For performance reasons, it is better not to 6439 // run queryIntent twice for the same userId 6440 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6441 int size = matchingFilters.size(); 6442 for (int i = 0; i < size; i++) { 6443 CrossProfileIntentFilter filter = matchingFilters.get(i); 6444 int targetUserId = filter.getTargetUserId(); 6445 boolean skipCurrentProfile = 6446 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6447 boolean skipCurrentProfileIfNoMatchFound = 6448 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6449 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6450 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6451 // Checking if there are activities in the target user that can handle the 6452 // intent. 6453 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6454 resolvedType, flags, sourceUserId); 6455 if (resolveInfo != null) return resolveInfo; 6456 alreadyTriedUserIds.put(targetUserId, true); 6457 } 6458 } 6459 } 6460 return null; 6461 } 6462 6463 /** 6464 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6465 * will forward the intent to the filter's target user. 6466 * Otherwise, returns null. 6467 */ 6468 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6469 String resolvedType, int flags, int sourceUserId) { 6470 int targetUserId = filter.getTargetUserId(); 6471 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6472 resolvedType, flags, targetUserId); 6473 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6474 // If all the matches in the target profile are suspended, return null. 6475 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6476 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6477 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6478 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6479 targetUserId); 6480 } 6481 } 6482 } 6483 return null; 6484 } 6485 6486 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6487 int sourceUserId, int targetUserId) { 6488 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6489 long ident = Binder.clearCallingIdentity(); 6490 boolean targetIsProfile; 6491 try { 6492 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6493 } finally { 6494 Binder.restoreCallingIdentity(ident); 6495 } 6496 String className; 6497 if (targetIsProfile) { 6498 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6499 } else { 6500 className = FORWARD_INTENT_TO_PARENT; 6501 } 6502 ComponentName forwardingActivityComponentName = new ComponentName( 6503 mAndroidApplication.packageName, className); 6504 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6505 sourceUserId); 6506 if (!targetIsProfile) { 6507 forwardingActivityInfo.showUserIcon = targetUserId; 6508 forwardingResolveInfo.noResourceId = true; 6509 } 6510 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6511 forwardingResolveInfo.priority = 0; 6512 forwardingResolveInfo.preferredOrder = 0; 6513 forwardingResolveInfo.match = 0; 6514 forwardingResolveInfo.isDefault = true; 6515 forwardingResolveInfo.filter = filter; 6516 forwardingResolveInfo.targetUserId = targetUserId; 6517 return forwardingResolveInfo; 6518 } 6519 6520 @Override 6521 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6522 Intent[] specifics, String[] specificTypes, Intent intent, 6523 String resolvedType, int flags, int userId) { 6524 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6525 specificTypes, intent, resolvedType, flags, userId)); 6526 } 6527 6528 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6529 Intent[] specifics, String[] specificTypes, Intent intent, 6530 String resolvedType, int flags, int userId) { 6531 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6532 flags = updateFlagsForResolve(flags, userId, intent); 6533 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6534 false /* requireFullPermission */, false /* checkShell */, 6535 "query intent activity options"); 6536 final String resultsAction = intent.getAction(); 6537 6538 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6539 | PackageManager.GET_RESOLVED_FILTER, userId); 6540 6541 if (DEBUG_INTENT_MATCHING) { 6542 Log.v(TAG, "Query " + intent + ": " + results); 6543 } 6544 6545 int specificsPos = 0; 6546 int N; 6547 6548 // todo: note that the algorithm used here is O(N^2). This 6549 // isn't a problem in our current environment, but if we start running 6550 // into situations where we have more than 5 or 10 matches then this 6551 // should probably be changed to something smarter... 6552 6553 // First we go through and resolve each of the specific items 6554 // that were supplied, taking care of removing any corresponding 6555 // duplicate items in the generic resolve list. 6556 if (specifics != null) { 6557 for (int i=0; i<specifics.length; i++) { 6558 final Intent sintent = specifics[i]; 6559 if (sintent == null) { 6560 continue; 6561 } 6562 6563 if (DEBUG_INTENT_MATCHING) { 6564 Log.v(TAG, "Specific #" + i + ": " + sintent); 6565 } 6566 6567 String action = sintent.getAction(); 6568 if (resultsAction != null && resultsAction.equals(action)) { 6569 // If this action was explicitly requested, then don't 6570 // remove things that have it. 6571 action = null; 6572 } 6573 6574 ResolveInfo ri = null; 6575 ActivityInfo ai = null; 6576 6577 ComponentName comp = sintent.getComponent(); 6578 if (comp == null) { 6579 ri = resolveIntent( 6580 sintent, 6581 specificTypes != null ? specificTypes[i] : null, 6582 flags, userId); 6583 if (ri == null) { 6584 continue; 6585 } 6586 if (ri == mResolveInfo) { 6587 // ACK! Must do something better with this. 6588 } 6589 ai = ri.activityInfo; 6590 comp = new ComponentName(ai.applicationInfo.packageName, 6591 ai.name); 6592 } else { 6593 ai = getActivityInfo(comp, flags, userId); 6594 if (ai == null) { 6595 continue; 6596 } 6597 } 6598 6599 // Look for any generic query activities that are duplicates 6600 // of this specific one, and remove them from the results. 6601 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6602 N = results.size(); 6603 int j; 6604 for (j=specificsPos; j<N; j++) { 6605 ResolveInfo sri = results.get(j); 6606 if ((sri.activityInfo.name.equals(comp.getClassName()) 6607 && sri.activityInfo.applicationInfo.packageName.equals( 6608 comp.getPackageName())) 6609 || (action != null && sri.filter.matchAction(action))) { 6610 results.remove(j); 6611 if (DEBUG_INTENT_MATCHING) Log.v( 6612 TAG, "Removing duplicate item from " + j 6613 + " due to specific " + specificsPos); 6614 if (ri == null) { 6615 ri = sri; 6616 } 6617 j--; 6618 N--; 6619 } 6620 } 6621 6622 // Add this specific item to its proper place. 6623 if (ri == null) { 6624 ri = new ResolveInfo(); 6625 ri.activityInfo = ai; 6626 } 6627 results.add(specificsPos, ri); 6628 ri.specificIndex = i; 6629 specificsPos++; 6630 } 6631 } 6632 6633 // Now we go through the remaining generic results and remove any 6634 // duplicate actions that are found here. 6635 N = results.size(); 6636 for (int i=specificsPos; i<N-1; i++) { 6637 final ResolveInfo rii = results.get(i); 6638 if (rii.filter == null) { 6639 continue; 6640 } 6641 6642 // Iterate over all of the actions of this result's intent 6643 // filter... typically this should be just one. 6644 final Iterator<String> it = rii.filter.actionsIterator(); 6645 if (it == null) { 6646 continue; 6647 } 6648 while (it.hasNext()) { 6649 final String action = it.next(); 6650 if (resultsAction != null && resultsAction.equals(action)) { 6651 // If this action was explicitly requested, then don't 6652 // remove things that have it. 6653 continue; 6654 } 6655 for (int j=i+1; j<N; j++) { 6656 final ResolveInfo rij = results.get(j); 6657 if (rij.filter != null && rij.filter.hasAction(action)) { 6658 results.remove(j); 6659 if (DEBUG_INTENT_MATCHING) Log.v( 6660 TAG, "Removing duplicate item from " + j 6661 + " due to action " + action + " at " + i); 6662 j--; 6663 N--; 6664 } 6665 } 6666 } 6667 6668 // If the caller didn't request filter information, drop it now 6669 // so we don't have to marshall/unmarshall it. 6670 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6671 rii.filter = null; 6672 } 6673 } 6674 6675 // Filter out the caller activity if so requested. 6676 if (caller != null) { 6677 N = results.size(); 6678 for (int i=0; i<N; i++) { 6679 ActivityInfo ainfo = results.get(i).activityInfo; 6680 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6681 && caller.getClassName().equals(ainfo.name)) { 6682 results.remove(i); 6683 break; 6684 } 6685 } 6686 } 6687 6688 // If the caller didn't request filter information, 6689 // drop them now so we don't have to 6690 // marshall/unmarshall it. 6691 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6692 N = results.size(); 6693 for (int i=0; i<N; i++) { 6694 results.get(i).filter = null; 6695 } 6696 } 6697 6698 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6699 return results; 6700 } 6701 6702 @Override 6703 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6704 String resolvedType, int flags, int userId) { 6705 return new ParceledListSlice<>( 6706 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6707 } 6708 6709 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6710 String resolvedType, int flags, int userId) { 6711 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6712 flags = updateFlagsForResolve(flags, userId, intent); 6713 ComponentName comp = intent.getComponent(); 6714 if (comp == null) { 6715 if (intent.getSelector() != null) { 6716 intent = intent.getSelector(); 6717 comp = intent.getComponent(); 6718 } 6719 } 6720 if (comp != null) { 6721 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6722 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6723 if (ai != null) { 6724 ResolveInfo ri = new ResolveInfo(); 6725 ri.activityInfo = ai; 6726 list.add(ri); 6727 } 6728 return list; 6729 } 6730 6731 // reader 6732 synchronized (mPackages) { 6733 String pkgName = intent.getPackage(); 6734 if (pkgName == null) { 6735 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6736 } 6737 final PackageParser.Package pkg = mPackages.get(pkgName); 6738 if (pkg != null) { 6739 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6740 userId); 6741 } 6742 return Collections.emptyList(); 6743 } 6744 } 6745 6746 @Override 6747 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6748 if (!sUserManager.exists(userId)) return null; 6749 flags = updateFlagsForResolve(flags, userId, intent); 6750 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6751 if (query != null) { 6752 if (query.size() >= 1) { 6753 // If there is more than one service with the same priority, 6754 // just arbitrarily pick the first one. 6755 return query.get(0); 6756 } 6757 } 6758 return null; 6759 } 6760 6761 @Override 6762 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6763 String resolvedType, int flags, int userId) { 6764 return new ParceledListSlice<>( 6765 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6766 } 6767 6768 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6769 String resolvedType, int flags, int userId) { 6770 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6771 flags = updateFlagsForResolve(flags, userId, intent); 6772 ComponentName comp = intent.getComponent(); 6773 if (comp == null) { 6774 if (intent.getSelector() != null) { 6775 intent = intent.getSelector(); 6776 comp = intent.getComponent(); 6777 } 6778 } 6779 if (comp != null) { 6780 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6781 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6782 if (si != null) { 6783 final ResolveInfo ri = new ResolveInfo(); 6784 ri.serviceInfo = si; 6785 list.add(ri); 6786 } 6787 return list; 6788 } 6789 6790 // reader 6791 synchronized (mPackages) { 6792 String pkgName = intent.getPackage(); 6793 if (pkgName == null) { 6794 return mServices.queryIntent(intent, resolvedType, flags, userId); 6795 } 6796 final PackageParser.Package pkg = mPackages.get(pkgName); 6797 if (pkg != null) { 6798 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6799 userId); 6800 } 6801 return Collections.emptyList(); 6802 } 6803 } 6804 6805 @Override 6806 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6807 String resolvedType, int flags, int userId) { 6808 return new ParceledListSlice<>( 6809 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6810 } 6811 6812 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6813 Intent intent, String resolvedType, int flags, int userId) { 6814 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6815 flags = updateFlagsForResolve(flags, userId, intent); 6816 ComponentName comp = intent.getComponent(); 6817 if (comp == null) { 6818 if (intent.getSelector() != null) { 6819 intent = intent.getSelector(); 6820 comp = intent.getComponent(); 6821 } 6822 } 6823 if (comp != null) { 6824 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6825 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6826 if (pi != null) { 6827 final ResolveInfo ri = new ResolveInfo(); 6828 ri.providerInfo = pi; 6829 list.add(ri); 6830 } 6831 return list; 6832 } 6833 6834 // reader 6835 synchronized (mPackages) { 6836 String pkgName = intent.getPackage(); 6837 if (pkgName == null) { 6838 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6839 } 6840 final PackageParser.Package pkg = mPackages.get(pkgName); 6841 if (pkg != null) { 6842 return mProviders.queryIntentForPackage( 6843 intent, resolvedType, flags, pkg.providers, userId); 6844 } 6845 return Collections.emptyList(); 6846 } 6847 } 6848 6849 @Override 6850 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6851 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6852 flags = updateFlagsForPackage(flags, userId, null); 6853 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6854 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6855 true /* requireFullPermission */, false /* checkShell */, 6856 "get installed packages"); 6857 6858 // writer 6859 synchronized (mPackages) { 6860 ArrayList<PackageInfo> list; 6861 if (listUninstalled) { 6862 list = new ArrayList<>(mSettings.mPackages.size()); 6863 for (PackageSetting ps : mSettings.mPackages.values()) { 6864 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6865 continue; 6866 } 6867 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6868 if (pi != null) { 6869 list.add(pi); 6870 } 6871 } 6872 } else { 6873 list = new ArrayList<>(mPackages.size()); 6874 for (PackageParser.Package p : mPackages.values()) { 6875 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 6876 Binder.getCallingUid(), userId)) { 6877 continue; 6878 } 6879 final PackageInfo pi = generatePackageInfo((PackageSetting) 6880 p.mExtras, flags, userId); 6881 if (pi != null) { 6882 list.add(pi); 6883 } 6884 } 6885 } 6886 6887 return new ParceledListSlice<>(list); 6888 } 6889 } 6890 6891 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6892 String[] permissions, boolean[] tmp, int flags, int userId) { 6893 int numMatch = 0; 6894 final PermissionsState permissionsState = ps.getPermissionsState(); 6895 for (int i=0; i<permissions.length; i++) { 6896 final String permission = permissions[i]; 6897 if (permissionsState.hasPermission(permission, userId)) { 6898 tmp[i] = true; 6899 numMatch++; 6900 } else { 6901 tmp[i] = false; 6902 } 6903 } 6904 if (numMatch == 0) { 6905 return; 6906 } 6907 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6908 6909 // The above might return null in cases of uninstalled apps or install-state 6910 // skew across users/profiles. 6911 if (pi != null) { 6912 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6913 if (numMatch == permissions.length) { 6914 pi.requestedPermissions = permissions; 6915 } else { 6916 pi.requestedPermissions = new String[numMatch]; 6917 numMatch = 0; 6918 for (int i=0; i<permissions.length; i++) { 6919 if (tmp[i]) { 6920 pi.requestedPermissions[numMatch] = permissions[i]; 6921 numMatch++; 6922 } 6923 } 6924 } 6925 } 6926 list.add(pi); 6927 } 6928 } 6929 6930 @Override 6931 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6932 String[] permissions, int flags, int userId) { 6933 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6934 flags = updateFlagsForPackage(flags, userId, permissions); 6935 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6936 true /* requireFullPermission */, false /* checkShell */, 6937 "get packages holding permissions"); 6938 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6939 6940 // writer 6941 synchronized (mPackages) { 6942 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6943 boolean[] tmpBools = new boolean[permissions.length]; 6944 if (listUninstalled) { 6945 for (PackageSetting ps : mSettings.mPackages.values()) { 6946 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6947 userId); 6948 } 6949 } else { 6950 for (PackageParser.Package pkg : mPackages.values()) { 6951 PackageSetting ps = (PackageSetting)pkg.mExtras; 6952 if (ps != null) { 6953 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6954 userId); 6955 } 6956 } 6957 } 6958 6959 return new ParceledListSlice<PackageInfo>(list); 6960 } 6961 } 6962 6963 @Override 6964 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6965 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6966 flags = updateFlagsForApplication(flags, userId, null); 6967 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6968 6969 // writer 6970 synchronized (mPackages) { 6971 ArrayList<ApplicationInfo> list; 6972 if (listUninstalled) { 6973 list = new ArrayList<>(mSettings.mPackages.size()); 6974 for (PackageSetting ps : mSettings.mPackages.values()) { 6975 ApplicationInfo ai; 6976 int effectiveFlags = flags; 6977 if (ps.isSystem()) { 6978 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6979 } 6980 if (ps.pkg != null) { 6981 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6982 continue; 6983 } 6984 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6985 ps.readUserState(userId), userId); 6986 if (ai != null) { 6987 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 6988 } 6989 } else { 6990 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 6991 // and already converts to externally visible package name 6992 ai = generateApplicationInfoFromSettingsLPw(ps.name, 6993 Binder.getCallingUid(), effectiveFlags, userId); 6994 } 6995 if (ai != null) { 6996 list.add(ai); 6997 } 6998 } 6999 } else { 7000 list = new ArrayList<>(mPackages.size()); 7001 for (PackageParser.Package p : mPackages.values()) { 7002 if (p.mExtras != null) { 7003 PackageSetting ps = (PackageSetting) p.mExtras; 7004 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7005 continue; 7006 } 7007 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7008 ps.readUserState(userId), userId); 7009 if (ai != null) { 7010 ai.packageName = resolveExternalPackageNameLPr(p); 7011 list.add(ai); 7012 } 7013 } 7014 } 7015 } 7016 7017 return new ParceledListSlice<>(list); 7018 } 7019 } 7020 7021 @Override 7022 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 7023 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7024 return null; 7025 } 7026 7027 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 7028 "getEphemeralApplications"); 7029 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7030 true /* requireFullPermission */, false /* checkShell */, 7031 "getEphemeralApplications"); 7032 synchronized (mPackages) { 7033 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 7034 .getEphemeralApplicationsLPw(userId); 7035 if (ephemeralApps != null) { 7036 return new ParceledListSlice<>(ephemeralApps); 7037 } 7038 } 7039 return null; 7040 } 7041 7042 @Override 7043 public boolean isEphemeralApplication(String packageName, int userId) { 7044 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7045 true /* requireFullPermission */, false /* checkShell */, 7046 "isEphemeral"); 7047 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7048 return false; 7049 } 7050 7051 if (!isCallerSameApp(packageName)) { 7052 return false; 7053 } 7054 synchronized (mPackages) { 7055 PackageParser.Package pkg = mPackages.get(packageName); 7056 if (pkg != null) { 7057 return pkg.applicationInfo.isEphemeralApp(); 7058 } 7059 } 7060 return false; 7061 } 7062 7063 @Override 7064 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 7065 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7066 return null; 7067 } 7068 7069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7070 true /* requireFullPermission */, false /* checkShell */, 7071 "getCookie"); 7072 if (!isCallerSameApp(packageName)) { 7073 return null; 7074 } 7075 synchronized (mPackages) { 7076 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 7077 packageName, userId); 7078 } 7079 } 7080 7081 @Override 7082 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 7083 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7084 return true; 7085 } 7086 7087 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7088 true /* requireFullPermission */, true /* checkShell */, 7089 "setCookie"); 7090 if (!isCallerSameApp(packageName)) { 7091 return false; 7092 } 7093 synchronized (mPackages) { 7094 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 7095 packageName, cookie, userId); 7096 } 7097 } 7098 7099 @Override 7100 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 7101 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7102 return null; 7103 } 7104 7105 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 7106 "getEphemeralApplicationIcon"); 7107 7108 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7109 true /* requireFullPermission */, false /* checkShell */, 7110 "getEphemeralApplicationIcon"); 7111 synchronized (mPackages) { 7112 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 7113 packageName, userId); 7114 } 7115 } 7116 7117 private boolean isCallerSameApp(String packageName) { 7118 PackageParser.Package pkg = mPackages.get(packageName); 7119 return pkg != null 7120 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7121 } 7122 7123 @Override 7124 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7125 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7126 } 7127 7128 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7129 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7130 7131 // reader 7132 synchronized (mPackages) { 7133 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7134 final int userId = UserHandle.getCallingUserId(); 7135 while (i.hasNext()) { 7136 final PackageParser.Package p = i.next(); 7137 if (p.applicationInfo == null) continue; 7138 7139 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7140 && !p.applicationInfo.isDirectBootAware(); 7141 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7142 && p.applicationInfo.isDirectBootAware(); 7143 7144 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7145 && (!mSafeMode || isSystemApp(p)) 7146 && (matchesUnaware || matchesAware)) { 7147 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7148 if (ps != null) { 7149 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7150 ps.readUserState(userId), userId); 7151 if (ai != null) { 7152 finalList.add(ai); 7153 } 7154 } 7155 } 7156 } 7157 } 7158 7159 return finalList; 7160 } 7161 7162 @Override 7163 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7164 if (!sUserManager.exists(userId)) return null; 7165 flags = updateFlagsForComponent(flags, userId, name); 7166 // reader 7167 synchronized (mPackages) { 7168 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7169 PackageSetting ps = provider != null 7170 ? mSettings.mPackages.get(provider.owner.packageName) 7171 : null; 7172 return ps != null 7173 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7174 ? PackageParser.generateProviderInfo(provider, flags, 7175 ps.readUserState(userId), userId) 7176 : null; 7177 } 7178 } 7179 7180 /** 7181 * @deprecated 7182 */ 7183 @Deprecated 7184 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7185 // reader 7186 synchronized (mPackages) { 7187 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7188 .entrySet().iterator(); 7189 final int userId = UserHandle.getCallingUserId(); 7190 while (i.hasNext()) { 7191 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7192 PackageParser.Provider p = entry.getValue(); 7193 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7194 7195 if (ps != null && p.syncable 7196 && (!mSafeMode || (p.info.applicationInfo.flags 7197 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7198 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7199 ps.readUserState(userId), userId); 7200 if (info != null) { 7201 outNames.add(entry.getKey()); 7202 outInfo.add(info); 7203 } 7204 } 7205 } 7206 } 7207 } 7208 7209 @Override 7210 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7211 int uid, int flags) { 7212 final int userId = processName != null ? UserHandle.getUserId(uid) 7213 : UserHandle.getCallingUserId(); 7214 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7215 flags = updateFlagsForComponent(flags, userId, processName); 7216 7217 ArrayList<ProviderInfo> finalList = null; 7218 // reader 7219 synchronized (mPackages) { 7220 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7221 while (i.hasNext()) { 7222 final PackageParser.Provider p = i.next(); 7223 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7224 if (ps != null && p.info.authority != null 7225 && (processName == null 7226 || (p.info.processName.equals(processName) 7227 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7228 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7229 if (finalList == null) { 7230 finalList = new ArrayList<ProviderInfo>(3); 7231 } 7232 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7233 ps.readUserState(userId), userId); 7234 if (info != null) { 7235 finalList.add(info); 7236 } 7237 } 7238 } 7239 } 7240 7241 if (finalList != null) { 7242 Collections.sort(finalList, mProviderInitOrderSorter); 7243 return new ParceledListSlice<ProviderInfo>(finalList); 7244 } 7245 7246 return ParceledListSlice.emptyList(); 7247 } 7248 7249 @Override 7250 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7251 // reader 7252 synchronized (mPackages) { 7253 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7254 return PackageParser.generateInstrumentationInfo(i, flags); 7255 } 7256 } 7257 7258 @Override 7259 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7260 String targetPackage, int flags) { 7261 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7262 } 7263 7264 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7265 int flags) { 7266 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7267 7268 // reader 7269 synchronized (mPackages) { 7270 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7271 while (i.hasNext()) { 7272 final PackageParser.Instrumentation p = i.next(); 7273 if (targetPackage == null 7274 || targetPackage.equals(p.info.targetPackage)) { 7275 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7276 flags); 7277 if (ii != null) { 7278 finalList.add(ii); 7279 } 7280 } 7281 } 7282 } 7283 7284 return finalList; 7285 } 7286 7287 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7288 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7289 if (overlays == null) { 7290 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7291 return; 7292 } 7293 for (PackageParser.Package opkg : overlays.values()) { 7294 // Not much to do if idmap fails: we already logged the error 7295 // and we certainly don't want to abort installation of pkg simply 7296 // because an overlay didn't fit properly. For these reasons, 7297 // ignore the return value of createIdmapForPackagePairLI. 7298 createIdmapForPackagePairLI(pkg, opkg); 7299 } 7300 } 7301 7302 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7303 PackageParser.Package opkg) { 7304 if (!opkg.mTrustedOverlay) { 7305 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7306 opkg.baseCodePath + ": overlay not trusted"); 7307 return false; 7308 } 7309 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7310 if (overlaySet == null) { 7311 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7312 opkg.baseCodePath + " but target package has no known overlays"); 7313 return false; 7314 } 7315 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7316 // TODO: generate idmap for split APKs 7317 try { 7318 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7319 } catch (InstallerException e) { 7320 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7321 + opkg.baseCodePath); 7322 return false; 7323 } 7324 PackageParser.Package[] overlayArray = 7325 overlaySet.values().toArray(new PackageParser.Package[0]); 7326 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7327 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7328 return p1.mOverlayPriority - p2.mOverlayPriority; 7329 } 7330 }; 7331 Arrays.sort(overlayArray, cmp); 7332 7333 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7334 int i = 0; 7335 for (PackageParser.Package p : overlayArray) { 7336 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7337 } 7338 return true; 7339 } 7340 7341 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7343 try { 7344 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7345 } finally { 7346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7347 } 7348 } 7349 7350 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7351 final File[] files = dir.listFiles(); 7352 if (ArrayUtils.isEmpty(files)) { 7353 Log.d(TAG, "No files in app dir " + dir); 7354 return; 7355 } 7356 7357 if (DEBUG_PACKAGE_SCANNING) { 7358 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7359 + " flags=0x" + Integer.toHexString(parseFlags)); 7360 } 7361 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7362 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7363 7364 // Submit files for parsing in parallel 7365 int fileCount = 0; 7366 for (File file : files) { 7367 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7368 && !PackageInstallerService.isStageName(file.getName()); 7369 if (!isPackage) { 7370 // Ignore entries which are not packages 7371 continue; 7372 } 7373 parallelPackageParser.submit(file, parseFlags); 7374 fileCount++; 7375 } 7376 7377 // Process results one by one 7378 for (; fileCount > 0; fileCount--) { 7379 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7380 Throwable throwable = parseResult.throwable; 7381 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7382 7383 if (throwable == null) { 7384 // Static shared libraries have synthetic package names 7385 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7386 renameStaticSharedLibraryPackage(parseResult.pkg); 7387 } 7388 try { 7389 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7390 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7391 currentTime, null); 7392 } 7393 } catch (PackageManagerException e) { 7394 errorCode = e.error; 7395 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7396 } 7397 } else if (throwable instanceof PackageParser.PackageParserException) { 7398 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7399 throwable; 7400 errorCode = e.error; 7401 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7402 } else { 7403 throw new IllegalStateException("Unexpected exception occurred while parsing " 7404 + parseResult.scanFile, throwable); 7405 } 7406 7407 // Delete invalid userdata apps 7408 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7409 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7410 logCriticalInfo(Log.WARN, 7411 "Deleting invalid package at " + parseResult.scanFile); 7412 removeCodePathLI(parseResult.scanFile); 7413 } 7414 } 7415 parallelPackageParser.close(); 7416 } 7417 7418 private static File getSettingsProblemFile() { 7419 File dataDir = Environment.getDataDirectory(); 7420 File systemDir = new File(dataDir, "system"); 7421 File fname = new File(systemDir, "uiderrors.txt"); 7422 return fname; 7423 } 7424 7425 static void reportSettingsProblem(int priority, String msg) { 7426 logCriticalInfo(priority, msg); 7427 } 7428 7429 static void logCriticalInfo(int priority, String msg) { 7430 Slog.println(priority, TAG, msg); 7431 EventLogTags.writePmCriticalInfo(msg); 7432 try { 7433 File fname = getSettingsProblemFile(); 7434 FileOutputStream out = new FileOutputStream(fname, true); 7435 PrintWriter pw = new FastPrintWriter(out); 7436 SimpleDateFormat formatter = new SimpleDateFormat(); 7437 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7438 pw.println(dateString + ": " + msg); 7439 pw.close(); 7440 FileUtils.setPermissions( 7441 fname.toString(), 7442 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7443 -1, -1); 7444 } catch (java.io.IOException e) { 7445 } 7446 } 7447 7448 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7449 if (srcFile.isDirectory()) { 7450 final File baseFile = new File(pkg.baseCodePath); 7451 long maxModifiedTime = baseFile.lastModified(); 7452 if (pkg.splitCodePaths != null) { 7453 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7454 final File splitFile = new File(pkg.splitCodePaths[i]); 7455 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7456 } 7457 } 7458 return maxModifiedTime; 7459 } 7460 return srcFile.lastModified(); 7461 } 7462 7463 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7464 final int policyFlags) throws PackageManagerException { 7465 // When upgrading from pre-N MR1, verify the package time stamp using the package 7466 // directory and not the APK file. 7467 final long lastModifiedTime = mIsPreNMR1Upgrade 7468 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7469 if (ps != null 7470 && ps.codePath.equals(srcFile) 7471 && ps.timeStamp == lastModifiedTime 7472 && !isCompatSignatureUpdateNeeded(pkg) 7473 && !isRecoverSignatureUpdateNeeded(pkg)) { 7474 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7475 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7476 ArraySet<PublicKey> signingKs; 7477 synchronized (mPackages) { 7478 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7479 } 7480 if (ps.signatures.mSignatures != null 7481 && ps.signatures.mSignatures.length != 0 7482 && signingKs != null) { 7483 // Optimization: reuse the existing cached certificates 7484 // if the package appears to be unchanged. 7485 pkg.mSignatures = ps.signatures.mSignatures; 7486 pkg.mSigningKeys = signingKs; 7487 return; 7488 } 7489 7490 Slog.w(TAG, "PackageSetting for " + ps.name 7491 + " is missing signatures. Collecting certs again to recover them."); 7492 } else { 7493 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7494 } 7495 7496 try { 7497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7498 PackageParser.collectCertificates(pkg, policyFlags); 7499 } catch (PackageParserException e) { 7500 throw PackageManagerException.from(e); 7501 } finally { 7502 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7503 } 7504 } 7505 7506 /** 7507 * Traces a package scan. 7508 * @see #scanPackageLI(File, int, int, long, UserHandle) 7509 */ 7510 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7511 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7513 try { 7514 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7515 } finally { 7516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7517 } 7518 } 7519 7520 /** 7521 * Scans a package and returns the newly parsed package. 7522 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7523 */ 7524 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7525 long currentTime, UserHandle user) throws PackageManagerException { 7526 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7527 PackageParser pp = new PackageParser(); 7528 pp.setSeparateProcesses(mSeparateProcesses); 7529 pp.setOnlyCoreApps(mOnlyCore); 7530 pp.setDisplayMetrics(mMetrics); 7531 7532 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7533 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7534 } 7535 7536 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7537 final PackageParser.Package pkg; 7538 try { 7539 pkg = pp.parsePackage(scanFile, parseFlags); 7540 } catch (PackageParserException e) { 7541 throw PackageManagerException.from(e); 7542 } finally { 7543 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7544 } 7545 7546 // Static shared libraries have synthetic package names 7547 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7548 renameStaticSharedLibraryPackage(pkg); 7549 } 7550 7551 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7552 } 7553 7554 /** 7555 * Scans a package and returns the newly parsed package. 7556 * @throws PackageManagerException on a parse error. 7557 */ 7558 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7559 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7560 throws PackageManagerException { 7561 // If the package has children and this is the first dive in the function 7562 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7563 // packages (parent and children) would be successfully scanned before the 7564 // actual scan since scanning mutates internal state and we want to atomically 7565 // install the package and its children. 7566 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7567 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7568 scanFlags |= SCAN_CHECK_ONLY; 7569 } 7570 } else { 7571 scanFlags &= ~SCAN_CHECK_ONLY; 7572 } 7573 7574 // Scan the parent 7575 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7576 scanFlags, currentTime, user); 7577 7578 // Scan the children 7579 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7580 for (int i = 0; i < childCount; i++) { 7581 PackageParser.Package childPackage = pkg.childPackages.get(i); 7582 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7583 currentTime, user); 7584 } 7585 7586 7587 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7588 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7589 } 7590 7591 return scannedPkg; 7592 } 7593 7594 /** 7595 * Scans a package and returns the newly parsed package. 7596 * @throws PackageManagerException on a parse error. 7597 */ 7598 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7599 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7600 throws PackageManagerException { 7601 PackageSetting ps = null; 7602 PackageSetting updatedPkg; 7603 // reader 7604 synchronized (mPackages) { 7605 // Look to see if we already know about this package. 7606 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7607 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7608 // This package has been renamed to its original name. Let's 7609 // use that. 7610 ps = mSettings.getPackageLPr(oldName); 7611 } 7612 // If there was no original package, see one for the real package name. 7613 if (ps == null) { 7614 ps = mSettings.getPackageLPr(pkg.packageName); 7615 } 7616 // Check to see if this package could be hiding/updating a system 7617 // package. Must look for it either under the original or real 7618 // package name depending on our state. 7619 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7620 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7621 7622 // If this is a package we don't know about on the system partition, we 7623 // may need to remove disabled child packages on the system partition 7624 // or may need to not add child packages if the parent apk is updated 7625 // on the data partition and no longer defines this child package. 7626 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7627 // If this is a parent package for an updated system app and this system 7628 // app got an OTA update which no longer defines some of the child packages 7629 // we have to prune them from the disabled system packages. 7630 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7631 if (disabledPs != null) { 7632 final int scannedChildCount = (pkg.childPackages != null) 7633 ? pkg.childPackages.size() : 0; 7634 final int disabledChildCount = disabledPs.childPackageNames != null 7635 ? disabledPs.childPackageNames.size() : 0; 7636 for (int i = 0; i < disabledChildCount; i++) { 7637 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7638 boolean disabledPackageAvailable = false; 7639 for (int j = 0; j < scannedChildCount; j++) { 7640 PackageParser.Package childPkg = pkg.childPackages.get(j); 7641 if (childPkg.packageName.equals(disabledChildPackageName)) { 7642 disabledPackageAvailable = true; 7643 break; 7644 } 7645 } 7646 if (!disabledPackageAvailable) { 7647 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7648 } 7649 } 7650 } 7651 } 7652 } 7653 7654 boolean updatedPkgBetter = false; 7655 // First check if this is a system package that may involve an update 7656 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7657 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7658 // it needs to drop FLAG_PRIVILEGED. 7659 if (locationIsPrivileged(scanFile)) { 7660 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7661 } else { 7662 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7663 } 7664 7665 if (ps != null && !ps.codePath.equals(scanFile)) { 7666 // The path has changed from what was last scanned... check the 7667 // version of the new path against what we have stored to determine 7668 // what to do. 7669 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7670 if (pkg.mVersionCode <= ps.versionCode) { 7671 // The system package has been updated and the code path does not match 7672 // Ignore entry. Skip it. 7673 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7674 + " ignored: updated version " + ps.versionCode 7675 + " better than this " + pkg.mVersionCode); 7676 if (!updatedPkg.codePath.equals(scanFile)) { 7677 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7678 + ps.name + " changing from " + updatedPkg.codePathString 7679 + " to " + scanFile); 7680 updatedPkg.codePath = scanFile; 7681 updatedPkg.codePathString = scanFile.toString(); 7682 updatedPkg.resourcePath = scanFile; 7683 updatedPkg.resourcePathString = scanFile.toString(); 7684 } 7685 updatedPkg.pkg = pkg; 7686 updatedPkg.versionCode = pkg.mVersionCode; 7687 7688 // Update the disabled system child packages to point to the package too. 7689 final int childCount = updatedPkg.childPackageNames != null 7690 ? updatedPkg.childPackageNames.size() : 0; 7691 for (int i = 0; i < childCount; i++) { 7692 String childPackageName = updatedPkg.childPackageNames.get(i); 7693 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7694 childPackageName); 7695 if (updatedChildPkg != null) { 7696 updatedChildPkg.pkg = pkg; 7697 updatedChildPkg.versionCode = pkg.mVersionCode; 7698 } 7699 } 7700 7701 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7702 + scanFile + " ignored: updated version " + ps.versionCode 7703 + " better than this " + pkg.mVersionCode); 7704 } else { 7705 // The current app on the system partition is better than 7706 // what we have updated to on the data partition; switch 7707 // back to the system partition version. 7708 // At this point, its safely assumed that package installation for 7709 // apps in system partition will go through. If not there won't be a working 7710 // version of the app 7711 // writer 7712 synchronized (mPackages) { 7713 // Just remove the loaded entries from package lists. 7714 mPackages.remove(ps.name); 7715 } 7716 7717 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7718 + " reverting from " + ps.codePathString 7719 + ": new version " + pkg.mVersionCode 7720 + " better than installed " + ps.versionCode); 7721 7722 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7723 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7724 synchronized (mInstallLock) { 7725 args.cleanUpResourcesLI(); 7726 } 7727 synchronized (mPackages) { 7728 mSettings.enableSystemPackageLPw(ps.name); 7729 } 7730 updatedPkgBetter = true; 7731 } 7732 } 7733 } 7734 7735 if (updatedPkg != null) { 7736 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7737 // initially 7738 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7739 7740 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7741 // flag set initially 7742 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7743 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7744 } 7745 } 7746 7747 // Verify certificates against what was last scanned 7748 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7749 7750 /* 7751 * A new system app appeared, but we already had a non-system one of the 7752 * same name installed earlier. 7753 */ 7754 boolean shouldHideSystemApp = false; 7755 if (updatedPkg == null && ps != null 7756 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7757 /* 7758 * Check to make sure the signatures match first. If they don't, 7759 * wipe the installed application and its data. 7760 */ 7761 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7762 != PackageManager.SIGNATURE_MATCH) { 7763 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7764 + " signatures don't match existing userdata copy; removing"); 7765 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7766 "scanPackageInternalLI")) { 7767 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7768 } 7769 ps = null; 7770 } else { 7771 /* 7772 * If the newly-added system app is an older version than the 7773 * already installed version, hide it. It will be scanned later 7774 * and re-added like an update. 7775 */ 7776 if (pkg.mVersionCode <= ps.versionCode) { 7777 shouldHideSystemApp = true; 7778 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7779 + " but new version " + pkg.mVersionCode + " better than installed " 7780 + ps.versionCode + "; hiding system"); 7781 } else { 7782 /* 7783 * The newly found system app is a newer version that the 7784 * one previously installed. Simply remove the 7785 * already-installed application and replace it with our own 7786 * while keeping the application data. 7787 */ 7788 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7789 + " reverting from " + ps.codePathString + ": new version " 7790 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7791 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7792 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7793 synchronized (mInstallLock) { 7794 args.cleanUpResourcesLI(); 7795 } 7796 } 7797 } 7798 } 7799 7800 // The apk is forward locked (not public) if its code and resources 7801 // are kept in different files. (except for app in either system or 7802 // vendor path). 7803 // TODO grab this value from PackageSettings 7804 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7805 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7806 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7807 } 7808 } 7809 7810 // TODO: extend to support forward-locked splits 7811 String resourcePath = null; 7812 String baseResourcePath = null; 7813 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7814 if (ps != null && ps.resourcePathString != null) { 7815 resourcePath = ps.resourcePathString; 7816 baseResourcePath = ps.resourcePathString; 7817 } else { 7818 // Should not happen at all. Just log an error. 7819 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7820 } 7821 } else { 7822 resourcePath = pkg.codePath; 7823 baseResourcePath = pkg.baseCodePath; 7824 } 7825 7826 // Set application objects path explicitly. 7827 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7828 pkg.setApplicationInfoCodePath(pkg.codePath); 7829 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7830 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7831 pkg.setApplicationInfoResourcePath(resourcePath); 7832 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7833 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7834 7835 // Note that we invoke the following method only if we are about to unpack an application 7836 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7837 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7838 7839 /* 7840 * If the system app should be overridden by a previously installed 7841 * data, hide the system app now and let the /data/app scan pick it up 7842 * again. 7843 */ 7844 if (shouldHideSystemApp) { 7845 synchronized (mPackages) { 7846 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7847 } 7848 } 7849 7850 return scannedPkg; 7851 } 7852 7853 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7854 // Derive the new package synthetic package name 7855 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7856 + pkg.staticSharedLibVersion); 7857 } 7858 7859 private static String fixProcessName(String defProcessName, 7860 String processName) { 7861 if (processName == null) { 7862 return defProcessName; 7863 } 7864 return processName; 7865 } 7866 7867 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7868 throws PackageManagerException { 7869 if (pkgSetting.signatures.mSignatures != null) { 7870 // Already existing package. Make sure signatures match 7871 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7872 == PackageManager.SIGNATURE_MATCH; 7873 if (!match) { 7874 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7875 == PackageManager.SIGNATURE_MATCH; 7876 } 7877 if (!match) { 7878 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7879 == PackageManager.SIGNATURE_MATCH; 7880 } 7881 if (!match) { 7882 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7883 + pkg.packageName + " signatures do not match the " 7884 + "previously installed version; ignoring!"); 7885 } 7886 } 7887 7888 // Check for shared user signatures 7889 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7890 // Already existing package. Make sure signatures match 7891 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7892 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7893 if (!match) { 7894 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7895 == PackageManager.SIGNATURE_MATCH; 7896 } 7897 if (!match) { 7898 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7899 == PackageManager.SIGNATURE_MATCH; 7900 } 7901 if (!match) { 7902 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7903 "Package " + pkg.packageName 7904 + " has no signatures that match those in shared user " 7905 + pkgSetting.sharedUser.name + "; ignoring!"); 7906 } 7907 } 7908 } 7909 7910 /** 7911 * Enforces that only the system UID or root's UID can call a method exposed 7912 * via Binder. 7913 * 7914 * @param message used as message if SecurityException is thrown 7915 * @throws SecurityException if the caller is not system or root 7916 */ 7917 private static final void enforceSystemOrRoot(String message) { 7918 final int uid = Binder.getCallingUid(); 7919 if (uid != Process.SYSTEM_UID && uid != 0) { 7920 throw new SecurityException(message); 7921 } 7922 } 7923 7924 @Override 7925 public void performFstrimIfNeeded() { 7926 enforceSystemOrRoot("Only the system can request fstrim"); 7927 7928 // Before everything else, see whether we need to fstrim. 7929 try { 7930 IStorageManager sm = PackageHelper.getStorageManager(); 7931 if (sm != null) { 7932 boolean doTrim = false; 7933 final long interval = android.provider.Settings.Global.getLong( 7934 mContext.getContentResolver(), 7935 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7936 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7937 if (interval > 0) { 7938 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7939 if (timeSinceLast > interval) { 7940 doTrim = true; 7941 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7942 + "; running immediately"); 7943 } 7944 } 7945 if (doTrim) { 7946 final boolean dexOptDialogShown; 7947 synchronized (mPackages) { 7948 dexOptDialogShown = mDexOptDialogShown; 7949 } 7950 if (!isFirstBoot() && dexOptDialogShown) { 7951 try { 7952 ActivityManager.getService().showBootMessage( 7953 mContext.getResources().getString( 7954 R.string.android_upgrading_fstrim), true); 7955 } catch (RemoteException e) { 7956 } 7957 } 7958 sm.runMaintenance(); 7959 } 7960 } else { 7961 Slog.e(TAG, "storageManager service unavailable!"); 7962 } 7963 } catch (RemoteException e) { 7964 // Can't happen; StorageManagerService is local 7965 } 7966 } 7967 7968 @Override 7969 public void updatePackagesIfNeeded() { 7970 enforceSystemOrRoot("Only the system can request package update"); 7971 7972 // We need to re-extract after an OTA. 7973 boolean causeUpgrade = isUpgrade(); 7974 7975 // First boot or factory reset. 7976 // Note: we also handle devices that are upgrading to N right now as if it is their 7977 // first boot, as they do not have profile data. 7978 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7979 7980 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7981 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7982 7983 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7984 return; 7985 } 7986 7987 List<PackageParser.Package> pkgs; 7988 synchronized (mPackages) { 7989 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7990 } 7991 7992 final long startTime = System.nanoTime(); 7993 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7994 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7995 7996 final int elapsedTimeSeconds = 7997 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7998 7999 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8000 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8001 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8002 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8003 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8004 } 8005 8006 /** 8007 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8008 * containing statistics about the invocation. The array consists of three elements, 8009 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8010 * and {@code numberOfPackagesFailed}. 8011 */ 8012 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8013 String compilerFilter) { 8014 8015 int numberOfPackagesVisited = 0; 8016 int numberOfPackagesOptimized = 0; 8017 int numberOfPackagesSkipped = 0; 8018 int numberOfPackagesFailed = 0; 8019 final int numberOfPackagesToDexopt = pkgs.size(); 8020 8021 for (PackageParser.Package pkg : pkgs) { 8022 numberOfPackagesVisited++; 8023 8024 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8025 if (DEBUG_DEXOPT) { 8026 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8027 } 8028 numberOfPackagesSkipped++; 8029 continue; 8030 } 8031 8032 if (DEBUG_DEXOPT) { 8033 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8034 numberOfPackagesToDexopt + ": " + pkg.packageName); 8035 } 8036 8037 if (showDialog) { 8038 try { 8039 ActivityManager.getService().showBootMessage( 8040 mContext.getResources().getString(R.string.android_upgrading_apk, 8041 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8042 } catch (RemoteException e) { 8043 } 8044 synchronized (mPackages) { 8045 mDexOptDialogShown = true; 8046 } 8047 } 8048 8049 // If the OTA updates a system app which was previously preopted to a non-preopted state 8050 // the app might end up being verified at runtime. That's because by default the apps 8051 // are verify-profile but for preopted apps there's no profile. 8052 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8053 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8054 // filter (by default interpret-only). 8055 // Note that at this stage unused apps are already filtered. 8056 if (isSystemApp(pkg) && 8057 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8058 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8059 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8060 } 8061 8062 // checkProfiles is false to avoid merging profiles during boot which 8063 // might interfere with background compilation (b/28612421). 8064 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8065 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8066 // trade-off worth doing to save boot time work. 8067 int dexOptStatus = performDexOptTraced(pkg.packageName, 8068 false /* checkProfiles */, 8069 compilerFilter, 8070 false /* force */); 8071 switch (dexOptStatus) { 8072 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8073 numberOfPackagesOptimized++; 8074 break; 8075 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8076 numberOfPackagesSkipped++; 8077 break; 8078 case PackageDexOptimizer.DEX_OPT_FAILED: 8079 numberOfPackagesFailed++; 8080 break; 8081 default: 8082 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8083 break; 8084 } 8085 } 8086 8087 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8088 numberOfPackagesFailed }; 8089 } 8090 8091 @Override 8092 public void notifyPackageUse(String packageName, int reason) { 8093 synchronized (mPackages) { 8094 PackageParser.Package p = mPackages.get(packageName); 8095 if (p == null) { 8096 return; 8097 } 8098 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8099 } 8100 } 8101 8102 @Override 8103 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8104 int userId = UserHandle.getCallingUserId(); 8105 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8106 if (ai == null) { 8107 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8108 + loadingPackageName + ", user=" + userId); 8109 return; 8110 } 8111 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8112 } 8113 8114 // TODO: this is not used nor needed. Delete it. 8115 @Override 8116 public boolean performDexOptIfNeeded(String packageName) { 8117 int dexOptStatus = performDexOptTraced(packageName, 8118 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8119 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8120 } 8121 8122 @Override 8123 public boolean performDexOpt(String packageName, 8124 boolean checkProfiles, int compileReason, boolean force) { 8125 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8126 getCompilerFilterForReason(compileReason), force); 8127 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8128 } 8129 8130 @Override 8131 public boolean performDexOptMode(String packageName, 8132 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8133 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8134 targetCompilerFilter, force); 8135 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8136 } 8137 8138 private int performDexOptTraced(String packageName, 8139 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8140 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8141 try { 8142 return performDexOptInternal(packageName, checkProfiles, 8143 targetCompilerFilter, force); 8144 } finally { 8145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8146 } 8147 } 8148 8149 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8150 // if the package can now be considered up to date for the given filter. 8151 private int performDexOptInternal(String packageName, 8152 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8153 PackageParser.Package p; 8154 synchronized (mPackages) { 8155 p = mPackages.get(packageName); 8156 if (p == null) { 8157 // Package could not be found. Report failure. 8158 return PackageDexOptimizer.DEX_OPT_FAILED; 8159 } 8160 mPackageUsage.maybeWriteAsync(mPackages); 8161 mCompilerStats.maybeWriteAsync(); 8162 } 8163 long callingId = Binder.clearCallingIdentity(); 8164 try { 8165 synchronized (mInstallLock) { 8166 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8167 targetCompilerFilter, force); 8168 } 8169 } finally { 8170 Binder.restoreCallingIdentity(callingId); 8171 } 8172 } 8173 8174 public ArraySet<String> getOptimizablePackages() { 8175 ArraySet<String> pkgs = new ArraySet<String>(); 8176 synchronized (mPackages) { 8177 for (PackageParser.Package p : mPackages.values()) { 8178 if (PackageDexOptimizer.canOptimizePackage(p)) { 8179 pkgs.add(p.packageName); 8180 } 8181 } 8182 } 8183 return pkgs; 8184 } 8185 8186 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8187 boolean checkProfiles, String targetCompilerFilter, 8188 boolean force) { 8189 // Select the dex optimizer based on the force parameter. 8190 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8191 // allocate an object here. 8192 PackageDexOptimizer pdo = force 8193 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8194 : mPackageDexOptimizer; 8195 8196 // Optimize all dependencies first. Note: we ignore the return value and march on 8197 // on errors. 8198 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8199 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8200 if (!deps.isEmpty()) { 8201 for (PackageParser.Package depPackage : deps) { 8202 // TODO: Analyze and investigate if we (should) profile libraries. 8203 // Currently this will do a full compilation of the library by default. 8204 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8205 false /* checkProfiles */, 8206 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8207 getOrCreateCompilerPackageStats(depPackage)); 8208 } 8209 } 8210 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8211 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8212 } 8213 8214 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8215 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8216 || p.usesStaticLibraries != null) { 8217 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8218 Set<String> collectedNames = new HashSet<>(); 8219 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8220 8221 retValue.remove(p); 8222 8223 return retValue; 8224 } else { 8225 return Collections.emptyList(); 8226 } 8227 } 8228 8229 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8230 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8231 if (!collectedNames.contains(p.packageName)) { 8232 collectedNames.add(p.packageName); 8233 collected.add(p); 8234 8235 if (p.usesLibraries != null) { 8236 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8237 null, collected, collectedNames); 8238 } 8239 if (p.usesOptionalLibraries != null) { 8240 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8241 null, collected, collectedNames); 8242 } 8243 if (p.usesStaticLibraries != null) { 8244 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8245 p.usesStaticLibrariesVersions, collected, collectedNames); 8246 } 8247 } 8248 } 8249 8250 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8251 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8252 final int libNameCount = libs.size(); 8253 for (int i = 0; i < libNameCount; i++) { 8254 String libName = libs.get(i); 8255 int version = (versions != null && versions.length == libNameCount) 8256 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8257 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8258 if (libPkg != null) { 8259 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8260 } 8261 } 8262 } 8263 8264 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8265 synchronized (mPackages) { 8266 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8267 if (libEntry != null) { 8268 return mPackages.get(libEntry.apk); 8269 } 8270 return null; 8271 } 8272 } 8273 8274 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8275 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8276 if (versionedLib == null) { 8277 return null; 8278 } 8279 return versionedLib.get(version); 8280 } 8281 8282 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8283 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8284 pkg.staticSharedLibName); 8285 if (versionedLib == null) { 8286 return null; 8287 } 8288 int previousLibVersion = -1; 8289 final int versionCount = versionedLib.size(); 8290 for (int i = 0; i < versionCount; i++) { 8291 final int libVersion = versionedLib.keyAt(i); 8292 if (libVersion < pkg.staticSharedLibVersion) { 8293 previousLibVersion = Math.max(previousLibVersion, libVersion); 8294 } 8295 } 8296 if (previousLibVersion >= 0) { 8297 return versionedLib.get(previousLibVersion); 8298 } 8299 return null; 8300 } 8301 8302 public void shutdown() { 8303 mPackageUsage.writeNow(mPackages); 8304 mCompilerStats.writeNow(); 8305 } 8306 8307 @Override 8308 public void dumpProfiles(String packageName) { 8309 PackageParser.Package pkg; 8310 synchronized (mPackages) { 8311 pkg = mPackages.get(packageName); 8312 if (pkg == null) { 8313 throw new IllegalArgumentException("Unknown package: " + packageName); 8314 } 8315 } 8316 /* Only the shell, root, or the app user should be able to dump profiles. */ 8317 int callingUid = Binder.getCallingUid(); 8318 if (callingUid != Process.SHELL_UID && 8319 callingUid != Process.ROOT_UID && 8320 callingUid != pkg.applicationInfo.uid) { 8321 throw new SecurityException("dumpProfiles"); 8322 } 8323 8324 synchronized (mInstallLock) { 8325 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8326 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8327 try { 8328 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8329 String codePaths = TextUtils.join(";", allCodePaths); 8330 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8331 } catch (InstallerException e) { 8332 Slog.w(TAG, "Failed to dump profiles", e); 8333 } 8334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8335 } 8336 } 8337 8338 @Override 8339 public void forceDexOpt(String packageName) { 8340 enforceSystemOrRoot("forceDexOpt"); 8341 8342 PackageParser.Package pkg; 8343 synchronized (mPackages) { 8344 pkg = mPackages.get(packageName); 8345 if (pkg == null) { 8346 throw new IllegalArgumentException("Unknown package: " + packageName); 8347 } 8348 } 8349 8350 synchronized (mInstallLock) { 8351 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8352 8353 // Whoever is calling forceDexOpt wants a fully compiled package. 8354 // Don't use profiles since that may cause compilation to be skipped. 8355 final int res = performDexOptInternalWithDependenciesLI(pkg, 8356 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8357 true /* force */); 8358 8359 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8360 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8361 throw new IllegalStateException("Failed to dexopt: " + res); 8362 } 8363 } 8364 } 8365 8366 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8367 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8368 Slog.w(TAG, "Unable to update from " + oldPkg.name 8369 + " to " + newPkg.packageName 8370 + ": old package not in system partition"); 8371 return false; 8372 } else if (mPackages.get(oldPkg.name) != null) { 8373 Slog.w(TAG, "Unable to update from " + oldPkg.name 8374 + " to " + newPkg.packageName 8375 + ": old package still exists"); 8376 return false; 8377 } 8378 return true; 8379 } 8380 8381 void removeCodePathLI(File codePath) { 8382 if (codePath.isDirectory()) { 8383 try { 8384 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8385 } catch (InstallerException e) { 8386 Slog.w(TAG, "Failed to remove code path", e); 8387 } 8388 } else { 8389 codePath.delete(); 8390 } 8391 } 8392 8393 private int[] resolveUserIds(int userId) { 8394 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8395 } 8396 8397 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8398 if (pkg == null) { 8399 Slog.wtf(TAG, "Package was null!", new Throwable()); 8400 return; 8401 } 8402 clearAppDataLeafLIF(pkg, userId, flags); 8403 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8404 for (int i = 0; i < childCount; i++) { 8405 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8406 } 8407 } 8408 8409 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8410 final PackageSetting ps; 8411 synchronized (mPackages) { 8412 ps = mSettings.mPackages.get(pkg.packageName); 8413 } 8414 for (int realUserId : resolveUserIds(userId)) { 8415 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8416 try { 8417 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8418 ceDataInode); 8419 } catch (InstallerException e) { 8420 Slog.w(TAG, String.valueOf(e)); 8421 } 8422 } 8423 } 8424 8425 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8426 if (pkg == null) { 8427 Slog.wtf(TAG, "Package was null!", new Throwable()); 8428 return; 8429 } 8430 destroyAppDataLeafLIF(pkg, userId, flags); 8431 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8432 for (int i = 0; i < childCount; i++) { 8433 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8434 } 8435 } 8436 8437 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8438 final PackageSetting ps; 8439 synchronized (mPackages) { 8440 ps = mSettings.mPackages.get(pkg.packageName); 8441 } 8442 for (int realUserId : resolveUserIds(userId)) { 8443 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8444 try { 8445 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8446 ceDataInode); 8447 } catch (InstallerException e) { 8448 Slog.w(TAG, String.valueOf(e)); 8449 } 8450 } 8451 } 8452 8453 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8454 if (pkg == null) { 8455 Slog.wtf(TAG, "Package was null!", new Throwable()); 8456 return; 8457 } 8458 destroyAppProfilesLeafLIF(pkg); 8459 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8460 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8461 for (int i = 0; i < childCount; i++) { 8462 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8463 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8464 true /* removeBaseMarker */); 8465 } 8466 } 8467 8468 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8469 boolean removeBaseMarker) { 8470 if (pkg.isForwardLocked()) { 8471 return; 8472 } 8473 8474 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8475 try { 8476 path = PackageManagerServiceUtils.realpath(new File(path)); 8477 } catch (IOException e) { 8478 // TODO: Should we return early here ? 8479 Slog.w(TAG, "Failed to get canonical path", e); 8480 continue; 8481 } 8482 8483 final String useMarker = path.replace('/', '@'); 8484 for (int realUserId : resolveUserIds(userId)) { 8485 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8486 if (removeBaseMarker) { 8487 File foreignUseMark = new File(profileDir, useMarker); 8488 if (foreignUseMark.exists()) { 8489 if (!foreignUseMark.delete()) { 8490 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8491 + pkg.packageName); 8492 } 8493 } 8494 } 8495 8496 File[] markers = profileDir.listFiles(); 8497 if (markers != null) { 8498 final String searchString = "@" + pkg.packageName + "@"; 8499 // We also delete all markers that contain the package name we're 8500 // uninstalling. These are associated with secondary dex-files belonging 8501 // to the package. Reconstructing the path of these dex files is messy 8502 // in general. 8503 for (File marker : markers) { 8504 if (marker.getName().indexOf(searchString) > 0) { 8505 if (!marker.delete()) { 8506 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8507 + pkg.packageName); 8508 } 8509 } 8510 } 8511 } 8512 } 8513 } 8514 } 8515 8516 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8517 try { 8518 mInstaller.destroyAppProfiles(pkg.packageName); 8519 } catch (InstallerException e) { 8520 Slog.w(TAG, String.valueOf(e)); 8521 } 8522 } 8523 8524 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8525 if (pkg == null) { 8526 Slog.wtf(TAG, "Package was null!", new Throwable()); 8527 return; 8528 } 8529 clearAppProfilesLeafLIF(pkg); 8530 // We don't remove the base foreign use marker when clearing profiles because 8531 // we will rename it when the app is updated. Unlike the actual profile contents, 8532 // the foreign use marker is good across installs. 8533 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8534 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8535 for (int i = 0; i < childCount; i++) { 8536 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8537 } 8538 } 8539 8540 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8541 try { 8542 mInstaller.clearAppProfiles(pkg.packageName); 8543 } catch (InstallerException e) { 8544 Slog.w(TAG, String.valueOf(e)); 8545 } 8546 } 8547 8548 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8549 long lastUpdateTime) { 8550 // Set parent install/update time 8551 PackageSetting ps = (PackageSetting) pkg.mExtras; 8552 if (ps != null) { 8553 ps.firstInstallTime = firstInstallTime; 8554 ps.lastUpdateTime = lastUpdateTime; 8555 } 8556 // Set children install/update time 8557 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8558 for (int i = 0; i < childCount; i++) { 8559 PackageParser.Package childPkg = pkg.childPackages.get(i); 8560 ps = (PackageSetting) childPkg.mExtras; 8561 if (ps != null) { 8562 ps.firstInstallTime = firstInstallTime; 8563 ps.lastUpdateTime = lastUpdateTime; 8564 } 8565 } 8566 } 8567 8568 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8569 PackageParser.Package changingLib) { 8570 if (file.path != null) { 8571 usesLibraryFiles.add(file.path); 8572 return; 8573 } 8574 PackageParser.Package p = mPackages.get(file.apk); 8575 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8576 // If we are doing this while in the middle of updating a library apk, 8577 // then we need to make sure to use that new apk for determining the 8578 // dependencies here. (We haven't yet finished committing the new apk 8579 // to the package manager state.) 8580 if (p == null || p.packageName.equals(changingLib.packageName)) { 8581 p = changingLib; 8582 } 8583 } 8584 if (p != null) { 8585 usesLibraryFiles.addAll(p.getAllCodePaths()); 8586 } 8587 } 8588 8589 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8590 PackageParser.Package changingLib) throws PackageManagerException { 8591 if (pkg == null) { 8592 return; 8593 } 8594 ArraySet<String> usesLibraryFiles = null; 8595 if (pkg.usesLibraries != null) { 8596 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8597 null, null, pkg.packageName, changingLib, true, null); 8598 } 8599 if (pkg.usesStaticLibraries != null) { 8600 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8601 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8602 pkg.packageName, changingLib, true, usesLibraryFiles); 8603 } 8604 if (pkg.usesOptionalLibraries != null) { 8605 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8606 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8607 } 8608 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8609 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8610 } else { 8611 pkg.usesLibraryFiles = null; 8612 } 8613 } 8614 8615 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8616 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8617 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8618 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8619 throws PackageManagerException { 8620 final int libCount = requestedLibraries.size(); 8621 for (int i = 0; i < libCount; i++) { 8622 final String libName = requestedLibraries.get(i); 8623 final int libVersion = requiredVersions != null ? requiredVersions[i] 8624 : SharedLibraryInfo.VERSION_UNDEFINED; 8625 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8626 if (libEntry == null) { 8627 if (required) { 8628 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8629 "Package " + packageName + " requires unavailable shared library " 8630 + libName + "; failing!"); 8631 } else { 8632 Slog.w(TAG, "Package " + packageName 8633 + " desires unavailable shared library " 8634 + libName + "; ignoring!"); 8635 } 8636 } else { 8637 if (requiredVersions != null && requiredCertDigests != null) { 8638 if (libEntry.info.getVersion() != requiredVersions[i]) { 8639 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8640 "Package " + packageName + " requires unavailable static shared" 8641 + " library " + libName + " version " 8642 + libEntry.info.getVersion() + "; failing!"); 8643 } 8644 8645 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8646 if (libPkg == null) { 8647 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8648 "Package " + packageName + " requires unavailable static shared" 8649 + " library; failing!"); 8650 } 8651 8652 String expectedCertDigest = requiredCertDigests[i]; 8653 String libCertDigest = PackageUtils.computeCertSha256Digest( 8654 libPkg.mSignatures[0]); 8655 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8656 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8657 "Package " + packageName + " requires differently signed" + 8658 " static shared library; failing!"); 8659 } 8660 } 8661 8662 if (outUsedLibraries == null) { 8663 outUsedLibraries = new ArraySet<>(); 8664 } 8665 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8666 } 8667 } 8668 return outUsedLibraries; 8669 } 8670 8671 private static boolean hasString(List<String> list, List<String> which) { 8672 if (list == null) { 8673 return false; 8674 } 8675 for (int i=list.size()-1; i>=0; i--) { 8676 for (int j=which.size()-1; j>=0; j--) { 8677 if (which.get(j).equals(list.get(i))) { 8678 return true; 8679 } 8680 } 8681 } 8682 return false; 8683 } 8684 8685 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8686 PackageParser.Package changingPkg) { 8687 ArrayList<PackageParser.Package> res = null; 8688 for (PackageParser.Package pkg : mPackages.values()) { 8689 if (changingPkg != null 8690 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8691 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8692 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8693 changingPkg.staticSharedLibName)) { 8694 return null; 8695 } 8696 if (res == null) { 8697 res = new ArrayList<>(); 8698 } 8699 res.add(pkg); 8700 try { 8701 updateSharedLibrariesLPr(pkg, changingPkg); 8702 } catch (PackageManagerException e) { 8703 // If a system app update or an app and a required lib missing we 8704 // delete the package and for updated system apps keep the data as 8705 // it is better for the user to reinstall than to be in an limbo 8706 // state. Also libs disappearing under an app should never happen 8707 // - just in case. 8708 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8709 final int flags = pkg.isUpdatedSystemApp() 8710 ? PackageManager.DELETE_KEEP_DATA : 0; 8711 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8712 flags , null, true, null); 8713 } 8714 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8715 } 8716 } 8717 return res; 8718 } 8719 8720 /** 8721 * Derive the value of the {@code cpuAbiOverride} based on the provided 8722 * value and an optional stored value from the package settings. 8723 */ 8724 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8725 String cpuAbiOverride = null; 8726 8727 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8728 cpuAbiOverride = null; 8729 } else if (abiOverride != null) { 8730 cpuAbiOverride = abiOverride; 8731 } else if (settings != null) { 8732 cpuAbiOverride = settings.cpuAbiOverrideString; 8733 } 8734 8735 return cpuAbiOverride; 8736 } 8737 8738 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8739 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8740 throws PackageManagerException { 8741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8742 // If the package has children and this is the first dive in the function 8743 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8744 // whether all packages (parent and children) would be successfully scanned 8745 // before the actual scan since scanning mutates internal state and we want 8746 // to atomically install the package and its children. 8747 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8748 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8749 scanFlags |= SCAN_CHECK_ONLY; 8750 } 8751 } else { 8752 scanFlags &= ~SCAN_CHECK_ONLY; 8753 } 8754 8755 final PackageParser.Package scannedPkg; 8756 try { 8757 // Scan the parent 8758 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8759 // Scan the children 8760 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8761 for (int i = 0; i < childCount; i++) { 8762 PackageParser.Package childPkg = pkg.childPackages.get(i); 8763 scanPackageLI(childPkg, policyFlags, 8764 scanFlags, currentTime, user); 8765 } 8766 } finally { 8767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8768 } 8769 8770 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8771 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8772 } 8773 8774 return scannedPkg; 8775 } 8776 8777 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8778 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8779 boolean success = false; 8780 try { 8781 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8782 currentTime, user); 8783 success = true; 8784 return res; 8785 } finally { 8786 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8787 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8788 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8789 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8790 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8791 } 8792 } 8793 } 8794 8795 /** 8796 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8797 */ 8798 private static boolean apkHasCode(String fileName) { 8799 StrictJarFile jarFile = null; 8800 try { 8801 jarFile = new StrictJarFile(fileName, 8802 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8803 return jarFile.findEntry("classes.dex") != null; 8804 } catch (IOException ignore) { 8805 } finally { 8806 try { 8807 if (jarFile != null) { 8808 jarFile.close(); 8809 } 8810 } catch (IOException ignore) {} 8811 } 8812 return false; 8813 } 8814 8815 /** 8816 * Enforces code policy for the package. This ensures that if an APK has 8817 * declared hasCode="true" in its manifest that the APK actually contains 8818 * code. 8819 * 8820 * @throws PackageManagerException If bytecode could not be found when it should exist 8821 */ 8822 private static void assertCodePolicy(PackageParser.Package pkg) 8823 throws PackageManagerException { 8824 final boolean shouldHaveCode = 8825 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8826 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8827 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8828 "Package " + pkg.baseCodePath + " code is missing"); 8829 } 8830 8831 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8832 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8833 final boolean splitShouldHaveCode = 8834 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8835 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8836 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8837 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8838 } 8839 } 8840 } 8841 } 8842 8843 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8844 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8845 throws PackageManagerException { 8846 if (DEBUG_PACKAGE_SCANNING) { 8847 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8848 Log.d(TAG, "Scanning package " + pkg.packageName); 8849 } 8850 8851 applyPolicy(pkg, policyFlags); 8852 8853 assertPackageIsValid(pkg, policyFlags, scanFlags); 8854 8855 // Initialize package source and resource directories 8856 final File scanFile = new File(pkg.codePath); 8857 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8858 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8859 8860 SharedUserSetting suid = null; 8861 PackageSetting pkgSetting = null; 8862 8863 // Getting the package setting may have a side-effect, so if we 8864 // are only checking if scan would succeed, stash a copy of the 8865 // old setting to restore at the end. 8866 PackageSetting nonMutatedPs = null; 8867 8868 // We keep references to the derived CPU Abis from settings in oder to reuse 8869 // them in the case where we're not upgrading or booting for the first time. 8870 String primaryCpuAbiFromSettings = null; 8871 String secondaryCpuAbiFromSettings = null; 8872 8873 // writer 8874 synchronized (mPackages) { 8875 if (pkg.mSharedUserId != null) { 8876 // SIDE EFFECTS; may potentially allocate a new shared user 8877 suid = mSettings.getSharedUserLPw( 8878 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8879 if (DEBUG_PACKAGE_SCANNING) { 8880 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8881 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8882 + "): packages=" + suid.packages); 8883 } 8884 } 8885 8886 // Check if we are renaming from an original package name. 8887 PackageSetting origPackage = null; 8888 String realName = null; 8889 if (pkg.mOriginalPackages != null) { 8890 // This package may need to be renamed to a previously 8891 // installed name. Let's check on that... 8892 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8893 if (pkg.mOriginalPackages.contains(renamed)) { 8894 // This package had originally been installed as the 8895 // original name, and we have already taken care of 8896 // transitioning to the new one. Just update the new 8897 // one to continue using the old name. 8898 realName = pkg.mRealPackage; 8899 if (!pkg.packageName.equals(renamed)) { 8900 // Callers into this function may have already taken 8901 // care of renaming the package; only do it here if 8902 // it is not already done. 8903 pkg.setPackageName(renamed); 8904 } 8905 } else { 8906 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8907 if ((origPackage = mSettings.getPackageLPr( 8908 pkg.mOriginalPackages.get(i))) != null) { 8909 // We do have the package already installed under its 8910 // original name... should we use it? 8911 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8912 // New package is not compatible with original. 8913 origPackage = null; 8914 continue; 8915 } else if (origPackage.sharedUser != null) { 8916 // Make sure uid is compatible between packages. 8917 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8918 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8919 + " to " + pkg.packageName + ": old uid " 8920 + origPackage.sharedUser.name 8921 + " differs from " + pkg.mSharedUserId); 8922 origPackage = null; 8923 continue; 8924 } 8925 // TODO: Add case when shared user id is added [b/28144775] 8926 } else { 8927 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8928 + pkg.packageName + " to old name " + origPackage.name); 8929 } 8930 break; 8931 } 8932 } 8933 } 8934 } 8935 8936 if (mTransferedPackages.contains(pkg.packageName)) { 8937 Slog.w(TAG, "Package " + pkg.packageName 8938 + " was transferred to another, but its .apk remains"); 8939 } 8940 8941 // See comments in nonMutatedPs declaration 8942 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8943 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8944 if (foundPs != null) { 8945 nonMutatedPs = new PackageSetting(foundPs); 8946 } 8947 } 8948 8949 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8950 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8951 if (foundPs != null) { 8952 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8953 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8954 } 8955 } 8956 8957 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8958 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8959 PackageManagerService.reportSettingsProblem(Log.WARN, 8960 "Package " + pkg.packageName + " shared user changed from " 8961 + (pkgSetting.sharedUser != null 8962 ? pkgSetting.sharedUser.name : "<nothing>") 8963 + " to " 8964 + (suid != null ? suid.name : "<nothing>") 8965 + "; replacing with new"); 8966 pkgSetting = null; 8967 } 8968 final PackageSetting oldPkgSetting = 8969 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8970 final PackageSetting disabledPkgSetting = 8971 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8972 8973 String[] usesStaticLibraries = null; 8974 if (pkg.usesStaticLibraries != null) { 8975 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 8976 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 8977 } 8978 8979 if (pkgSetting == null) { 8980 final String parentPackageName = (pkg.parentPackage != null) 8981 ? pkg.parentPackage.packageName : null; 8982 8983 // REMOVE SharedUserSetting from method; update in a separate call 8984 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8985 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8986 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8987 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8988 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8989 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8990 UserManagerService.getInstance(), usesStaticLibraries, 8991 pkg.usesStaticLibrariesVersions); 8992 // SIDE EFFECTS; updates system state; move elsewhere 8993 if (origPackage != null) { 8994 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8995 } 8996 mSettings.addUserToSettingLPw(pkgSetting); 8997 } else { 8998 // REMOVE SharedUserSetting from method; update in a separate call. 8999 // 9000 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9001 // secondaryCpuAbi are not known at this point so we always update them 9002 // to null here, only to reset them at a later point. 9003 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9004 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9005 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9006 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9007 UserManagerService.getInstance(), usesStaticLibraries, 9008 pkg.usesStaticLibrariesVersions); 9009 } 9010 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9011 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9012 9013 // SIDE EFFECTS; modifies system state; move elsewhere 9014 if (pkgSetting.origPackage != null) { 9015 // If we are first transitioning from an original package, 9016 // fix up the new package's name now. We need to do this after 9017 // looking up the package under its new name, so getPackageLP 9018 // can take care of fiddling things correctly. 9019 pkg.setPackageName(origPackage.name); 9020 9021 // File a report about this. 9022 String msg = "New package " + pkgSetting.realName 9023 + " renamed to replace old package " + pkgSetting.name; 9024 reportSettingsProblem(Log.WARN, msg); 9025 9026 // Make a note of it. 9027 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9028 mTransferedPackages.add(origPackage.name); 9029 } 9030 9031 // No longer need to retain this. 9032 pkgSetting.origPackage = null; 9033 } 9034 9035 // SIDE EFFECTS; modifies system state; move elsewhere 9036 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9037 // Make a note of it. 9038 mTransferedPackages.add(pkg.packageName); 9039 } 9040 9041 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9042 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9043 } 9044 9045 if ((scanFlags & SCAN_BOOTING) == 0 9046 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9047 // Check all shared libraries and map to their actual file path. 9048 // We only do this here for apps not on a system dir, because those 9049 // are the only ones that can fail an install due to this. We 9050 // will take care of the system apps by updating all of their 9051 // library paths after the scan is done. Also during the initial 9052 // scan don't update any libs as we do this wholesale after all 9053 // apps are scanned to avoid dependency based scanning. 9054 updateSharedLibrariesLPr(pkg, null); 9055 } 9056 9057 if (mFoundPolicyFile) { 9058 SELinuxMMAC.assignSeinfoValue(pkg); 9059 } 9060 9061 pkg.applicationInfo.uid = pkgSetting.appId; 9062 pkg.mExtras = pkgSetting; 9063 9064 9065 // Static shared libs have same package with different versions where 9066 // we internally use a synthetic package name to allow multiple versions 9067 // of the same package, therefore we need to compare signatures against 9068 // the package setting for the latest library version. 9069 PackageSetting signatureCheckPs = pkgSetting; 9070 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9071 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9072 if (libraryEntry != null) { 9073 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9074 } 9075 } 9076 9077 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9078 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9079 // We just determined the app is signed correctly, so bring 9080 // over the latest parsed certs. 9081 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9082 } else { 9083 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9084 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9085 "Package " + pkg.packageName + " upgrade keys do not match the " 9086 + "previously installed version"); 9087 } else { 9088 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9089 String msg = "System package " + pkg.packageName 9090 + " signature changed; retaining data."; 9091 reportSettingsProblem(Log.WARN, msg); 9092 } 9093 } 9094 } else { 9095 try { 9096 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9097 verifySignaturesLP(signatureCheckPs, pkg); 9098 // We just determined the app is signed correctly, so bring 9099 // over the latest parsed certs. 9100 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9101 } catch (PackageManagerException e) { 9102 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9103 throw e; 9104 } 9105 // The signature has changed, but this package is in the system 9106 // image... let's recover! 9107 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9108 // However... if this package is part of a shared user, but it 9109 // doesn't match the signature of the shared user, let's fail. 9110 // What this means is that you can't change the signatures 9111 // associated with an overall shared user, which doesn't seem all 9112 // that unreasonable. 9113 if (signatureCheckPs.sharedUser != null) { 9114 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9115 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9116 throw new PackageManagerException( 9117 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9118 "Signature mismatch for shared user: " 9119 + pkgSetting.sharedUser); 9120 } 9121 } 9122 // File a report about this. 9123 String msg = "System package " + pkg.packageName 9124 + " signature changed; retaining data."; 9125 reportSettingsProblem(Log.WARN, msg); 9126 } 9127 } 9128 9129 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9130 // This package wants to adopt ownership of permissions from 9131 // another package. 9132 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9133 final String origName = pkg.mAdoptPermissions.get(i); 9134 final PackageSetting orig = mSettings.getPackageLPr(origName); 9135 if (orig != null) { 9136 if (verifyPackageUpdateLPr(orig, pkg)) { 9137 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9138 + pkg.packageName); 9139 // SIDE EFFECTS; updates permissions system state; move elsewhere 9140 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9141 } 9142 } 9143 } 9144 } 9145 } 9146 9147 pkg.applicationInfo.processName = fixProcessName( 9148 pkg.applicationInfo.packageName, 9149 pkg.applicationInfo.processName); 9150 9151 if (pkg != mPlatformPackage) { 9152 // Get all of our default paths setup 9153 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9154 } 9155 9156 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9157 9158 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9159 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9161 derivePackageAbi( 9162 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9163 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9164 9165 // Some system apps still use directory structure for native libraries 9166 // in which case we might end up not detecting abi solely based on apk 9167 // structure. Try to detect abi based on directory structure. 9168 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9169 pkg.applicationInfo.primaryCpuAbi == null) { 9170 setBundledAppAbisAndRoots(pkg, pkgSetting); 9171 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9172 } 9173 } else { 9174 // This is not a first boot or an upgrade, don't bother deriving the 9175 // ABI during the scan. Instead, trust the value that was stored in the 9176 // package setting. 9177 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9178 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9179 9180 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9181 9182 if (DEBUG_ABI_SELECTION) { 9183 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9184 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9185 pkg.applicationInfo.secondaryCpuAbi); 9186 } 9187 } 9188 } else { 9189 if ((scanFlags & SCAN_MOVE) != 0) { 9190 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9191 // but we already have this packages package info in the PackageSetting. We just 9192 // use that and derive the native library path based on the new codepath. 9193 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9194 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9195 } 9196 9197 // Set native library paths again. For moves, the path will be updated based on the 9198 // ABIs we've determined above. For non-moves, the path will be updated based on the 9199 // ABIs we determined during compilation, but the path will depend on the final 9200 // package path (after the rename away from the stage path). 9201 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9202 } 9203 9204 // This is a special case for the "system" package, where the ABI is 9205 // dictated by the zygote configuration (and init.rc). We should keep track 9206 // of this ABI so that we can deal with "normal" applications that run under 9207 // the same UID correctly. 9208 if (mPlatformPackage == pkg) { 9209 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9210 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9211 } 9212 9213 // If there's a mismatch between the abi-override in the package setting 9214 // and the abiOverride specified for the install. Warn about this because we 9215 // would've already compiled the app without taking the package setting into 9216 // account. 9217 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9218 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9219 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9220 " for package " + pkg.packageName); 9221 } 9222 } 9223 9224 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9225 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9226 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9227 9228 // Copy the derived override back to the parsed package, so that we can 9229 // update the package settings accordingly. 9230 pkg.cpuAbiOverride = cpuAbiOverride; 9231 9232 if (DEBUG_ABI_SELECTION) { 9233 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9234 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9235 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9236 } 9237 9238 // Push the derived path down into PackageSettings so we know what to 9239 // clean up at uninstall time. 9240 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9241 9242 if (DEBUG_ABI_SELECTION) { 9243 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9244 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9245 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9246 } 9247 9248 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9249 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9250 // We don't do this here during boot because we can do it all 9251 // at once after scanning all existing packages. 9252 // 9253 // We also do this *before* we perform dexopt on this package, so that 9254 // we can avoid redundant dexopts, and also to make sure we've got the 9255 // code and package path correct. 9256 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9257 } 9258 9259 if (mFactoryTest && pkg.requestedPermissions.contains( 9260 android.Manifest.permission.FACTORY_TEST)) { 9261 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9262 } 9263 9264 if (isSystemApp(pkg)) { 9265 pkgSetting.isOrphaned = true; 9266 } 9267 9268 // Take care of first install / last update times. 9269 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9270 if (currentTime != 0) { 9271 if (pkgSetting.firstInstallTime == 0) { 9272 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9273 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9274 pkgSetting.lastUpdateTime = currentTime; 9275 } 9276 } else if (pkgSetting.firstInstallTime == 0) { 9277 // We need *something*. Take time time stamp of the file. 9278 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9279 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9280 if (scanFileTime != pkgSetting.timeStamp) { 9281 // A package on the system image has changed; consider this 9282 // to be an update. 9283 pkgSetting.lastUpdateTime = scanFileTime; 9284 } 9285 } 9286 pkgSetting.setTimeStamp(scanFileTime); 9287 9288 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9289 if (nonMutatedPs != null) { 9290 synchronized (mPackages) { 9291 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9292 } 9293 } 9294 } else { 9295 // Modify state for the given package setting 9296 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9297 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9298 if (isEphemeral(pkg)) { 9299 final int userId = user == null ? 0 : user.getIdentifier(); 9300 mEphemeralApplicationRegistry.addEphemeralAppLPw(userId, pkgSetting.appId); 9301 } 9302 } 9303 return pkg; 9304 } 9305 9306 /** 9307 * Applies policy to the parsed package based upon the given policy flags. 9308 * Ensures the package is in a good state. 9309 * <p> 9310 * Implementation detail: This method must NOT have any side effect. It would 9311 * ideally be static, but, it requires locks to read system state. 9312 */ 9313 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9314 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9315 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9316 if (pkg.applicationInfo.isDirectBootAware()) { 9317 // we're direct boot aware; set for all components 9318 for (PackageParser.Service s : pkg.services) { 9319 s.info.encryptionAware = s.info.directBootAware = true; 9320 } 9321 for (PackageParser.Provider p : pkg.providers) { 9322 p.info.encryptionAware = p.info.directBootAware = true; 9323 } 9324 for (PackageParser.Activity a : pkg.activities) { 9325 a.info.encryptionAware = a.info.directBootAware = true; 9326 } 9327 for (PackageParser.Activity r : pkg.receivers) { 9328 r.info.encryptionAware = r.info.directBootAware = true; 9329 } 9330 } 9331 } else { 9332 // Only allow system apps to be flagged as core apps. 9333 pkg.coreApp = false; 9334 // clear flags not applicable to regular apps 9335 pkg.applicationInfo.privateFlags &= 9336 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9337 pkg.applicationInfo.privateFlags &= 9338 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9339 } 9340 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9341 9342 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9343 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9344 } 9345 9346 if (!isSystemApp(pkg)) { 9347 // Only system apps can use these features. 9348 pkg.mOriginalPackages = null; 9349 pkg.mRealPackage = null; 9350 pkg.mAdoptPermissions = null; 9351 } 9352 } 9353 9354 /** 9355 * Asserts the parsed package is valid according to the given policy. If the 9356 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9357 * <p> 9358 * Implementation detail: This method must NOT have any side effects. It would 9359 * ideally be static, but, it requires locks to read system state. 9360 * 9361 * @throws PackageManagerException If the package fails any of the validation checks 9362 */ 9363 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9364 throws PackageManagerException { 9365 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9366 assertCodePolicy(pkg); 9367 } 9368 9369 if (pkg.applicationInfo.getCodePath() == null || 9370 pkg.applicationInfo.getResourcePath() == null) { 9371 // Bail out. The resource and code paths haven't been set. 9372 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9373 "Code and resource paths haven't been set correctly"); 9374 } 9375 9376 // Make sure we're not adding any bogus keyset info 9377 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9378 ksms.assertScannedPackageValid(pkg); 9379 9380 synchronized (mPackages) { 9381 // The special "android" package can only be defined once 9382 if (pkg.packageName.equals("android")) { 9383 if (mAndroidApplication != null) { 9384 Slog.w(TAG, "*************************************************"); 9385 Slog.w(TAG, "Core android package being redefined. Skipping."); 9386 Slog.w(TAG, " codePath=" + pkg.codePath); 9387 Slog.w(TAG, "*************************************************"); 9388 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9389 "Core android package being redefined. Skipping."); 9390 } 9391 } 9392 9393 // A package name must be unique; don't allow duplicates 9394 if (mPackages.containsKey(pkg.packageName)) { 9395 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9396 "Application package " + pkg.packageName 9397 + " already installed. Skipping duplicate."); 9398 } 9399 9400 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9401 // Static libs have a synthetic package name containing the version 9402 // but we still want the base name to be unique. 9403 if (mPackages.containsKey(pkg.manifestPackageName)) { 9404 throw new PackageManagerException( 9405 "Duplicate static shared lib provider package"); 9406 } 9407 9408 // Static shared libraries should have at least O target SDK 9409 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9410 throw new PackageManagerException( 9411 "Packages declaring static-shared libs must target O SDK or higher"); 9412 } 9413 9414 // Package declaring static a shared lib cannot be ephemeral 9415 if (pkg.applicationInfo.isEphemeralApp()) { 9416 throw new PackageManagerException( 9417 "Packages declaring static-shared libs cannot be ephemeral"); 9418 } 9419 9420 // Package declaring static a shared lib cannot be renamed since the package 9421 // name is synthetic and apps can't code around package manager internals. 9422 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9423 throw new PackageManagerException( 9424 "Packages declaring static-shared libs cannot be renamed"); 9425 } 9426 9427 // Package declaring static a shared lib cannot declare child packages 9428 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9429 throw new PackageManagerException( 9430 "Packages declaring static-shared libs cannot have child packages"); 9431 } 9432 9433 // Package declaring static a shared lib cannot declare dynamic libs 9434 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9435 throw new PackageManagerException( 9436 "Packages declaring static-shared libs cannot declare dynamic libs"); 9437 } 9438 9439 // Package declaring static a shared lib cannot declare shared users 9440 if (pkg.mSharedUserId != null) { 9441 throw new PackageManagerException( 9442 "Packages declaring static-shared libs cannot declare shared users"); 9443 } 9444 9445 // Static shared libs cannot declare activities 9446 if (!pkg.activities.isEmpty()) { 9447 throw new PackageManagerException( 9448 "Static shared libs cannot declare activities"); 9449 } 9450 9451 // Static shared libs cannot declare services 9452 if (!pkg.services.isEmpty()) { 9453 throw new PackageManagerException( 9454 "Static shared libs cannot declare services"); 9455 } 9456 9457 // Static shared libs cannot declare providers 9458 if (!pkg.providers.isEmpty()) { 9459 throw new PackageManagerException( 9460 "Static shared libs cannot declare content providers"); 9461 } 9462 9463 // Static shared libs cannot declare receivers 9464 if (!pkg.receivers.isEmpty()) { 9465 throw new PackageManagerException( 9466 "Static shared libs cannot declare broadcast receivers"); 9467 } 9468 9469 // Static shared libs cannot declare permission groups 9470 if (!pkg.permissionGroups.isEmpty()) { 9471 throw new PackageManagerException( 9472 "Static shared libs cannot declare permission groups"); 9473 } 9474 9475 // Static shared libs cannot declare permissions 9476 if (!pkg.permissions.isEmpty()) { 9477 throw new PackageManagerException( 9478 "Static shared libs cannot declare permissions"); 9479 } 9480 9481 // Static shared libs cannot declare protected broadcasts 9482 if (pkg.protectedBroadcasts != null) { 9483 throw new PackageManagerException( 9484 "Static shared libs cannot declare protected broadcasts"); 9485 } 9486 9487 // Static shared libs cannot be overlay targets 9488 if (pkg.mOverlayTarget != null) { 9489 throw new PackageManagerException( 9490 "Static shared libs cannot be overlay targets"); 9491 } 9492 9493 // The version codes must be ordered as lib versions 9494 int minVersionCode = Integer.MIN_VALUE; 9495 int maxVersionCode = Integer.MAX_VALUE; 9496 9497 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9498 pkg.staticSharedLibName); 9499 if (versionedLib != null) { 9500 final int versionCount = versionedLib.size(); 9501 for (int i = 0; i < versionCount; i++) { 9502 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9503 // TODO: We will change version code to long, so in the new API it is long 9504 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9505 .getVersionCode(); 9506 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9507 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9508 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9509 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9510 } else { 9511 minVersionCode = maxVersionCode = libVersionCode; 9512 break; 9513 } 9514 } 9515 } 9516 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9517 throw new PackageManagerException("Static shared" 9518 + " lib version codes must be ordered as lib versions"); 9519 } 9520 } 9521 9522 // Only privileged apps and updated privileged apps can add child packages. 9523 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9524 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9525 throw new PackageManagerException("Only privileged apps can add child " 9526 + "packages. Ignoring package " + pkg.packageName); 9527 } 9528 final int childCount = pkg.childPackages.size(); 9529 for (int i = 0; i < childCount; i++) { 9530 PackageParser.Package childPkg = pkg.childPackages.get(i); 9531 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9532 childPkg.packageName)) { 9533 throw new PackageManagerException("Can't override child of " 9534 + "another disabled app. Ignoring package " + pkg.packageName); 9535 } 9536 } 9537 } 9538 9539 // If we're only installing presumed-existing packages, require that the 9540 // scanned APK is both already known and at the path previously established 9541 // for it. Previously unknown packages we pick up normally, but if we have an 9542 // a priori expectation about this package's install presence, enforce it. 9543 // With a singular exception for new system packages. When an OTA contains 9544 // a new system package, we allow the codepath to change from a system location 9545 // to the user-installed location. If we don't allow this change, any newer, 9546 // user-installed version of the application will be ignored. 9547 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9548 if (mExpectingBetter.containsKey(pkg.packageName)) { 9549 logCriticalInfo(Log.WARN, 9550 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9551 } else { 9552 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9553 if (known != null) { 9554 if (DEBUG_PACKAGE_SCANNING) { 9555 Log.d(TAG, "Examining " + pkg.codePath 9556 + " and requiring known paths " + known.codePathString 9557 + " & " + known.resourcePathString); 9558 } 9559 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9560 || !pkg.applicationInfo.getResourcePath().equals( 9561 known.resourcePathString)) { 9562 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9563 "Application package " + pkg.packageName 9564 + " found at " + pkg.applicationInfo.getCodePath() 9565 + " but expected at " + known.codePathString 9566 + "; ignoring."); 9567 } 9568 } 9569 } 9570 } 9571 9572 // Verify that this new package doesn't have any content providers 9573 // that conflict with existing packages. Only do this if the 9574 // package isn't already installed, since we don't want to break 9575 // things that are installed. 9576 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9577 final int N = pkg.providers.size(); 9578 int i; 9579 for (i=0; i<N; i++) { 9580 PackageParser.Provider p = pkg.providers.get(i); 9581 if (p.info.authority != null) { 9582 String names[] = p.info.authority.split(";"); 9583 for (int j = 0; j < names.length; j++) { 9584 if (mProvidersByAuthority.containsKey(names[j])) { 9585 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9586 final String otherPackageName = 9587 ((other != null && other.getComponentName() != null) ? 9588 other.getComponentName().getPackageName() : "?"); 9589 throw new PackageManagerException( 9590 INSTALL_FAILED_CONFLICTING_PROVIDER, 9591 "Can't install because provider name " + names[j] 9592 + " (in package " + pkg.applicationInfo.packageName 9593 + ") is already used by " + otherPackageName); 9594 } 9595 } 9596 } 9597 } 9598 } 9599 } 9600 } 9601 9602 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9603 int type, String declaringPackageName, int declaringVersionCode) { 9604 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9605 if (versionedLib == null) { 9606 versionedLib = new SparseArray<>(); 9607 mSharedLibraries.put(name, versionedLib); 9608 if (type == SharedLibraryInfo.TYPE_STATIC) { 9609 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9610 } 9611 } else if (versionedLib.indexOfKey(version) >= 0) { 9612 return false; 9613 } 9614 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9615 version, type, declaringPackageName, declaringVersionCode); 9616 versionedLib.put(version, libEntry); 9617 return true; 9618 } 9619 9620 private boolean removeSharedLibraryLPw(String name, int version) { 9621 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9622 if (versionedLib == null) { 9623 return false; 9624 } 9625 final int libIdx = versionedLib.indexOfKey(version); 9626 if (libIdx < 0) { 9627 return false; 9628 } 9629 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9630 versionedLib.remove(version); 9631 if (versionedLib.size() <= 0) { 9632 mSharedLibraries.remove(name); 9633 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9634 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9635 .getPackageName()); 9636 } 9637 } 9638 return true; 9639 } 9640 9641 /** 9642 * Adds a scanned package to the system. When this method is finished, the package will 9643 * be available for query, resolution, etc... 9644 */ 9645 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9646 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9647 final String pkgName = pkg.packageName; 9648 if (mCustomResolverComponentName != null && 9649 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9650 setUpCustomResolverActivity(pkg); 9651 } 9652 9653 if (pkg.packageName.equals("android")) { 9654 synchronized (mPackages) { 9655 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9656 // Set up information for our fall-back user intent resolution activity. 9657 mPlatformPackage = pkg; 9658 pkg.mVersionCode = mSdkVersion; 9659 mAndroidApplication = pkg.applicationInfo; 9660 9661 if (!mResolverReplaced) { 9662 mResolveActivity.applicationInfo = mAndroidApplication; 9663 mResolveActivity.name = ResolverActivity.class.getName(); 9664 mResolveActivity.packageName = mAndroidApplication.packageName; 9665 mResolveActivity.processName = "system:ui"; 9666 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9667 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9668 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9669 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9670 mResolveActivity.exported = true; 9671 mResolveActivity.enabled = true; 9672 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9673 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9674 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9675 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9676 | ActivityInfo.CONFIG_ORIENTATION 9677 | ActivityInfo.CONFIG_KEYBOARD 9678 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9679 mResolveInfo.activityInfo = mResolveActivity; 9680 mResolveInfo.priority = 0; 9681 mResolveInfo.preferredOrder = 0; 9682 mResolveInfo.match = 0; 9683 mResolveComponentName = new ComponentName( 9684 mAndroidApplication.packageName, mResolveActivity.name); 9685 } 9686 } 9687 } 9688 } 9689 9690 ArrayList<PackageParser.Package> clientLibPkgs = null; 9691 // writer 9692 synchronized (mPackages) { 9693 boolean hasStaticSharedLibs = false; 9694 9695 // Any app can add new static shared libraries 9696 if (pkg.staticSharedLibName != null) { 9697 // Static shared libs don't allow renaming as they have synthetic package 9698 // names to allow install of multiple versions, so use name from manifest. 9699 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9700 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9701 pkg.manifestPackageName, pkg.mVersionCode)) { 9702 hasStaticSharedLibs = true; 9703 } else { 9704 Slog.w(TAG, "Package " + pkg.packageName + " library " 9705 + pkg.staticSharedLibName + " already exists; skipping"); 9706 } 9707 // Static shared libs cannot be updated once installed since they 9708 // use synthetic package name which includes the version code, so 9709 // not need to update other packages's shared lib dependencies. 9710 } 9711 9712 if (!hasStaticSharedLibs 9713 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9714 // Only system apps can add new dynamic shared libraries. 9715 if (pkg.libraryNames != null) { 9716 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9717 String name = pkg.libraryNames.get(i); 9718 boolean allowed = false; 9719 if (pkg.isUpdatedSystemApp()) { 9720 // New library entries can only be added through the 9721 // system image. This is important to get rid of a lot 9722 // of nasty edge cases: for example if we allowed a non- 9723 // system update of the app to add a library, then uninstalling 9724 // the update would make the library go away, and assumptions 9725 // we made such as through app install filtering would now 9726 // have allowed apps on the device which aren't compatible 9727 // with it. Better to just have the restriction here, be 9728 // conservative, and create many fewer cases that can negatively 9729 // impact the user experience. 9730 final PackageSetting sysPs = mSettings 9731 .getDisabledSystemPkgLPr(pkg.packageName); 9732 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9733 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9734 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9735 allowed = true; 9736 break; 9737 } 9738 } 9739 } 9740 } else { 9741 allowed = true; 9742 } 9743 if (allowed) { 9744 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9745 SharedLibraryInfo.VERSION_UNDEFINED, 9746 SharedLibraryInfo.TYPE_DYNAMIC, 9747 pkg.packageName, pkg.mVersionCode)) { 9748 Slog.w(TAG, "Package " + pkg.packageName + " library " 9749 + name + " already exists; skipping"); 9750 } 9751 } else { 9752 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9753 + name + " that is not declared on system image; skipping"); 9754 } 9755 } 9756 9757 if ((scanFlags & SCAN_BOOTING) == 0) { 9758 // If we are not booting, we need to update any applications 9759 // that are clients of our shared library. If we are booting, 9760 // this will all be done once the scan is complete. 9761 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9762 } 9763 } 9764 } 9765 } 9766 9767 if ((scanFlags & SCAN_BOOTING) != 0) { 9768 // No apps can run during boot scan, so they don't need to be frozen 9769 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9770 // Caller asked to not kill app, so it's probably not frozen 9771 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9772 // Caller asked us to ignore frozen check for some reason; they 9773 // probably didn't know the package name 9774 } else { 9775 // We're doing major surgery on this package, so it better be frozen 9776 // right now to keep it from launching 9777 checkPackageFrozen(pkgName); 9778 } 9779 9780 // Also need to kill any apps that are dependent on the library. 9781 if (clientLibPkgs != null) { 9782 for (int i=0; i<clientLibPkgs.size(); i++) { 9783 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9784 killApplication(clientPkg.applicationInfo.packageName, 9785 clientPkg.applicationInfo.uid, "update lib"); 9786 } 9787 } 9788 9789 // writer 9790 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9791 9792 boolean createIdmapFailed = false; 9793 synchronized (mPackages) { 9794 // We don't expect installation to fail beyond this point 9795 9796 if (pkgSetting.pkg != null) { 9797 // Note that |user| might be null during the initial boot scan. If a codePath 9798 // for an app has changed during a boot scan, it's due to an app update that's 9799 // part of the system partition and marker changes must be applied to all users. 9800 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9801 final int[] userIds = resolveUserIds(userId); 9802 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9803 } 9804 9805 // Add the new setting to mSettings 9806 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9807 // Add the new setting to mPackages 9808 mPackages.put(pkg.applicationInfo.packageName, pkg); 9809 // Make sure we don't accidentally delete its data. 9810 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9811 while (iter.hasNext()) { 9812 PackageCleanItem item = iter.next(); 9813 if (pkgName.equals(item.packageName)) { 9814 iter.remove(); 9815 } 9816 } 9817 9818 // Add the package's KeySets to the global KeySetManagerService 9819 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9820 ksms.addScannedPackageLPw(pkg); 9821 9822 int N = pkg.providers.size(); 9823 StringBuilder r = null; 9824 int i; 9825 for (i=0; i<N; i++) { 9826 PackageParser.Provider p = pkg.providers.get(i); 9827 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9828 p.info.processName); 9829 mProviders.addProvider(p); 9830 p.syncable = p.info.isSyncable; 9831 if (p.info.authority != null) { 9832 String names[] = p.info.authority.split(";"); 9833 p.info.authority = null; 9834 for (int j = 0; j < names.length; j++) { 9835 if (j == 1 && p.syncable) { 9836 // We only want the first authority for a provider to possibly be 9837 // syncable, so if we already added this provider using a different 9838 // authority clear the syncable flag. We copy the provider before 9839 // changing it because the mProviders object contains a reference 9840 // to a provider that we don't want to change. 9841 // Only do this for the second authority since the resulting provider 9842 // object can be the same for all future authorities for this provider. 9843 p = new PackageParser.Provider(p); 9844 p.syncable = false; 9845 } 9846 if (!mProvidersByAuthority.containsKey(names[j])) { 9847 mProvidersByAuthority.put(names[j], p); 9848 if (p.info.authority == null) { 9849 p.info.authority = names[j]; 9850 } else { 9851 p.info.authority = p.info.authority + ";" + names[j]; 9852 } 9853 if (DEBUG_PACKAGE_SCANNING) { 9854 if (chatty) 9855 Log.d(TAG, "Registered content provider: " + names[j] 9856 + ", className = " + p.info.name + ", isSyncable = " 9857 + p.info.isSyncable); 9858 } 9859 } else { 9860 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9861 Slog.w(TAG, "Skipping provider name " + names[j] + 9862 " (in package " + pkg.applicationInfo.packageName + 9863 "): name already used by " 9864 + ((other != null && other.getComponentName() != null) 9865 ? other.getComponentName().getPackageName() : "?")); 9866 } 9867 } 9868 } 9869 if (chatty) { 9870 if (r == null) { 9871 r = new StringBuilder(256); 9872 } else { 9873 r.append(' '); 9874 } 9875 r.append(p.info.name); 9876 } 9877 } 9878 if (r != null) { 9879 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9880 } 9881 9882 N = pkg.services.size(); 9883 r = null; 9884 for (i=0; i<N; i++) { 9885 PackageParser.Service s = pkg.services.get(i); 9886 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9887 s.info.processName); 9888 mServices.addService(s); 9889 if (chatty) { 9890 if (r == null) { 9891 r = new StringBuilder(256); 9892 } else { 9893 r.append(' '); 9894 } 9895 r.append(s.info.name); 9896 } 9897 } 9898 if (r != null) { 9899 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9900 } 9901 9902 N = pkg.receivers.size(); 9903 r = null; 9904 for (i=0; i<N; i++) { 9905 PackageParser.Activity a = pkg.receivers.get(i); 9906 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9907 a.info.processName); 9908 mReceivers.addActivity(a, "receiver"); 9909 if (chatty) { 9910 if (r == null) { 9911 r = new StringBuilder(256); 9912 } else { 9913 r.append(' '); 9914 } 9915 r.append(a.info.name); 9916 } 9917 } 9918 if (r != null) { 9919 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9920 } 9921 9922 N = pkg.activities.size(); 9923 r = null; 9924 for (i=0; i<N; i++) { 9925 PackageParser.Activity a = pkg.activities.get(i); 9926 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9927 a.info.processName); 9928 mActivities.addActivity(a, "activity"); 9929 if (chatty) { 9930 if (r == null) { 9931 r = new StringBuilder(256); 9932 } else { 9933 r.append(' '); 9934 } 9935 r.append(a.info.name); 9936 } 9937 } 9938 if (r != null) { 9939 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9940 } 9941 9942 N = pkg.permissionGroups.size(); 9943 r = null; 9944 for (i=0; i<N; i++) { 9945 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9946 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9947 final String curPackageName = cur == null ? null : cur.info.packageName; 9948 // Dont allow ephemeral apps to define new permission groups. 9949 if (pkg.applicationInfo.isEphemeralApp()) { 9950 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9951 + pg.info.packageName 9952 + " ignored: ephemeral apps cannot define new permission groups."); 9953 continue; 9954 } 9955 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9956 if (cur == null || isPackageUpdate) { 9957 mPermissionGroups.put(pg.info.name, pg); 9958 if (chatty) { 9959 if (r == null) { 9960 r = new StringBuilder(256); 9961 } else { 9962 r.append(' '); 9963 } 9964 if (isPackageUpdate) { 9965 r.append("UPD:"); 9966 } 9967 r.append(pg.info.name); 9968 } 9969 } else { 9970 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9971 + pg.info.packageName + " ignored: original from " 9972 + cur.info.packageName); 9973 if (chatty) { 9974 if (r == null) { 9975 r = new StringBuilder(256); 9976 } else { 9977 r.append(' '); 9978 } 9979 r.append("DUP:"); 9980 r.append(pg.info.name); 9981 } 9982 } 9983 } 9984 if (r != null) { 9985 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9986 } 9987 9988 N = pkg.permissions.size(); 9989 r = null; 9990 for (i=0; i<N; i++) { 9991 PackageParser.Permission p = pkg.permissions.get(i); 9992 9993 // Dont allow ephemeral apps to define new permissions. 9994 if (pkg.applicationInfo.isEphemeralApp()) { 9995 Slog.w(TAG, "Permission " + p.info.name + " from package " 9996 + p.info.packageName 9997 + " ignored: ephemeral apps cannot define new permissions."); 9998 continue; 9999 } 10000 10001 // Assume by default that we did not install this permission into the system. 10002 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10003 10004 // Now that permission groups have a special meaning, we ignore permission 10005 // groups for legacy apps to prevent unexpected behavior. In particular, 10006 // permissions for one app being granted to someone just becase they happen 10007 // to be in a group defined by another app (before this had no implications). 10008 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10009 p.group = mPermissionGroups.get(p.info.group); 10010 // Warn for a permission in an unknown group. 10011 if (p.info.group != null && p.group == null) { 10012 Slog.w(TAG, "Permission " + p.info.name + " from package " 10013 + p.info.packageName + " in an unknown group " + p.info.group); 10014 } 10015 } 10016 10017 ArrayMap<String, BasePermission> permissionMap = 10018 p.tree ? mSettings.mPermissionTrees 10019 : mSettings.mPermissions; 10020 BasePermission bp = permissionMap.get(p.info.name); 10021 10022 // Allow system apps to redefine non-system permissions 10023 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10024 final boolean currentOwnerIsSystem = (bp.perm != null 10025 && isSystemApp(bp.perm.owner)); 10026 if (isSystemApp(p.owner)) { 10027 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10028 // It's a built-in permission and no owner, take ownership now 10029 bp.packageSetting = pkgSetting; 10030 bp.perm = p; 10031 bp.uid = pkg.applicationInfo.uid; 10032 bp.sourcePackage = p.info.packageName; 10033 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10034 } else if (!currentOwnerIsSystem) { 10035 String msg = "New decl " + p.owner + " of permission " 10036 + p.info.name + " is system; overriding " + bp.sourcePackage; 10037 reportSettingsProblem(Log.WARN, msg); 10038 bp = null; 10039 } 10040 } 10041 } 10042 10043 if (bp == null) { 10044 bp = new BasePermission(p.info.name, p.info.packageName, 10045 BasePermission.TYPE_NORMAL); 10046 permissionMap.put(p.info.name, bp); 10047 } 10048 10049 if (bp.perm == null) { 10050 if (bp.sourcePackage == null 10051 || bp.sourcePackage.equals(p.info.packageName)) { 10052 BasePermission tree = findPermissionTreeLP(p.info.name); 10053 if (tree == null 10054 || tree.sourcePackage.equals(p.info.packageName)) { 10055 bp.packageSetting = pkgSetting; 10056 bp.perm = p; 10057 bp.uid = pkg.applicationInfo.uid; 10058 bp.sourcePackage = p.info.packageName; 10059 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10060 if (chatty) { 10061 if (r == null) { 10062 r = new StringBuilder(256); 10063 } else { 10064 r.append(' '); 10065 } 10066 r.append(p.info.name); 10067 } 10068 } else { 10069 Slog.w(TAG, "Permission " + p.info.name + " from package " 10070 + p.info.packageName + " ignored: base tree " 10071 + tree.name + " is from package " 10072 + tree.sourcePackage); 10073 } 10074 } else { 10075 Slog.w(TAG, "Permission " + p.info.name + " from package " 10076 + p.info.packageName + " ignored: original from " 10077 + bp.sourcePackage); 10078 } 10079 } else if (chatty) { 10080 if (r == null) { 10081 r = new StringBuilder(256); 10082 } else { 10083 r.append(' '); 10084 } 10085 r.append("DUP:"); 10086 r.append(p.info.name); 10087 } 10088 if (bp.perm == p) { 10089 bp.protectionLevel = p.info.protectionLevel; 10090 } 10091 } 10092 10093 if (r != null) { 10094 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10095 } 10096 10097 N = pkg.instrumentation.size(); 10098 r = null; 10099 for (i=0; i<N; i++) { 10100 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10101 a.info.packageName = pkg.applicationInfo.packageName; 10102 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10103 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10104 a.info.splitNames = pkg.splitNames; 10105 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10106 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10107 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10108 a.info.dataDir = pkg.applicationInfo.dataDir; 10109 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10110 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10111 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10112 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10113 mInstrumentation.put(a.getComponentName(), a); 10114 if (chatty) { 10115 if (r == null) { 10116 r = new StringBuilder(256); 10117 } else { 10118 r.append(' '); 10119 } 10120 r.append(a.info.name); 10121 } 10122 } 10123 if (r != null) { 10124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10125 } 10126 10127 if (pkg.protectedBroadcasts != null) { 10128 N = pkg.protectedBroadcasts.size(); 10129 for (i=0; i<N; i++) { 10130 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10131 } 10132 } 10133 10134 // Create idmap files for pairs of (packages, overlay packages). 10135 // Note: "android", ie framework-res.apk, is handled by native layers. 10136 if (pkg.mOverlayTarget != null) { 10137 // This is an overlay package. 10138 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10139 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10140 mOverlays.put(pkg.mOverlayTarget, 10141 new ArrayMap<String, PackageParser.Package>()); 10142 } 10143 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10144 map.put(pkg.packageName, pkg); 10145 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10146 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10147 createIdmapFailed = true; 10148 } 10149 } 10150 } else if (mOverlays.containsKey(pkg.packageName) && 10151 !pkg.packageName.equals("android")) { 10152 // This is a regular package, with one or more known overlay packages. 10153 createIdmapsForPackageLI(pkg); 10154 } 10155 } 10156 10157 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10158 10159 if (createIdmapFailed) { 10160 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10161 "scanPackageLI failed to createIdmap"); 10162 } 10163 } 10164 10165 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10166 PackageParser.Package update, int[] userIds) { 10167 if (existing.applicationInfo == null || update.applicationInfo == null) { 10168 // This isn't due to an app installation. 10169 return; 10170 } 10171 10172 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10173 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10174 10175 // The codePath hasn't changed, so there's nothing for us to do. 10176 if (Objects.equals(oldCodePath, newCodePath)) { 10177 return; 10178 } 10179 10180 File canonicalNewCodePath; 10181 try { 10182 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10183 } catch (IOException e) { 10184 Slog.w(TAG, "Failed to get canonical path.", e); 10185 return; 10186 } 10187 10188 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10189 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10190 // that the last component of the path (i.e, the name) doesn't need canonicalization 10191 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10192 // but may change in the future. Hopefully this function won't exist at that point. 10193 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10194 oldCodePath.getName()); 10195 10196 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10197 // with "@". 10198 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10199 if (!oldMarkerPrefix.endsWith("@")) { 10200 oldMarkerPrefix += "@"; 10201 } 10202 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10203 if (!newMarkerPrefix.endsWith("@")) { 10204 newMarkerPrefix += "@"; 10205 } 10206 10207 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10208 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10209 for (String updatedPath : updatedPaths) { 10210 String updatedPathName = new File(updatedPath).getName(); 10211 markerSuffixes.add(updatedPathName.replace('/', '@')); 10212 } 10213 10214 for (int userId : userIds) { 10215 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10216 10217 for (String markerSuffix : markerSuffixes) { 10218 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10219 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10220 if (oldForeignUseMark.exists()) { 10221 try { 10222 Os.rename(oldForeignUseMark.getAbsolutePath(), 10223 newForeignUseMark.getAbsolutePath()); 10224 } catch (ErrnoException e) { 10225 Slog.w(TAG, "Failed to rename foreign use marker", e); 10226 oldForeignUseMark.delete(); 10227 } 10228 } 10229 } 10230 } 10231 } 10232 10233 /** 10234 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10235 * is derived purely on the basis of the contents of {@code scanFile} and 10236 * {@code cpuAbiOverride}. 10237 * 10238 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10239 */ 10240 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10241 String cpuAbiOverride, boolean extractLibs, 10242 File appLib32InstallDir) 10243 throws PackageManagerException { 10244 // Give ourselves some initial paths; we'll come back for another 10245 // pass once we've determined ABI below. 10246 setNativeLibraryPaths(pkg, appLib32InstallDir); 10247 10248 // We would never need to extract libs for forward-locked and external packages, 10249 // since the container service will do it for us. We shouldn't attempt to 10250 // extract libs from system app when it was not updated. 10251 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10252 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10253 extractLibs = false; 10254 } 10255 10256 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10257 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10258 10259 NativeLibraryHelper.Handle handle = null; 10260 try { 10261 handle = NativeLibraryHelper.Handle.create(pkg); 10262 // TODO(multiArch): This can be null for apps that didn't go through the 10263 // usual installation process. We can calculate it again, like we 10264 // do during install time. 10265 // 10266 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10267 // unnecessary. 10268 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10269 10270 // Null out the abis so that they can be recalculated. 10271 pkg.applicationInfo.primaryCpuAbi = null; 10272 pkg.applicationInfo.secondaryCpuAbi = null; 10273 if (isMultiArch(pkg.applicationInfo)) { 10274 // Warn if we've set an abiOverride for multi-lib packages.. 10275 // By definition, we need to copy both 32 and 64 bit libraries for 10276 // such packages. 10277 if (pkg.cpuAbiOverride != null 10278 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10279 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10280 } 10281 10282 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10283 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10284 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10285 if (extractLibs) { 10286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10287 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10288 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10289 useIsaSpecificSubdirs); 10290 } else { 10291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10292 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10293 } 10294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10295 } 10296 10297 maybeThrowExceptionForMultiArchCopy( 10298 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10299 10300 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10301 if (extractLibs) { 10302 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10303 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10304 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10305 useIsaSpecificSubdirs); 10306 } else { 10307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10308 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10309 } 10310 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10311 } 10312 10313 maybeThrowExceptionForMultiArchCopy( 10314 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10315 10316 if (abi64 >= 0) { 10317 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10318 } 10319 10320 if (abi32 >= 0) { 10321 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10322 if (abi64 >= 0) { 10323 if (pkg.use32bitAbi) { 10324 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10325 pkg.applicationInfo.primaryCpuAbi = abi; 10326 } else { 10327 pkg.applicationInfo.secondaryCpuAbi = abi; 10328 } 10329 } else { 10330 pkg.applicationInfo.primaryCpuAbi = abi; 10331 } 10332 } 10333 10334 } else { 10335 String[] abiList = (cpuAbiOverride != null) ? 10336 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10337 10338 // Enable gross and lame hacks for apps that are built with old 10339 // SDK tools. We must scan their APKs for renderscript bitcode and 10340 // not launch them if it's present. Don't bother checking on devices 10341 // that don't have 64 bit support. 10342 boolean needsRenderScriptOverride = false; 10343 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10344 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10345 abiList = Build.SUPPORTED_32_BIT_ABIS; 10346 needsRenderScriptOverride = true; 10347 } 10348 10349 final int copyRet; 10350 if (extractLibs) { 10351 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10352 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10353 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10354 } else { 10355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10356 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10357 } 10358 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10359 10360 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10361 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10362 "Error unpackaging native libs for app, errorCode=" + copyRet); 10363 } 10364 10365 if (copyRet >= 0) { 10366 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10367 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10368 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10369 } else if (needsRenderScriptOverride) { 10370 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10371 } 10372 } 10373 } catch (IOException ioe) { 10374 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10375 } finally { 10376 IoUtils.closeQuietly(handle); 10377 } 10378 10379 // Now that we've calculated the ABIs and determined if it's an internal app, 10380 // we will go ahead and populate the nativeLibraryPath. 10381 setNativeLibraryPaths(pkg, appLib32InstallDir); 10382 } 10383 10384 /** 10385 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10386 * i.e, so that all packages can be run inside a single process if required. 10387 * 10388 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10389 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10390 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10391 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10392 * updating a package that belongs to a shared user. 10393 * 10394 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10395 * adds unnecessary complexity. 10396 */ 10397 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10398 PackageParser.Package scannedPackage) { 10399 String requiredInstructionSet = null; 10400 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10401 requiredInstructionSet = VMRuntime.getInstructionSet( 10402 scannedPackage.applicationInfo.primaryCpuAbi); 10403 } 10404 10405 PackageSetting requirer = null; 10406 for (PackageSetting ps : packagesForUser) { 10407 // If packagesForUser contains scannedPackage, we skip it. This will happen 10408 // when scannedPackage is an update of an existing package. Without this check, 10409 // we will never be able to change the ABI of any package belonging to a shared 10410 // user, even if it's compatible with other packages. 10411 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10412 if (ps.primaryCpuAbiString == null) { 10413 continue; 10414 } 10415 10416 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10417 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10418 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10419 // this but there's not much we can do. 10420 String errorMessage = "Instruction set mismatch, " 10421 + ((requirer == null) ? "[caller]" : requirer) 10422 + " requires " + requiredInstructionSet + " whereas " + ps 10423 + " requires " + instructionSet; 10424 Slog.w(TAG, errorMessage); 10425 } 10426 10427 if (requiredInstructionSet == null) { 10428 requiredInstructionSet = instructionSet; 10429 requirer = ps; 10430 } 10431 } 10432 } 10433 10434 if (requiredInstructionSet != null) { 10435 String adjustedAbi; 10436 if (requirer != null) { 10437 // requirer != null implies that either scannedPackage was null or that scannedPackage 10438 // did not require an ABI, in which case we have to adjust scannedPackage to match 10439 // the ABI of the set (which is the same as requirer's ABI) 10440 adjustedAbi = requirer.primaryCpuAbiString; 10441 if (scannedPackage != null) { 10442 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10443 } 10444 } else { 10445 // requirer == null implies that we're updating all ABIs in the set to 10446 // match scannedPackage. 10447 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10448 } 10449 10450 for (PackageSetting ps : packagesForUser) { 10451 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10452 if (ps.primaryCpuAbiString != null) { 10453 continue; 10454 } 10455 10456 ps.primaryCpuAbiString = adjustedAbi; 10457 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10458 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10459 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10460 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10461 + " (requirer=" 10462 + (requirer == null ? "null" : requirer.pkg.packageName) 10463 + ", scannedPackage=" 10464 + (scannedPackage != null ? scannedPackage.packageName : "null") 10465 + ")"); 10466 try { 10467 mInstaller.rmdex(ps.codePathString, 10468 getDexCodeInstructionSet(getPreferredInstructionSet())); 10469 } catch (InstallerException ignored) { 10470 } 10471 } 10472 } 10473 } 10474 } 10475 } 10476 10477 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10478 synchronized (mPackages) { 10479 mResolverReplaced = true; 10480 // Set up information for custom user intent resolution activity. 10481 mResolveActivity.applicationInfo = pkg.applicationInfo; 10482 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10483 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10484 mResolveActivity.processName = pkg.applicationInfo.packageName; 10485 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10486 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10487 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10488 mResolveActivity.theme = 0; 10489 mResolveActivity.exported = true; 10490 mResolveActivity.enabled = true; 10491 mResolveInfo.activityInfo = mResolveActivity; 10492 mResolveInfo.priority = 0; 10493 mResolveInfo.preferredOrder = 0; 10494 mResolveInfo.match = 0; 10495 mResolveComponentName = mCustomResolverComponentName; 10496 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10497 mResolveComponentName); 10498 } 10499 } 10500 10501 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 10502 if (installerComponent == null) { 10503 if (DEBUG_EPHEMERAL) { 10504 Slog.d(TAG, "Clear ephemeral installer activity"); 10505 } 10506 mEphemeralInstallerActivity.applicationInfo = null; 10507 return; 10508 } 10509 10510 if (DEBUG_EPHEMERAL) { 10511 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10512 } 10513 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10514 // Set up information for ephemeral installer activity 10515 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 10516 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 10517 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 10518 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 10519 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10520 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10521 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10522 mEphemeralInstallerActivity.theme = 0; 10523 mEphemeralInstallerActivity.exported = true; 10524 mEphemeralInstallerActivity.enabled = true; 10525 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 10526 mEphemeralInstallerInfo.priority = 0; 10527 mEphemeralInstallerInfo.preferredOrder = 1; 10528 mEphemeralInstallerInfo.isDefault = true; 10529 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10530 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10531 } 10532 10533 private static String calculateBundledApkRoot(final String codePathString) { 10534 final File codePath = new File(codePathString); 10535 final File codeRoot; 10536 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10537 codeRoot = Environment.getRootDirectory(); 10538 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10539 codeRoot = Environment.getOemDirectory(); 10540 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10541 codeRoot = Environment.getVendorDirectory(); 10542 } else { 10543 // Unrecognized code path; take its top real segment as the apk root: 10544 // e.g. /something/app/blah.apk => /something 10545 try { 10546 File f = codePath.getCanonicalFile(); 10547 File parent = f.getParentFile(); // non-null because codePath is a file 10548 File tmp; 10549 while ((tmp = parent.getParentFile()) != null) { 10550 f = parent; 10551 parent = tmp; 10552 } 10553 codeRoot = f; 10554 Slog.w(TAG, "Unrecognized code path " 10555 + codePath + " - using " + codeRoot); 10556 } catch (IOException e) { 10557 // Can't canonicalize the code path -- shenanigans? 10558 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10559 return Environment.getRootDirectory().getPath(); 10560 } 10561 } 10562 return codeRoot.getPath(); 10563 } 10564 10565 /** 10566 * Derive and set the location of native libraries for the given package, 10567 * which varies depending on where and how the package was installed. 10568 */ 10569 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10570 final ApplicationInfo info = pkg.applicationInfo; 10571 final String codePath = pkg.codePath; 10572 final File codeFile = new File(codePath); 10573 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10574 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10575 10576 info.nativeLibraryRootDir = null; 10577 info.nativeLibraryRootRequiresIsa = false; 10578 info.nativeLibraryDir = null; 10579 info.secondaryNativeLibraryDir = null; 10580 10581 if (isApkFile(codeFile)) { 10582 // Monolithic install 10583 if (bundledApp) { 10584 // If "/system/lib64/apkname" exists, assume that is the per-package 10585 // native library directory to use; otherwise use "/system/lib/apkname". 10586 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10587 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10588 getPrimaryInstructionSet(info)); 10589 10590 // This is a bundled system app so choose the path based on the ABI. 10591 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10592 // is just the default path. 10593 final String apkName = deriveCodePathName(codePath); 10594 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10595 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10596 apkName).getAbsolutePath(); 10597 10598 if (info.secondaryCpuAbi != null) { 10599 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10600 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10601 secondaryLibDir, apkName).getAbsolutePath(); 10602 } 10603 } else if (asecApp) { 10604 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10605 .getAbsolutePath(); 10606 } else { 10607 final String apkName = deriveCodePathName(codePath); 10608 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10609 .getAbsolutePath(); 10610 } 10611 10612 info.nativeLibraryRootRequiresIsa = false; 10613 info.nativeLibraryDir = info.nativeLibraryRootDir; 10614 } else { 10615 // Cluster install 10616 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10617 info.nativeLibraryRootRequiresIsa = true; 10618 10619 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10620 getPrimaryInstructionSet(info)).getAbsolutePath(); 10621 10622 if (info.secondaryCpuAbi != null) { 10623 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10624 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10625 } 10626 } 10627 } 10628 10629 /** 10630 * Calculate the abis and roots for a bundled app. These can uniquely 10631 * be determined from the contents of the system partition, i.e whether 10632 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10633 * of this information, and instead assume that the system was built 10634 * sensibly. 10635 */ 10636 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10637 PackageSetting pkgSetting) { 10638 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10639 10640 // If "/system/lib64/apkname" exists, assume that is the per-package 10641 // native library directory to use; otherwise use "/system/lib/apkname". 10642 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10643 setBundledAppAbi(pkg, apkRoot, apkName); 10644 // pkgSetting might be null during rescan following uninstall of updates 10645 // to a bundled app, so accommodate that possibility. The settings in 10646 // that case will be established later from the parsed package. 10647 // 10648 // If the settings aren't null, sync them up with what we've just derived. 10649 // note that apkRoot isn't stored in the package settings. 10650 if (pkgSetting != null) { 10651 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10652 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10653 } 10654 } 10655 10656 /** 10657 * Deduces the ABI of a bundled app and sets the relevant fields on the 10658 * parsed pkg object. 10659 * 10660 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10661 * under which system libraries are installed. 10662 * @param apkName the name of the installed package. 10663 */ 10664 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10665 final File codeFile = new File(pkg.codePath); 10666 10667 final boolean has64BitLibs; 10668 final boolean has32BitLibs; 10669 if (isApkFile(codeFile)) { 10670 // Monolithic install 10671 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10672 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10673 } else { 10674 // Cluster install 10675 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10676 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10677 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10678 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10679 has64BitLibs = (new File(rootDir, isa)).exists(); 10680 } else { 10681 has64BitLibs = false; 10682 } 10683 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10684 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10685 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10686 has32BitLibs = (new File(rootDir, isa)).exists(); 10687 } else { 10688 has32BitLibs = false; 10689 } 10690 } 10691 10692 if (has64BitLibs && !has32BitLibs) { 10693 // The package has 64 bit libs, but not 32 bit libs. Its primary 10694 // ABI should be 64 bit. We can safely assume here that the bundled 10695 // native libraries correspond to the most preferred ABI in the list. 10696 10697 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10698 pkg.applicationInfo.secondaryCpuAbi = null; 10699 } else if (has32BitLibs && !has64BitLibs) { 10700 // The package has 32 bit libs but not 64 bit libs. Its primary 10701 // ABI should be 32 bit. 10702 10703 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10704 pkg.applicationInfo.secondaryCpuAbi = null; 10705 } else if (has32BitLibs && has64BitLibs) { 10706 // The application has both 64 and 32 bit bundled libraries. We check 10707 // here that the app declares multiArch support, and warn if it doesn't. 10708 // 10709 // We will be lenient here and record both ABIs. The primary will be the 10710 // ABI that's higher on the list, i.e, a device that's configured to prefer 10711 // 64 bit apps will see a 64 bit primary ABI, 10712 10713 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10714 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10715 } 10716 10717 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10718 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10719 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10720 } else { 10721 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10722 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10723 } 10724 } else { 10725 pkg.applicationInfo.primaryCpuAbi = null; 10726 pkg.applicationInfo.secondaryCpuAbi = null; 10727 } 10728 } 10729 10730 private void killApplication(String pkgName, int appId, String reason) { 10731 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10732 } 10733 10734 private void killApplication(String pkgName, int appId, int userId, String reason) { 10735 // Request the ActivityManager to kill the process(only for existing packages) 10736 // so that we do not end up in a confused state while the user is still using the older 10737 // version of the application while the new one gets installed. 10738 final long token = Binder.clearCallingIdentity(); 10739 try { 10740 IActivityManager am = ActivityManager.getService(); 10741 if (am != null) { 10742 try { 10743 am.killApplication(pkgName, appId, userId, reason); 10744 } catch (RemoteException e) { 10745 } 10746 } 10747 } finally { 10748 Binder.restoreCallingIdentity(token); 10749 } 10750 } 10751 10752 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10753 // Remove the parent package setting 10754 PackageSetting ps = (PackageSetting) pkg.mExtras; 10755 if (ps != null) { 10756 removePackageLI(ps, chatty); 10757 } 10758 // Remove the child package setting 10759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10760 for (int i = 0; i < childCount; i++) { 10761 PackageParser.Package childPkg = pkg.childPackages.get(i); 10762 ps = (PackageSetting) childPkg.mExtras; 10763 if (ps != null) { 10764 removePackageLI(ps, chatty); 10765 } 10766 } 10767 } 10768 10769 void removePackageLI(PackageSetting ps, boolean chatty) { 10770 if (DEBUG_INSTALL) { 10771 if (chatty) 10772 Log.d(TAG, "Removing package " + ps.name); 10773 } 10774 10775 // writer 10776 synchronized (mPackages) { 10777 mPackages.remove(ps.name); 10778 final PackageParser.Package pkg = ps.pkg; 10779 if (pkg != null) { 10780 cleanPackageDataStructuresLILPw(pkg, chatty); 10781 } 10782 } 10783 } 10784 10785 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10786 if (DEBUG_INSTALL) { 10787 if (chatty) 10788 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10789 } 10790 10791 // writer 10792 synchronized (mPackages) { 10793 // Remove the parent package 10794 mPackages.remove(pkg.applicationInfo.packageName); 10795 cleanPackageDataStructuresLILPw(pkg, chatty); 10796 10797 // Remove the child packages 10798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10799 for (int i = 0; i < childCount; i++) { 10800 PackageParser.Package childPkg = pkg.childPackages.get(i); 10801 mPackages.remove(childPkg.applicationInfo.packageName); 10802 cleanPackageDataStructuresLILPw(childPkg, chatty); 10803 } 10804 } 10805 } 10806 10807 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10808 int N = pkg.providers.size(); 10809 StringBuilder r = null; 10810 int i; 10811 for (i=0; i<N; i++) { 10812 PackageParser.Provider p = pkg.providers.get(i); 10813 mProviders.removeProvider(p); 10814 if (p.info.authority == null) { 10815 10816 /* There was another ContentProvider with this authority when 10817 * this app was installed so this authority is null, 10818 * Ignore it as we don't have to unregister the provider. 10819 */ 10820 continue; 10821 } 10822 String names[] = p.info.authority.split(";"); 10823 for (int j = 0; j < names.length; j++) { 10824 if (mProvidersByAuthority.get(names[j]) == p) { 10825 mProvidersByAuthority.remove(names[j]); 10826 if (DEBUG_REMOVE) { 10827 if (chatty) 10828 Log.d(TAG, "Unregistered content provider: " + names[j] 10829 + ", className = " + p.info.name + ", isSyncable = " 10830 + p.info.isSyncable); 10831 } 10832 } 10833 } 10834 if (DEBUG_REMOVE && chatty) { 10835 if (r == null) { 10836 r = new StringBuilder(256); 10837 } else { 10838 r.append(' '); 10839 } 10840 r.append(p.info.name); 10841 } 10842 } 10843 if (r != null) { 10844 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10845 } 10846 10847 N = pkg.services.size(); 10848 r = null; 10849 for (i=0; i<N; i++) { 10850 PackageParser.Service s = pkg.services.get(i); 10851 mServices.removeService(s); 10852 if (chatty) { 10853 if (r == null) { 10854 r = new StringBuilder(256); 10855 } else { 10856 r.append(' '); 10857 } 10858 r.append(s.info.name); 10859 } 10860 } 10861 if (r != null) { 10862 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10863 } 10864 10865 N = pkg.receivers.size(); 10866 r = null; 10867 for (i=0; i<N; i++) { 10868 PackageParser.Activity a = pkg.receivers.get(i); 10869 mReceivers.removeActivity(a, "receiver"); 10870 if (DEBUG_REMOVE && chatty) { 10871 if (r == null) { 10872 r = new StringBuilder(256); 10873 } else { 10874 r.append(' '); 10875 } 10876 r.append(a.info.name); 10877 } 10878 } 10879 if (r != null) { 10880 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10881 } 10882 10883 N = pkg.activities.size(); 10884 r = null; 10885 for (i=0; i<N; i++) { 10886 PackageParser.Activity a = pkg.activities.get(i); 10887 mActivities.removeActivity(a, "activity"); 10888 if (DEBUG_REMOVE && chatty) { 10889 if (r == null) { 10890 r = new StringBuilder(256); 10891 } else { 10892 r.append(' '); 10893 } 10894 r.append(a.info.name); 10895 } 10896 } 10897 if (r != null) { 10898 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10899 } 10900 10901 N = pkg.permissions.size(); 10902 r = null; 10903 for (i=0; i<N; i++) { 10904 PackageParser.Permission p = pkg.permissions.get(i); 10905 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10906 if (bp == null) { 10907 bp = mSettings.mPermissionTrees.get(p.info.name); 10908 } 10909 if (bp != null && bp.perm == p) { 10910 bp.perm = null; 10911 if (DEBUG_REMOVE && chatty) { 10912 if (r == null) { 10913 r = new StringBuilder(256); 10914 } else { 10915 r.append(' '); 10916 } 10917 r.append(p.info.name); 10918 } 10919 } 10920 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10921 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10922 if (appOpPkgs != null) { 10923 appOpPkgs.remove(pkg.packageName); 10924 } 10925 } 10926 } 10927 if (r != null) { 10928 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10929 } 10930 10931 N = pkg.requestedPermissions.size(); 10932 r = null; 10933 for (i=0; i<N; i++) { 10934 String perm = pkg.requestedPermissions.get(i); 10935 BasePermission bp = mSettings.mPermissions.get(perm); 10936 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10937 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10938 if (appOpPkgs != null) { 10939 appOpPkgs.remove(pkg.packageName); 10940 if (appOpPkgs.isEmpty()) { 10941 mAppOpPermissionPackages.remove(perm); 10942 } 10943 } 10944 } 10945 } 10946 if (r != null) { 10947 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10948 } 10949 10950 N = pkg.instrumentation.size(); 10951 r = null; 10952 for (i=0; i<N; i++) { 10953 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10954 mInstrumentation.remove(a.getComponentName()); 10955 if (DEBUG_REMOVE && chatty) { 10956 if (r == null) { 10957 r = new StringBuilder(256); 10958 } else { 10959 r.append(' '); 10960 } 10961 r.append(a.info.name); 10962 } 10963 } 10964 if (r != null) { 10965 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10966 } 10967 10968 r = null; 10969 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10970 // Only system apps can hold shared libraries. 10971 if (pkg.libraryNames != null) { 10972 for (i = 0; i < pkg.libraryNames.size(); i++) { 10973 String name = pkg.libraryNames.get(i); 10974 if (removeSharedLibraryLPw(name, 0)) { 10975 if (DEBUG_REMOVE && chatty) { 10976 if (r == null) { 10977 r = new StringBuilder(256); 10978 } else { 10979 r.append(' '); 10980 } 10981 r.append(name); 10982 } 10983 } 10984 } 10985 } 10986 } 10987 10988 r = null; 10989 10990 // Any package can hold static shared libraries. 10991 if (pkg.staticSharedLibName != null) { 10992 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 10993 if (DEBUG_REMOVE && chatty) { 10994 if (r == null) { 10995 r = new StringBuilder(256); 10996 } else { 10997 r.append(' '); 10998 } 10999 r.append(pkg.staticSharedLibName); 11000 } 11001 } 11002 } 11003 11004 if (r != null) { 11005 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11006 } 11007 } 11008 11009 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11010 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11011 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11012 return true; 11013 } 11014 } 11015 return false; 11016 } 11017 11018 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11019 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11020 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11021 11022 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11023 // Update the parent permissions 11024 updatePermissionsLPw(pkg.packageName, pkg, flags); 11025 // Update the child permissions 11026 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11027 for (int i = 0; i < childCount; i++) { 11028 PackageParser.Package childPkg = pkg.childPackages.get(i); 11029 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11030 } 11031 } 11032 11033 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11034 int flags) { 11035 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11036 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11037 } 11038 11039 private void updatePermissionsLPw(String changingPkg, 11040 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11041 // Make sure there are no dangling permission trees. 11042 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11043 while (it.hasNext()) { 11044 final BasePermission bp = it.next(); 11045 if (bp.packageSetting == null) { 11046 // We may not yet have parsed the package, so just see if 11047 // we still know about its settings. 11048 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11049 } 11050 if (bp.packageSetting == null) { 11051 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11052 + " from package " + bp.sourcePackage); 11053 it.remove(); 11054 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11055 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11056 Slog.i(TAG, "Removing old permission tree: " + bp.name 11057 + " from package " + bp.sourcePackage); 11058 flags |= UPDATE_PERMISSIONS_ALL; 11059 it.remove(); 11060 } 11061 } 11062 } 11063 11064 // Make sure all dynamic permissions have been assigned to a package, 11065 // and make sure there are no dangling permissions. 11066 it = mSettings.mPermissions.values().iterator(); 11067 while (it.hasNext()) { 11068 final BasePermission bp = it.next(); 11069 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11070 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11071 + bp.name + " pkg=" + bp.sourcePackage 11072 + " info=" + bp.pendingInfo); 11073 if (bp.packageSetting == null && bp.pendingInfo != null) { 11074 final BasePermission tree = findPermissionTreeLP(bp.name); 11075 if (tree != null && tree.perm != null) { 11076 bp.packageSetting = tree.packageSetting; 11077 bp.perm = new PackageParser.Permission(tree.perm.owner, 11078 new PermissionInfo(bp.pendingInfo)); 11079 bp.perm.info.packageName = tree.perm.info.packageName; 11080 bp.perm.info.name = bp.name; 11081 bp.uid = tree.uid; 11082 } 11083 } 11084 } 11085 if (bp.packageSetting == null) { 11086 // We may not yet have parsed the package, so just see if 11087 // we still know about its settings. 11088 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11089 } 11090 if (bp.packageSetting == null) { 11091 Slog.w(TAG, "Removing dangling permission: " + bp.name 11092 + " from package " + bp.sourcePackage); 11093 it.remove(); 11094 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11095 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11096 Slog.i(TAG, "Removing old permission: " + bp.name 11097 + " from package " + bp.sourcePackage); 11098 flags |= UPDATE_PERMISSIONS_ALL; 11099 it.remove(); 11100 } 11101 } 11102 } 11103 11104 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11105 // Now update the permissions for all packages, in particular 11106 // replace the granted permissions of the system packages. 11107 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11108 for (PackageParser.Package pkg : mPackages.values()) { 11109 if (pkg != pkgInfo) { 11110 // Only replace for packages on requested volume 11111 final String volumeUuid = getVolumeUuidForPackage(pkg); 11112 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11113 && Objects.equals(replaceVolumeUuid, volumeUuid); 11114 grantPermissionsLPw(pkg, replace, changingPkg); 11115 } 11116 } 11117 } 11118 11119 if (pkgInfo != null) { 11120 // Only replace for packages on requested volume 11121 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11122 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11123 && Objects.equals(replaceVolumeUuid, volumeUuid); 11124 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11125 } 11126 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11127 } 11128 11129 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11130 String packageOfInterest) { 11131 // IMPORTANT: There are two types of permissions: install and runtime. 11132 // Install time permissions are granted when the app is installed to 11133 // all device users and users added in the future. Runtime permissions 11134 // are granted at runtime explicitly to specific users. Normal and signature 11135 // protected permissions are install time permissions. Dangerous permissions 11136 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11137 // otherwise they are runtime permissions. This function does not manage 11138 // runtime permissions except for the case an app targeting Lollipop MR1 11139 // being upgraded to target a newer SDK, in which case dangerous permissions 11140 // are transformed from install time to runtime ones. 11141 11142 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11143 if (ps == null) { 11144 return; 11145 } 11146 11147 PermissionsState permissionsState = ps.getPermissionsState(); 11148 PermissionsState origPermissions = permissionsState; 11149 11150 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11151 11152 boolean runtimePermissionsRevoked = false; 11153 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11154 11155 boolean changedInstallPermission = false; 11156 11157 if (replace) { 11158 ps.installPermissionsFixed = false; 11159 if (!ps.isSharedUser()) { 11160 origPermissions = new PermissionsState(permissionsState); 11161 permissionsState.reset(); 11162 } else { 11163 // We need to know only about runtime permission changes since the 11164 // calling code always writes the install permissions state but 11165 // the runtime ones are written only if changed. The only cases of 11166 // changed runtime permissions here are promotion of an install to 11167 // runtime and revocation of a runtime from a shared user. 11168 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11169 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11170 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11171 runtimePermissionsRevoked = true; 11172 } 11173 } 11174 } 11175 11176 permissionsState.setGlobalGids(mGlobalGids); 11177 11178 final int N = pkg.requestedPermissions.size(); 11179 for (int i=0; i<N; i++) { 11180 final String name = pkg.requestedPermissions.get(i); 11181 final BasePermission bp = mSettings.mPermissions.get(name); 11182 11183 if (DEBUG_INSTALL) { 11184 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11185 } 11186 11187 if (bp == null || bp.packageSetting == null) { 11188 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11189 Slog.w(TAG, "Unknown permission " + name 11190 + " in package " + pkg.packageName); 11191 } 11192 continue; 11193 } 11194 11195 11196 // Limit ephemeral apps to ephemeral allowed permissions. 11197 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 11198 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11199 + pkg.packageName); 11200 continue; 11201 } 11202 11203 final String perm = bp.name; 11204 boolean allowedSig = false; 11205 int grant = GRANT_DENIED; 11206 11207 // Keep track of app op permissions. 11208 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11209 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11210 if (pkgs == null) { 11211 pkgs = new ArraySet<>(); 11212 mAppOpPermissionPackages.put(bp.name, pkgs); 11213 } 11214 pkgs.add(pkg.packageName); 11215 } 11216 11217 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11218 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11219 >= Build.VERSION_CODES.M; 11220 switch (level) { 11221 case PermissionInfo.PROTECTION_NORMAL: { 11222 // For all apps normal permissions are install time ones. 11223 grant = GRANT_INSTALL; 11224 } break; 11225 11226 case PermissionInfo.PROTECTION_DANGEROUS: { 11227 // If a permission review is required for legacy apps we represent 11228 // their permissions as always granted runtime ones since we need 11229 // to keep the review required permission flag per user while an 11230 // install permission's state is shared across all users. 11231 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11232 // For legacy apps dangerous permissions are install time ones. 11233 grant = GRANT_INSTALL; 11234 } else if (origPermissions.hasInstallPermission(bp.name)) { 11235 // For legacy apps that became modern, install becomes runtime. 11236 grant = GRANT_UPGRADE; 11237 } else if (mPromoteSystemApps 11238 && isSystemApp(ps) 11239 && mExistingSystemPackages.contains(ps.name)) { 11240 // For legacy system apps, install becomes runtime. 11241 // We cannot check hasInstallPermission() for system apps since those 11242 // permissions were granted implicitly and not persisted pre-M. 11243 grant = GRANT_UPGRADE; 11244 } else { 11245 // For modern apps keep runtime permissions unchanged. 11246 grant = GRANT_RUNTIME; 11247 } 11248 } break; 11249 11250 case PermissionInfo.PROTECTION_SIGNATURE: { 11251 // For all apps signature permissions are install time ones. 11252 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11253 if (allowedSig) { 11254 grant = GRANT_INSTALL; 11255 } 11256 } break; 11257 } 11258 11259 if (DEBUG_INSTALL) { 11260 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11261 } 11262 11263 if (grant != GRANT_DENIED) { 11264 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11265 // If this is an existing, non-system package, then 11266 // we can't add any new permissions to it. 11267 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11268 // Except... if this is a permission that was added 11269 // to the platform (note: need to only do this when 11270 // updating the platform). 11271 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11272 grant = GRANT_DENIED; 11273 } 11274 } 11275 } 11276 11277 switch (grant) { 11278 case GRANT_INSTALL: { 11279 // Revoke this as runtime permission to handle the case of 11280 // a runtime permission being downgraded to an install one. 11281 // Also in permission review mode we keep dangerous permissions 11282 // for legacy apps 11283 for (int userId : UserManagerService.getInstance().getUserIds()) { 11284 if (origPermissions.getRuntimePermissionState( 11285 bp.name, userId) != null) { 11286 // Revoke the runtime permission and clear the flags. 11287 origPermissions.revokeRuntimePermission(bp, userId); 11288 origPermissions.updatePermissionFlags(bp, userId, 11289 PackageManager.MASK_PERMISSION_FLAGS, 0); 11290 // If we revoked a permission permission, we have to write. 11291 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11292 changedRuntimePermissionUserIds, userId); 11293 } 11294 } 11295 // Grant an install permission. 11296 if (permissionsState.grantInstallPermission(bp) != 11297 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11298 changedInstallPermission = true; 11299 } 11300 } break; 11301 11302 case GRANT_RUNTIME: { 11303 // Grant previously granted runtime permissions. 11304 for (int userId : UserManagerService.getInstance().getUserIds()) { 11305 PermissionState permissionState = origPermissions 11306 .getRuntimePermissionState(bp.name, userId); 11307 int flags = permissionState != null 11308 ? permissionState.getFlags() : 0; 11309 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11310 // Don't propagate the permission in a permission review mode if 11311 // the former was revoked, i.e. marked to not propagate on upgrade. 11312 // Note that in a permission review mode install permissions are 11313 // represented as constantly granted runtime ones since we need to 11314 // keep a per user state associated with the permission. Also the 11315 // revoke on upgrade flag is no longer applicable and is reset. 11316 final boolean revokeOnUpgrade = (flags & PackageManager 11317 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11318 if (revokeOnUpgrade) { 11319 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11320 // Since we changed the flags, we have to write. 11321 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11322 changedRuntimePermissionUserIds, userId); 11323 } 11324 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11325 if (permissionsState.grantRuntimePermission(bp, userId) == 11326 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11327 // If we cannot put the permission as it was, 11328 // we have to write. 11329 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11330 changedRuntimePermissionUserIds, userId); 11331 } 11332 } 11333 11334 // If the app supports runtime permissions no need for a review. 11335 if (mPermissionReviewRequired 11336 && appSupportsRuntimePermissions 11337 && (flags & PackageManager 11338 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11339 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11340 // Since we changed the flags, we have to write. 11341 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11342 changedRuntimePermissionUserIds, userId); 11343 } 11344 } else if (mPermissionReviewRequired 11345 && !appSupportsRuntimePermissions) { 11346 // For legacy apps that need a permission review, every new 11347 // runtime permission is granted but it is pending a review. 11348 // We also need to review only platform defined runtime 11349 // permissions as these are the only ones the platform knows 11350 // how to disable the API to simulate revocation as legacy 11351 // apps don't expect to run with revoked permissions. 11352 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11353 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11354 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11355 // We changed the flags, hence have to write. 11356 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11357 changedRuntimePermissionUserIds, userId); 11358 } 11359 } 11360 if (permissionsState.grantRuntimePermission(bp, userId) 11361 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11362 // We changed the permission, hence have to write. 11363 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11364 changedRuntimePermissionUserIds, userId); 11365 } 11366 } 11367 // Propagate the permission flags. 11368 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11369 } 11370 } break; 11371 11372 case GRANT_UPGRADE: { 11373 // Grant runtime permissions for a previously held install permission. 11374 PermissionState permissionState = origPermissions 11375 .getInstallPermissionState(bp.name); 11376 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11377 11378 if (origPermissions.revokeInstallPermission(bp) 11379 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11380 // We will be transferring the permission flags, so clear them. 11381 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11382 PackageManager.MASK_PERMISSION_FLAGS, 0); 11383 changedInstallPermission = true; 11384 } 11385 11386 // If the permission is not to be promoted to runtime we ignore it and 11387 // also its other flags as they are not applicable to install permissions. 11388 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11389 for (int userId : currentUserIds) { 11390 if (permissionsState.grantRuntimePermission(bp, userId) != 11391 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11392 // Transfer the permission flags. 11393 permissionsState.updatePermissionFlags(bp, userId, 11394 flags, flags); 11395 // If we granted the permission, we have to write. 11396 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11397 changedRuntimePermissionUserIds, userId); 11398 } 11399 } 11400 } 11401 } break; 11402 11403 default: { 11404 if (packageOfInterest == null 11405 || packageOfInterest.equals(pkg.packageName)) { 11406 Slog.w(TAG, "Not granting permission " + perm 11407 + " to package " + pkg.packageName 11408 + " because it was previously installed without"); 11409 } 11410 } break; 11411 } 11412 } else { 11413 if (permissionsState.revokeInstallPermission(bp) != 11414 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11415 // Also drop the permission flags. 11416 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11417 PackageManager.MASK_PERMISSION_FLAGS, 0); 11418 changedInstallPermission = true; 11419 Slog.i(TAG, "Un-granting permission " + perm 11420 + " from package " + pkg.packageName 11421 + " (protectionLevel=" + bp.protectionLevel 11422 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11423 + ")"); 11424 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11425 // Don't print warning for app op permissions, since it is fine for them 11426 // not to be granted, there is a UI for the user to decide. 11427 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11428 Slog.w(TAG, "Not granting permission " + perm 11429 + " to package " + pkg.packageName 11430 + " (protectionLevel=" + bp.protectionLevel 11431 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11432 + ")"); 11433 } 11434 } 11435 } 11436 } 11437 11438 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11439 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11440 // This is the first that we have heard about this package, so the 11441 // permissions we have now selected are fixed until explicitly 11442 // changed. 11443 ps.installPermissionsFixed = true; 11444 } 11445 11446 // Persist the runtime permissions state for users with changes. If permissions 11447 // were revoked because no app in the shared user declares them we have to 11448 // write synchronously to avoid losing runtime permissions state. 11449 for (int userId : changedRuntimePermissionUserIds) { 11450 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11451 } 11452 } 11453 11454 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11455 boolean allowed = false; 11456 final int NP = PackageParser.NEW_PERMISSIONS.length; 11457 for (int ip=0; ip<NP; ip++) { 11458 final PackageParser.NewPermissionInfo npi 11459 = PackageParser.NEW_PERMISSIONS[ip]; 11460 if (npi.name.equals(perm) 11461 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11462 allowed = true; 11463 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11464 + pkg.packageName); 11465 break; 11466 } 11467 } 11468 return allowed; 11469 } 11470 11471 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11472 BasePermission bp, PermissionsState origPermissions) { 11473 boolean privilegedPermission = (bp.protectionLevel 11474 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11475 boolean privappPermissionsDisable = 11476 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11477 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11478 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11479 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11480 && !platformPackage && platformPermission) { 11481 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11482 .getPrivAppPermissions(pkg.packageName); 11483 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11484 if (!whitelisted) { 11485 Slog.w(TAG, "Privileged permission " + perm + " for package " 11486 + pkg.packageName + " - not in privapp-permissions whitelist"); 11487 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11488 return false; 11489 } 11490 } 11491 } 11492 boolean allowed = (compareSignatures( 11493 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11494 == PackageManager.SIGNATURE_MATCH) 11495 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11496 == PackageManager.SIGNATURE_MATCH); 11497 if (!allowed && privilegedPermission) { 11498 if (isSystemApp(pkg)) { 11499 // For updated system applications, a system permission 11500 // is granted only if it had been defined by the original application. 11501 if (pkg.isUpdatedSystemApp()) { 11502 final PackageSetting sysPs = mSettings 11503 .getDisabledSystemPkgLPr(pkg.packageName); 11504 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11505 // If the original was granted this permission, we take 11506 // that grant decision as read and propagate it to the 11507 // update. 11508 if (sysPs.isPrivileged()) { 11509 allowed = true; 11510 } 11511 } else { 11512 // The system apk may have been updated with an older 11513 // version of the one on the data partition, but which 11514 // granted a new system permission that it didn't have 11515 // before. In this case we do want to allow the app to 11516 // now get the new permission if the ancestral apk is 11517 // privileged to get it. 11518 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11519 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11520 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11521 allowed = true; 11522 break; 11523 } 11524 } 11525 } 11526 // Also if a privileged parent package on the system image or any of 11527 // its children requested a privileged permission, the updated child 11528 // packages can also get the permission. 11529 if (pkg.parentPackage != null) { 11530 final PackageSetting disabledSysParentPs = mSettings 11531 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11532 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11533 && disabledSysParentPs.isPrivileged()) { 11534 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11535 allowed = true; 11536 } else if (disabledSysParentPs.pkg.childPackages != null) { 11537 final int count = disabledSysParentPs.pkg.childPackages.size(); 11538 for (int i = 0; i < count; i++) { 11539 PackageParser.Package disabledSysChildPkg = 11540 disabledSysParentPs.pkg.childPackages.get(i); 11541 if (isPackageRequestingPermission(disabledSysChildPkg, 11542 perm)) { 11543 allowed = true; 11544 break; 11545 } 11546 } 11547 } 11548 } 11549 } 11550 } 11551 } else { 11552 allowed = isPrivilegedApp(pkg); 11553 } 11554 } 11555 } 11556 if (!allowed) { 11557 if (!allowed && (bp.protectionLevel 11558 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11559 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11560 // If this was a previously normal/dangerous permission that got moved 11561 // to a system permission as part of the runtime permission redesign, then 11562 // we still want to blindly grant it to old apps. 11563 allowed = true; 11564 } 11565 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11566 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11567 // If this permission is to be granted to the system installer and 11568 // this app is an installer, then it gets the permission. 11569 allowed = true; 11570 } 11571 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11572 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11573 // If this permission is to be granted to the system verifier and 11574 // this app is a verifier, then it gets the permission. 11575 allowed = true; 11576 } 11577 if (!allowed && (bp.protectionLevel 11578 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11579 && isSystemApp(pkg)) { 11580 // Any pre-installed system app is allowed to get this permission. 11581 allowed = true; 11582 } 11583 if (!allowed && (bp.protectionLevel 11584 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11585 // For development permissions, a development permission 11586 // is granted only if it was already granted. 11587 allowed = origPermissions.hasInstallPermission(perm); 11588 } 11589 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11590 && pkg.packageName.equals(mSetupWizardPackage)) { 11591 // If this permission is to be granted to the system setup wizard and 11592 // this app is a setup wizard, then it gets the permission. 11593 allowed = true; 11594 } 11595 } 11596 return allowed; 11597 } 11598 11599 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11600 final int permCount = pkg.requestedPermissions.size(); 11601 for (int j = 0; j < permCount; j++) { 11602 String requestedPermission = pkg.requestedPermissions.get(j); 11603 if (permission.equals(requestedPermission)) { 11604 return true; 11605 } 11606 } 11607 return false; 11608 } 11609 11610 final class ActivityIntentResolver 11611 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11612 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11613 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11614 if (!sUserManager.exists(userId)) return null; 11615 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 11616 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 11617 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 11618 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11619 isEphemeral, userId); 11620 } 11621 11622 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11623 int userId) { 11624 if (!sUserManager.exists(userId)) return null; 11625 mFlags = flags; 11626 return super.queryIntent(intent, resolvedType, 11627 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11628 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11629 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11630 } 11631 11632 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11633 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11634 if (!sUserManager.exists(userId)) return null; 11635 if (packageActivities == null) { 11636 return null; 11637 } 11638 mFlags = flags; 11639 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11640 final boolean vislbleToEphemeral = 11641 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11642 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 11643 final int N = packageActivities.size(); 11644 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11645 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11646 11647 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11648 for (int i = 0; i < N; ++i) { 11649 intentFilters = packageActivities.get(i).intents; 11650 if (intentFilters != null && intentFilters.size() > 0) { 11651 PackageParser.ActivityIntentInfo[] array = 11652 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11653 intentFilters.toArray(array); 11654 listCut.add(array); 11655 } 11656 } 11657 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11658 vislbleToEphemeral, isEphemeral, listCut, userId); 11659 } 11660 11661 /** 11662 * Finds a privileged activity that matches the specified activity names. 11663 */ 11664 private PackageParser.Activity findMatchingActivity( 11665 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11666 for (PackageParser.Activity sysActivity : activityList) { 11667 if (sysActivity.info.name.equals(activityInfo.name)) { 11668 return sysActivity; 11669 } 11670 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11671 return sysActivity; 11672 } 11673 if (sysActivity.info.targetActivity != null) { 11674 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11675 return sysActivity; 11676 } 11677 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11678 return sysActivity; 11679 } 11680 } 11681 } 11682 return null; 11683 } 11684 11685 public class IterGenerator<E> { 11686 public Iterator<E> generate(ActivityIntentInfo info) { 11687 return null; 11688 } 11689 } 11690 11691 public class ActionIterGenerator extends IterGenerator<String> { 11692 @Override 11693 public Iterator<String> generate(ActivityIntentInfo info) { 11694 return info.actionsIterator(); 11695 } 11696 } 11697 11698 public class CategoriesIterGenerator extends IterGenerator<String> { 11699 @Override 11700 public Iterator<String> generate(ActivityIntentInfo info) { 11701 return info.categoriesIterator(); 11702 } 11703 } 11704 11705 public class SchemesIterGenerator extends IterGenerator<String> { 11706 @Override 11707 public Iterator<String> generate(ActivityIntentInfo info) { 11708 return info.schemesIterator(); 11709 } 11710 } 11711 11712 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11713 @Override 11714 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11715 return info.authoritiesIterator(); 11716 } 11717 } 11718 11719 /** 11720 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11721 * MODIFIED. Do not pass in a list that should not be changed. 11722 */ 11723 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11724 IterGenerator<T> generator, Iterator<T> searchIterator) { 11725 // loop through the set of actions; every one must be found in the intent filter 11726 while (searchIterator.hasNext()) { 11727 // we must have at least one filter in the list to consider a match 11728 if (intentList.size() == 0) { 11729 break; 11730 } 11731 11732 final T searchAction = searchIterator.next(); 11733 11734 // loop through the set of intent filters 11735 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11736 while (intentIter.hasNext()) { 11737 final ActivityIntentInfo intentInfo = intentIter.next(); 11738 boolean selectionFound = false; 11739 11740 // loop through the intent filter's selection criteria; at least one 11741 // of them must match the searched criteria 11742 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11743 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11744 final T intentSelection = intentSelectionIter.next(); 11745 if (intentSelection != null && intentSelection.equals(searchAction)) { 11746 selectionFound = true; 11747 break; 11748 } 11749 } 11750 11751 // the selection criteria wasn't found in this filter's set; this filter 11752 // is not a potential match 11753 if (!selectionFound) { 11754 intentIter.remove(); 11755 } 11756 } 11757 } 11758 } 11759 11760 private boolean isProtectedAction(ActivityIntentInfo filter) { 11761 final Iterator<String> actionsIter = filter.actionsIterator(); 11762 while (actionsIter != null && actionsIter.hasNext()) { 11763 final String filterAction = actionsIter.next(); 11764 if (PROTECTED_ACTIONS.contains(filterAction)) { 11765 return true; 11766 } 11767 } 11768 return false; 11769 } 11770 11771 /** 11772 * Adjusts the priority of the given intent filter according to policy. 11773 * <p> 11774 * <ul> 11775 * <li>The priority for non privileged applications is capped to '0'</li> 11776 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11777 * <li>The priority for unbundled updates to privileged applications is capped to the 11778 * priority defined on the system partition</li> 11779 * </ul> 11780 * <p> 11781 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11782 * allowed to obtain any priority on any action. 11783 */ 11784 private void adjustPriority( 11785 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11786 // nothing to do; priority is fine as-is 11787 if (intent.getPriority() <= 0) { 11788 return; 11789 } 11790 11791 final ActivityInfo activityInfo = intent.activity.info; 11792 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11793 11794 final boolean privilegedApp = 11795 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11796 if (!privilegedApp) { 11797 // non-privileged applications can never define a priority >0 11798 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11799 + " package: " + applicationInfo.packageName 11800 + " activity: " + intent.activity.className 11801 + " origPrio: " + intent.getPriority()); 11802 intent.setPriority(0); 11803 return; 11804 } 11805 11806 if (systemActivities == null) { 11807 // the system package is not disabled; we're parsing the system partition 11808 if (isProtectedAction(intent)) { 11809 if (mDeferProtectedFilters) { 11810 // We can't deal with these just yet. No component should ever obtain a 11811 // >0 priority for a protected actions, with ONE exception -- the setup 11812 // wizard. The setup wizard, however, cannot be known until we're able to 11813 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11814 // until all intent filters have been processed. Chicken, meet egg. 11815 // Let the filter temporarily have a high priority and rectify the 11816 // priorities after all system packages have been scanned. 11817 mProtectedFilters.add(intent); 11818 if (DEBUG_FILTERS) { 11819 Slog.i(TAG, "Protected action; save for later;" 11820 + " package: " + applicationInfo.packageName 11821 + " activity: " + intent.activity.className 11822 + " origPrio: " + intent.getPriority()); 11823 } 11824 return; 11825 } else { 11826 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11827 Slog.i(TAG, "No setup wizard;" 11828 + " All protected intents capped to priority 0"); 11829 } 11830 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11831 if (DEBUG_FILTERS) { 11832 Slog.i(TAG, "Found setup wizard;" 11833 + " allow priority " + intent.getPriority() + ";" 11834 + " package: " + intent.activity.info.packageName 11835 + " activity: " + intent.activity.className 11836 + " priority: " + intent.getPriority()); 11837 } 11838 // setup wizard gets whatever it wants 11839 return; 11840 } 11841 Slog.w(TAG, "Protected action; cap priority to 0;" 11842 + " package: " + intent.activity.info.packageName 11843 + " activity: " + intent.activity.className 11844 + " origPrio: " + intent.getPriority()); 11845 intent.setPriority(0); 11846 return; 11847 } 11848 } 11849 // privileged apps on the system image get whatever priority they request 11850 return; 11851 } 11852 11853 // privileged app unbundled update ... try to find the same activity 11854 final PackageParser.Activity foundActivity = 11855 findMatchingActivity(systemActivities, activityInfo); 11856 if (foundActivity == null) { 11857 // this is a new activity; it cannot obtain >0 priority 11858 if (DEBUG_FILTERS) { 11859 Slog.i(TAG, "New activity; cap priority to 0;" 11860 + " package: " + applicationInfo.packageName 11861 + " activity: " + intent.activity.className 11862 + " origPrio: " + intent.getPriority()); 11863 } 11864 intent.setPriority(0); 11865 return; 11866 } 11867 11868 // found activity, now check for filter equivalence 11869 11870 // a shallow copy is enough; we modify the list, not its contents 11871 final List<ActivityIntentInfo> intentListCopy = 11872 new ArrayList<>(foundActivity.intents); 11873 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11874 11875 // find matching action subsets 11876 final Iterator<String> actionsIterator = intent.actionsIterator(); 11877 if (actionsIterator != null) { 11878 getIntentListSubset( 11879 intentListCopy, new ActionIterGenerator(), actionsIterator); 11880 if (intentListCopy.size() == 0) { 11881 // no more intents to match; we're not equivalent 11882 if (DEBUG_FILTERS) { 11883 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11884 + " package: " + applicationInfo.packageName 11885 + " activity: " + intent.activity.className 11886 + " origPrio: " + intent.getPriority()); 11887 } 11888 intent.setPriority(0); 11889 return; 11890 } 11891 } 11892 11893 // find matching category subsets 11894 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11895 if (categoriesIterator != null) { 11896 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11897 categoriesIterator); 11898 if (intentListCopy.size() == 0) { 11899 // no more intents to match; we're not equivalent 11900 if (DEBUG_FILTERS) { 11901 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11902 + " package: " + applicationInfo.packageName 11903 + " activity: " + intent.activity.className 11904 + " origPrio: " + intent.getPriority()); 11905 } 11906 intent.setPriority(0); 11907 return; 11908 } 11909 } 11910 11911 // find matching schemes subsets 11912 final Iterator<String> schemesIterator = intent.schemesIterator(); 11913 if (schemesIterator != null) { 11914 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11915 schemesIterator); 11916 if (intentListCopy.size() == 0) { 11917 // no more intents to match; we're not equivalent 11918 if (DEBUG_FILTERS) { 11919 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11920 + " package: " + applicationInfo.packageName 11921 + " activity: " + intent.activity.className 11922 + " origPrio: " + intent.getPriority()); 11923 } 11924 intent.setPriority(0); 11925 return; 11926 } 11927 } 11928 11929 // find matching authorities subsets 11930 final Iterator<IntentFilter.AuthorityEntry> 11931 authoritiesIterator = intent.authoritiesIterator(); 11932 if (authoritiesIterator != null) { 11933 getIntentListSubset(intentListCopy, 11934 new AuthoritiesIterGenerator(), 11935 authoritiesIterator); 11936 if (intentListCopy.size() == 0) { 11937 // no more intents to match; we're not equivalent 11938 if (DEBUG_FILTERS) { 11939 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11940 + " package: " + applicationInfo.packageName 11941 + " activity: " + intent.activity.className 11942 + " origPrio: " + intent.getPriority()); 11943 } 11944 intent.setPriority(0); 11945 return; 11946 } 11947 } 11948 11949 // we found matching filter(s); app gets the max priority of all intents 11950 int cappedPriority = 0; 11951 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11952 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11953 } 11954 if (intent.getPriority() > cappedPriority) { 11955 if (DEBUG_FILTERS) { 11956 Slog.i(TAG, "Found matching filter(s);" 11957 + " cap priority to " + cappedPriority + ";" 11958 + " package: " + applicationInfo.packageName 11959 + " activity: " + intent.activity.className 11960 + " origPrio: " + intent.getPriority()); 11961 } 11962 intent.setPriority(cappedPriority); 11963 return; 11964 } 11965 // all this for nothing; the requested priority was <= what was on the system 11966 } 11967 11968 public final void addActivity(PackageParser.Activity a, String type) { 11969 mActivities.put(a.getComponentName(), a); 11970 if (DEBUG_SHOW_INFO) 11971 Log.v( 11972 TAG, " " + type + " " + 11973 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11974 if (DEBUG_SHOW_INFO) 11975 Log.v(TAG, " Class=" + a.info.name); 11976 final int NI = a.intents.size(); 11977 for (int j=0; j<NI; j++) { 11978 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11979 if ("activity".equals(type)) { 11980 final PackageSetting ps = 11981 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11982 final List<PackageParser.Activity> systemActivities = 11983 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11984 adjustPriority(systemActivities, intent); 11985 } 11986 if (DEBUG_SHOW_INFO) { 11987 Log.v(TAG, " IntentFilter:"); 11988 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11989 } 11990 if (!intent.debugCheck()) { 11991 Log.w(TAG, "==> For Activity " + a.info.name); 11992 } 11993 addFilter(intent); 11994 } 11995 } 11996 11997 public final void removeActivity(PackageParser.Activity a, String type) { 11998 mActivities.remove(a.getComponentName()); 11999 if (DEBUG_SHOW_INFO) { 12000 Log.v(TAG, " " + type + " " 12001 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12002 : a.info.name) + ":"); 12003 Log.v(TAG, " Class=" + a.info.name); 12004 } 12005 final int NI = a.intents.size(); 12006 for (int j=0; j<NI; j++) { 12007 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12008 if (DEBUG_SHOW_INFO) { 12009 Log.v(TAG, " IntentFilter:"); 12010 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12011 } 12012 removeFilter(intent); 12013 } 12014 } 12015 12016 @Override 12017 protected boolean allowFilterResult( 12018 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12019 ActivityInfo filterAi = filter.activity.info; 12020 for (int i=dest.size()-1; i>=0; i--) { 12021 ActivityInfo destAi = dest.get(i).activityInfo; 12022 if (destAi.name == filterAi.name 12023 && destAi.packageName == filterAi.packageName) { 12024 return false; 12025 } 12026 } 12027 return true; 12028 } 12029 12030 @Override 12031 protected ActivityIntentInfo[] newArray(int size) { 12032 return new ActivityIntentInfo[size]; 12033 } 12034 12035 @Override 12036 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12037 if (!sUserManager.exists(userId)) return true; 12038 PackageParser.Package p = filter.activity.owner; 12039 if (p != null) { 12040 PackageSetting ps = (PackageSetting)p.mExtras; 12041 if (ps != null) { 12042 // System apps are never considered stopped for purposes of 12043 // filtering, because there may be no way for the user to 12044 // actually re-launch them. 12045 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12046 && ps.getStopped(userId); 12047 } 12048 } 12049 return false; 12050 } 12051 12052 @Override 12053 protected boolean isPackageForFilter(String packageName, 12054 PackageParser.ActivityIntentInfo info) { 12055 return packageName.equals(info.activity.owner.packageName); 12056 } 12057 12058 @Override 12059 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12060 int match, int userId) { 12061 if (!sUserManager.exists(userId)) return null; 12062 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12063 return null; 12064 } 12065 final PackageParser.Activity activity = info.activity; 12066 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12067 if (ps == null) { 12068 return null; 12069 } 12070 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12071 ps.readUserState(userId), userId); 12072 if (ai == null) { 12073 return null; 12074 } 12075 final ResolveInfo res = new ResolveInfo(); 12076 res.activityInfo = ai; 12077 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12078 res.filter = info; 12079 } 12080 if (info != null) { 12081 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12082 } 12083 res.priority = info.getPriority(); 12084 res.preferredOrder = activity.owner.mPreferredOrder; 12085 //System.out.println("Result: " + res.activityInfo.className + 12086 // " = " + res.priority); 12087 res.match = match; 12088 res.isDefault = info.hasDefault; 12089 res.labelRes = info.labelRes; 12090 res.nonLocalizedLabel = info.nonLocalizedLabel; 12091 if (userNeedsBadging(userId)) { 12092 res.noResourceId = true; 12093 } else { 12094 res.icon = info.icon; 12095 } 12096 res.iconResourceId = info.icon; 12097 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12098 return res; 12099 } 12100 12101 @Override 12102 protected void sortResults(List<ResolveInfo> results) { 12103 Collections.sort(results, mResolvePrioritySorter); 12104 } 12105 12106 @Override 12107 protected void dumpFilter(PrintWriter out, String prefix, 12108 PackageParser.ActivityIntentInfo filter) { 12109 out.print(prefix); out.print( 12110 Integer.toHexString(System.identityHashCode(filter.activity))); 12111 out.print(' '); 12112 filter.activity.printComponentShortName(out); 12113 out.print(" filter "); 12114 out.println(Integer.toHexString(System.identityHashCode(filter))); 12115 } 12116 12117 @Override 12118 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12119 return filter.activity; 12120 } 12121 12122 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12123 PackageParser.Activity activity = (PackageParser.Activity)label; 12124 out.print(prefix); out.print( 12125 Integer.toHexString(System.identityHashCode(activity))); 12126 out.print(' '); 12127 activity.printComponentShortName(out); 12128 if (count > 1) { 12129 out.print(" ("); out.print(count); out.print(" filters)"); 12130 } 12131 out.println(); 12132 } 12133 12134 // Keys are String (activity class name), values are Activity. 12135 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12136 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12137 private int mFlags; 12138 } 12139 12140 private final class ServiceIntentResolver 12141 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12142 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12143 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12144 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12145 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12146 isEphemeral, userId); 12147 } 12148 12149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12150 int userId) { 12151 if (!sUserManager.exists(userId)) return null; 12152 mFlags = flags; 12153 return super.queryIntent(intent, resolvedType, 12154 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12155 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12156 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12157 } 12158 12159 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12160 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12161 if (!sUserManager.exists(userId)) return null; 12162 if (packageServices == null) { 12163 return null; 12164 } 12165 mFlags = flags; 12166 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12167 final boolean vislbleToEphemeral = 12168 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12169 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12170 final int N = packageServices.size(); 12171 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12172 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12173 12174 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12175 for (int i = 0; i < N; ++i) { 12176 intentFilters = packageServices.get(i).intents; 12177 if (intentFilters != null && intentFilters.size() > 0) { 12178 PackageParser.ServiceIntentInfo[] array = 12179 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12180 intentFilters.toArray(array); 12181 listCut.add(array); 12182 } 12183 } 12184 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12185 vislbleToEphemeral, isEphemeral, listCut, userId); 12186 } 12187 12188 public final void addService(PackageParser.Service s) { 12189 mServices.put(s.getComponentName(), s); 12190 if (DEBUG_SHOW_INFO) { 12191 Log.v(TAG, " " 12192 + (s.info.nonLocalizedLabel != null 12193 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12194 Log.v(TAG, " Class=" + s.info.name); 12195 } 12196 final int NI = s.intents.size(); 12197 int j; 12198 for (j=0; j<NI; j++) { 12199 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12200 if (DEBUG_SHOW_INFO) { 12201 Log.v(TAG, " IntentFilter:"); 12202 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12203 } 12204 if (!intent.debugCheck()) { 12205 Log.w(TAG, "==> For Service " + s.info.name); 12206 } 12207 addFilter(intent); 12208 } 12209 } 12210 12211 public final void removeService(PackageParser.Service s) { 12212 mServices.remove(s.getComponentName()); 12213 if (DEBUG_SHOW_INFO) { 12214 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12215 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12216 Log.v(TAG, " Class=" + s.info.name); 12217 } 12218 final int NI = s.intents.size(); 12219 int j; 12220 for (j=0; j<NI; j++) { 12221 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12222 if (DEBUG_SHOW_INFO) { 12223 Log.v(TAG, " IntentFilter:"); 12224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12225 } 12226 removeFilter(intent); 12227 } 12228 } 12229 12230 @Override 12231 protected boolean allowFilterResult( 12232 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12233 ServiceInfo filterSi = filter.service.info; 12234 for (int i=dest.size()-1; i>=0; i--) { 12235 ServiceInfo destAi = dest.get(i).serviceInfo; 12236 if (destAi.name == filterSi.name 12237 && destAi.packageName == filterSi.packageName) { 12238 return false; 12239 } 12240 } 12241 return true; 12242 } 12243 12244 @Override 12245 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12246 return new PackageParser.ServiceIntentInfo[size]; 12247 } 12248 12249 @Override 12250 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12251 if (!sUserManager.exists(userId)) return true; 12252 PackageParser.Package p = filter.service.owner; 12253 if (p != null) { 12254 PackageSetting ps = (PackageSetting)p.mExtras; 12255 if (ps != null) { 12256 // System apps are never considered stopped for purposes of 12257 // filtering, because there may be no way for the user to 12258 // actually re-launch them. 12259 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12260 && ps.getStopped(userId); 12261 } 12262 } 12263 return false; 12264 } 12265 12266 @Override 12267 protected boolean isPackageForFilter(String packageName, 12268 PackageParser.ServiceIntentInfo info) { 12269 return packageName.equals(info.service.owner.packageName); 12270 } 12271 12272 @Override 12273 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12274 int match, int userId) { 12275 if (!sUserManager.exists(userId)) return null; 12276 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12277 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12278 return null; 12279 } 12280 final PackageParser.Service service = info.service; 12281 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12282 if (ps == null) { 12283 return null; 12284 } 12285 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12286 ps.readUserState(userId), userId); 12287 if (si == null) { 12288 return null; 12289 } 12290 final ResolveInfo res = new ResolveInfo(); 12291 res.serviceInfo = si; 12292 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12293 res.filter = filter; 12294 } 12295 res.priority = info.getPriority(); 12296 res.preferredOrder = service.owner.mPreferredOrder; 12297 res.match = match; 12298 res.isDefault = info.hasDefault; 12299 res.labelRes = info.labelRes; 12300 res.nonLocalizedLabel = info.nonLocalizedLabel; 12301 res.icon = info.icon; 12302 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12303 return res; 12304 } 12305 12306 @Override 12307 protected void sortResults(List<ResolveInfo> results) { 12308 Collections.sort(results, mResolvePrioritySorter); 12309 } 12310 12311 @Override 12312 protected void dumpFilter(PrintWriter out, String prefix, 12313 PackageParser.ServiceIntentInfo filter) { 12314 out.print(prefix); out.print( 12315 Integer.toHexString(System.identityHashCode(filter.service))); 12316 out.print(' '); 12317 filter.service.printComponentShortName(out); 12318 out.print(" filter "); 12319 out.println(Integer.toHexString(System.identityHashCode(filter))); 12320 } 12321 12322 @Override 12323 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12324 return filter.service; 12325 } 12326 12327 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12328 PackageParser.Service service = (PackageParser.Service)label; 12329 out.print(prefix); out.print( 12330 Integer.toHexString(System.identityHashCode(service))); 12331 out.print(' '); 12332 service.printComponentShortName(out); 12333 if (count > 1) { 12334 out.print(" ("); out.print(count); out.print(" filters)"); 12335 } 12336 out.println(); 12337 } 12338 12339// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12340// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12341// final List<ResolveInfo> retList = Lists.newArrayList(); 12342// while (i.hasNext()) { 12343// final ResolveInfo resolveInfo = (ResolveInfo) i; 12344// if (isEnabledLP(resolveInfo.serviceInfo)) { 12345// retList.add(resolveInfo); 12346// } 12347// } 12348// return retList; 12349// } 12350 12351 // Keys are String (activity class name), values are Activity. 12352 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12353 = new ArrayMap<ComponentName, PackageParser.Service>(); 12354 private int mFlags; 12355 } 12356 12357 private final class ProviderIntentResolver 12358 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12359 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12360 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 12361 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12362 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 12363 isEphemeral, userId); 12364 } 12365 12366 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12367 int userId) { 12368 if (!sUserManager.exists(userId)) 12369 return null; 12370 mFlags = flags; 12371 return super.queryIntent(intent, resolvedType, 12372 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12373 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 12374 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 12375 } 12376 12377 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12378 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12379 if (!sUserManager.exists(userId)) 12380 return null; 12381 if (packageProviders == null) { 12382 return null; 12383 } 12384 mFlags = flags; 12385 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12386 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 12387 final boolean vislbleToEphemeral = 12388 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 12389 final int N = packageProviders.size(); 12390 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12391 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12392 12393 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12394 for (int i = 0; i < N; ++i) { 12395 intentFilters = packageProviders.get(i).intents; 12396 if (intentFilters != null && intentFilters.size() > 0) { 12397 PackageParser.ProviderIntentInfo[] array = 12398 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12399 intentFilters.toArray(array); 12400 listCut.add(array); 12401 } 12402 } 12403 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 12404 vislbleToEphemeral, isEphemeral, listCut, userId); 12405 } 12406 12407 public final void addProvider(PackageParser.Provider p) { 12408 if (mProviders.containsKey(p.getComponentName())) { 12409 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12410 return; 12411 } 12412 12413 mProviders.put(p.getComponentName(), p); 12414 if (DEBUG_SHOW_INFO) { 12415 Log.v(TAG, " " 12416 + (p.info.nonLocalizedLabel != null 12417 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12418 Log.v(TAG, " Class=" + p.info.name); 12419 } 12420 final int NI = p.intents.size(); 12421 int j; 12422 for (j = 0; j < NI; j++) { 12423 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12424 if (DEBUG_SHOW_INFO) { 12425 Log.v(TAG, " IntentFilter:"); 12426 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12427 } 12428 if (!intent.debugCheck()) { 12429 Log.w(TAG, "==> For Provider " + p.info.name); 12430 } 12431 addFilter(intent); 12432 } 12433 } 12434 12435 public final void removeProvider(PackageParser.Provider p) { 12436 mProviders.remove(p.getComponentName()); 12437 if (DEBUG_SHOW_INFO) { 12438 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12439 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12440 Log.v(TAG, " Class=" + p.info.name); 12441 } 12442 final int NI = p.intents.size(); 12443 int j; 12444 for (j = 0; j < NI; j++) { 12445 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12446 if (DEBUG_SHOW_INFO) { 12447 Log.v(TAG, " IntentFilter:"); 12448 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12449 } 12450 removeFilter(intent); 12451 } 12452 } 12453 12454 @Override 12455 protected boolean allowFilterResult( 12456 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12457 ProviderInfo filterPi = filter.provider.info; 12458 for (int i = dest.size() - 1; i >= 0; i--) { 12459 ProviderInfo destPi = dest.get(i).providerInfo; 12460 if (destPi.name == filterPi.name 12461 && destPi.packageName == filterPi.packageName) { 12462 return false; 12463 } 12464 } 12465 return true; 12466 } 12467 12468 @Override 12469 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12470 return new PackageParser.ProviderIntentInfo[size]; 12471 } 12472 12473 @Override 12474 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12475 if (!sUserManager.exists(userId)) 12476 return true; 12477 PackageParser.Package p = filter.provider.owner; 12478 if (p != null) { 12479 PackageSetting ps = (PackageSetting) p.mExtras; 12480 if (ps != null) { 12481 // System apps are never considered stopped for purposes of 12482 // filtering, because there may be no way for the user to 12483 // actually re-launch them. 12484 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12485 && ps.getStopped(userId); 12486 } 12487 } 12488 return false; 12489 } 12490 12491 @Override 12492 protected boolean isPackageForFilter(String packageName, 12493 PackageParser.ProviderIntentInfo info) { 12494 return packageName.equals(info.provider.owner.packageName); 12495 } 12496 12497 @Override 12498 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12499 int match, int userId) { 12500 if (!sUserManager.exists(userId)) 12501 return null; 12502 final PackageParser.ProviderIntentInfo info = filter; 12503 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12504 return null; 12505 } 12506 final PackageParser.Provider provider = info.provider; 12507 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12508 if (ps == null) { 12509 return null; 12510 } 12511 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12512 ps.readUserState(userId), userId); 12513 if (pi == null) { 12514 return null; 12515 } 12516 final ResolveInfo res = new ResolveInfo(); 12517 res.providerInfo = pi; 12518 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12519 res.filter = filter; 12520 } 12521 res.priority = info.getPriority(); 12522 res.preferredOrder = provider.owner.mPreferredOrder; 12523 res.match = match; 12524 res.isDefault = info.hasDefault; 12525 res.labelRes = info.labelRes; 12526 res.nonLocalizedLabel = info.nonLocalizedLabel; 12527 res.icon = info.icon; 12528 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12529 return res; 12530 } 12531 12532 @Override 12533 protected void sortResults(List<ResolveInfo> results) { 12534 Collections.sort(results, mResolvePrioritySorter); 12535 } 12536 12537 @Override 12538 protected void dumpFilter(PrintWriter out, String prefix, 12539 PackageParser.ProviderIntentInfo filter) { 12540 out.print(prefix); 12541 out.print( 12542 Integer.toHexString(System.identityHashCode(filter.provider))); 12543 out.print(' '); 12544 filter.provider.printComponentShortName(out); 12545 out.print(" filter "); 12546 out.println(Integer.toHexString(System.identityHashCode(filter))); 12547 } 12548 12549 @Override 12550 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12551 return filter.provider; 12552 } 12553 12554 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12555 PackageParser.Provider provider = (PackageParser.Provider)label; 12556 out.print(prefix); out.print( 12557 Integer.toHexString(System.identityHashCode(provider))); 12558 out.print(' '); 12559 provider.printComponentShortName(out); 12560 if (count > 1) { 12561 out.print(" ("); out.print(count); out.print(" filters)"); 12562 } 12563 out.println(); 12564 } 12565 12566 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12567 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12568 private int mFlags; 12569 } 12570 12571 static final class EphemeralIntentResolver 12572 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 12573 /** 12574 * The result that has the highest defined order. Ordering applies on a 12575 * per-package basis. Mapping is from package name to Pair of order and 12576 * EphemeralResolveInfo. 12577 * <p> 12578 * NOTE: This is implemented as a field variable for convenience and efficiency. 12579 * By having a field variable, we're able to track filter ordering as soon as 12580 * a non-zero order is defined. Otherwise, multiple loops across the result set 12581 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12582 * this needs to be contained entirely within {@link #filterResults()}. 12583 */ 12584 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12585 12586 @Override 12587 protected EphemeralResponse[] newArray(int size) { 12588 return new EphemeralResponse[size]; 12589 } 12590 12591 @Override 12592 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 12593 return true; 12594 } 12595 12596 @Override 12597 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 12598 int userId) { 12599 if (!sUserManager.exists(userId)) { 12600 return null; 12601 } 12602 final String packageName = responseObj.resolveInfo.getPackageName(); 12603 final Integer order = responseObj.getOrder(); 12604 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12605 mOrderResult.get(packageName); 12606 // ordering is enabled and this item's order isn't high enough 12607 if (lastOrderResult != null && lastOrderResult.first >= order) { 12608 return null; 12609 } 12610 final EphemeralResolveInfo res = responseObj.resolveInfo; 12611 if (order > 0) { 12612 // non-zero order, enable ordering 12613 mOrderResult.put(packageName, new Pair<>(order, res)); 12614 } 12615 return responseObj; 12616 } 12617 12618 @Override 12619 protected void filterResults(List<EphemeralResponse> results) { 12620 // only do work if ordering is enabled [most of the time it won't be] 12621 if (mOrderResult.size() == 0) { 12622 return; 12623 } 12624 int resultSize = results.size(); 12625 for (int i = 0; i < resultSize; i++) { 12626 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12627 final String packageName = info.getPackageName(); 12628 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12629 if (savedInfo == null) { 12630 // package doesn't having ordering 12631 continue; 12632 } 12633 if (savedInfo.second == info) { 12634 // circled back to the highest ordered item; remove from order list 12635 mOrderResult.remove(savedInfo); 12636 if (mOrderResult.size() == 0) { 12637 // no more ordered items 12638 break; 12639 } 12640 continue; 12641 } 12642 // item has a worse order, remove it from the result list 12643 results.remove(i); 12644 resultSize--; 12645 i--; 12646 } 12647 } 12648 } 12649 12650 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12651 new Comparator<ResolveInfo>() { 12652 public int compare(ResolveInfo r1, ResolveInfo r2) { 12653 int v1 = r1.priority; 12654 int v2 = r2.priority; 12655 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12656 if (v1 != v2) { 12657 return (v1 > v2) ? -1 : 1; 12658 } 12659 v1 = r1.preferredOrder; 12660 v2 = r2.preferredOrder; 12661 if (v1 != v2) { 12662 return (v1 > v2) ? -1 : 1; 12663 } 12664 if (r1.isDefault != r2.isDefault) { 12665 return r1.isDefault ? -1 : 1; 12666 } 12667 v1 = r1.match; 12668 v2 = r2.match; 12669 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12670 if (v1 != v2) { 12671 return (v1 > v2) ? -1 : 1; 12672 } 12673 if (r1.system != r2.system) { 12674 return r1.system ? -1 : 1; 12675 } 12676 if (r1.activityInfo != null) { 12677 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12678 } 12679 if (r1.serviceInfo != null) { 12680 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12681 } 12682 if (r1.providerInfo != null) { 12683 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12684 } 12685 return 0; 12686 } 12687 }; 12688 12689 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12690 new Comparator<ProviderInfo>() { 12691 public int compare(ProviderInfo p1, ProviderInfo p2) { 12692 final int v1 = p1.initOrder; 12693 final int v2 = p2.initOrder; 12694 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12695 } 12696 }; 12697 12698 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12699 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12700 final int[] userIds) { 12701 mHandler.post(new Runnable() { 12702 @Override 12703 public void run() { 12704 try { 12705 final IActivityManager am = ActivityManager.getService(); 12706 if (am == null) return; 12707 final int[] resolvedUserIds; 12708 if (userIds == null) { 12709 resolvedUserIds = am.getRunningUserIds(); 12710 } else { 12711 resolvedUserIds = userIds; 12712 } 12713 for (int id : resolvedUserIds) { 12714 final Intent intent = new Intent(action, 12715 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12716 if (extras != null) { 12717 intent.putExtras(extras); 12718 } 12719 if (targetPkg != null) { 12720 intent.setPackage(targetPkg); 12721 } 12722 // Modify the UID when posting to other users 12723 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12724 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12725 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12726 intent.putExtra(Intent.EXTRA_UID, uid); 12727 } 12728 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12729 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12730 if (DEBUG_BROADCASTS) { 12731 RuntimeException here = new RuntimeException("here"); 12732 here.fillInStackTrace(); 12733 Slog.d(TAG, "Sending to user " + id + ": " 12734 + intent.toShortString(false, true, false, false) 12735 + " " + intent.getExtras(), here); 12736 } 12737 am.broadcastIntent(null, intent, null, finishedReceiver, 12738 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12739 null, finishedReceiver != null, false, id); 12740 } 12741 } catch (RemoteException ex) { 12742 } 12743 } 12744 }); 12745 } 12746 12747 /** 12748 * Check if the external storage media is available. This is true if there 12749 * is a mounted external storage medium or if the external storage is 12750 * emulated. 12751 */ 12752 private boolean isExternalMediaAvailable() { 12753 return mMediaMounted || Environment.isExternalStorageEmulated(); 12754 } 12755 12756 @Override 12757 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12758 // writer 12759 synchronized (mPackages) { 12760 if (!isExternalMediaAvailable()) { 12761 // If the external storage is no longer mounted at this point, 12762 // the caller may not have been able to delete all of this 12763 // packages files and can not delete any more. Bail. 12764 return null; 12765 } 12766 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12767 if (lastPackage != null) { 12768 pkgs.remove(lastPackage); 12769 } 12770 if (pkgs.size() > 0) { 12771 return pkgs.get(0); 12772 } 12773 } 12774 return null; 12775 } 12776 12777 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12778 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12779 userId, andCode ? 1 : 0, packageName); 12780 if (mSystemReady) { 12781 msg.sendToTarget(); 12782 } else { 12783 if (mPostSystemReadyMessages == null) { 12784 mPostSystemReadyMessages = new ArrayList<>(); 12785 } 12786 mPostSystemReadyMessages.add(msg); 12787 } 12788 } 12789 12790 void startCleaningPackages() { 12791 // reader 12792 if (!isExternalMediaAvailable()) { 12793 return; 12794 } 12795 synchronized (mPackages) { 12796 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12797 return; 12798 } 12799 } 12800 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12801 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12802 IActivityManager am = ActivityManager.getService(); 12803 if (am != null) { 12804 try { 12805 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12806 UserHandle.USER_SYSTEM); 12807 } catch (RemoteException e) { 12808 } 12809 } 12810 } 12811 12812 @Override 12813 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12814 int installFlags, String installerPackageName, int userId) { 12815 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12816 12817 final int callingUid = Binder.getCallingUid(); 12818 enforceCrossUserPermission(callingUid, userId, 12819 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12820 12821 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12822 try { 12823 if (observer != null) { 12824 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12825 } 12826 } catch (RemoteException re) { 12827 } 12828 return; 12829 } 12830 12831 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12832 installFlags |= PackageManager.INSTALL_FROM_ADB; 12833 12834 } else { 12835 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12836 // about installerPackageName. 12837 12838 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12839 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12840 } 12841 12842 UserHandle user; 12843 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12844 user = UserHandle.ALL; 12845 } else { 12846 user = new UserHandle(userId); 12847 } 12848 12849 // Only system components can circumvent runtime permissions when installing. 12850 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12851 && mContext.checkCallingOrSelfPermission(Manifest.permission 12852 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12853 throw new SecurityException("You need the " 12854 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12855 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12856 } 12857 12858 final File originFile = new File(originPath); 12859 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12860 12861 final Message msg = mHandler.obtainMessage(INIT_COPY); 12862 final VerificationInfo verificationInfo = new VerificationInfo( 12863 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12864 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12865 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12866 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12867 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12868 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12869 msg.obj = params; 12870 12871 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12872 System.identityHashCode(msg.obj)); 12873 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12874 System.identityHashCode(msg.obj)); 12875 12876 mHandler.sendMessage(msg); 12877 } 12878 12879 12880 /** 12881 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12882 * it is acting on behalf on an enterprise or the user). 12883 * 12884 * Note that the ordering of the conditionals in this method is important. The checks we perform 12885 * are as follows, in this order: 12886 * 12887 * 1) If the install is being performed by a system app, we can trust the app to have set the 12888 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12889 * what it is. 12890 * 2) If the install is being performed by a device or profile owner app, the install reason 12891 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12892 * set the install reason correctly. If the app targets an older SDK version where install 12893 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12894 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12895 * 3) In all other cases, the install is being performed by a regular app that is neither part 12896 * of the system nor a device or profile owner. We have no reason to believe that this app is 12897 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12898 * set to enterprise policy and if so, change it to unknown instead. 12899 */ 12900 private int fixUpInstallReason(String installerPackageName, int installerUid, 12901 int installReason) { 12902 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 12903 == PERMISSION_GRANTED) { 12904 // If the install is being performed by a system app, we trust that app to have set the 12905 // install reason correctly. 12906 return installReason; 12907 } 12908 12909 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12910 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12911 if (dpm != null) { 12912 ComponentName owner = null; 12913 try { 12914 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 12915 if (owner == null) { 12916 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 12917 } 12918 } catch (RemoteException e) { 12919 } 12920 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 12921 // If the install is being performed by a device or profile owner, the install 12922 // reason should be enterprise policy. 12923 return PackageManager.INSTALL_REASON_POLICY; 12924 } 12925 } 12926 12927 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 12928 // If the install is being performed by a regular app (i.e. neither system app nor 12929 // device or profile owner), we have no reason to believe that the app is acting on 12930 // behalf of an enterprise. If the app set the install reason to enterprise policy, 12931 // change it to unknown instead. 12932 return PackageManager.INSTALL_REASON_UNKNOWN; 12933 } 12934 12935 // If the install is being performed by a regular app and the install reason was set to any 12936 // value but enterprise policy, leave the install reason unchanged. 12937 return installReason; 12938 } 12939 12940 void installStage(String packageName, File stagedDir, String stagedCid, 12941 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12942 String installerPackageName, int installerUid, UserHandle user, 12943 Certificate[][] certificates) { 12944 if (DEBUG_EPHEMERAL) { 12945 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12946 Slog.d(TAG, "Ephemeral install of " + packageName); 12947 } 12948 } 12949 final VerificationInfo verificationInfo = new VerificationInfo( 12950 sessionParams.originatingUri, sessionParams.referrerUri, 12951 sessionParams.originatingUid, installerUid); 12952 12953 final OriginInfo origin; 12954 if (stagedDir != null) { 12955 origin = OriginInfo.fromStagedFile(stagedDir); 12956 } else { 12957 origin = OriginInfo.fromStagedContainer(stagedCid); 12958 } 12959 12960 final Message msg = mHandler.obtainMessage(INIT_COPY); 12961 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 12962 sessionParams.installReason); 12963 final InstallParams params = new InstallParams(origin, null, observer, 12964 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12965 verificationInfo, user, sessionParams.abiOverride, 12966 sessionParams.grantedRuntimePermissions, certificates, installReason); 12967 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12968 msg.obj = params; 12969 12970 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12971 System.identityHashCode(msg.obj)); 12972 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12973 System.identityHashCode(msg.obj)); 12974 12975 mHandler.sendMessage(msg); 12976 } 12977 12978 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12979 int userId) { 12980 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12981 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12982 } 12983 12984 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12985 int appId, int... userIds) { 12986 if (ArrayUtils.isEmpty(userIds)) { 12987 return; 12988 } 12989 Bundle extras = new Bundle(1); 12990 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12991 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12992 12993 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12994 packageName, extras, 0, null, null, userIds); 12995 if (isSystem) { 12996 mHandler.post(() -> { 12997 for (int userId : userIds) { 12998 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12999 } 13000 } 13001 ); 13002 } 13003 } 13004 13005 /** 13006 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13007 * automatically without needing an explicit launch. 13008 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13009 */ 13010 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13011 // If user is not running, the app didn't miss any broadcast 13012 if (!mUserManagerInternal.isUserRunning(userId)) { 13013 return; 13014 } 13015 final IActivityManager am = ActivityManager.getService(); 13016 try { 13017 // Deliver LOCKED_BOOT_COMPLETED first 13018 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13019 .setPackage(packageName); 13020 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13021 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13022 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13023 13024 // Deliver BOOT_COMPLETED only if user is unlocked 13025 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13026 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13027 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13028 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13029 } 13030 } catch (RemoteException e) { 13031 throw e.rethrowFromSystemServer(); 13032 } 13033 } 13034 13035 @Override 13036 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13037 int userId) { 13038 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13039 PackageSetting pkgSetting; 13040 final int uid = Binder.getCallingUid(); 13041 enforceCrossUserPermission(uid, userId, 13042 true /* requireFullPermission */, true /* checkShell */, 13043 "setApplicationHiddenSetting for user " + userId); 13044 13045 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13046 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13047 return false; 13048 } 13049 13050 long callingId = Binder.clearCallingIdentity(); 13051 try { 13052 boolean sendAdded = false; 13053 boolean sendRemoved = false; 13054 // writer 13055 synchronized (mPackages) { 13056 pkgSetting = mSettings.mPackages.get(packageName); 13057 if (pkgSetting == null) { 13058 return false; 13059 } 13060 // Do not allow "android" is being disabled 13061 if ("android".equals(packageName)) { 13062 Slog.w(TAG, "Cannot hide package: android"); 13063 return false; 13064 } 13065 // Cannot hide static shared libs as they are considered 13066 // a part of the using app (emulating static linking). Also 13067 // static libs are installed always on internal storage. 13068 PackageParser.Package pkg = mPackages.get(packageName); 13069 if (pkg != null && pkg.staticSharedLibName != null) { 13070 Slog.w(TAG, "Cannot hide package: " + packageName 13071 + " providing static shared library: " 13072 + pkg.staticSharedLibName); 13073 return false; 13074 } 13075 // Only allow protected packages to hide themselves. 13076 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13077 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13078 Slog.w(TAG, "Not hiding protected package: " + packageName); 13079 return false; 13080 } 13081 13082 if (pkgSetting.getHidden(userId) != hidden) { 13083 pkgSetting.setHidden(hidden, userId); 13084 mSettings.writePackageRestrictionsLPr(userId); 13085 if (hidden) { 13086 sendRemoved = true; 13087 } else { 13088 sendAdded = true; 13089 } 13090 } 13091 } 13092 if (sendAdded) { 13093 sendPackageAddedForUser(packageName, pkgSetting, userId); 13094 return true; 13095 } 13096 if (sendRemoved) { 13097 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13098 "hiding pkg"); 13099 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13100 return true; 13101 } 13102 } finally { 13103 Binder.restoreCallingIdentity(callingId); 13104 } 13105 return false; 13106 } 13107 13108 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13109 int userId) { 13110 final PackageRemovedInfo info = new PackageRemovedInfo(); 13111 info.removedPackage = packageName; 13112 info.removedUsers = new int[] {userId}; 13113 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13114 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13115 } 13116 13117 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13118 if (pkgList.length > 0) { 13119 Bundle extras = new Bundle(1); 13120 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13121 13122 sendPackageBroadcast( 13123 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13124 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13125 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13126 new int[] {userId}); 13127 } 13128 } 13129 13130 /** 13131 * Returns true if application is not found or there was an error. Otherwise it returns 13132 * the hidden state of the package for the given user. 13133 */ 13134 @Override 13135 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13136 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13137 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13138 true /* requireFullPermission */, false /* checkShell */, 13139 "getApplicationHidden for user " + userId); 13140 PackageSetting pkgSetting; 13141 long callingId = Binder.clearCallingIdentity(); 13142 try { 13143 // writer 13144 synchronized (mPackages) { 13145 pkgSetting = mSettings.mPackages.get(packageName); 13146 if (pkgSetting == null) { 13147 return true; 13148 } 13149 return pkgSetting.getHidden(userId); 13150 } 13151 } finally { 13152 Binder.restoreCallingIdentity(callingId); 13153 } 13154 } 13155 13156 /** 13157 * @hide 13158 */ 13159 @Override 13160 public int installExistingPackageAsUser(String packageName, int userId, int installReason) { 13161 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13162 null); 13163 PackageSetting pkgSetting; 13164 final int uid = Binder.getCallingUid(); 13165 enforceCrossUserPermission(uid, userId, 13166 true /* requireFullPermission */, true /* checkShell */, 13167 "installExistingPackage for user " + userId); 13168 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13169 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13170 } 13171 13172 long callingId = Binder.clearCallingIdentity(); 13173 try { 13174 boolean installed = false; 13175 13176 // writer 13177 synchronized (mPackages) { 13178 pkgSetting = mSettings.mPackages.get(packageName); 13179 if (pkgSetting == null) { 13180 return PackageManager.INSTALL_FAILED_INVALID_URI; 13181 } 13182 if (!pkgSetting.getInstalled(userId)) { 13183 pkgSetting.setInstalled(true, userId); 13184 pkgSetting.setHidden(false, userId); 13185 pkgSetting.setInstallReason(installReason, userId); 13186 mSettings.writePackageRestrictionsLPr(userId); 13187 installed = true; 13188 } 13189 } 13190 13191 if (installed) { 13192 if (pkgSetting.pkg != null) { 13193 synchronized (mInstallLock) { 13194 // We don't need to freeze for a brand new install 13195 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13196 } 13197 } 13198 sendPackageAddedForUser(packageName, pkgSetting, userId); 13199 } 13200 } finally { 13201 Binder.restoreCallingIdentity(callingId); 13202 } 13203 13204 return PackageManager.INSTALL_SUCCEEDED; 13205 } 13206 13207 boolean isUserRestricted(int userId, String restrictionKey) { 13208 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13209 if (restrictions.getBoolean(restrictionKey, false)) { 13210 Log.w(TAG, "User is restricted: " + restrictionKey); 13211 return true; 13212 } 13213 return false; 13214 } 13215 13216 @Override 13217 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13218 int userId) { 13219 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13220 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13221 true /* requireFullPermission */, true /* checkShell */, 13222 "setPackagesSuspended for user " + userId); 13223 13224 if (ArrayUtils.isEmpty(packageNames)) { 13225 return packageNames; 13226 } 13227 13228 // List of package names for whom the suspended state has changed. 13229 List<String> changedPackages = new ArrayList<>(packageNames.length); 13230 // List of package names for whom the suspended state is not set as requested in this 13231 // method. 13232 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13233 long callingId = Binder.clearCallingIdentity(); 13234 try { 13235 for (int i = 0; i < packageNames.length; i++) { 13236 String packageName = packageNames[i]; 13237 boolean changed = false; 13238 final int appId; 13239 synchronized (mPackages) { 13240 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13241 if (pkgSetting == null) { 13242 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13243 + "\". Skipping suspending/un-suspending."); 13244 unactionedPackages.add(packageName); 13245 continue; 13246 } 13247 appId = pkgSetting.appId; 13248 if (pkgSetting.getSuspended(userId) != suspended) { 13249 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13250 unactionedPackages.add(packageName); 13251 continue; 13252 } 13253 pkgSetting.setSuspended(suspended, userId); 13254 mSettings.writePackageRestrictionsLPr(userId); 13255 changed = true; 13256 changedPackages.add(packageName); 13257 } 13258 } 13259 13260 if (changed && suspended) { 13261 killApplication(packageName, UserHandle.getUid(userId, appId), 13262 "suspending package"); 13263 } 13264 } 13265 } finally { 13266 Binder.restoreCallingIdentity(callingId); 13267 } 13268 13269 if (!changedPackages.isEmpty()) { 13270 sendPackagesSuspendedForUser(changedPackages.toArray( 13271 new String[changedPackages.size()]), userId, suspended); 13272 } 13273 13274 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13275 } 13276 13277 @Override 13278 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13279 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13280 true /* requireFullPermission */, false /* checkShell */, 13281 "isPackageSuspendedForUser for user " + userId); 13282 synchronized (mPackages) { 13283 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13284 if (pkgSetting == null) { 13285 throw new IllegalArgumentException("Unknown target package: " + packageName); 13286 } 13287 return pkgSetting.getSuspended(userId); 13288 } 13289 } 13290 13291 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13292 if (isPackageDeviceAdmin(packageName, userId)) { 13293 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13294 + "\": has an active device admin"); 13295 return false; 13296 } 13297 13298 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13299 if (packageName.equals(activeLauncherPackageName)) { 13300 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13301 + "\": contains the active launcher"); 13302 return false; 13303 } 13304 13305 if (packageName.equals(mRequiredInstallerPackage)) { 13306 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13307 + "\": required for package installation"); 13308 return false; 13309 } 13310 13311 if (packageName.equals(mRequiredUninstallerPackage)) { 13312 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13313 + "\": required for package uninstallation"); 13314 return false; 13315 } 13316 13317 if (packageName.equals(mRequiredVerifierPackage)) { 13318 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13319 + "\": required for package verification"); 13320 return false; 13321 } 13322 13323 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13324 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13325 + "\": is the default dialer"); 13326 return false; 13327 } 13328 13329 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13330 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13331 + "\": protected package"); 13332 return false; 13333 } 13334 13335 // Cannot suspend static shared libs as they are considered 13336 // a part of the using app (emulating static linking). Also 13337 // static libs are installed always on internal storage. 13338 PackageParser.Package pkg = mPackages.get(packageName); 13339 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13340 Slog.w(TAG, "Cannot suspend package: " + packageName 13341 + " providing static shared library: " 13342 + pkg.staticSharedLibName); 13343 return false; 13344 } 13345 13346 return true; 13347 } 13348 13349 private String getActiveLauncherPackageName(int userId) { 13350 Intent intent = new Intent(Intent.ACTION_MAIN); 13351 intent.addCategory(Intent.CATEGORY_HOME); 13352 ResolveInfo resolveInfo = resolveIntent( 13353 intent, 13354 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13355 PackageManager.MATCH_DEFAULT_ONLY, 13356 userId); 13357 13358 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13359 } 13360 13361 private String getDefaultDialerPackageName(int userId) { 13362 synchronized (mPackages) { 13363 return mSettings.getDefaultDialerPackageNameLPw(userId); 13364 } 13365 } 13366 13367 @Override 13368 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13369 mContext.enforceCallingOrSelfPermission( 13370 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13371 "Only package verification agents can verify applications"); 13372 13373 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13374 final PackageVerificationResponse response = new PackageVerificationResponse( 13375 verificationCode, Binder.getCallingUid()); 13376 msg.arg1 = id; 13377 msg.obj = response; 13378 mHandler.sendMessage(msg); 13379 } 13380 13381 @Override 13382 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13383 long millisecondsToDelay) { 13384 mContext.enforceCallingOrSelfPermission( 13385 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13386 "Only package verification agents can extend verification timeouts"); 13387 13388 final PackageVerificationState state = mPendingVerification.get(id); 13389 final PackageVerificationResponse response = new PackageVerificationResponse( 13390 verificationCodeAtTimeout, Binder.getCallingUid()); 13391 13392 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13393 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13394 } 13395 if (millisecondsToDelay < 0) { 13396 millisecondsToDelay = 0; 13397 } 13398 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13399 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13400 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13401 } 13402 13403 if ((state != null) && !state.timeoutExtended()) { 13404 state.extendTimeout(); 13405 13406 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13407 msg.arg1 = id; 13408 msg.obj = response; 13409 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13410 } 13411 } 13412 13413 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13414 int verificationCode, UserHandle user) { 13415 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13416 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13417 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13418 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13419 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13420 13421 mContext.sendBroadcastAsUser(intent, user, 13422 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13423 } 13424 13425 private ComponentName matchComponentForVerifier(String packageName, 13426 List<ResolveInfo> receivers) { 13427 ActivityInfo targetReceiver = null; 13428 13429 final int NR = receivers.size(); 13430 for (int i = 0; i < NR; i++) { 13431 final ResolveInfo info = receivers.get(i); 13432 if (info.activityInfo == null) { 13433 continue; 13434 } 13435 13436 if (packageName.equals(info.activityInfo.packageName)) { 13437 targetReceiver = info.activityInfo; 13438 break; 13439 } 13440 } 13441 13442 if (targetReceiver == null) { 13443 return null; 13444 } 13445 13446 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13447 } 13448 13449 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13450 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13451 if (pkgInfo.verifiers.length == 0) { 13452 return null; 13453 } 13454 13455 final int N = pkgInfo.verifiers.length; 13456 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13457 for (int i = 0; i < N; i++) { 13458 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13459 13460 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13461 receivers); 13462 if (comp == null) { 13463 continue; 13464 } 13465 13466 final int verifierUid = getUidForVerifier(verifierInfo); 13467 if (verifierUid == -1) { 13468 continue; 13469 } 13470 13471 if (DEBUG_VERIFY) { 13472 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13473 + " with the correct signature"); 13474 } 13475 sufficientVerifiers.add(comp); 13476 verificationState.addSufficientVerifier(verifierUid); 13477 } 13478 13479 return sufficientVerifiers; 13480 } 13481 13482 private int getUidForVerifier(VerifierInfo verifierInfo) { 13483 synchronized (mPackages) { 13484 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13485 if (pkg == null) { 13486 return -1; 13487 } else if (pkg.mSignatures.length != 1) { 13488 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13489 + " has more than one signature; ignoring"); 13490 return -1; 13491 } 13492 13493 /* 13494 * If the public key of the package's signature does not match 13495 * our expected public key, then this is a different package and 13496 * we should skip. 13497 */ 13498 13499 final byte[] expectedPublicKey; 13500 try { 13501 final Signature verifierSig = pkg.mSignatures[0]; 13502 final PublicKey publicKey = verifierSig.getPublicKey(); 13503 expectedPublicKey = publicKey.getEncoded(); 13504 } catch (CertificateException e) { 13505 return -1; 13506 } 13507 13508 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13509 13510 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13511 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13512 + " does not have the expected public key; ignoring"); 13513 return -1; 13514 } 13515 13516 return pkg.applicationInfo.uid; 13517 } 13518 } 13519 13520 @Override 13521 public void finishPackageInstall(int token, boolean didLaunch) { 13522 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13523 13524 if (DEBUG_INSTALL) { 13525 Slog.v(TAG, "BM finishing package install for " + token); 13526 } 13527 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13528 13529 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13530 mHandler.sendMessage(msg); 13531 } 13532 13533 /** 13534 * Get the verification agent timeout. 13535 * 13536 * @return verification timeout in milliseconds 13537 */ 13538 private long getVerificationTimeout() { 13539 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13540 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13541 DEFAULT_VERIFICATION_TIMEOUT); 13542 } 13543 13544 /** 13545 * Get the default verification agent response code. 13546 * 13547 * @return default verification response code 13548 */ 13549 private int getDefaultVerificationResponse() { 13550 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13551 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13552 DEFAULT_VERIFICATION_RESPONSE); 13553 } 13554 13555 /** 13556 * Check whether or not package verification has been enabled. 13557 * 13558 * @return true if verification should be performed 13559 */ 13560 private boolean isVerificationEnabled(int userId, int installFlags) { 13561 if (!DEFAULT_VERIFY_ENABLE) { 13562 return false; 13563 } 13564 // Ephemeral apps don't get the full verification treatment 13565 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 13566 if (DEBUG_EPHEMERAL) { 13567 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13568 } 13569 return false; 13570 } 13571 13572 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13573 13574 // Check if installing from ADB 13575 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13576 // Do not run verification in a test harness environment 13577 if (ActivityManager.isRunningInTestHarness()) { 13578 return false; 13579 } 13580 if (ensureVerifyAppsEnabled) { 13581 return true; 13582 } 13583 // Check if the developer does not want package verification for ADB installs 13584 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13585 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13586 return false; 13587 } 13588 } 13589 13590 if (ensureVerifyAppsEnabled) { 13591 return true; 13592 } 13593 13594 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13595 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13596 } 13597 13598 @Override 13599 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13600 throws RemoteException { 13601 mContext.enforceCallingOrSelfPermission( 13602 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13603 "Only intentfilter verification agents can verify applications"); 13604 13605 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13606 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13607 Binder.getCallingUid(), verificationCode, failedDomains); 13608 msg.arg1 = id; 13609 msg.obj = response; 13610 mHandler.sendMessage(msg); 13611 } 13612 13613 @Override 13614 public int getIntentVerificationStatus(String packageName, int userId) { 13615 synchronized (mPackages) { 13616 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13617 } 13618 } 13619 13620 @Override 13621 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13622 mContext.enforceCallingOrSelfPermission( 13623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13624 13625 boolean result = false; 13626 synchronized (mPackages) { 13627 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13628 } 13629 if (result) { 13630 scheduleWritePackageRestrictionsLocked(userId); 13631 } 13632 return result; 13633 } 13634 13635 @Override 13636 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13637 String packageName) { 13638 synchronized (mPackages) { 13639 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13640 } 13641 } 13642 13643 @Override 13644 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13645 if (TextUtils.isEmpty(packageName)) { 13646 return ParceledListSlice.emptyList(); 13647 } 13648 synchronized (mPackages) { 13649 PackageParser.Package pkg = mPackages.get(packageName); 13650 if (pkg == null || pkg.activities == null) { 13651 return ParceledListSlice.emptyList(); 13652 } 13653 final int count = pkg.activities.size(); 13654 ArrayList<IntentFilter> result = new ArrayList<>(); 13655 for (int n=0; n<count; n++) { 13656 PackageParser.Activity activity = pkg.activities.get(n); 13657 if (activity.intents != null && activity.intents.size() > 0) { 13658 result.addAll(activity.intents); 13659 } 13660 } 13661 return new ParceledListSlice<>(result); 13662 } 13663 } 13664 13665 @Override 13666 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13667 mContext.enforceCallingOrSelfPermission( 13668 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13669 13670 synchronized (mPackages) { 13671 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13672 if (packageName != null) { 13673 result |= updateIntentVerificationStatus(packageName, 13674 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13675 userId); 13676 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13677 packageName, userId); 13678 } 13679 return result; 13680 } 13681 } 13682 13683 @Override 13684 public String getDefaultBrowserPackageName(int userId) { 13685 synchronized (mPackages) { 13686 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13687 } 13688 } 13689 13690 /** 13691 * Get the "allow unknown sources" setting. 13692 * 13693 * @return the current "allow unknown sources" setting 13694 */ 13695 private int getUnknownSourcesSettings() { 13696 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13697 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13698 -1); 13699 } 13700 13701 @Override 13702 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13703 final int uid = Binder.getCallingUid(); 13704 // writer 13705 synchronized (mPackages) { 13706 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13707 if (targetPackageSetting == null) { 13708 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13709 } 13710 13711 PackageSetting installerPackageSetting; 13712 if (installerPackageName != null) { 13713 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13714 if (installerPackageSetting == null) { 13715 throw new IllegalArgumentException("Unknown installer package: " 13716 + installerPackageName); 13717 } 13718 } else { 13719 installerPackageSetting = null; 13720 } 13721 13722 Signature[] callerSignature; 13723 Object obj = mSettings.getUserIdLPr(uid); 13724 if (obj != null) { 13725 if (obj instanceof SharedUserSetting) { 13726 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13727 } else if (obj instanceof PackageSetting) { 13728 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13729 } else { 13730 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13731 } 13732 } else { 13733 throw new SecurityException("Unknown calling UID: " + uid); 13734 } 13735 13736 // Verify: can't set installerPackageName to a package that is 13737 // not signed with the same cert as the caller. 13738 if (installerPackageSetting != null) { 13739 if (compareSignatures(callerSignature, 13740 installerPackageSetting.signatures.mSignatures) 13741 != PackageManager.SIGNATURE_MATCH) { 13742 throw new SecurityException( 13743 "Caller does not have same cert as new installer package " 13744 + installerPackageName); 13745 } 13746 } 13747 13748 // Verify: if target already has an installer package, it must 13749 // be signed with the same cert as the caller. 13750 if (targetPackageSetting.installerPackageName != null) { 13751 PackageSetting setting = mSettings.mPackages.get( 13752 targetPackageSetting.installerPackageName); 13753 // If the currently set package isn't valid, then it's always 13754 // okay to change it. 13755 if (setting != null) { 13756 if (compareSignatures(callerSignature, 13757 setting.signatures.mSignatures) 13758 != PackageManager.SIGNATURE_MATCH) { 13759 throw new SecurityException( 13760 "Caller does not have same cert as old installer package " 13761 + targetPackageSetting.installerPackageName); 13762 } 13763 } 13764 } 13765 13766 // Okay! 13767 targetPackageSetting.installerPackageName = installerPackageName; 13768 if (installerPackageName != null) { 13769 mSettings.mInstallerPackages.add(installerPackageName); 13770 } 13771 scheduleWriteSettingsLocked(); 13772 } 13773 } 13774 13775 @Override 13776 public void setApplicationCategoryHint(String packageName, int categoryHint, 13777 String callerPackageName) { 13778 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13779 callerPackageName); 13780 synchronized (mPackages) { 13781 PackageSetting ps = mSettings.mPackages.get(packageName); 13782 if (ps == null) { 13783 throw new IllegalArgumentException("Unknown target package " + packageName); 13784 } 13785 13786 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13787 throw new IllegalArgumentException("Calling package " + callerPackageName 13788 + " is not installer for " + packageName); 13789 } 13790 13791 if (ps.categoryHint != categoryHint) { 13792 ps.categoryHint = categoryHint; 13793 scheduleWriteSettingsLocked(); 13794 } 13795 } 13796 } 13797 13798 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13799 // Queue up an async operation since the package installation may take a little while. 13800 mHandler.post(new Runnable() { 13801 public void run() { 13802 mHandler.removeCallbacks(this); 13803 // Result object to be returned 13804 PackageInstalledInfo res = new PackageInstalledInfo(); 13805 res.setReturnCode(currentStatus); 13806 res.uid = -1; 13807 res.pkg = null; 13808 res.removedInfo = null; 13809 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13810 args.doPreInstall(res.returnCode); 13811 synchronized (mInstallLock) { 13812 installPackageTracedLI(args, res); 13813 } 13814 args.doPostInstall(res.returnCode, res.uid); 13815 } 13816 13817 // A restore should be performed at this point if (a) the install 13818 // succeeded, (b) the operation is not an update, and (c) the new 13819 // package has not opted out of backup participation. 13820 final boolean update = res.removedInfo != null 13821 && res.removedInfo.removedPackage != null; 13822 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13823 boolean doRestore = !update 13824 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13825 13826 // Set up the post-install work request bookkeeping. This will be used 13827 // and cleaned up by the post-install event handling regardless of whether 13828 // there's a restore pass performed. Token values are >= 1. 13829 int token; 13830 if (mNextInstallToken < 0) mNextInstallToken = 1; 13831 token = mNextInstallToken++; 13832 13833 PostInstallData data = new PostInstallData(args, res); 13834 mRunningInstalls.put(token, data); 13835 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13836 13837 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13838 // Pass responsibility to the Backup Manager. It will perform a 13839 // restore if appropriate, then pass responsibility back to the 13840 // Package Manager to run the post-install observer callbacks 13841 // and broadcasts. 13842 IBackupManager bm = IBackupManager.Stub.asInterface( 13843 ServiceManager.getService(Context.BACKUP_SERVICE)); 13844 if (bm != null) { 13845 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13846 + " to BM for possible restore"); 13847 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13848 try { 13849 // TODO: http://b/22388012 13850 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13851 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13852 } else { 13853 doRestore = false; 13854 } 13855 } catch (RemoteException e) { 13856 // can't happen; the backup manager is local 13857 } catch (Exception e) { 13858 Slog.e(TAG, "Exception trying to enqueue restore", e); 13859 doRestore = false; 13860 } 13861 } else { 13862 Slog.e(TAG, "Backup Manager not found!"); 13863 doRestore = false; 13864 } 13865 } 13866 13867 if (!doRestore) { 13868 // No restore possible, or the Backup Manager was mysteriously not 13869 // available -- just fire the post-install work request directly. 13870 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13871 13872 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13873 13874 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13875 mHandler.sendMessage(msg); 13876 } 13877 } 13878 }); 13879 } 13880 13881 /** 13882 * Callback from PackageSettings whenever an app is first transitioned out of the 13883 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13884 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13885 * here whether the app is the target of an ongoing install, and only send the 13886 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13887 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13888 * handling. 13889 */ 13890 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13891 // Serialize this with the rest of the install-process message chain. In the 13892 // restore-at-install case, this Runnable will necessarily run before the 13893 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13894 // are coherent. In the non-restore case, the app has already completed install 13895 // and been launched through some other means, so it is not in a problematic 13896 // state for observers to see the FIRST_LAUNCH signal. 13897 mHandler.post(new Runnable() { 13898 @Override 13899 public void run() { 13900 for (int i = 0; i < mRunningInstalls.size(); i++) { 13901 final PostInstallData data = mRunningInstalls.valueAt(i); 13902 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13903 continue; 13904 } 13905 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13906 // right package; but is it for the right user? 13907 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13908 if (userId == data.res.newUsers[uIndex]) { 13909 if (DEBUG_BACKUP) { 13910 Slog.i(TAG, "Package " + pkgName 13911 + " being restored so deferring FIRST_LAUNCH"); 13912 } 13913 return; 13914 } 13915 } 13916 } 13917 } 13918 // didn't find it, so not being restored 13919 if (DEBUG_BACKUP) { 13920 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13921 } 13922 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13923 } 13924 }); 13925 } 13926 13927 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13928 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13929 installerPkg, null, userIds); 13930 } 13931 13932 private abstract class HandlerParams { 13933 private static final int MAX_RETRIES = 4; 13934 13935 /** 13936 * Number of times startCopy() has been attempted and had a non-fatal 13937 * error. 13938 */ 13939 private int mRetries = 0; 13940 13941 /** User handle for the user requesting the information or installation. */ 13942 private final UserHandle mUser; 13943 String traceMethod; 13944 int traceCookie; 13945 13946 HandlerParams(UserHandle user) { 13947 mUser = user; 13948 } 13949 13950 UserHandle getUser() { 13951 return mUser; 13952 } 13953 13954 HandlerParams setTraceMethod(String traceMethod) { 13955 this.traceMethod = traceMethod; 13956 return this; 13957 } 13958 13959 HandlerParams setTraceCookie(int traceCookie) { 13960 this.traceCookie = traceCookie; 13961 return this; 13962 } 13963 13964 final boolean startCopy() { 13965 boolean res; 13966 try { 13967 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13968 13969 if (++mRetries > MAX_RETRIES) { 13970 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13971 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13972 handleServiceError(); 13973 return false; 13974 } else { 13975 handleStartCopy(); 13976 res = true; 13977 } 13978 } catch (RemoteException e) { 13979 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13980 mHandler.sendEmptyMessage(MCS_RECONNECT); 13981 res = false; 13982 } 13983 handleReturnCode(); 13984 return res; 13985 } 13986 13987 final void serviceError() { 13988 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13989 handleServiceError(); 13990 handleReturnCode(); 13991 } 13992 13993 abstract void handleStartCopy() throws RemoteException; 13994 abstract void handleServiceError(); 13995 abstract void handleReturnCode(); 13996 } 13997 13998 class MeasureParams extends HandlerParams { 13999 private final PackageStats mStats; 14000 private boolean mSuccess; 14001 14002 private final IPackageStatsObserver mObserver; 14003 14004 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14005 super(new UserHandle(stats.userHandle)); 14006 mObserver = observer; 14007 mStats = stats; 14008 } 14009 14010 @Override 14011 public String toString() { 14012 return "MeasureParams{" 14013 + Integer.toHexString(System.identityHashCode(this)) 14014 + " " + mStats.packageName + "}"; 14015 } 14016 14017 @Override 14018 void handleStartCopy() throws RemoteException { 14019 synchronized (mInstallLock) { 14020 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14021 } 14022 14023 if (mSuccess) { 14024 boolean mounted = false; 14025 try { 14026 final String status = Environment.getExternalStorageState(); 14027 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14028 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14029 } catch (Exception e) { 14030 } 14031 14032 if (mounted) { 14033 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14034 14035 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14036 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14037 14038 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14039 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14040 14041 // Always subtract cache size, since it's a subdirectory 14042 mStats.externalDataSize -= mStats.externalCacheSize; 14043 14044 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14045 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14046 14047 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14048 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14049 } 14050 } 14051 } 14052 14053 @Override 14054 void handleReturnCode() { 14055 if (mObserver != null) { 14056 try { 14057 mObserver.onGetStatsCompleted(mStats, mSuccess); 14058 } catch (RemoteException e) { 14059 Slog.i(TAG, "Observer no longer exists."); 14060 } 14061 } 14062 } 14063 14064 @Override 14065 void handleServiceError() { 14066 Slog.e(TAG, "Could not measure application " + mStats.packageName 14067 + " external storage"); 14068 } 14069 } 14070 14071 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14072 throws RemoteException { 14073 long result = 0; 14074 for (File path : paths) { 14075 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14076 } 14077 return result; 14078 } 14079 14080 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14081 for (File path : paths) { 14082 try { 14083 mcs.clearDirectory(path.getAbsolutePath()); 14084 } catch (RemoteException e) { 14085 } 14086 } 14087 } 14088 14089 static class OriginInfo { 14090 /** 14091 * Location where install is coming from, before it has been 14092 * copied/renamed into place. This could be a single monolithic APK 14093 * file, or a cluster directory. This location may be untrusted. 14094 */ 14095 final File file; 14096 final String cid; 14097 14098 /** 14099 * Flag indicating that {@link #file} or {@link #cid} has already been 14100 * staged, meaning downstream users don't need to defensively copy the 14101 * contents. 14102 */ 14103 final boolean staged; 14104 14105 /** 14106 * Flag indicating that {@link #file} or {@link #cid} is an already 14107 * installed app that is being moved. 14108 */ 14109 final boolean existing; 14110 14111 final String resolvedPath; 14112 final File resolvedFile; 14113 14114 static OriginInfo fromNothing() { 14115 return new OriginInfo(null, null, false, false); 14116 } 14117 14118 static OriginInfo fromUntrustedFile(File file) { 14119 return new OriginInfo(file, null, false, false); 14120 } 14121 14122 static OriginInfo fromExistingFile(File file) { 14123 return new OriginInfo(file, null, false, true); 14124 } 14125 14126 static OriginInfo fromStagedFile(File file) { 14127 return new OriginInfo(file, null, true, false); 14128 } 14129 14130 static OriginInfo fromStagedContainer(String cid) { 14131 return new OriginInfo(null, cid, true, false); 14132 } 14133 14134 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14135 this.file = file; 14136 this.cid = cid; 14137 this.staged = staged; 14138 this.existing = existing; 14139 14140 if (cid != null) { 14141 resolvedPath = PackageHelper.getSdDir(cid); 14142 resolvedFile = new File(resolvedPath); 14143 } else if (file != null) { 14144 resolvedPath = file.getAbsolutePath(); 14145 resolvedFile = file; 14146 } else { 14147 resolvedPath = null; 14148 resolvedFile = null; 14149 } 14150 } 14151 } 14152 14153 static class MoveInfo { 14154 final int moveId; 14155 final String fromUuid; 14156 final String toUuid; 14157 final String packageName; 14158 final String dataAppName; 14159 final int appId; 14160 final String seinfo; 14161 final int targetSdkVersion; 14162 14163 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14164 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14165 this.moveId = moveId; 14166 this.fromUuid = fromUuid; 14167 this.toUuid = toUuid; 14168 this.packageName = packageName; 14169 this.dataAppName = dataAppName; 14170 this.appId = appId; 14171 this.seinfo = seinfo; 14172 this.targetSdkVersion = targetSdkVersion; 14173 } 14174 } 14175 14176 static class VerificationInfo { 14177 /** A constant used to indicate that a uid value is not present. */ 14178 public static final int NO_UID = -1; 14179 14180 /** URI referencing where the package was downloaded from. */ 14181 final Uri originatingUri; 14182 14183 /** HTTP referrer URI associated with the originatingURI. */ 14184 final Uri referrer; 14185 14186 /** UID of the application that the install request originated from. */ 14187 final int originatingUid; 14188 14189 /** UID of application requesting the install */ 14190 final int installerUid; 14191 14192 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14193 this.originatingUri = originatingUri; 14194 this.referrer = referrer; 14195 this.originatingUid = originatingUid; 14196 this.installerUid = installerUid; 14197 } 14198 } 14199 14200 class InstallParams extends HandlerParams { 14201 final OriginInfo origin; 14202 final MoveInfo move; 14203 final IPackageInstallObserver2 observer; 14204 int installFlags; 14205 final String installerPackageName; 14206 final String volumeUuid; 14207 private InstallArgs mArgs; 14208 private int mRet; 14209 final String packageAbiOverride; 14210 final String[] grantedRuntimePermissions; 14211 final VerificationInfo verificationInfo; 14212 final Certificate[][] certificates; 14213 final int installReason; 14214 14215 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14216 int installFlags, String installerPackageName, String volumeUuid, 14217 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14218 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14219 super(user); 14220 this.origin = origin; 14221 this.move = move; 14222 this.observer = observer; 14223 this.installFlags = installFlags; 14224 this.installerPackageName = installerPackageName; 14225 this.volumeUuid = volumeUuid; 14226 this.verificationInfo = verificationInfo; 14227 this.packageAbiOverride = packageAbiOverride; 14228 this.grantedRuntimePermissions = grantedPermissions; 14229 this.certificates = certificates; 14230 this.installReason = installReason; 14231 } 14232 14233 @Override 14234 public String toString() { 14235 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14236 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14237 } 14238 14239 private int installLocationPolicy(PackageInfoLite pkgLite) { 14240 String packageName = pkgLite.packageName; 14241 int installLocation = pkgLite.installLocation; 14242 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14243 // reader 14244 synchronized (mPackages) { 14245 // Currently installed package which the new package is attempting to replace or 14246 // null if no such package is installed. 14247 PackageParser.Package installedPkg = mPackages.get(packageName); 14248 // Package which currently owns the data which the new package will own if installed. 14249 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14250 // will be null whereas dataOwnerPkg will contain information about the package 14251 // which was uninstalled while keeping its data. 14252 PackageParser.Package dataOwnerPkg = installedPkg; 14253 if (dataOwnerPkg == null) { 14254 PackageSetting ps = mSettings.mPackages.get(packageName); 14255 if (ps != null) { 14256 dataOwnerPkg = ps.pkg; 14257 } 14258 } 14259 14260 if (dataOwnerPkg != null) { 14261 // If installed, the package will get access to data left on the device by its 14262 // predecessor. As a security measure, this is permited only if this is not a 14263 // version downgrade or if the predecessor package is marked as debuggable and 14264 // a downgrade is explicitly requested. 14265 // 14266 // On debuggable platform builds, downgrades are permitted even for 14267 // non-debuggable packages to make testing easier. Debuggable platform builds do 14268 // not offer security guarantees and thus it's OK to disable some security 14269 // mechanisms to make debugging/testing easier on those builds. However, even on 14270 // debuggable builds downgrades of packages are permitted only if requested via 14271 // installFlags. This is because we aim to keep the behavior of debuggable 14272 // platform builds as close as possible to the behavior of non-debuggable 14273 // platform builds. 14274 final boolean downgradeRequested = 14275 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14276 final boolean packageDebuggable = 14277 (dataOwnerPkg.applicationInfo.flags 14278 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14279 final boolean downgradePermitted = 14280 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14281 if (!downgradePermitted) { 14282 try { 14283 checkDowngrade(dataOwnerPkg, pkgLite); 14284 } catch (PackageManagerException e) { 14285 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14286 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14287 } 14288 } 14289 } 14290 14291 if (installedPkg != null) { 14292 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14293 // Check for updated system application. 14294 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14295 if (onSd) { 14296 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14297 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14298 } 14299 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14300 } else { 14301 if (onSd) { 14302 // Install flag overrides everything. 14303 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14304 } 14305 // If current upgrade specifies particular preference 14306 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14307 // Application explicitly specified internal. 14308 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14309 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14310 // App explictly prefers external. Let policy decide 14311 } else { 14312 // Prefer previous location 14313 if (isExternal(installedPkg)) { 14314 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14315 } 14316 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14317 } 14318 } 14319 } else { 14320 // Invalid install. Return error code 14321 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14322 } 14323 } 14324 } 14325 // All the special cases have been taken care of. 14326 // Return result based on recommended install location. 14327 if (onSd) { 14328 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14329 } 14330 return pkgLite.recommendedInstallLocation; 14331 } 14332 14333 /* 14334 * Invoke remote method to get package information and install 14335 * location values. Override install location based on default 14336 * policy if needed and then create install arguments based 14337 * on the install location. 14338 */ 14339 public void handleStartCopy() throws RemoteException { 14340 int ret = PackageManager.INSTALL_SUCCEEDED; 14341 14342 // If we're already staged, we've firmly committed to an install location 14343 if (origin.staged) { 14344 if (origin.file != null) { 14345 installFlags |= PackageManager.INSTALL_INTERNAL; 14346 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14347 } else if (origin.cid != null) { 14348 installFlags |= PackageManager.INSTALL_EXTERNAL; 14349 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14350 } else { 14351 throw new IllegalStateException("Invalid stage location"); 14352 } 14353 } 14354 14355 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14356 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14357 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14358 PackageInfoLite pkgLite = null; 14359 14360 if (onInt && onSd) { 14361 // Check if both bits are set. 14362 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14363 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14364 } else if (onSd && ephemeral) { 14365 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14366 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14367 } else { 14368 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14369 packageAbiOverride); 14370 14371 if (DEBUG_EPHEMERAL && ephemeral) { 14372 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14373 } 14374 14375 /* 14376 * If we have too little free space, try to free cache 14377 * before giving up. 14378 */ 14379 if (!origin.staged && pkgLite.recommendedInstallLocation 14380 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14381 // TODO: focus freeing disk space on the target device 14382 final StorageManager storage = StorageManager.from(mContext); 14383 final long lowThreshold = storage.getStorageLowBytes( 14384 Environment.getDataDirectory()); 14385 14386 final long sizeBytes = mContainerService.calculateInstalledSize( 14387 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14388 14389 try { 14390 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14391 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14392 installFlags, packageAbiOverride); 14393 } catch (InstallerException e) { 14394 Slog.w(TAG, "Failed to free cache", e); 14395 } 14396 14397 /* 14398 * The cache free must have deleted the file we 14399 * downloaded to install. 14400 * 14401 * TODO: fix the "freeCache" call to not delete 14402 * the file we care about. 14403 */ 14404 if (pkgLite.recommendedInstallLocation 14405 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14406 pkgLite.recommendedInstallLocation 14407 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14408 } 14409 } 14410 } 14411 14412 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14413 int loc = pkgLite.recommendedInstallLocation; 14414 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14415 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14416 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14417 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14418 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14419 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14420 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14421 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14422 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14423 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14424 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14425 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14426 } else { 14427 // Override with defaults if needed. 14428 loc = installLocationPolicy(pkgLite); 14429 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14430 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14431 } else if (!onSd && !onInt) { 14432 // Override install location with flags 14433 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14434 // Set the flag to install on external media. 14435 installFlags |= PackageManager.INSTALL_EXTERNAL; 14436 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14437 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14438 if (DEBUG_EPHEMERAL) { 14439 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14440 } 14441 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14442 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14443 |PackageManager.INSTALL_INTERNAL); 14444 } else { 14445 // Make sure the flag for installing on external 14446 // media is unset 14447 installFlags |= PackageManager.INSTALL_INTERNAL; 14448 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14449 } 14450 } 14451 } 14452 } 14453 14454 final InstallArgs args = createInstallArgs(this); 14455 mArgs = args; 14456 14457 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14458 // TODO: http://b/22976637 14459 // Apps installed for "all" users use the device owner to verify the app 14460 UserHandle verifierUser = getUser(); 14461 if (verifierUser == UserHandle.ALL) { 14462 verifierUser = UserHandle.SYSTEM; 14463 } 14464 14465 /* 14466 * Determine if we have any installed package verifiers. If we 14467 * do, then we'll defer to them to verify the packages. 14468 */ 14469 final int requiredUid = mRequiredVerifierPackage == null ? -1 14470 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14471 verifierUser.getIdentifier()); 14472 if (!origin.existing && requiredUid != -1 14473 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14474 final Intent verification = new Intent( 14475 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14476 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14477 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14478 PACKAGE_MIME_TYPE); 14479 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14480 14481 // Query all live verifiers based on current user state 14482 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14483 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14484 14485 if (DEBUG_VERIFY) { 14486 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14487 + verification.toString() + " with " + pkgLite.verifiers.length 14488 + " optional verifiers"); 14489 } 14490 14491 final int verificationId = mPendingVerificationToken++; 14492 14493 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14494 14495 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14496 installerPackageName); 14497 14498 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14499 installFlags); 14500 14501 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14502 pkgLite.packageName); 14503 14504 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14505 pkgLite.versionCode); 14506 14507 if (verificationInfo != null) { 14508 if (verificationInfo.originatingUri != null) { 14509 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14510 verificationInfo.originatingUri); 14511 } 14512 if (verificationInfo.referrer != null) { 14513 verification.putExtra(Intent.EXTRA_REFERRER, 14514 verificationInfo.referrer); 14515 } 14516 if (verificationInfo.originatingUid >= 0) { 14517 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14518 verificationInfo.originatingUid); 14519 } 14520 if (verificationInfo.installerUid >= 0) { 14521 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14522 verificationInfo.installerUid); 14523 } 14524 } 14525 14526 final PackageVerificationState verificationState = new PackageVerificationState( 14527 requiredUid, args); 14528 14529 mPendingVerification.append(verificationId, verificationState); 14530 14531 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14532 receivers, verificationState); 14533 14534 /* 14535 * If any sufficient verifiers were listed in the package 14536 * manifest, attempt to ask them. 14537 */ 14538 if (sufficientVerifiers != null) { 14539 final int N = sufficientVerifiers.size(); 14540 if (N == 0) { 14541 Slog.i(TAG, "Additional verifiers required, but none installed."); 14542 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14543 } else { 14544 for (int i = 0; i < N; i++) { 14545 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14546 14547 final Intent sufficientIntent = new Intent(verification); 14548 sufficientIntent.setComponent(verifierComponent); 14549 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14550 } 14551 } 14552 } 14553 14554 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14555 mRequiredVerifierPackage, receivers); 14556 if (ret == PackageManager.INSTALL_SUCCEEDED 14557 && mRequiredVerifierPackage != null) { 14558 Trace.asyncTraceBegin( 14559 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14560 /* 14561 * Send the intent to the required verification agent, 14562 * but only start the verification timeout after the 14563 * target BroadcastReceivers have run. 14564 */ 14565 verification.setComponent(requiredVerifierComponent); 14566 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14567 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14568 new BroadcastReceiver() { 14569 @Override 14570 public void onReceive(Context context, Intent intent) { 14571 final Message msg = mHandler 14572 .obtainMessage(CHECK_PENDING_VERIFICATION); 14573 msg.arg1 = verificationId; 14574 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14575 } 14576 }, null, 0, null, null); 14577 14578 /* 14579 * We don't want the copy to proceed until verification 14580 * succeeds, so null out this field. 14581 */ 14582 mArgs = null; 14583 } 14584 } else { 14585 /* 14586 * No package verification is enabled, so immediately start 14587 * the remote call to initiate copy using temporary file. 14588 */ 14589 ret = args.copyApk(mContainerService, true); 14590 } 14591 } 14592 14593 mRet = ret; 14594 } 14595 14596 @Override 14597 void handleReturnCode() { 14598 // If mArgs is null, then MCS couldn't be reached. When it 14599 // reconnects, it will try again to install. At that point, this 14600 // will succeed. 14601 if (mArgs != null) { 14602 processPendingInstall(mArgs, mRet); 14603 } 14604 } 14605 14606 @Override 14607 void handleServiceError() { 14608 mArgs = createInstallArgs(this); 14609 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14610 } 14611 14612 public boolean isForwardLocked() { 14613 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14614 } 14615 } 14616 14617 /** 14618 * Used during creation of InstallArgs 14619 * 14620 * @param installFlags package installation flags 14621 * @return true if should be installed on external storage 14622 */ 14623 private static boolean installOnExternalAsec(int installFlags) { 14624 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14625 return false; 14626 } 14627 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14628 return true; 14629 } 14630 return false; 14631 } 14632 14633 /** 14634 * Used during creation of InstallArgs 14635 * 14636 * @param installFlags package installation flags 14637 * @return true if should be installed as forward locked 14638 */ 14639 private static boolean installForwardLocked(int installFlags) { 14640 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14641 } 14642 14643 private InstallArgs createInstallArgs(InstallParams params) { 14644 if (params.move != null) { 14645 return new MoveInstallArgs(params); 14646 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14647 return new AsecInstallArgs(params); 14648 } else { 14649 return new FileInstallArgs(params); 14650 } 14651 } 14652 14653 /** 14654 * Create args that describe an existing installed package. Typically used 14655 * when cleaning up old installs, or used as a move source. 14656 */ 14657 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14658 String resourcePath, String[] instructionSets) { 14659 final boolean isInAsec; 14660 if (installOnExternalAsec(installFlags)) { 14661 /* Apps on SD card are always in ASEC containers. */ 14662 isInAsec = true; 14663 } else if (installForwardLocked(installFlags) 14664 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14665 /* 14666 * Forward-locked apps are only in ASEC containers if they're the 14667 * new style 14668 */ 14669 isInAsec = true; 14670 } else { 14671 isInAsec = false; 14672 } 14673 14674 if (isInAsec) { 14675 return new AsecInstallArgs(codePath, instructionSets, 14676 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14677 } else { 14678 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14679 } 14680 } 14681 14682 static abstract class InstallArgs { 14683 /** @see InstallParams#origin */ 14684 final OriginInfo origin; 14685 /** @see InstallParams#move */ 14686 final MoveInfo move; 14687 14688 final IPackageInstallObserver2 observer; 14689 // Always refers to PackageManager flags only 14690 final int installFlags; 14691 final String installerPackageName; 14692 final String volumeUuid; 14693 final UserHandle user; 14694 final String abiOverride; 14695 final String[] installGrantPermissions; 14696 /** If non-null, drop an async trace when the install completes */ 14697 final String traceMethod; 14698 final int traceCookie; 14699 final Certificate[][] certificates; 14700 final int installReason; 14701 14702 // The list of instruction sets supported by this app. This is currently 14703 // only used during the rmdex() phase to clean up resources. We can get rid of this 14704 // if we move dex files under the common app path. 14705 /* nullable */ String[] instructionSets; 14706 14707 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14708 int installFlags, String installerPackageName, String volumeUuid, 14709 UserHandle user, String[] instructionSets, 14710 String abiOverride, String[] installGrantPermissions, 14711 String traceMethod, int traceCookie, Certificate[][] certificates, 14712 int installReason) { 14713 this.origin = origin; 14714 this.move = move; 14715 this.installFlags = installFlags; 14716 this.observer = observer; 14717 this.installerPackageName = installerPackageName; 14718 this.volumeUuid = volumeUuid; 14719 this.user = user; 14720 this.instructionSets = instructionSets; 14721 this.abiOverride = abiOverride; 14722 this.installGrantPermissions = installGrantPermissions; 14723 this.traceMethod = traceMethod; 14724 this.traceCookie = traceCookie; 14725 this.certificates = certificates; 14726 this.installReason = installReason; 14727 } 14728 14729 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14730 abstract int doPreInstall(int status); 14731 14732 /** 14733 * Rename package into final resting place. All paths on the given 14734 * scanned package should be updated to reflect the rename. 14735 */ 14736 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14737 abstract int doPostInstall(int status, int uid); 14738 14739 /** @see PackageSettingBase#codePathString */ 14740 abstract String getCodePath(); 14741 /** @see PackageSettingBase#resourcePathString */ 14742 abstract String getResourcePath(); 14743 14744 // Need installer lock especially for dex file removal. 14745 abstract void cleanUpResourcesLI(); 14746 abstract boolean doPostDeleteLI(boolean delete); 14747 14748 /** 14749 * Called before the source arguments are copied. This is used mostly 14750 * for MoveParams when it needs to read the source file to put it in the 14751 * destination. 14752 */ 14753 int doPreCopy() { 14754 return PackageManager.INSTALL_SUCCEEDED; 14755 } 14756 14757 /** 14758 * Called after the source arguments are copied. This is used mostly for 14759 * MoveParams when it needs to read the source file to put it in the 14760 * destination. 14761 */ 14762 int doPostCopy(int uid) { 14763 return PackageManager.INSTALL_SUCCEEDED; 14764 } 14765 14766 protected boolean isFwdLocked() { 14767 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14768 } 14769 14770 protected boolean isExternalAsec() { 14771 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14772 } 14773 14774 protected boolean isEphemeral() { 14775 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14776 } 14777 14778 UserHandle getUser() { 14779 return user; 14780 } 14781 } 14782 14783 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14784 if (!allCodePaths.isEmpty()) { 14785 if (instructionSets == null) { 14786 throw new IllegalStateException("instructionSet == null"); 14787 } 14788 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14789 for (String codePath : allCodePaths) { 14790 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14791 try { 14792 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14793 } catch (InstallerException ignored) { 14794 } 14795 } 14796 } 14797 } 14798 } 14799 14800 /** 14801 * Logic to handle installation of non-ASEC applications, including copying 14802 * and renaming logic. 14803 */ 14804 class FileInstallArgs extends InstallArgs { 14805 private File codeFile; 14806 private File resourceFile; 14807 14808 // Example topology: 14809 // /data/app/com.example/base.apk 14810 // /data/app/com.example/split_foo.apk 14811 // /data/app/com.example/lib/arm/libfoo.so 14812 // /data/app/com.example/lib/arm64/libfoo.so 14813 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14814 14815 /** New install */ 14816 FileInstallArgs(InstallParams params) { 14817 super(params.origin, params.move, params.observer, params.installFlags, 14818 params.installerPackageName, params.volumeUuid, 14819 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14820 params.grantedRuntimePermissions, 14821 params.traceMethod, params.traceCookie, params.certificates, 14822 params.installReason); 14823 if (isFwdLocked()) { 14824 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14825 } 14826 } 14827 14828 /** Existing install */ 14829 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14830 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14831 null, null, null, 0, null /*certificates*/, 14832 PackageManager.INSTALL_REASON_UNKNOWN); 14833 this.codeFile = (codePath != null) ? new File(codePath) : null; 14834 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14835 } 14836 14837 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14839 try { 14840 return doCopyApk(imcs, temp); 14841 } finally { 14842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14843 } 14844 } 14845 14846 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14847 if (origin.staged) { 14848 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14849 codeFile = origin.file; 14850 resourceFile = origin.file; 14851 return PackageManager.INSTALL_SUCCEEDED; 14852 } 14853 14854 try { 14855 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14856 final File tempDir = 14857 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14858 codeFile = tempDir; 14859 resourceFile = tempDir; 14860 } catch (IOException e) { 14861 Slog.w(TAG, "Failed to create copy file: " + e); 14862 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14863 } 14864 14865 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14866 @Override 14867 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14868 if (!FileUtils.isValidExtFilename(name)) { 14869 throw new IllegalArgumentException("Invalid filename: " + name); 14870 } 14871 try { 14872 final File file = new File(codeFile, name); 14873 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14874 O_RDWR | O_CREAT, 0644); 14875 Os.chmod(file.getAbsolutePath(), 0644); 14876 return new ParcelFileDescriptor(fd); 14877 } catch (ErrnoException e) { 14878 throw new RemoteException("Failed to open: " + e.getMessage()); 14879 } 14880 } 14881 }; 14882 14883 int ret = PackageManager.INSTALL_SUCCEEDED; 14884 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14885 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14886 Slog.e(TAG, "Failed to copy package"); 14887 return ret; 14888 } 14889 14890 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14891 NativeLibraryHelper.Handle handle = null; 14892 try { 14893 handle = NativeLibraryHelper.Handle.create(codeFile); 14894 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14895 abiOverride); 14896 } catch (IOException e) { 14897 Slog.e(TAG, "Copying native libraries failed", e); 14898 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14899 } finally { 14900 IoUtils.closeQuietly(handle); 14901 } 14902 14903 return ret; 14904 } 14905 14906 int doPreInstall(int status) { 14907 if (status != PackageManager.INSTALL_SUCCEEDED) { 14908 cleanUp(); 14909 } 14910 return status; 14911 } 14912 14913 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14914 if (status != PackageManager.INSTALL_SUCCEEDED) { 14915 cleanUp(); 14916 return false; 14917 } 14918 14919 final File targetDir = codeFile.getParentFile(); 14920 final File beforeCodeFile = codeFile; 14921 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14922 14923 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14924 try { 14925 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14926 } catch (ErrnoException e) { 14927 Slog.w(TAG, "Failed to rename", e); 14928 return false; 14929 } 14930 14931 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14932 Slog.w(TAG, "Failed to restorecon"); 14933 return false; 14934 } 14935 14936 // Reflect the rename internally 14937 codeFile = afterCodeFile; 14938 resourceFile = afterCodeFile; 14939 14940 // Reflect the rename in scanned details 14941 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14942 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14943 afterCodeFile, pkg.baseCodePath)); 14944 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14945 afterCodeFile, pkg.splitCodePaths)); 14946 14947 // Reflect the rename in app info 14948 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14949 pkg.setApplicationInfoCodePath(pkg.codePath); 14950 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14951 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14952 pkg.setApplicationInfoResourcePath(pkg.codePath); 14953 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14954 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14955 14956 return true; 14957 } 14958 14959 int doPostInstall(int status, int uid) { 14960 if (status != PackageManager.INSTALL_SUCCEEDED) { 14961 cleanUp(); 14962 } 14963 return status; 14964 } 14965 14966 @Override 14967 String getCodePath() { 14968 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14969 } 14970 14971 @Override 14972 String getResourcePath() { 14973 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14974 } 14975 14976 private boolean cleanUp() { 14977 if (codeFile == null || !codeFile.exists()) { 14978 return false; 14979 } 14980 14981 removeCodePathLI(codeFile); 14982 14983 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14984 resourceFile.delete(); 14985 } 14986 14987 return true; 14988 } 14989 14990 void cleanUpResourcesLI() { 14991 // Try enumerating all code paths before deleting 14992 List<String> allCodePaths = Collections.EMPTY_LIST; 14993 if (codeFile != null && codeFile.exists()) { 14994 try { 14995 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14996 allCodePaths = pkg.getAllCodePaths(); 14997 } catch (PackageParserException e) { 14998 // Ignored; we tried our best 14999 } 15000 } 15001 15002 cleanUp(); 15003 removeDexFiles(allCodePaths, instructionSets); 15004 } 15005 15006 boolean doPostDeleteLI(boolean delete) { 15007 // XXX err, shouldn't we respect the delete flag? 15008 cleanUpResourcesLI(); 15009 return true; 15010 } 15011 } 15012 15013 private boolean isAsecExternal(String cid) { 15014 final String asecPath = PackageHelper.getSdFilesystem(cid); 15015 return !asecPath.startsWith(mAsecInternalPath); 15016 } 15017 15018 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15019 PackageManagerException { 15020 if (copyRet < 0) { 15021 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15022 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15023 throw new PackageManagerException(copyRet, message); 15024 } 15025 } 15026 } 15027 15028 /** 15029 * Extract the StorageManagerService "container ID" from the full code path of an 15030 * .apk. 15031 */ 15032 static String cidFromCodePath(String fullCodePath) { 15033 int eidx = fullCodePath.lastIndexOf("/"); 15034 String subStr1 = fullCodePath.substring(0, eidx); 15035 int sidx = subStr1.lastIndexOf("/"); 15036 return subStr1.substring(sidx+1, eidx); 15037 } 15038 15039 /** 15040 * Logic to handle installation of ASEC applications, including copying and 15041 * renaming logic. 15042 */ 15043 class AsecInstallArgs extends InstallArgs { 15044 static final String RES_FILE_NAME = "pkg.apk"; 15045 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15046 15047 String cid; 15048 String packagePath; 15049 String resourcePath; 15050 15051 /** New install */ 15052 AsecInstallArgs(InstallParams params) { 15053 super(params.origin, params.move, params.observer, params.installFlags, 15054 params.installerPackageName, params.volumeUuid, 15055 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15056 params.grantedRuntimePermissions, 15057 params.traceMethod, params.traceCookie, params.certificates, 15058 params.installReason); 15059 } 15060 15061 /** Existing install */ 15062 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15063 boolean isExternal, boolean isForwardLocked) { 15064 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15065 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15066 instructionSets, null, null, null, 0, null /*certificates*/, 15067 PackageManager.INSTALL_REASON_UNKNOWN); 15068 // Hackily pretend we're still looking at a full code path 15069 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15070 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15071 } 15072 15073 // Extract cid from fullCodePath 15074 int eidx = fullCodePath.lastIndexOf("/"); 15075 String subStr1 = fullCodePath.substring(0, eidx); 15076 int sidx = subStr1.lastIndexOf("/"); 15077 cid = subStr1.substring(sidx+1, eidx); 15078 setMountPath(subStr1); 15079 } 15080 15081 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15082 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15083 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15084 instructionSets, null, null, null, 0, null /*certificates*/, 15085 PackageManager.INSTALL_REASON_UNKNOWN); 15086 this.cid = cid; 15087 setMountPath(PackageHelper.getSdDir(cid)); 15088 } 15089 15090 void createCopyFile() { 15091 cid = mInstallerService.allocateExternalStageCidLegacy(); 15092 } 15093 15094 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15095 if (origin.staged && origin.cid != null) { 15096 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15097 cid = origin.cid; 15098 setMountPath(PackageHelper.getSdDir(cid)); 15099 return PackageManager.INSTALL_SUCCEEDED; 15100 } 15101 15102 if (temp) { 15103 createCopyFile(); 15104 } else { 15105 /* 15106 * Pre-emptively destroy the container since it's destroyed if 15107 * copying fails due to it existing anyway. 15108 */ 15109 PackageHelper.destroySdDir(cid); 15110 } 15111 15112 final String newMountPath = imcs.copyPackageToContainer( 15113 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15114 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15115 15116 if (newMountPath != null) { 15117 setMountPath(newMountPath); 15118 return PackageManager.INSTALL_SUCCEEDED; 15119 } else { 15120 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15121 } 15122 } 15123 15124 @Override 15125 String getCodePath() { 15126 return packagePath; 15127 } 15128 15129 @Override 15130 String getResourcePath() { 15131 return resourcePath; 15132 } 15133 15134 int doPreInstall(int status) { 15135 if (status != PackageManager.INSTALL_SUCCEEDED) { 15136 // Destroy container 15137 PackageHelper.destroySdDir(cid); 15138 } else { 15139 boolean mounted = PackageHelper.isContainerMounted(cid); 15140 if (!mounted) { 15141 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15142 Process.SYSTEM_UID); 15143 if (newMountPath != null) { 15144 setMountPath(newMountPath); 15145 } else { 15146 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15147 } 15148 } 15149 } 15150 return status; 15151 } 15152 15153 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15154 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15155 String newMountPath = null; 15156 if (PackageHelper.isContainerMounted(cid)) { 15157 // Unmount the container 15158 if (!PackageHelper.unMountSdDir(cid)) { 15159 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15160 return false; 15161 } 15162 } 15163 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15164 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15165 " which might be stale. Will try to clean up."); 15166 // Clean up the stale container and proceed to recreate. 15167 if (!PackageHelper.destroySdDir(newCacheId)) { 15168 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15169 return false; 15170 } 15171 // Successfully cleaned up stale container. Try to rename again. 15172 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15173 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15174 + " inspite of cleaning it up."); 15175 return false; 15176 } 15177 } 15178 if (!PackageHelper.isContainerMounted(newCacheId)) { 15179 Slog.w(TAG, "Mounting container " + newCacheId); 15180 newMountPath = PackageHelper.mountSdDir(newCacheId, 15181 getEncryptKey(), Process.SYSTEM_UID); 15182 } else { 15183 newMountPath = PackageHelper.getSdDir(newCacheId); 15184 } 15185 if (newMountPath == null) { 15186 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15187 return false; 15188 } 15189 Log.i(TAG, "Succesfully renamed " + cid + 15190 " to " + newCacheId + 15191 " at new path: " + newMountPath); 15192 cid = newCacheId; 15193 15194 final File beforeCodeFile = new File(packagePath); 15195 setMountPath(newMountPath); 15196 final File afterCodeFile = new File(packagePath); 15197 15198 // Reflect the rename in scanned details 15199 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15200 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15201 afterCodeFile, pkg.baseCodePath)); 15202 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15203 afterCodeFile, pkg.splitCodePaths)); 15204 15205 // Reflect the rename in app info 15206 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15207 pkg.setApplicationInfoCodePath(pkg.codePath); 15208 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15209 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15210 pkg.setApplicationInfoResourcePath(pkg.codePath); 15211 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15212 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15213 15214 return true; 15215 } 15216 15217 private void setMountPath(String mountPath) { 15218 final File mountFile = new File(mountPath); 15219 15220 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15221 if (monolithicFile.exists()) { 15222 packagePath = monolithicFile.getAbsolutePath(); 15223 if (isFwdLocked()) { 15224 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15225 } else { 15226 resourcePath = packagePath; 15227 } 15228 } else { 15229 packagePath = mountFile.getAbsolutePath(); 15230 resourcePath = packagePath; 15231 } 15232 } 15233 15234 int doPostInstall(int status, int uid) { 15235 if (status != PackageManager.INSTALL_SUCCEEDED) { 15236 cleanUp(); 15237 } else { 15238 final int groupOwner; 15239 final String protectedFile; 15240 if (isFwdLocked()) { 15241 groupOwner = UserHandle.getSharedAppGid(uid); 15242 protectedFile = RES_FILE_NAME; 15243 } else { 15244 groupOwner = -1; 15245 protectedFile = null; 15246 } 15247 15248 if (uid < Process.FIRST_APPLICATION_UID 15249 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15250 Slog.e(TAG, "Failed to finalize " + cid); 15251 PackageHelper.destroySdDir(cid); 15252 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15253 } 15254 15255 boolean mounted = PackageHelper.isContainerMounted(cid); 15256 if (!mounted) { 15257 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15258 } 15259 } 15260 return status; 15261 } 15262 15263 private void cleanUp() { 15264 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15265 15266 // Destroy secure container 15267 PackageHelper.destroySdDir(cid); 15268 } 15269 15270 private List<String> getAllCodePaths() { 15271 final File codeFile = new File(getCodePath()); 15272 if (codeFile != null && codeFile.exists()) { 15273 try { 15274 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15275 return pkg.getAllCodePaths(); 15276 } catch (PackageParserException e) { 15277 // Ignored; we tried our best 15278 } 15279 } 15280 return Collections.EMPTY_LIST; 15281 } 15282 15283 void cleanUpResourcesLI() { 15284 // Enumerate all code paths before deleting 15285 cleanUpResourcesLI(getAllCodePaths()); 15286 } 15287 15288 private void cleanUpResourcesLI(List<String> allCodePaths) { 15289 cleanUp(); 15290 removeDexFiles(allCodePaths, instructionSets); 15291 } 15292 15293 String getPackageName() { 15294 return getAsecPackageName(cid); 15295 } 15296 15297 boolean doPostDeleteLI(boolean delete) { 15298 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15299 final List<String> allCodePaths = getAllCodePaths(); 15300 boolean mounted = PackageHelper.isContainerMounted(cid); 15301 if (mounted) { 15302 // Unmount first 15303 if (PackageHelper.unMountSdDir(cid)) { 15304 mounted = false; 15305 } 15306 } 15307 if (!mounted && delete) { 15308 cleanUpResourcesLI(allCodePaths); 15309 } 15310 return !mounted; 15311 } 15312 15313 @Override 15314 int doPreCopy() { 15315 if (isFwdLocked()) { 15316 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15317 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15318 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15319 } 15320 } 15321 15322 return PackageManager.INSTALL_SUCCEEDED; 15323 } 15324 15325 @Override 15326 int doPostCopy(int uid) { 15327 if (isFwdLocked()) { 15328 if (uid < Process.FIRST_APPLICATION_UID 15329 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15330 RES_FILE_NAME)) { 15331 Slog.e(TAG, "Failed to finalize " + cid); 15332 PackageHelper.destroySdDir(cid); 15333 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15334 } 15335 } 15336 15337 return PackageManager.INSTALL_SUCCEEDED; 15338 } 15339 } 15340 15341 /** 15342 * Logic to handle movement of existing installed applications. 15343 */ 15344 class MoveInstallArgs extends InstallArgs { 15345 private File codeFile; 15346 private File resourceFile; 15347 15348 /** New install */ 15349 MoveInstallArgs(InstallParams params) { 15350 super(params.origin, params.move, params.observer, params.installFlags, 15351 params.installerPackageName, params.volumeUuid, 15352 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15353 params.grantedRuntimePermissions, 15354 params.traceMethod, params.traceCookie, params.certificates, 15355 params.installReason); 15356 } 15357 15358 int copyApk(IMediaContainerService imcs, boolean temp) { 15359 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15360 + move.fromUuid + " to " + move.toUuid); 15361 synchronized (mInstaller) { 15362 try { 15363 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15364 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15365 } catch (InstallerException e) { 15366 Slog.w(TAG, "Failed to move app", e); 15367 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15368 } 15369 } 15370 15371 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15372 resourceFile = codeFile; 15373 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15374 15375 return PackageManager.INSTALL_SUCCEEDED; 15376 } 15377 15378 int doPreInstall(int status) { 15379 if (status != PackageManager.INSTALL_SUCCEEDED) { 15380 cleanUp(move.toUuid); 15381 } 15382 return status; 15383 } 15384 15385 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15386 if (status != PackageManager.INSTALL_SUCCEEDED) { 15387 cleanUp(move.toUuid); 15388 return false; 15389 } 15390 15391 // Reflect the move in app info 15392 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15393 pkg.setApplicationInfoCodePath(pkg.codePath); 15394 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15395 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15396 pkg.setApplicationInfoResourcePath(pkg.codePath); 15397 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15398 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15399 15400 return true; 15401 } 15402 15403 int doPostInstall(int status, int uid) { 15404 if (status == PackageManager.INSTALL_SUCCEEDED) { 15405 cleanUp(move.fromUuid); 15406 } else { 15407 cleanUp(move.toUuid); 15408 } 15409 return status; 15410 } 15411 15412 @Override 15413 String getCodePath() { 15414 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15415 } 15416 15417 @Override 15418 String getResourcePath() { 15419 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15420 } 15421 15422 private boolean cleanUp(String volumeUuid) { 15423 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15424 move.dataAppName); 15425 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15426 final int[] userIds = sUserManager.getUserIds(); 15427 synchronized (mInstallLock) { 15428 // Clean up both app data and code 15429 // All package moves are frozen until finished 15430 for (int userId : userIds) { 15431 try { 15432 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15433 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15434 } catch (InstallerException e) { 15435 Slog.w(TAG, String.valueOf(e)); 15436 } 15437 } 15438 removeCodePathLI(codeFile); 15439 } 15440 return true; 15441 } 15442 15443 void cleanUpResourcesLI() { 15444 throw new UnsupportedOperationException(); 15445 } 15446 15447 boolean doPostDeleteLI(boolean delete) { 15448 throw new UnsupportedOperationException(); 15449 } 15450 } 15451 15452 static String getAsecPackageName(String packageCid) { 15453 int idx = packageCid.lastIndexOf("-"); 15454 if (idx == -1) { 15455 return packageCid; 15456 } 15457 return packageCid.substring(0, idx); 15458 } 15459 15460 // Utility method used to create code paths based on package name and available index. 15461 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15462 String idxStr = ""; 15463 int idx = 1; 15464 // Fall back to default value of idx=1 if prefix is not 15465 // part of oldCodePath 15466 if (oldCodePath != null) { 15467 String subStr = oldCodePath; 15468 // Drop the suffix right away 15469 if (suffix != null && subStr.endsWith(suffix)) { 15470 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15471 } 15472 // If oldCodePath already contains prefix find out the 15473 // ending index to either increment or decrement. 15474 int sidx = subStr.lastIndexOf(prefix); 15475 if (sidx != -1) { 15476 subStr = subStr.substring(sidx + prefix.length()); 15477 if (subStr != null) { 15478 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15479 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15480 } 15481 try { 15482 idx = Integer.parseInt(subStr); 15483 if (idx <= 1) { 15484 idx++; 15485 } else { 15486 idx--; 15487 } 15488 } catch(NumberFormatException e) { 15489 } 15490 } 15491 } 15492 } 15493 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15494 return prefix + idxStr; 15495 } 15496 15497 private File getNextCodePath(File targetDir, String packageName) { 15498 File result; 15499 SecureRandom random = new SecureRandom(); 15500 byte[] bytes = new byte[16]; 15501 do { 15502 random.nextBytes(bytes); 15503 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15504 result = new File(targetDir, packageName + "-" + suffix); 15505 } while (result.exists()); 15506 return result; 15507 } 15508 15509 // Utility method that returns the relative package path with respect 15510 // to the installation directory. Like say for /data/data/com.test-1.apk 15511 // string com.test-1 is returned. 15512 static String deriveCodePathName(String codePath) { 15513 if (codePath == null) { 15514 return null; 15515 } 15516 final File codeFile = new File(codePath); 15517 final String name = codeFile.getName(); 15518 if (codeFile.isDirectory()) { 15519 return name; 15520 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15521 final int lastDot = name.lastIndexOf('.'); 15522 return name.substring(0, lastDot); 15523 } else { 15524 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15525 return null; 15526 } 15527 } 15528 15529 static class PackageInstalledInfo { 15530 String name; 15531 int uid; 15532 // The set of users that originally had this package installed. 15533 int[] origUsers; 15534 // The set of users that now have this package installed. 15535 int[] newUsers; 15536 PackageParser.Package pkg; 15537 int returnCode; 15538 String returnMsg; 15539 PackageRemovedInfo removedInfo; 15540 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15541 15542 public void setError(int code, String msg) { 15543 setReturnCode(code); 15544 setReturnMessage(msg); 15545 Slog.w(TAG, msg); 15546 } 15547 15548 public void setError(String msg, PackageParserException e) { 15549 setReturnCode(e.error); 15550 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15551 Slog.w(TAG, msg, e); 15552 } 15553 15554 public void setError(String msg, PackageManagerException e) { 15555 returnCode = e.error; 15556 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15557 Slog.w(TAG, msg, e); 15558 } 15559 15560 public void setReturnCode(int returnCode) { 15561 this.returnCode = returnCode; 15562 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15563 for (int i = 0; i < childCount; i++) { 15564 addedChildPackages.valueAt(i).returnCode = returnCode; 15565 } 15566 } 15567 15568 private void setReturnMessage(String returnMsg) { 15569 this.returnMsg = returnMsg; 15570 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15571 for (int i = 0; i < childCount; i++) { 15572 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15573 } 15574 } 15575 15576 // In some error cases we want to convey more info back to the observer 15577 String origPackage; 15578 String origPermission; 15579 } 15580 15581 /* 15582 * Install a non-existing package. 15583 */ 15584 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15585 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15586 PackageInstalledInfo res, int installReason) { 15587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15588 15589 // Remember this for later, in case we need to rollback this install 15590 String pkgName = pkg.packageName; 15591 15592 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15593 15594 synchronized(mPackages) { 15595 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15596 if (renamedPackage != null) { 15597 // A package with the same name is already installed, though 15598 // it has been renamed to an older name. The package we 15599 // are trying to install should be installed as an update to 15600 // the existing one, but that has not been requested, so bail. 15601 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15602 + " without first uninstalling package running as " 15603 + renamedPackage); 15604 return; 15605 } 15606 if (mPackages.containsKey(pkgName)) { 15607 // Don't allow installation over an existing package with the same name. 15608 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15609 + " without first uninstalling."); 15610 return; 15611 } 15612 } 15613 15614 try { 15615 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15616 System.currentTimeMillis(), user); 15617 15618 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15619 15620 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15621 prepareAppDataAfterInstallLIF(newPackage); 15622 15623 } else { 15624 // Remove package from internal structures, but keep around any 15625 // data that might have already existed 15626 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15627 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15628 } 15629 } catch (PackageManagerException e) { 15630 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15631 } 15632 15633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15634 } 15635 15636 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15637 // Can't rotate keys during boot or if sharedUser. 15638 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15639 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15640 return false; 15641 } 15642 // app is using upgradeKeySets; make sure all are valid 15643 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15644 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15645 for (int i = 0; i < upgradeKeySets.length; i++) { 15646 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15647 Slog.wtf(TAG, "Package " 15648 + (oldPs.name != null ? oldPs.name : "<null>") 15649 + " contains upgrade-key-set reference to unknown key-set: " 15650 + upgradeKeySets[i] 15651 + " reverting to signatures check."); 15652 return false; 15653 } 15654 } 15655 return true; 15656 } 15657 15658 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15659 // Upgrade keysets are being used. Determine if new package has a superset of the 15660 // required keys. 15661 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15662 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15663 for (int i = 0; i < upgradeKeySets.length; i++) { 15664 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15665 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15666 return true; 15667 } 15668 } 15669 return false; 15670 } 15671 15672 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15673 try (DigestInputStream digestStream = 15674 new DigestInputStream(new FileInputStream(file), digest)) { 15675 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15676 } 15677 } 15678 15679 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15680 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15681 int installReason) { 15682 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 15683 15684 final PackageParser.Package oldPackage; 15685 final String pkgName = pkg.packageName; 15686 final int[] allUsers; 15687 final int[] installedUsers; 15688 15689 synchronized(mPackages) { 15690 oldPackage = mPackages.get(pkgName); 15691 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15692 15693 // don't allow upgrade to target a release SDK from a pre-release SDK 15694 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15695 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15696 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15697 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15698 if (oldTargetsPreRelease 15699 && !newTargetsPreRelease 15700 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15701 Slog.w(TAG, "Can't install package targeting released sdk"); 15702 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15703 return; 15704 } 15705 15706 // don't allow an upgrade from full to ephemeral 15707 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 15708 if (isEphemeral && !oldIsEphemeral) { 15709 // can't downgrade from full to ephemeral 15710 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 15711 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15712 return; 15713 } 15714 15715 // verify signatures are valid 15716 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15717 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15718 if (!checkUpgradeKeySetLP(ps, pkg)) { 15719 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15720 "New package not signed by keys specified by upgrade-keysets: " 15721 + pkgName); 15722 return; 15723 } 15724 } else { 15725 // default to original signature matching 15726 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15727 != PackageManager.SIGNATURE_MATCH) { 15728 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15729 "New package has a different signature: " + pkgName); 15730 return; 15731 } 15732 } 15733 15734 // don't allow a system upgrade unless the upgrade hash matches 15735 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15736 byte[] digestBytes = null; 15737 try { 15738 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15739 updateDigest(digest, new File(pkg.baseCodePath)); 15740 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15741 for (String path : pkg.splitCodePaths) { 15742 updateDigest(digest, new File(path)); 15743 } 15744 } 15745 digestBytes = digest.digest(); 15746 } catch (NoSuchAlgorithmException | IOException e) { 15747 res.setError(INSTALL_FAILED_INVALID_APK, 15748 "Could not compute hash: " + pkgName); 15749 return; 15750 } 15751 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15752 res.setError(INSTALL_FAILED_INVALID_APK, 15753 "New package fails restrict-update check: " + pkgName); 15754 return; 15755 } 15756 // retain upgrade restriction 15757 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15758 } 15759 15760 // Check for shared user id changes 15761 String invalidPackageName = 15762 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15763 if (invalidPackageName != null) { 15764 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15765 "Package " + invalidPackageName + " tried to change user " 15766 + oldPackage.mSharedUserId); 15767 return; 15768 } 15769 15770 // In case of rollback, remember per-user/profile install state 15771 allUsers = sUserManager.getUserIds(); 15772 installedUsers = ps.queryInstalledUsers(allUsers, true); 15773 } 15774 15775 // Update what is removed 15776 res.removedInfo = new PackageRemovedInfo(); 15777 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15778 res.removedInfo.removedPackage = oldPackage.packageName; 15779 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15780 res.removedInfo.isUpdate = true; 15781 res.removedInfo.origUsers = installedUsers; 15782 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15783 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15784 for (int i = 0; i < installedUsers.length; i++) { 15785 final int userId = installedUsers[i]; 15786 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15787 } 15788 15789 final int childCount = (oldPackage.childPackages != null) 15790 ? oldPackage.childPackages.size() : 0; 15791 for (int i = 0; i < childCount; i++) { 15792 boolean childPackageUpdated = false; 15793 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15794 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15795 if (res.addedChildPackages != null) { 15796 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15797 if (childRes != null) { 15798 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15799 childRes.removedInfo.removedPackage = childPkg.packageName; 15800 childRes.removedInfo.isUpdate = true; 15801 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15802 childPackageUpdated = true; 15803 } 15804 } 15805 if (!childPackageUpdated) { 15806 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15807 childRemovedRes.removedPackage = childPkg.packageName; 15808 childRemovedRes.isUpdate = false; 15809 childRemovedRes.dataRemoved = true; 15810 synchronized (mPackages) { 15811 if (childPs != null) { 15812 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15813 } 15814 } 15815 if (res.removedInfo.removedChildPackages == null) { 15816 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15817 } 15818 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15819 } 15820 } 15821 15822 boolean sysPkg = (isSystemApp(oldPackage)); 15823 if (sysPkg) { 15824 // Set the system/privileged flags as needed 15825 final boolean privileged = 15826 (oldPackage.applicationInfo.privateFlags 15827 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15828 final int systemPolicyFlags = policyFlags 15829 | PackageParser.PARSE_IS_SYSTEM 15830 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15831 15832 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15833 user, allUsers, installerPackageName, res, installReason); 15834 } else { 15835 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15836 user, allUsers, installerPackageName, res, installReason); 15837 } 15838 } 15839 15840 public List<String> getPreviousCodePaths(String packageName) { 15841 final PackageSetting ps = mSettings.mPackages.get(packageName); 15842 final List<String> result = new ArrayList<String>(); 15843 if (ps != null && ps.oldCodePaths != null) { 15844 result.addAll(ps.oldCodePaths); 15845 } 15846 return result; 15847 } 15848 15849 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15850 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15851 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15852 int installReason) { 15853 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15854 + deletedPackage); 15855 15856 String pkgName = deletedPackage.packageName; 15857 boolean deletedPkg = true; 15858 boolean addedPkg = false; 15859 boolean updatedSettings = false; 15860 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15861 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15862 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15863 15864 final long origUpdateTime = (pkg.mExtras != null) 15865 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15866 15867 // First delete the existing package while retaining the data directory 15868 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15869 res.removedInfo, true, pkg)) { 15870 // If the existing package wasn't successfully deleted 15871 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15872 deletedPkg = false; 15873 } else { 15874 // Successfully deleted the old package; proceed with replace. 15875 15876 // If deleted package lived in a container, give users a chance to 15877 // relinquish resources before killing. 15878 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15879 if (DEBUG_INSTALL) { 15880 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15881 } 15882 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15883 final ArrayList<String> pkgList = new ArrayList<String>(1); 15884 pkgList.add(deletedPackage.applicationInfo.packageName); 15885 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15886 } 15887 15888 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15889 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15890 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15891 15892 try { 15893 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15894 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15895 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15896 installReason); 15897 15898 // Update the in-memory copy of the previous code paths. 15899 PackageSetting ps = mSettings.mPackages.get(pkgName); 15900 if (!killApp) { 15901 if (ps.oldCodePaths == null) { 15902 ps.oldCodePaths = new ArraySet<>(); 15903 } 15904 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15905 if (deletedPackage.splitCodePaths != null) { 15906 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15907 } 15908 } else { 15909 ps.oldCodePaths = null; 15910 } 15911 if (ps.childPackageNames != null) { 15912 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15913 final String childPkgName = ps.childPackageNames.get(i); 15914 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15915 childPs.oldCodePaths = ps.oldCodePaths; 15916 } 15917 } 15918 prepareAppDataAfterInstallLIF(newPackage); 15919 addedPkg = true; 15920 } catch (PackageManagerException e) { 15921 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15922 } 15923 } 15924 15925 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15926 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15927 15928 // Revert all internal state mutations and added folders for the failed install 15929 if (addedPkg) { 15930 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15931 res.removedInfo, true, null); 15932 } 15933 15934 // Restore the old package 15935 if (deletedPkg) { 15936 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15937 File restoreFile = new File(deletedPackage.codePath); 15938 // Parse old package 15939 boolean oldExternal = isExternal(deletedPackage); 15940 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15941 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15942 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15943 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15944 try { 15945 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15946 null); 15947 } catch (PackageManagerException e) { 15948 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15949 + e.getMessage()); 15950 return; 15951 } 15952 15953 synchronized (mPackages) { 15954 // Ensure the installer package name up to date 15955 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15956 15957 // Update permissions for restored package 15958 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15959 15960 mSettings.writeLPr(); 15961 } 15962 15963 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15964 } 15965 } else { 15966 synchronized (mPackages) { 15967 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15968 if (ps != null) { 15969 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15970 if (res.removedInfo.removedChildPackages != null) { 15971 final int childCount = res.removedInfo.removedChildPackages.size(); 15972 // Iterate in reverse as we may modify the collection 15973 for (int i = childCount - 1; i >= 0; i--) { 15974 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15975 if (res.addedChildPackages.containsKey(childPackageName)) { 15976 res.removedInfo.removedChildPackages.removeAt(i); 15977 } else { 15978 PackageRemovedInfo childInfo = res.removedInfo 15979 .removedChildPackages.valueAt(i); 15980 childInfo.removedForAllUsers = mPackages.get( 15981 childInfo.removedPackage) == null; 15982 } 15983 } 15984 } 15985 } 15986 } 15987 } 15988 } 15989 15990 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15991 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15992 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15993 int installReason) { 15994 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15995 + ", old=" + deletedPackage); 15996 15997 final boolean disabledSystem; 15998 15999 // Remove existing system package 16000 removePackageLI(deletedPackage, true); 16001 16002 synchronized (mPackages) { 16003 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16004 } 16005 if (!disabledSystem) { 16006 // We didn't need to disable the .apk as a current system package, 16007 // which means we are replacing another update that is already 16008 // installed. We need to make sure to delete the older one's .apk. 16009 res.removedInfo.args = createInstallArgsForExisting(0, 16010 deletedPackage.applicationInfo.getCodePath(), 16011 deletedPackage.applicationInfo.getResourcePath(), 16012 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16013 } else { 16014 res.removedInfo.args = null; 16015 } 16016 16017 // Successfully disabled the old package. Now proceed with re-installation 16018 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16019 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16020 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16021 16022 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16023 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16024 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16025 16026 PackageParser.Package newPackage = null; 16027 try { 16028 // Add the package to the internal data structures 16029 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16030 16031 // Set the update and install times 16032 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16033 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16034 System.currentTimeMillis()); 16035 16036 // Update the package dynamic state if succeeded 16037 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16038 // Now that the install succeeded make sure we remove data 16039 // directories for any child package the update removed. 16040 final int deletedChildCount = (deletedPackage.childPackages != null) 16041 ? deletedPackage.childPackages.size() : 0; 16042 final int newChildCount = (newPackage.childPackages != null) 16043 ? newPackage.childPackages.size() : 0; 16044 for (int i = 0; i < deletedChildCount; i++) { 16045 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16046 boolean childPackageDeleted = true; 16047 for (int j = 0; j < newChildCount; j++) { 16048 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16049 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16050 childPackageDeleted = false; 16051 break; 16052 } 16053 } 16054 if (childPackageDeleted) { 16055 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16056 deletedChildPkg.packageName); 16057 if (ps != null && res.removedInfo.removedChildPackages != null) { 16058 PackageRemovedInfo removedChildRes = res.removedInfo 16059 .removedChildPackages.get(deletedChildPkg.packageName); 16060 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16061 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16062 } 16063 } 16064 } 16065 16066 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16067 installReason); 16068 prepareAppDataAfterInstallLIF(newPackage); 16069 } 16070 } catch (PackageManagerException e) { 16071 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16072 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16073 } 16074 16075 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16076 // Re installation failed. Restore old information 16077 // Remove new pkg information 16078 if (newPackage != null) { 16079 removeInstalledPackageLI(newPackage, true); 16080 } 16081 // Add back the old system package 16082 try { 16083 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16084 } catch (PackageManagerException e) { 16085 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16086 } 16087 16088 synchronized (mPackages) { 16089 if (disabledSystem) { 16090 enableSystemPackageLPw(deletedPackage); 16091 } 16092 16093 // Ensure the installer package name up to date 16094 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16095 16096 // Update permissions for restored package 16097 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16098 16099 mSettings.writeLPr(); 16100 } 16101 16102 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16103 + " after failed upgrade"); 16104 } 16105 } 16106 16107 /** 16108 * Checks whether the parent or any of the child packages have a change shared 16109 * user. For a package to be a valid update the shred users of the parent and 16110 * the children should match. We may later support changing child shared users. 16111 * @param oldPkg The updated package. 16112 * @param newPkg The update package. 16113 * @return The shared user that change between the versions. 16114 */ 16115 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16116 PackageParser.Package newPkg) { 16117 // Check parent shared user 16118 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16119 return newPkg.packageName; 16120 } 16121 // Check child shared users 16122 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16123 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16124 for (int i = 0; i < newChildCount; i++) { 16125 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16126 // If this child was present, did it have the same shared user? 16127 for (int j = 0; j < oldChildCount; j++) { 16128 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16129 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16130 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16131 return newChildPkg.packageName; 16132 } 16133 } 16134 } 16135 return null; 16136 } 16137 16138 private void removeNativeBinariesLI(PackageSetting ps) { 16139 // Remove the lib path for the parent package 16140 if (ps != null) { 16141 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16142 // Remove the lib path for the child packages 16143 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16144 for (int i = 0; i < childCount; i++) { 16145 PackageSetting childPs = null; 16146 synchronized (mPackages) { 16147 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16148 } 16149 if (childPs != null) { 16150 NativeLibraryHelper.removeNativeBinariesLI(childPs 16151 .legacyNativeLibraryPathString); 16152 } 16153 } 16154 } 16155 } 16156 16157 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16158 // Enable the parent package 16159 mSettings.enableSystemPackageLPw(pkg.packageName); 16160 // Enable the child packages 16161 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16162 for (int i = 0; i < childCount; i++) { 16163 PackageParser.Package childPkg = pkg.childPackages.get(i); 16164 mSettings.enableSystemPackageLPw(childPkg.packageName); 16165 } 16166 } 16167 16168 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16169 PackageParser.Package newPkg) { 16170 // Disable the parent package (parent always replaced) 16171 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16172 // Disable the child packages 16173 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16174 for (int i = 0; i < childCount; i++) { 16175 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16176 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16177 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16178 } 16179 return disabled; 16180 } 16181 16182 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16183 String installerPackageName) { 16184 // Enable the parent package 16185 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16186 // Enable the child packages 16187 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16188 for (int i = 0; i < childCount; i++) { 16189 PackageParser.Package childPkg = pkg.childPackages.get(i); 16190 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16191 } 16192 } 16193 16194 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16195 // Collect all used permissions in the UID 16196 ArraySet<String> usedPermissions = new ArraySet<>(); 16197 final int packageCount = su.packages.size(); 16198 for (int i = 0; i < packageCount; i++) { 16199 PackageSetting ps = su.packages.valueAt(i); 16200 if (ps.pkg == null) { 16201 continue; 16202 } 16203 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16204 for (int j = 0; j < requestedPermCount; j++) { 16205 String permission = ps.pkg.requestedPermissions.get(j); 16206 BasePermission bp = mSettings.mPermissions.get(permission); 16207 if (bp != null) { 16208 usedPermissions.add(permission); 16209 } 16210 } 16211 } 16212 16213 PermissionsState permissionsState = su.getPermissionsState(); 16214 // Prune install permissions 16215 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16216 final int installPermCount = installPermStates.size(); 16217 for (int i = installPermCount - 1; i >= 0; i--) { 16218 PermissionState permissionState = installPermStates.get(i); 16219 if (!usedPermissions.contains(permissionState.getName())) { 16220 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16221 if (bp != null) { 16222 permissionsState.revokeInstallPermission(bp); 16223 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16224 PackageManager.MASK_PERMISSION_FLAGS, 0); 16225 } 16226 } 16227 } 16228 16229 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16230 16231 // Prune runtime permissions 16232 for (int userId : allUserIds) { 16233 List<PermissionState> runtimePermStates = permissionsState 16234 .getRuntimePermissionStates(userId); 16235 final int runtimePermCount = runtimePermStates.size(); 16236 for (int i = runtimePermCount - 1; i >= 0; i--) { 16237 PermissionState permissionState = runtimePermStates.get(i); 16238 if (!usedPermissions.contains(permissionState.getName())) { 16239 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16240 if (bp != null) { 16241 permissionsState.revokeRuntimePermission(bp, userId); 16242 permissionsState.updatePermissionFlags(bp, userId, 16243 PackageManager.MASK_PERMISSION_FLAGS, 0); 16244 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16245 runtimePermissionChangedUserIds, userId); 16246 } 16247 } 16248 } 16249 } 16250 16251 return runtimePermissionChangedUserIds; 16252 } 16253 16254 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16255 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16256 // Update the parent package setting 16257 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16258 res, user, installReason); 16259 // Update the child packages setting 16260 final int childCount = (newPackage.childPackages != null) 16261 ? newPackage.childPackages.size() : 0; 16262 for (int i = 0; i < childCount; i++) { 16263 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16264 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16265 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16266 childRes.origUsers, childRes, user, installReason); 16267 } 16268 } 16269 16270 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16271 String installerPackageName, int[] allUsers, int[] installedForUsers, 16272 PackageInstalledInfo res, UserHandle user, int installReason) { 16273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16274 16275 String pkgName = newPackage.packageName; 16276 synchronized (mPackages) { 16277 //write settings. the installStatus will be incomplete at this stage. 16278 //note that the new package setting would have already been 16279 //added to mPackages. It hasn't been persisted yet. 16280 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16282 mSettings.writeLPr(); 16283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16284 } 16285 16286 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16287 synchronized (mPackages) { 16288 updatePermissionsLPw(newPackage.packageName, newPackage, 16289 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16290 ? UPDATE_PERMISSIONS_ALL : 0)); 16291 // For system-bundled packages, we assume that installing an upgraded version 16292 // of the package implies that the user actually wants to run that new code, 16293 // so we enable the package. 16294 PackageSetting ps = mSettings.mPackages.get(pkgName); 16295 final int userId = user.getIdentifier(); 16296 if (ps != null) { 16297 if (isSystemApp(newPackage)) { 16298 if (DEBUG_INSTALL) { 16299 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16300 } 16301 // Enable system package for requested users 16302 if (res.origUsers != null) { 16303 for (int origUserId : res.origUsers) { 16304 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16305 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16306 origUserId, installerPackageName); 16307 } 16308 } 16309 } 16310 // Also convey the prior install/uninstall state 16311 if (allUsers != null && installedForUsers != null) { 16312 for (int currentUserId : allUsers) { 16313 final boolean installed = ArrayUtils.contains( 16314 installedForUsers, currentUserId); 16315 if (DEBUG_INSTALL) { 16316 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16317 } 16318 ps.setInstalled(installed, currentUserId); 16319 } 16320 // these install state changes will be persisted in the 16321 // upcoming call to mSettings.writeLPr(). 16322 } 16323 } 16324 // It's implied that when a user requests installation, they want the app to be 16325 // installed and enabled. 16326 if (userId != UserHandle.USER_ALL) { 16327 ps.setInstalled(true, userId); 16328 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16329 } 16330 16331 // When replacing an existing package, preserve the original install reason for all 16332 // users that had the package installed before. 16333 final Set<Integer> previousUserIds = new ArraySet<>(); 16334 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16335 final int installReasonCount = res.removedInfo.installReasons.size(); 16336 for (int i = 0; i < installReasonCount; i++) { 16337 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16338 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16339 ps.setInstallReason(previousInstallReason, previousUserId); 16340 previousUserIds.add(previousUserId); 16341 } 16342 } 16343 16344 // Set install reason for users that are having the package newly installed. 16345 if (userId == UserHandle.USER_ALL) { 16346 for (int currentUserId : sUserManager.getUserIds()) { 16347 if (!previousUserIds.contains(currentUserId)) { 16348 ps.setInstallReason(installReason, currentUserId); 16349 } 16350 } 16351 } else if (!previousUserIds.contains(userId)) { 16352 ps.setInstallReason(installReason, userId); 16353 } 16354 } 16355 res.name = pkgName; 16356 res.uid = newPackage.applicationInfo.uid; 16357 res.pkg = newPackage; 16358 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16359 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16360 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16361 //to update install status 16362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16363 mSettings.writeLPr(); 16364 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16365 } 16366 16367 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16368 } 16369 16370 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16371 try { 16372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16373 installPackageLI(args, res); 16374 } finally { 16375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16376 } 16377 } 16378 16379 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16380 final int installFlags = args.installFlags; 16381 final String installerPackageName = args.installerPackageName; 16382 final String volumeUuid = args.volumeUuid; 16383 final File tmpPackageFile = new File(args.getCodePath()); 16384 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16385 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16386 || (args.volumeUuid != null)); 16387 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 16388 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16389 boolean replace = false; 16390 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16391 if (args.move != null) { 16392 // moving a complete application; perform an initial scan on the new install location 16393 scanFlags |= SCAN_INITIAL; 16394 } 16395 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16396 scanFlags |= SCAN_DONT_KILL_APP; 16397 } 16398 16399 // Result object to be returned 16400 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16401 16402 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16403 16404 // Sanity check 16405 if (ephemeral && (forwardLocked || onExternal)) { 16406 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16407 + " external=" + onExternal); 16408 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 16409 return; 16410 } 16411 16412 // Retrieve PackageSettings and parse package 16413 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16414 | PackageParser.PARSE_ENFORCE_CODE 16415 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16416 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16417 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16418 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16419 PackageParser pp = new PackageParser(); 16420 pp.setSeparateProcesses(mSeparateProcesses); 16421 pp.setDisplayMetrics(mMetrics); 16422 16423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16424 final PackageParser.Package pkg; 16425 try { 16426 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16427 } catch (PackageParserException e) { 16428 res.setError("Failed parse during installPackageLI", e); 16429 return; 16430 } finally { 16431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16432 } 16433 16434// // Ephemeral apps must have target SDK >= O. 16435// // TODO: Update conditional and error message when O gets locked down 16436// if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16437// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16438// "Ephemeral apps must have target SDK version of at least O"); 16439// return; 16440// } 16441 16442 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16443 // Static shared libraries have synthetic package names 16444 renameStaticSharedLibraryPackage(pkg); 16445 16446 // No static shared libs on external storage 16447 if (onExternal) { 16448 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16449 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16450 "Packages declaring static-shared libs cannot be updated"); 16451 return; 16452 } 16453 } 16454 16455 // If we are installing a clustered package add results for the children 16456 if (pkg.childPackages != null) { 16457 synchronized (mPackages) { 16458 final int childCount = pkg.childPackages.size(); 16459 for (int i = 0; i < childCount; i++) { 16460 PackageParser.Package childPkg = pkg.childPackages.get(i); 16461 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16462 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16463 childRes.pkg = childPkg; 16464 childRes.name = childPkg.packageName; 16465 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16466 if (childPs != null) { 16467 childRes.origUsers = childPs.queryInstalledUsers( 16468 sUserManager.getUserIds(), true); 16469 } 16470 if ((mPackages.containsKey(childPkg.packageName))) { 16471 childRes.removedInfo = new PackageRemovedInfo(); 16472 childRes.removedInfo.removedPackage = childPkg.packageName; 16473 } 16474 if (res.addedChildPackages == null) { 16475 res.addedChildPackages = new ArrayMap<>(); 16476 } 16477 res.addedChildPackages.put(childPkg.packageName, childRes); 16478 } 16479 } 16480 } 16481 16482 // If package doesn't declare API override, mark that we have an install 16483 // time CPU ABI override. 16484 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16485 pkg.cpuAbiOverride = args.abiOverride; 16486 } 16487 16488 String pkgName = res.name = pkg.packageName; 16489 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16490 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16491 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16492 return; 16493 } 16494 } 16495 16496 try { 16497 // either use what we've been given or parse directly from the APK 16498 if (args.certificates != null) { 16499 try { 16500 PackageParser.populateCertificates(pkg, args.certificates); 16501 } catch (PackageParserException e) { 16502 // there was something wrong with the certificates we were given; 16503 // try to pull them from the APK 16504 PackageParser.collectCertificates(pkg, parseFlags); 16505 } 16506 } else { 16507 PackageParser.collectCertificates(pkg, parseFlags); 16508 } 16509 } catch (PackageParserException e) { 16510 res.setError("Failed collect during installPackageLI", e); 16511 return; 16512 } 16513 16514 // Get rid of all references to package scan path via parser. 16515 pp = null; 16516 String oldCodePath = null; 16517 boolean systemApp = false; 16518 synchronized (mPackages) { 16519 // Check if installing already existing package 16520 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16521 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16522 if (pkg.mOriginalPackages != null 16523 && pkg.mOriginalPackages.contains(oldName) 16524 && mPackages.containsKey(oldName)) { 16525 // This package is derived from an original package, 16526 // and this device has been updating from that original 16527 // name. We must continue using the original name, so 16528 // rename the new package here. 16529 pkg.setPackageName(oldName); 16530 pkgName = pkg.packageName; 16531 replace = true; 16532 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16533 + oldName + " pkgName=" + pkgName); 16534 } else if (mPackages.containsKey(pkgName)) { 16535 // This package, under its official name, already exists 16536 // on the device; we should replace it. 16537 replace = true; 16538 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16539 } 16540 16541 // Child packages are installed through the parent package 16542 if (pkg.parentPackage != null) { 16543 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16544 "Package " + pkg.packageName + " is child of package " 16545 + pkg.parentPackage.parentPackage + ". Child packages " 16546 + "can be updated only through the parent package."); 16547 return; 16548 } 16549 16550 if (replace) { 16551 // Prevent apps opting out from runtime permissions 16552 PackageParser.Package oldPackage = mPackages.get(pkgName); 16553 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16554 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16555 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16556 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16557 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16558 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16559 + " doesn't support runtime permissions but the old" 16560 + " target SDK " + oldTargetSdk + " does."); 16561 return; 16562 } 16563 16564 // Prevent installing of child packages 16565 if (oldPackage.parentPackage != null) { 16566 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16567 "Package " + pkg.packageName + " is child of package " 16568 + oldPackage.parentPackage + ". Child packages " 16569 + "can be updated only through the parent package."); 16570 return; 16571 } 16572 } 16573 } 16574 16575 PackageSetting ps = mSettings.mPackages.get(pkgName); 16576 if (ps != null) { 16577 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16578 16579 // Static shared libs have same package with different versions where 16580 // we internally use a synthetic package name to allow multiple versions 16581 // of the same package, therefore we need to compare signatures against 16582 // the package setting for the latest library version. 16583 PackageSetting signatureCheckPs = ps; 16584 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16585 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16586 if (libraryEntry != null) { 16587 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16588 } 16589 } 16590 16591 // Quick sanity check that we're signed correctly if updating; 16592 // we'll check this again later when scanning, but we want to 16593 // bail early here before tripping over redefined permissions. 16594 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16595 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16596 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16597 + pkg.packageName + " upgrade keys do not match the " 16598 + "previously installed version"); 16599 return; 16600 } 16601 } else { 16602 try { 16603 verifySignaturesLP(signatureCheckPs, pkg); 16604 } catch (PackageManagerException e) { 16605 res.setError(e.error, e.getMessage()); 16606 return; 16607 } 16608 } 16609 16610 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16611 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16612 systemApp = (ps.pkg.applicationInfo.flags & 16613 ApplicationInfo.FLAG_SYSTEM) != 0; 16614 } 16615 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16616 } 16617 16618 // Check whether the newly-scanned package wants to define an already-defined perm 16619 int N = pkg.permissions.size(); 16620 for (int i = N-1; i >= 0; i--) { 16621 PackageParser.Permission perm = pkg.permissions.get(i); 16622 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16623 if (bp != null) { 16624 // If the defining package is signed with our cert, it's okay. This 16625 // also includes the "updating the same package" case, of course. 16626 // "updating same package" could also involve key-rotation. 16627 final boolean sigsOk; 16628 if (bp.sourcePackage.equals(pkg.packageName) 16629 && (bp.packageSetting instanceof PackageSetting) 16630 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16631 scanFlags))) { 16632 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16633 } else { 16634 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16635 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16636 } 16637 if (!sigsOk) { 16638 // If the owning package is the system itself, we log but allow 16639 // install to proceed; we fail the install on all other permission 16640 // redefinitions. 16641 if (!bp.sourcePackage.equals("android")) { 16642 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16643 + pkg.packageName + " attempting to redeclare permission " 16644 + perm.info.name + " already owned by " + bp.sourcePackage); 16645 res.origPermission = perm.info.name; 16646 res.origPackage = bp.sourcePackage; 16647 return; 16648 } else { 16649 Slog.w(TAG, "Package " + pkg.packageName 16650 + " attempting to redeclare system permission " 16651 + perm.info.name + "; ignoring new declaration"); 16652 pkg.permissions.remove(i); 16653 } 16654 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16655 // Prevent apps to change protection level to dangerous from any other 16656 // type as this would allow a privilege escalation where an app adds a 16657 // normal/signature permission in other app's group and later redefines 16658 // it as dangerous leading to the group auto-grant. 16659 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16660 == PermissionInfo.PROTECTION_DANGEROUS) { 16661 if (bp != null && !bp.isRuntime()) { 16662 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16663 + "non-runtime permission " + perm.info.name 16664 + " to runtime; keeping old protection level"); 16665 perm.info.protectionLevel = bp.protectionLevel; 16666 } 16667 } 16668 } 16669 } 16670 } 16671 } 16672 16673 if (systemApp) { 16674 if (onExternal) { 16675 // Abort update; system app can't be replaced with app on sdcard 16676 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16677 "Cannot install updates to system apps on sdcard"); 16678 return; 16679 } else if (ephemeral) { 16680 // Abort update; system app can't be replaced with an ephemeral app 16681 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 16682 "Cannot update a system app with an ephemeral app"); 16683 return; 16684 } 16685 } 16686 16687 if (args.move != null) { 16688 // We did an in-place move, so dex is ready to roll 16689 scanFlags |= SCAN_NO_DEX; 16690 scanFlags |= SCAN_MOVE; 16691 16692 synchronized (mPackages) { 16693 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16694 if (ps == null) { 16695 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16696 "Missing settings for moved package " + pkgName); 16697 } 16698 16699 // We moved the entire application as-is, so bring over the 16700 // previously derived ABI information. 16701 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16702 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16703 } 16704 16705 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16706 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16707 scanFlags |= SCAN_NO_DEX; 16708 16709 try { 16710 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16711 args.abiOverride : pkg.cpuAbiOverride); 16712 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16713 true /*extractLibs*/, mAppLib32InstallDir); 16714 } catch (PackageManagerException pme) { 16715 Slog.e(TAG, "Error deriving application ABI", pme); 16716 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16717 return; 16718 } 16719 16720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16721 // Do not run PackageDexOptimizer through the local performDexOpt 16722 // method because `pkg` may not be in `mPackages` yet. 16723 // 16724 // Also, don't fail application installs if the dexopt step fails. 16725 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16726 null /* instructionSets */, false /* checkProfiles */, 16727 getCompilerFilterForReason(REASON_INSTALL), 16728 getOrCreateCompilerPackageStats(pkg)); 16729 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16730 16731 // Notify BackgroundDexOptService that the package has been changed. 16732 // If this is an update of a package which used to fail to compile, 16733 // BDOS will remove it from its blacklist. 16734 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16735 } 16736 16737 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16738 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16739 return; 16740 } 16741 16742 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16743 16744 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16745 "installPackageLI")) { 16746 if (replace) { 16747 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16748 // Static libs have a synthetic package name containing the version 16749 // and cannot be updated as an update would get a new package name, 16750 // unless this is the exact same version code which is useful for 16751 // development. 16752 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16753 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16754 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16755 + "static-shared libs cannot be updated"); 16756 return; 16757 } 16758 } 16759 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16760 installerPackageName, res, args.installReason); 16761 } else { 16762 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16763 args.user, installerPackageName, volumeUuid, res, args.installReason); 16764 } 16765 } 16766 synchronized (mPackages) { 16767 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16768 if (ps != null) { 16769 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16770 } 16771 16772 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16773 for (int i = 0; i < childCount; i++) { 16774 PackageParser.Package childPkg = pkg.childPackages.get(i); 16775 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16776 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16777 if (childPs != null) { 16778 childRes.newUsers = childPs.queryInstalledUsers( 16779 sUserManager.getUserIds(), true); 16780 } 16781 } 16782 } 16783 } 16784 16785 private void startIntentFilterVerifications(int userId, boolean replacing, 16786 PackageParser.Package pkg) { 16787 if (mIntentFilterVerifierComponent == null) { 16788 Slog.w(TAG, "No IntentFilter verification will not be done as " 16789 + "there is no IntentFilterVerifier available!"); 16790 return; 16791 } 16792 16793 final int verifierUid = getPackageUid( 16794 mIntentFilterVerifierComponent.getPackageName(), 16795 MATCH_DEBUG_TRIAGED_MISSING, 16796 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16797 16798 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16799 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16800 mHandler.sendMessage(msg); 16801 16802 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16803 for (int i = 0; i < childCount; i++) { 16804 PackageParser.Package childPkg = pkg.childPackages.get(i); 16805 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16806 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16807 mHandler.sendMessage(msg); 16808 } 16809 } 16810 16811 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16812 PackageParser.Package pkg) { 16813 int size = pkg.activities.size(); 16814 if (size == 0) { 16815 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16816 "No activity, so no need to verify any IntentFilter!"); 16817 return; 16818 } 16819 16820 final boolean hasDomainURLs = hasDomainURLs(pkg); 16821 if (!hasDomainURLs) { 16822 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16823 "No domain URLs, so no need to verify any IntentFilter!"); 16824 return; 16825 } 16826 16827 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16828 + " if any IntentFilter from the " + size 16829 + " Activities needs verification ..."); 16830 16831 int count = 0; 16832 final String packageName = pkg.packageName; 16833 16834 synchronized (mPackages) { 16835 // If this is a new install and we see that we've already run verification for this 16836 // package, we have nothing to do: it means the state was restored from backup. 16837 if (!replacing) { 16838 IntentFilterVerificationInfo ivi = 16839 mSettings.getIntentFilterVerificationLPr(packageName); 16840 if (ivi != null) { 16841 if (DEBUG_DOMAIN_VERIFICATION) { 16842 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16843 + ivi.getStatusString()); 16844 } 16845 return; 16846 } 16847 } 16848 16849 // If any filters need to be verified, then all need to be. 16850 boolean needToVerify = false; 16851 for (PackageParser.Activity a : pkg.activities) { 16852 for (ActivityIntentInfo filter : a.intents) { 16853 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16854 if (DEBUG_DOMAIN_VERIFICATION) { 16855 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16856 } 16857 needToVerify = true; 16858 break; 16859 } 16860 } 16861 } 16862 16863 if (needToVerify) { 16864 final int verificationId = mIntentFilterVerificationToken++; 16865 for (PackageParser.Activity a : pkg.activities) { 16866 for (ActivityIntentInfo filter : a.intents) { 16867 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16868 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16869 "Verification needed for IntentFilter:" + filter.toString()); 16870 mIntentFilterVerifier.addOneIntentFilterVerification( 16871 verifierUid, userId, verificationId, filter, packageName); 16872 count++; 16873 } 16874 } 16875 } 16876 } 16877 } 16878 16879 if (count > 0) { 16880 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16881 + " IntentFilter verification" + (count > 1 ? "s" : "") 16882 + " for userId:" + userId); 16883 mIntentFilterVerifier.startVerifications(userId); 16884 } else { 16885 if (DEBUG_DOMAIN_VERIFICATION) { 16886 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16887 } 16888 } 16889 } 16890 16891 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16892 final ComponentName cn = filter.activity.getComponentName(); 16893 final String packageName = cn.getPackageName(); 16894 16895 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16896 packageName); 16897 if (ivi == null) { 16898 return true; 16899 } 16900 int status = ivi.getStatus(); 16901 switch (status) { 16902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16903 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16904 return true; 16905 16906 default: 16907 // Nothing to do 16908 return false; 16909 } 16910 } 16911 16912 private static boolean isMultiArch(ApplicationInfo info) { 16913 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16914 } 16915 16916 private static boolean isExternal(PackageParser.Package pkg) { 16917 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16918 } 16919 16920 private static boolean isExternal(PackageSetting ps) { 16921 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16922 } 16923 16924 private static boolean isEphemeral(PackageParser.Package pkg) { 16925 return pkg.applicationInfo.isEphemeralApp(); 16926 } 16927 16928 private static boolean isEphemeral(PackageSetting ps) { 16929 return ps.pkg != null && isEphemeral(ps.pkg); 16930 } 16931 16932 private static boolean isSystemApp(PackageParser.Package pkg) { 16933 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16934 } 16935 16936 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16937 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16938 } 16939 16940 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16941 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16942 } 16943 16944 private static boolean isSystemApp(PackageSetting ps) { 16945 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16946 } 16947 16948 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16949 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16950 } 16951 16952 private int packageFlagsToInstallFlags(PackageSetting ps) { 16953 int installFlags = 0; 16954 if (isEphemeral(ps)) { 16955 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16956 } 16957 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16958 // This existing package was an external ASEC install when we have 16959 // the external flag without a UUID 16960 installFlags |= PackageManager.INSTALL_EXTERNAL; 16961 } 16962 if (ps.isForwardLocked()) { 16963 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16964 } 16965 return installFlags; 16966 } 16967 16968 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16969 if (isExternal(pkg)) { 16970 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16971 return StorageManager.UUID_PRIMARY_PHYSICAL; 16972 } else { 16973 return pkg.volumeUuid; 16974 } 16975 } else { 16976 return StorageManager.UUID_PRIVATE_INTERNAL; 16977 } 16978 } 16979 16980 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16981 if (isExternal(pkg)) { 16982 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16983 return mSettings.getExternalVersion(); 16984 } else { 16985 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16986 } 16987 } else { 16988 return mSettings.getInternalVersion(); 16989 } 16990 } 16991 16992 private void deleteTempPackageFiles() { 16993 final FilenameFilter filter = new FilenameFilter() { 16994 public boolean accept(File dir, String name) { 16995 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16996 } 16997 }; 16998 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16999 file.delete(); 17000 } 17001 } 17002 17003 @Override 17004 public void deletePackageAsUser(String packageName, int versionCode, 17005 IPackageDeleteObserver observer, int userId, int flags) { 17006 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17007 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17008 } 17009 17010 @Override 17011 public void deletePackageVersioned(VersionedPackage versionedPackage, 17012 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17013 mContext.enforceCallingOrSelfPermission( 17014 android.Manifest.permission.DELETE_PACKAGES, null); 17015 Preconditions.checkNotNull(versionedPackage); 17016 Preconditions.checkNotNull(observer); 17017 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17018 PackageManager.VERSION_CODE_HIGHEST, 17019 Integer.MAX_VALUE, "versionCode must be >= -1"); 17020 17021 final String packageName = versionedPackage.getPackageName(); 17022 // TODO: We will change version code to long, so in the new API it is long 17023 final int versionCode = (int) versionedPackage.getVersionCode(); 17024 final String internalPackageName; 17025 synchronized (mPackages) { 17026 // Normalize package name to handle renamed packages and static libs 17027 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17028 // TODO: We will change version code to long, so in the new API it is long 17029 (int) versionedPackage.getVersionCode()); 17030 } 17031 17032 final int uid = Binder.getCallingUid(); 17033 if (!isOrphaned(internalPackageName) 17034 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17035 try { 17036 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17037 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17038 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17039 observer.onUserActionRequired(intent); 17040 } catch (RemoteException re) { 17041 } 17042 return; 17043 } 17044 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17045 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17046 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17047 mContext.enforceCallingOrSelfPermission( 17048 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17049 "deletePackage for user " + userId); 17050 } 17051 17052 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17053 try { 17054 observer.onPackageDeleted(packageName, 17055 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17056 } catch (RemoteException re) { 17057 } 17058 return; 17059 } 17060 17061 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17062 try { 17063 observer.onPackageDeleted(packageName, 17064 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17065 } catch (RemoteException re) { 17066 } 17067 return; 17068 } 17069 17070 if (DEBUG_REMOVE) { 17071 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17072 + " deleteAllUsers: " + deleteAllUsers + " version=" 17073 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17074 ? "VERSION_CODE_HIGHEST" : versionCode)); 17075 } 17076 // Queue up an async operation since the package deletion may take a little while. 17077 mHandler.post(new Runnable() { 17078 public void run() { 17079 mHandler.removeCallbacks(this); 17080 int returnCode; 17081 if (!deleteAllUsers) { 17082 returnCode = deletePackageX(internalPackageName, versionCode, 17083 userId, deleteFlags); 17084 } else { 17085 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17086 internalPackageName, users); 17087 // If nobody is blocking uninstall, proceed with delete for all users 17088 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17089 returnCode = deletePackageX(internalPackageName, versionCode, 17090 userId, deleteFlags); 17091 } else { 17092 // Otherwise uninstall individually for users with blockUninstalls=false 17093 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17094 for (int userId : users) { 17095 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17096 returnCode = deletePackageX(internalPackageName, versionCode, 17097 userId, userFlags); 17098 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17099 Slog.w(TAG, "Package delete failed for user " + userId 17100 + ", returnCode " + returnCode); 17101 } 17102 } 17103 } 17104 // The app has only been marked uninstalled for certain users. 17105 // We still need to report that delete was blocked 17106 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17107 } 17108 } 17109 try { 17110 observer.onPackageDeleted(packageName, returnCode, null); 17111 } catch (RemoteException e) { 17112 Log.i(TAG, "Observer no longer exists."); 17113 } //end catch 17114 } //end run 17115 }); 17116 } 17117 17118 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17119 if (pkg.staticSharedLibName != null) { 17120 return pkg.manifestPackageName; 17121 } 17122 return pkg.packageName; 17123 } 17124 17125 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17126 // Handle renamed packages 17127 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17128 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17129 17130 // Is this a static library? 17131 SparseArray<SharedLibraryEntry> versionedLib = 17132 mStaticLibsByDeclaringPackage.get(packageName); 17133 if (versionedLib == null || versionedLib.size() <= 0) { 17134 return packageName; 17135 } 17136 17137 // Figure out which lib versions the caller can see 17138 SparseIntArray versionsCallerCanSee = null; 17139 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17140 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17141 && callingAppId != Process.ROOT_UID) { 17142 versionsCallerCanSee = new SparseIntArray(); 17143 String libName = versionedLib.valueAt(0).info.getName(); 17144 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17145 if (uidPackages != null) { 17146 for (String uidPackage : uidPackages) { 17147 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17148 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17149 if (libIdx >= 0) { 17150 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17151 versionsCallerCanSee.append(libVersion, libVersion); 17152 } 17153 } 17154 } 17155 } 17156 17157 // Caller can see nothing - done 17158 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17159 return packageName; 17160 } 17161 17162 // Find the version the caller can see and the app version code 17163 SharedLibraryEntry highestVersion = null; 17164 final int versionCount = versionedLib.size(); 17165 for (int i = 0; i < versionCount; i++) { 17166 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17167 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17168 libEntry.info.getVersion()) < 0) { 17169 continue; 17170 } 17171 // TODO: We will change version code to long, so in the new API it is long 17172 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17173 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17174 if (libVersionCode == versionCode) { 17175 return libEntry.apk; 17176 } 17177 } else if (highestVersion == null) { 17178 highestVersion = libEntry; 17179 } else if (libVersionCode > highestVersion.info 17180 .getDeclaringPackage().getVersionCode()) { 17181 highestVersion = libEntry; 17182 } 17183 } 17184 17185 if (highestVersion != null) { 17186 return highestVersion.apk; 17187 } 17188 17189 return packageName; 17190 } 17191 17192 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17193 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17194 || callingUid == Process.SYSTEM_UID) { 17195 return true; 17196 } 17197 final int callingUserId = UserHandle.getUserId(callingUid); 17198 // If the caller installed the pkgName, then allow it to silently uninstall. 17199 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17200 return true; 17201 } 17202 17203 // Allow package verifier to silently uninstall. 17204 if (mRequiredVerifierPackage != null && 17205 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17206 return true; 17207 } 17208 17209 // Allow package uninstaller to silently uninstall. 17210 if (mRequiredUninstallerPackage != null && 17211 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17212 return true; 17213 } 17214 17215 // Allow storage manager to silently uninstall. 17216 if (mStorageManagerPackage != null && 17217 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17218 return true; 17219 } 17220 return false; 17221 } 17222 17223 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17224 int[] result = EMPTY_INT_ARRAY; 17225 for (int userId : userIds) { 17226 if (getBlockUninstallForUser(packageName, userId)) { 17227 result = ArrayUtils.appendInt(result, userId); 17228 } 17229 } 17230 return result; 17231 } 17232 17233 @Override 17234 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17235 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17236 } 17237 17238 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17239 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17240 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17241 try { 17242 if (dpm != null) { 17243 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17244 /* callingUserOnly =*/ false); 17245 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17246 : deviceOwnerComponentName.getPackageName(); 17247 // Does the package contains the device owner? 17248 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17249 // this check is probably not needed, since DO should be registered as a device 17250 // admin on some user too. (Original bug for this: b/17657954) 17251 if (packageName.equals(deviceOwnerPackageName)) { 17252 return true; 17253 } 17254 // Does it contain a device admin for any user? 17255 int[] users; 17256 if (userId == UserHandle.USER_ALL) { 17257 users = sUserManager.getUserIds(); 17258 } else { 17259 users = new int[]{userId}; 17260 } 17261 for (int i = 0; i < users.length; ++i) { 17262 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17263 return true; 17264 } 17265 } 17266 } 17267 } catch (RemoteException e) { 17268 } 17269 return false; 17270 } 17271 17272 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17273 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17274 } 17275 17276 /** 17277 * This method is an internal method that could be get invoked either 17278 * to delete an installed package or to clean up a failed installation. 17279 * After deleting an installed package, a broadcast is sent to notify any 17280 * listeners that the package has been removed. For cleaning up a failed 17281 * installation, the broadcast is not necessary since the package's 17282 * installation wouldn't have sent the initial broadcast either 17283 * The key steps in deleting a package are 17284 * deleting the package information in internal structures like mPackages, 17285 * deleting the packages base directories through installd 17286 * updating mSettings to reflect current status 17287 * persisting settings for later use 17288 * sending a broadcast if necessary 17289 */ 17290 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17291 final PackageRemovedInfo info = new PackageRemovedInfo(); 17292 final boolean res; 17293 17294 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17295 ? UserHandle.USER_ALL : userId; 17296 17297 if (isPackageDeviceAdmin(packageName, removeUser)) { 17298 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17299 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17300 } 17301 17302 PackageSetting uninstalledPs = null; 17303 17304 // for the uninstall-updates case and restricted profiles, remember the per- 17305 // user handle installed state 17306 int[] allUsers; 17307 synchronized (mPackages) { 17308 uninstalledPs = mSettings.mPackages.get(packageName); 17309 if (uninstalledPs == null) { 17310 Slog.w(TAG, "Not removing non-existent package " + packageName); 17311 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17312 } 17313 17314 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17315 && uninstalledPs.versionCode != versionCode) { 17316 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17317 + uninstalledPs.versionCode + " != " + versionCode); 17318 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17319 } 17320 17321 // Static shared libs can be declared by any package, so let us not 17322 // allow removing a package if it provides a lib others depend on. 17323 PackageParser.Package pkg = mPackages.get(packageName); 17324 if (pkg != null && pkg.staticSharedLibName != null) { 17325 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17326 pkg.staticSharedLibVersion); 17327 if (libEntry != null) { 17328 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17329 libEntry.info, 0, userId); 17330 if (!ArrayUtils.isEmpty(libClientPackages)) { 17331 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17332 + " hosting lib " + libEntry.info.getName() + " version " 17333 + libEntry.info.getVersion() + " used by " + libClientPackages); 17334 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17335 } 17336 } 17337 } 17338 17339 allUsers = sUserManager.getUserIds(); 17340 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17341 } 17342 17343 final int freezeUser; 17344 if (isUpdatedSystemApp(uninstalledPs) 17345 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17346 // We're downgrading a system app, which will apply to all users, so 17347 // freeze them all during the downgrade 17348 freezeUser = UserHandle.USER_ALL; 17349 } else { 17350 freezeUser = removeUser; 17351 } 17352 17353 synchronized (mInstallLock) { 17354 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17355 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17356 deleteFlags, "deletePackageX")) { 17357 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17358 deleteFlags | REMOVE_CHATTY, info, true, null); 17359 } 17360 synchronized (mPackages) { 17361 if (res) { 17362 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 17363 } 17364 } 17365 } 17366 17367 if (res) { 17368 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17369 info.sendPackageRemovedBroadcasts(killApp); 17370 info.sendSystemPackageUpdatedBroadcasts(); 17371 info.sendSystemPackageAppearedBroadcasts(); 17372 } 17373 // Force a gc here. 17374 Runtime.getRuntime().gc(); 17375 // Delete the resources here after sending the broadcast to let 17376 // other processes clean up before deleting resources. 17377 if (info.args != null) { 17378 synchronized (mInstallLock) { 17379 info.args.doPostDeleteLI(true); 17380 } 17381 } 17382 17383 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17384 } 17385 17386 class PackageRemovedInfo { 17387 String removedPackage; 17388 int uid = -1; 17389 int removedAppId = -1; 17390 int[] origUsers; 17391 int[] removedUsers = null; 17392 SparseArray<Integer> installReasons; 17393 boolean isRemovedPackageSystemUpdate = false; 17394 boolean isUpdate; 17395 boolean dataRemoved; 17396 boolean removedForAllUsers; 17397 boolean isStaticSharedLib; 17398 // Clean up resources deleted packages. 17399 InstallArgs args = null; 17400 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17401 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17402 17403 void sendPackageRemovedBroadcasts(boolean killApp) { 17404 sendPackageRemovedBroadcastInternal(killApp); 17405 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17406 for (int i = 0; i < childCount; i++) { 17407 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17408 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17409 } 17410 } 17411 17412 void sendSystemPackageUpdatedBroadcasts() { 17413 if (isRemovedPackageSystemUpdate) { 17414 sendSystemPackageUpdatedBroadcastsInternal(); 17415 final int childCount = (removedChildPackages != null) 17416 ? removedChildPackages.size() : 0; 17417 for (int i = 0; i < childCount; i++) { 17418 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17419 if (childInfo.isRemovedPackageSystemUpdate) { 17420 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17421 } 17422 } 17423 } 17424 } 17425 17426 void sendSystemPackageAppearedBroadcasts() { 17427 final int packageCount = (appearedChildPackages != null) 17428 ? appearedChildPackages.size() : 0; 17429 for (int i = 0; i < packageCount; i++) { 17430 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17431 sendPackageAddedForNewUsers(installedInfo.name, true, 17432 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17433 } 17434 } 17435 17436 private void sendSystemPackageUpdatedBroadcastsInternal() { 17437 Bundle extras = new Bundle(2); 17438 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17439 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17440 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17441 extras, 0, null, null, null); 17442 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17443 extras, 0, null, null, null); 17444 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17445 null, 0, removedPackage, null, null); 17446 } 17447 17448 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17449 // Don't send static shared library removal broadcasts as these 17450 // libs are visible only the the apps that depend on them an one 17451 // cannot remove the library if it has a dependency. 17452 if (isStaticSharedLib) { 17453 return; 17454 } 17455 Bundle extras = new Bundle(2); 17456 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17457 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17458 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17459 if (isUpdate || isRemovedPackageSystemUpdate) { 17460 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17461 } 17462 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17463 if (removedPackage != null) { 17464 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17465 extras, 0, null, null, removedUsers); 17466 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17467 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17468 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17469 null, null, removedUsers); 17470 } 17471 } 17472 if (removedAppId >= 0) { 17473 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17474 removedUsers); 17475 } 17476 } 17477 } 17478 17479 /* 17480 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17481 * flag is not set, the data directory is removed as well. 17482 * make sure this flag is set for partially installed apps. If not its meaningless to 17483 * delete a partially installed application. 17484 */ 17485 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17486 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17487 String packageName = ps.name; 17488 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17489 // Retrieve object to delete permissions for shared user later on 17490 final PackageParser.Package deletedPkg; 17491 final PackageSetting deletedPs; 17492 // reader 17493 synchronized (mPackages) { 17494 deletedPkg = mPackages.get(packageName); 17495 deletedPs = mSettings.mPackages.get(packageName); 17496 if (outInfo != null) { 17497 outInfo.removedPackage = packageName; 17498 outInfo.isStaticSharedLib = deletedPkg != null 17499 && deletedPkg.staticSharedLibName != null; 17500 outInfo.removedUsers = deletedPs != null 17501 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17502 : null; 17503 } 17504 } 17505 17506 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 17507 17508 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17509 final PackageParser.Package resolvedPkg; 17510 if (deletedPkg != null) { 17511 resolvedPkg = deletedPkg; 17512 } else { 17513 // We don't have a parsed package when it lives on an ejected 17514 // adopted storage device, so fake something together 17515 resolvedPkg = new PackageParser.Package(ps.name); 17516 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17517 } 17518 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17519 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17520 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17521 if (outInfo != null) { 17522 outInfo.dataRemoved = true; 17523 } 17524 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17525 } 17526 17527 int removedAppId = -1; 17528 17529 // writer 17530 synchronized (mPackages) { 17531 if (deletedPs != null) { 17532 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17533 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17534 clearDefaultBrowserIfNeeded(packageName); 17535 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17536 removedAppId = mSettings.removePackageLPw(packageName); 17537 if (outInfo != null) { 17538 outInfo.removedAppId = removedAppId; 17539 } 17540 updatePermissionsLPw(deletedPs.name, null, 0); 17541 if (deletedPs.sharedUser != null) { 17542 // Remove permissions associated with package. Since runtime 17543 // permissions are per user we have to kill the removed package 17544 // or packages running under the shared user of the removed 17545 // package if revoking the permissions requested only by the removed 17546 // package is successful and this causes a change in gids. 17547 for (int userId : UserManagerService.getInstance().getUserIds()) { 17548 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17549 userId); 17550 if (userIdToKill == UserHandle.USER_ALL 17551 || userIdToKill >= UserHandle.USER_SYSTEM) { 17552 // If gids changed for this user, kill all affected packages. 17553 mHandler.post(new Runnable() { 17554 @Override 17555 public void run() { 17556 // This has to happen with no lock held. 17557 killApplication(deletedPs.name, deletedPs.appId, 17558 KILL_APP_REASON_GIDS_CHANGED); 17559 } 17560 }); 17561 break; 17562 } 17563 } 17564 } 17565 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17566 } 17567 // make sure to preserve per-user disabled state if this removal was just 17568 // a downgrade of a system app to the factory package 17569 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17570 if (DEBUG_REMOVE) { 17571 Slog.d(TAG, "Propagating install state across downgrade"); 17572 } 17573 for (int userId : allUserHandles) { 17574 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17575 if (DEBUG_REMOVE) { 17576 Slog.d(TAG, " user " + userId + " => " + installed); 17577 } 17578 ps.setInstalled(installed, userId); 17579 } 17580 } 17581 } 17582 // can downgrade to reader 17583 if (writeSettings) { 17584 // Save settings now 17585 mSettings.writeLPr(); 17586 } 17587 } 17588 if (removedAppId != -1) { 17589 // A user ID was deleted here. Go through all users and remove it 17590 // from KeyStore. 17591 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17592 } 17593 } 17594 17595 static boolean locationIsPrivileged(File path) { 17596 try { 17597 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17598 .getCanonicalPath(); 17599 return path.getCanonicalPath().startsWith(privilegedAppDir); 17600 } catch (IOException e) { 17601 Slog.e(TAG, "Unable to access code path " + path); 17602 } 17603 return false; 17604 } 17605 17606 /* 17607 * Tries to delete system package. 17608 */ 17609 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17610 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17611 boolean writeSettings) { 17612 if (deletedPs.parentPackageName != null) { 17613 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17614 return false; 17615 } 17616 17617 final boolean applyUserRestrictions 17618 = (allUserHandles != null) && (outInfo.origUsers != null); 17619 final PackageSetting disabledPs; 17620 // Confirm if the system package has been updated 17621 // An updated system app can be deleted. This will also have to restore 17622 // the system pkg from system partition 17623 // reader 17624 synchronized (mPackages) { 17625 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17626 } 17627 17628 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17629 + " disabledPs=" + disabledPs); 17630 17631 if (disabledPs == null) { 17632 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17633 return false; 17634 } else if (DEBUG_REMOVE) { 17635 Slog.d(TAG, "Deleting system pkg from data partition"); 17636 } 17637 17638 if (DEBUG_REMOVE) { 17639 if (applyUserRestrictions) { 17640 Slog.d(TAG, "Remembering install states:"); 17641 for (int userId : allUserHandles) { 17642 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17643 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17644 } 17645 } 17646 } 17647 17648 // Delete the updated package 17649 outInfo.isRemovedPackageSystemUpdate = true; 17650 if (outInfo.removedChildPackages != null) { 17651 final int childCount = (deletedPs.childPackageNames != null) 17652 ? deletedPs.childPackageNames.size() : 0; 17653 for (int i = 0; i < childCount; i++) { 17654 String childPackageName = deletedPs.childPackageNames.get(i); 17655 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17656 .contains(childPackageName)) { 17657 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17658 childPackageName); 17659 if (childInfo != null) { 17660 childInfo.isRemovedPackageSystemUpdate = true; 17661 } 17662 } 17663 } 17664 } 17665 17666 if (disabledPs.versionCode < deletedPs.versionCode) { 17667 // Delete data for downgrades 17668 flags &= ~PackageManager.DELETE_KEEP_DATA; 17669 } else { 17670 // Preserve data by setting flag 17671 flags |= PackageManager.DELETE_KEEP_DATA; 17672 } 17673 17674 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17675 outInfo, writeSettings, disabledPs.pkg); 17676 if (!ret) { 17677 return false; 17678 } 17679 17680 // writer 17681 synchronized (mPackages) { 17682 // Reinstate the old system package 17683 enableSystemPackageLPw(disabledPs.pkg); 17684 // Remove any native libraries from the upgraded package. 17685 removeNativeBinariesLI(deletedPs); 17686 } 17687 17688 // Install the system package 17689 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17690 int parseFlags = mDefParseFlags 17691 | PackageParser.PARSE_MUST_BE_APK 17692 | PackageParser.PARSE_IS_SYSTEM 17693 | PackageParser.PARSE_IS_SYSTEM_DIR; 17694 if (locationIsPrivileged(disabledPs.codePath)) { 17695 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17696 } 17697 17698 final PackageParser.Package newPkg; 17699 try { 17700 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17701 0 /* currentTime */, null); 17702 } catch (PackageManagerException e) { 17703 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17704 + e.getMessage()); 17705 return false; 17706 } 17707 17708 try { 17709 // update shared libraries for the newly re-installed system package 17710 updateSharedLibrariesLPr(newPkg, null); 17711 } catch (PackageManagerException e) { 17712 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17713 } 17714 17715 prepareAppDataAfterInstallLIF(newPkg); 17716 17717 // writer 17718 synchronized (mPackages) { 17719 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17720 17721 // Propagate the permissions state as we do not want to drop on the floor 17722 // runtime permissions. The update permissions method below will take 17723 // care of removing obsolete permissions and grant install permissions. 17724 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17725 updatePermissionsLPw(newPkg.packageName, newPkg, 17726 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17727 17728 if (applyUserRestrictions) { 17729 if (DEBUG_REMOVE) { 17730 Slog.d(TAG, "Propagating install state across reinstall"); 17731 } 17732 for (int userId : allUserHandles) { 17733 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17734 if (DEBUG_REMOVE) { 17735 Slog.d(TAG, " user " + userId + " => " + installed); 17736 } 17737 ps.setInstalled(installed, userId); 17738 17739 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17740 } 17741 // Regardless of writeSettings we need to ensure that this restriction 17742 // state propagation is persisted 17743 mSettings.writeAllUsersPackageRestrictionsLPr(); 17744 } 17745 // can downgrade to reader here 17746 if (writeSettings) { 17747 mSettings.writeLPr(); 17748 } 17749 } 17750 return true; 17751 } 17752 17753 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17754 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17755 PackageRemovedInfo outInfo, boolean writeSettings, 17756 PackageParser.Package replacingPackage) { 17757 synchronized (mPackages) { 17758 if (outInfo != null) { 17759 outInfo.uid = ps.appId; 17760 } 17761 17762 if (outInfo != null && outInfo.removedChildPackages != null) { 17763 final int childCount = (ps.childPackageNames != null) 17764 ? ps.childPackageNames.size() : 0; 17765 for (int i = 0; i < childCount; i++) { 17766 String childPackageName = ps.childPackageNames.get(i); 17767 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17768 if (childPs == null) { 17769 return false; 17770 } 17771 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17772 childPackageName); 17773 if (childInfo != null) { 17774 childInfo.uid = childPs.appId; 17775 } 17776 } 17777 } 17778 } 17779 17780 // Delete package data from internal structures and also remove data if flag is set 17781 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17782 17783 // Delete the child packages data 17784 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17785 for (int i = 0; i < childCount; i++) { 17786 PackageSetting childPs; 17787 synchronized (mPackages) { 17788 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17789 } 17790 if (childPs != null) { 17791 PackageRemovedInfo childOutInfo = (outInfo != null 17792 && outInfo.removedChildPackages != null) 17793 ? outInfo.removedChildPackages.get(childPs.name) : null; 17794 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17795 && (replacingPackage != null 17796 && !replacingPackage.hasChildPackage(childPs.name)) 17797 ? flags & ~DELETE_KEEP_DATA : flags; 17798 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17799 deleteFlags, writeSettings); 17800 } 17801 } 17802 17803 // Delete application code and resources only for parent packages 17804 if (ps.parentPackageName == null) { 17805 if (deleteCodeAndResources && (outInfo != null)) { 17806 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17807 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17808 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17809 } 17810 } 17811 17812 return true; 17813 } 17814 17815 @Override 17816 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17817 int userId) { 17818 mContext.enforceCallingOrSelfPermission( 17819 android.Manifest.permission.DELETE_PACKAGES, null); 17820 synchronized (mPackages) { 17821 PackageSetting ps = mSettings.mPackages.get(packageName); 17822 if (ps == null) { 17823 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17824 return false; 17825 } 17826 // Cannot block uninstall of static shared libs as they are 17827 // considered a part of the using app (emulating static linking). 17828 // Also static libs are installed always on internal storage. 17829 PackageParser.Package pkg = mPackages.get(packageName); 17830 if (pkg != null && pkg.staticSharedLibName != null) { 17831 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17832 + " providing static shared library: " + pkg.staticSharedLibName); 17833 return false; 17834 } 17835 if (!ps.getInstalled(userId)) { 17836 // Can't block uninstall for an app that is not installed or enabled. 17837 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17838 return false; 17839 } 17840 ps.setBlockUninstall(blockUninstall, userId); 17841 mSettings.writePackageRestrictionsLPr(userId); 17842 } 17843 return true; 17844 } 17845 17846 @Override 17847 public boolean getBlockUninstallForUser(String packageName, int userId) { 17848 synchronized (mPackages) { 17849 PackageSetting ps = mSettings.mPackages.get(packageName); 17850 if (ps == null) { 17851 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 17852 return false; 17853 } 17854 return ps.getBlockUninstall(userId); 17855 } 17856 } 17857 17858 @Override 17859 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 17860 int callingUid = Binder.getCallingUid(); 17861 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 17862 throw new SecurityException( 17863 "setRequiredForSystemUser can only be run by the system or root"); 17864 } 17865 synchronized (mPackages) { 17866 PackageSetting ps = mSettings.mPackages.get(packageName); 17867 if (ps == null) { 17868 Log.w(TAG, "Package doesn't exist: " + packageName); 17869 return false; 17870 } 17871 if (systemUserApp) { 17872 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17873 } else { 17874 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17875 } 17876 mSettings.writeLPr(); 17877 } 17878 return true; 17879 } 17880 17881 /* 17882 * This method handles package deletion in general 17883 */ 17884 private boolean deletePackageLIF(String packageName, UserHandle user, 17885 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 17886 PackageRemovedInfo outInfo, boolean writeSettings, 17887 PackageParser.Package replacingPackage) { 17888 if (packageName == null) { 17889 Slog.w(TAG, "Attempt to delete null packageName."); 17890 return false; 17891 } 17892 17893 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 17894 17895 PackageSetting ps; 17896 synchronized (mPackages) { 17897 ps = mSettings.mPackages.get(packageName); 17898 if (ps == null) { 17899 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17900 return false; 17901 } 17902 17903 if (ps.parentPackageName != null && (!isSystemApp(ps) 17904 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 17905 if (DEBUG_REMOVE) { 17906 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 17907 + ((user == null) ? UserHandle.USER_ALL : user)); 17908 } 17909 final int removedUserId = (user != null) ? user.getIdentifier() 17910 : UserHandle.USER_ALL; 17911 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 17912 return false; 17913 } 17914 markPackageUninstalledForUserLPw(ps, user); 17915 scheduleWritePackageRestrictionsLocked(user); 17916 return true; 17917 } 17918 } 17919 17920 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 17921 && user.getIdentifier() != UserHandle.USER_ALL)) { 17922 // The caller is asking that the package only be deleted for a single 17923 // user. To do this, we just mark its uninstalled state and delete 17924 // its data. If this is a system app, we only allow this to happen if 17925 // they have set the special DELETE_SYSTEM_APP which requests different 17926 // semantics than normal for uninstalling system apps. 17927 markPackageUninstalledForUserLPw(ps, user); 17928 17929 if (!isSystemApp(ps)) { 17930 // Do not uninstall the APK if an app should be cached 17931 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 17932 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 17933 // Other user still have this package installed, so all 17934 // we need to do is clear this user's data and save that 17935 // it is uninstalled. 17936 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 17937 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17938 return false; 17939 } 17940 scheduleWritePackageRestrictionsLocked(user); 17941 return true; 17942 } else { 17943 // We need to set it back to 'installed' so the uninstall 17944 // broadcasts will be sent correctly. 17945 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 17946 ps.setInstalled(true, user.getIdentifier()); 17947 } 17948 } else { 17949 // This is a system app, so we assume that the 17950 // other users still have this package installed, so all 17951 // we need to do is clear this user's data and save that 17952 // it is uninstalled. 17953 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 17954 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17955 return false; 17956 } 17957 scheduleWritePackageRestrictionsLocked(user); 17958 return true; 17959 } 17960 } 17961 17962 // If we are deleting a composite package for all users, keep track 17963 // of result for each child. 17964 if (ps.childPackageNames != null && outInfo != null) { 17965 synchronized (mPackages) { 17966 final int childCount = ps.childPackageNames.size(); 17967 outInfo.removedChildPackages = new ArrayMap<>(childCount); 17968 for (int i = 0; i < childCount; i++) { 17969 String childPackageName = ps.childPackageNames.get(i); 17970 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 17971 childInfo.removedPackage = childPackageName; 17972 outInfo.removedChildPackages.put(childPackageName, childInfo); 17973 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17974 if (childPs != null) { 17975 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 17976 } 17977 } 17978 } 17979 } 17980 17981 boolean ret = false; 17982 if (isSystemApp(ps)) { 17983 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 17984 // When an updated system application is deleted we delete the existing resources 17985 // as well and fall back to existing code in system partition 17986 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 17987 } else { 17988 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 17989 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 17990 outInfo, writeSettings, replacingPackage); 17991 } 17992 17993 // Take a note whether we deleted the package for all users 17994 if (outInfo != null) { 17995 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17996 if (outInfo.removedChildPackages != null) { 17997 synchronized (mPackages) { 17998 final int childCount = outInfo.removedChildPackages.size(); 17999 for (int i = 0; i < childCount; i++) { 18000 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18001 if (childInfo != null) { 18002 childInfo.removedForAllUsers = mPackages.get( 18003 childInfo.removedPackage) == null; 18004 } 18005 } 18006 } 18007 } 18008 // If we uninstalled an update to a system app there may be some 18009 // child packages that appeared as they are declared in the system 18010 // app but were not declared in the update. 18011 if (isSystemApp(ps)) { 18012 synchronized (mPackages) { 18013 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18014 final int childCount = (updatedPs.childPackageNames != null) 18015 ? updatedPs.childPackageNames.size() : 0; 18016 for (int i = 0; i < childCount; i++) { 18017 String childPackageName = updatedPs.childPackageNames.get(i); 18018 if (outInfo.removedChildPackages == null 18019 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18020 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18021 if (childPs == null) { 18022 continue; 18023 } 18024 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18025 installRes.name = childPackageName; 18026 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18027 installRes.pkg = mPackages.get(childPackageName); 18028 installRes.uid = childPs.pkg.applicationInfo.uid; 18029 if (outInfo.appearedChildPackages == null) { 18030 outInfo.appearedChildPackages = new ArrayMap<>(); 18031 } 18032 outInfo.appearedChildPackages.put(childPackageName, installRes); 18033 } 18034 } 18035 } 18036 } 18037 } 18038 18039 return ret; 18040 } 18041 18042 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18043 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18044 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18045 for (int nextUserId : userIds) { 18046 if (DEBUG_REMOVE) { 18047 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18048 } 18049 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18050 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 18051 false /*hidden*/, false /*suspended*/, null, null, null, 18052 false /*blockUninstall*/, 18053 ps.readUserState(nextUserId).domainVerificationStatus, 0, 18054 PackageManager.INSTALL_REASON_UNKNOWN); 18055 } 18056 } 18057 18058 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18059 PackageRemovedInfo outInfo) { 18060 final PackageParser.Package pkg; 18061 synchronized (mPackages) { 18062 pkg = mPackages.get(ps.name); 18063 } 18064 18065 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18066 : new int[] {userId}; 18067 for (int nextUserId : userIds) { 18068 if (DEBUG_REMOVE) { 18069 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18070 + nextUserId); 18071 } 18072 18073 destroyAppDataLIF(pkg, userId, 18074 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18075 destroyAppProfilesLIF(pkg, userId); 18076 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18077 schedulePackageCleaning(ps.name, nextUserId, false); 18078 synchronized (mPackages) { 18079 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18080 scheduleWritePackageRestrictionsLocked(nextUserId); 18081 } 18082 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18083 } 18084 } 18085 18086 if (outInfo != null) { 18087 outInfo.removedPackage = ps.name; 18088 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18089 outInfo.removedAppId = ps.appId; 18090 outInfo.removedUsers = userIds; 18091 } 18092 18093 return true; 18094 } 18095 18096 private final class ClearStorageConnection implements ServiceConnection { 18097 IMediaContainerService mContainerService; 18098 18099 @Override 18100 public void onServiceConnected(ComponentName name, IBinder service) { 18101 synchronized (this) { 18102 mContainerService = IMediaContainerService.Stub 18103 .asInterface(Binder.allowBlocking(service)); 18104 notifyAll(); 18105 } 18106 } 18107 18108 @Override 18109 public void onServiceDisconnected(ComponentName name) { 18110 } 18111 } 18112 18113 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18114 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18115 18116 final boolean mounted; 18117 if (Environment.isExternalStorageEmulated()) { 18118 mounted = true; 18119 } else { 18120 final String status = Environment.getExternalStorageState(); 18121 18122 mounted = status.equals(Environment.MEDIA_MOUNTED) 18123 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18124 } 18125 18126 if (!mounted) { 18127 return; 18128 } 18129 18130 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18131 int[] users; 18132 if (userId == UserHandle.USER_ALL) { 18133 users = sUserManager.getUserIds(); 18134 } else { 18135 users = new int[] { userId }; 18136 } 18137 final ClearStorageConnection conn = new ClearStorageConnection(); 18138 if (mContext.bindServiceAsUser( 18139 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18140 try { 18141 for (int curUser : users) { 18142 long timeout = SystemClock.uptimeMillis() + 5000; 18143 synchronized (conn) { 18144 long now; 18145 while (conn.mContainerService == null && 18146 (now = SystemClock.uptimeMillis()) < timeout) { 18147 try { 18148 conn.wait(timeout - now); 18149 } catch (InterruptedException e) { 18150 } 18151 } 18152 } 18153 if (conn.mContainerService == null) { 18154 return; 18155 } 18156 18157 final UserEnvironment userEnv = new UserEnvironment(curUser); 18158 clearDirectory(conn.mContainerService, 18159 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18160 if (allData) { 18161 clearDirectory(conn.mContainerService, 18162 userEnv.buildExternalStorageAppDataDirs(packageName)); 18163 clearDirectory(conn.mContainerService, 18164 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18165 } 18166 } 18167 } finally { 18168 mContext.unbindService(conn); 18169 } 18170 } 18171 } 18172 18173 @Override 18174 public void clearApplicationProfileData(String packageName) { 18175 enforceSystemOrRoot("Only the system can clear all profile data"); 18176 18177 final PackageParser.Package pkg; 18178 synchronized (mPackages) { 18179 pkg = mPackages.get(packageName); 18180 } 18181 18182 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18183 synchronized (mInstallLock) { 18184 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18185 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18186 true /* removeBaseMarker */); 18187 } 18188 } 18189 } 18190 18191 @Override 18192 public void clearApplicationUserData(final String packageName, 18193 final IPackageDataObserver observer, final int userId) { 18194 mContext.enforceCallingOrSelfPermission( 18195 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18196 18197 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18198 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18199 18200 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18201 throw new SecurityException("Cannot clear data for a protected package: " 18202 + packageName); 18203 } 18204 // Queue up an async operation since the package deletion may take a little while. 18205 mHandler.post(new Runnable() { 18206 public void run() { 18207 mHandler.removeCallbacks(this); 18208 final boolean succeeded; 18209 try (PackageFreezer freezer = freezePackage(packageName, 18210 "clearApplicationUserData")) { 18211 synchronized (mInstallLock) { 18212 succeeded = clearApplicationUserDataLIF(packageName, userId); 18213 } 18214 clearExternalStorageDataSync(packageName, userId, true); 18215 } 18216 if (succeeded) { 18217 // invoke DeviceStorageMonitor's update method to clear any notifications 18218 DeviceStorageMonitorInternal dsm = LocalServices 18219 .getService(DeviceStorageMonitorInternal.class); 18220 if (dsm != null) { 18221 dsm.checkMemory(); 18222 } 18223 } 18224 if(observer != null) { 18225 try { 18226 observer.onRemoveCompleted(packageName, succeeded); 18227 } catch (RemoteException e) { 18228 Log.i(TAG, "Observer no longer exists."); 18229 } 18230 } //end if observer 18231 } //end run 18232 }); 18233 } 18234 18235 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18236 if (packageName == null) { 18237 Slog.w(TAG, "Attempt to delete null packageName."); 18238 return false; 18239 } 18240 18241 // Try finding details about the requested package 18242 PackageParser.Package pkg; 18243 synchronized (mPackages) { 18244 pkg = mPackages.get(packageName); 18245 if (pkg == null) { 18246 final PackageSetting ps = mSettings.mPackages.get(packageName); 18247 if (ps != null) { 18248 pkg = ps.pkg; 18249 } 18250 } 18251 18252 if (pkg == null) { 18253 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18254 return false; 18255 } 18256 18257 PackageSetting ps = (PackageSetting) pkg.mExtras; 18258 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18259 } 18260 18261 clearAppDataLIF(pkg, userId, 18262 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18263 18264 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18265 removeKeystoreDataIfNeeded(userId, appId); 18266 18267 UserManagerInternal umInternal = getUserManagerInternal(); 18268 final int flags; 18269 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18270 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18271 } else if (umInternal.isUserRunning(userId)) { 18272 flags = StorageManager.FLAG_STORAGE_DE; 18273 } else { 18274 flags = 0; 18275 } 18276 prepareAppDataContentsLIF(pkg, userId, flags); 18277 18278 return true; 18279 } 18280 18281 /** 18282 * Reverts user permission state changes (permissions and flags) in 18283 * all packages for a given user. 18284 * 18285 * @param userId The device user for which to do a reset. 18286 */ 18287 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18288 final int packageCount = mPackages.size(); 18289 for (int i = 0; i < packageCount; i++) { 18290 PackageParser.Package pkg = mPackages.valueAt(i); 18291 PackageSetting ps = (PackageSetting) pkg.mExtras; 18292 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18293 } 18294 } 18295 18296 private void resetNetworkPolicies(int userId) { 18297 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18298 } 18299 18300 /** 18301 * Reverts user permission state changes (permissions and flags). 18302 * 18303 * @param ps The package for which to reset. 18304 * @param userId The device user for which to do a reset. 18305 */ 18306 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18307 final PackageSetting ps, final int userId) { 18308 if (ps.pkg == null) { 18309 return; 18310 } 18311 18312 // These are flags that can change base on user actions. 18313 final int userSettableMask = FLAG_PERMISSION_USER_SET 18314 | FLAG_PERMISSION_USER_FIXED 18315 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18316 | FLAG_PERMISSION_REVIEW_REQUIRED; 18317 18318 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18319 | FLAG_PERMISSION_POLICY_FIXED; 18320 18321 boolean writeInstallPermissions = false; 18322 boolean writeRuntimePermissions = false; 18323 18324 final int permissionCount = ps.pkg.requestedPermissions.size(); 18325 for (int i = 0; i < permissionCount; i++) { 18326 String permission = ps.pkg.requestedPermissions.get(i); 18327 18328 BasePermission bp = mSettings.mPermissions.get(permission); 18329 if (bp == null) { 18330 continue; 18331 } 18332 18333 // If shared user we just reset the state to which only this app contributed. 18334 if (ps.sharedUser != null) { 18335 boolean used = false; 18336 final int packageCount = ps.sharedUser.packages.size(); 18337 for (int j = 0; j < packageCount; j++) { 18338 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18339 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18340 && pkg.pkg.requestedPermissions.contains(permission)) { 18341 used = true; 18342 break; 18343 } 18344 } 18345 if (used) { 18346 continue; 18347 } 18348 } 18349 18350 PermissionsState permissionsState = ps.getPermissionsState(); 18351 18352 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18353 18354 // Always clear the user settable flags. 18355 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18356 bp.name) != null; 18357 // If permission review is enabled and this is a legacy app, mark the 18358 // permission as requiring a review as this is the initial state. 18359 int flags = 0; 18360 if (mPermissionReviewRequired 18361 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18362 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18363 } 18364 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18365 if (hasInstallState) { 18366 writeInstallPermissions = true; 18367 } else { 18368 writeRuntimePermissions = true; 18369 } 18370 } 18371 18372 // Below is only runtime permission handling. 18373 if (!bp.isRuntime()) { 18374 continue; 18375 } 18376 18377 // Never clobber system or policy. 18378 if ((oldFlags & policyOrSystemFlags) != 0) { 18379 continue; 18380 } 18381 18382 // If this permission was granted by default, make sure it is. 18383 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18384 if (permissionsState.grantRuntimePermission(bp, userId) 18385 != PERMISSION_OPERATION_FAILURE) { 18386 writeRuntimePermissions = true; 18387 } 18388 // If permission review is enabled the permissions for a legacy apps 18389 // are represented as constantly granted runtime ones, so don't revoke. 18390 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18391 // Otherwise, reset the permission. 18392 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18393 switch (revokeResult) { 18394 case PERMISSION_OPERATION_SUCCESS: 18395 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18396 writeRuntimePermissions = true; 18397 final int appId = ps.appId; 18398 mHandler.post(new Runnable() { 18399 @Override 18400 public void run() { 18401 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18402 } 18403 }); 18404 } break; 18405 } 18406 } 18407 } 18408 18409 // Synchronously write as we are taking permissions away. 18410 if (writeRuntimePermissions) { 18411 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18412 } 18413 18414 // Synchronously write as we are taking permissions away. 18415 if (writeInstallPermissions) { 18416 mSettings.writeLPr(); 18417 } 18418 } 18419 18420 /** 18421 * Remove entries from the keystore daemon. Will only remove it if the 18422 * {@code appId} is valid. 18423 */ 18424 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18425 if (appId < 0) { 18426 return; 18427 } 18428 18429 final KeyStore keyStore = KeyStore.getInstance(); 18430 if (keyStore != null) { 18431 if (userId == UserHandle.USER_ALL) { 18432 for (final int individual : sUserManager.getUserIds()) { 18433 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18434 } 18435 } else { 18436 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18437 } 18438 } else { 18439 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18440 } 18441 } 18442 18443 @Override 18444 public void deleteApplicationCacheFiles(final String packageName, 18445 final IPackageDataObserver observer) { 18446 final int userId = UserHandle.getCallingUserId(); 18447 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18448 } 18449 18450 @Override 18451 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18452 final IPackageDataObserver observer) { 18453 mContext.enforceCallingOrSelfPermission( 18454 android.Manifest.permission.DELETE_CACHE_FILES, null); 18455 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18456 /* requireFullPermission= */ true, /* checkShell= */ false, 18457 "delete application cache files"); 18458 18459 final PackageParser.Package pkg; 18460 synchronized (mPackages) { 18461 pkg = mPackages.get(packageName); 18462 } 18463 18464 // Queue up an async operation since the package deletion may take a little while. 18465 mHandler.post(new Runnable() { 18466 public void run() { 18467 synchronized (mInstallLock) { 18468 final int flags = StorageManager.FLAG_STORAGE_DE 18469 | StorageManager.FLAG_STORAGE_CE; 18470 // We're only clearing cache files, so we don't care if the 18471 // app is unfrozen and still able to run 18472 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18473 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18474 } 18475 clearExternalStorageDataSync(packageName, userId, false); 18476 if (observer != null) { 18477 try { 18478 observer.onRemoveCompleted(packageName, true); 18479 } catch (RemoteException e) { 18480 Log.i(TAG, "Observer no longer exists."); 18481 } 18482 } 18483 } 18484 }); 18485 } 18486 18487 @Override 18488 public void getPackageSizeInfo(final String packageName, int userHandle, 18489 final IPackageStatsObserver observer) { 18490 mContext.enforceCallingOrSelfPermission( 18491 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18492 if (packageName == null) { 18493 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18494 } 18495 18496 PackageStats stats = new PackageStats(packageName, userHandle); 18497 18498 /* 18499 * Queue up an async operation since the package measurement may take a 18500 * little while. 18501 */ 18502 Message msg = mHandler.obtainMessage(INIT_COPY); 18503 msg.obj = new MeasureParams(stats, observer); 18504 mHandler.sendMessage(msg); 18505 } 18506 18507 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18508 final PackageSetting ps; 18509 synchronized (mPackages) { 18510 ps = mSettings.mPackages.get(packageName); 18511 if (ps == null) { 18512 Slog.w(TAG, "Failed to find settings for " + packageName); 18513 return false; 18514 } 18515 } 18516 18517 final String[] packageNames = { packageName }; 18518 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18519 final String[] codePaths = { ps.codePathString }; 18520 18521 try { 18522 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18523 ps.appId, ceDataInodes, codePaths, stats); 18524 18525 // For now, ignore code size of packages on system partition 18526 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18527 stats.codeSize = 0; 18528 } 18529 18530 // External clients expect these to be tracked separately 18531 stats.dataSize -= stats.cacheSize; 18532 18533 } catch (InstallerException e) { 18534 Slog.w(TAG, String.valueOf(e)); 18535 return false; 18536 } 18537 18538 return true; 18539 } 18540 18541 private int getUidTargetSdkVersionLockedLPr(int uid) { 18542 Object obj = mSettings.getUserIdLPr(uid); 18543 if (obj instanceof SharedUserSetting) { 18544 final SharedUserSetting sus = (SharedUserSetting) obj; 18545 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18546 final Iterator<PackageSetting> it = sus.packages.iterator(); 18547 while (it.hasNext()) { 18548 final PackageSetting ps = it.next(); 18549 if (ps.pkg != null) { 18550 int v = ps.pkg.applicationInfo.targetSdkVersion; 18551 if (v < vers) vers = v; 18552 } 18553 } 18554 return vers; 18555 } else if (obj instanceof PackageSetting) { 18556 final PackageSetting ps = (PackageSetting) obj; 18557 if (ps.pkg != null) { 18558 return ps.pkg.applicationInfo.targetSdkVersion; 18559 } 18560 } 18561 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18562 } 18563 18564 @Override 18565 public void addPreferredActivity(IntentFilter filter, int match, 18566 ComponentName[] set, ComponentName activity, int userId) { 18567 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18568 "Adding preferred"); 18569 } 18570 18571 private void addPreferredActivityInternal(IntentFilter filter, int match, 18572 ComponentName[] set, ComponentName activity, boolean always, int userId, 18573 String opname) { 18574 // writer 18575 int callingUid = Binder.getCallingUid(); 18576 enforceCrossUserPermission(callingUid, userId, 18577 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18578 if (filter.countActions() == 0) { 18579 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18580 return; 18581 } 18582 synchronized (mPackages) { 18583 if (mContext.checkCallingOrSelfPermission( 18584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18585 != PackageManager.PERMISSION_GRANTED) { 18586 if (getUidTargetSdkVersionLockedLPr(callingUid) 18587 < Build.VERSION_CODES.FROYO) { 18588 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18589 + callingUid); 18590 return; 18591 } 18592 mContext.enforceCallingOrSelfPermission( 18593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18594 } 18595 18596 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18597 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18598 + userId + ":"); 18599 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18600 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18601 scheduleWritePackageRestrictionsLocked(userId); 18602 postPreferredActivityChangedBroadcast(userId); 18603 } 18604 } 18605 18606 private void postPreferredActivityChangedBroadcast(int userId) { 18607 mHandler.post(() -> { 18608 final IActivityManager am = ActivityManager.getService(); 18609 if (am == null) { 18610 return; 18611 } 18612 18613 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18614 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18615 try { 18616 am.broadcastIntent(null, intent, null, null, 18617 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18618 null, false, false, userId); 18619 } catch (RemoteException e) { 18620 } 18621 }); 18622 } 18623 18624 @Override 18625 public void replacePreferredActivity(IntentFilter filter, int match, 18626 ComponentName[] set, ComponentName activity, int userId) { 18627 if (filter.countActions() != 1) { 18628 throw new IllegalArgumentException( 18629 "replacePreferredActivity expects filter to have only 1 action."); 18630 } 18631 if (filter.countDataAuthorities() != 0 18632 || filter.countDataPaths() != 0 18633 || filter.countDataSchemes() > 1 18634 || filter.countDataTypes() != 0) { 18635 throw new IllegalArgumentException( 18636 "replacePreferredActivity expects filter to have no data authorities, " + 18637 "paths, or types; and at most one scheme."); 18638 } 18639 18640 final int callingUid = Binder.getCallingUid(); 18641 enforceCrossUserPermission(callingUid, userId, 18642 true /* requireFullPermission */, false /* checkShell */, 18643 "replace preferred activity"); 18644 synchronized (mPackages) { 18645 if (mContext.checkCallingOrSelfPermission( 18646 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18647 != PackageManager.PERMISSION_GRANTED) { 18648 if (getUidTargetSdkVersionLockedLPr(callingUid) 18649 < Build.VERSION_CODES.FROYO) { 18650 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18651 + Binder.getCallingUid()); 18652 return; 18653 } 18654 mContext.enforceCallingOrSelfPermission( 18655 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18656 } 18657 18658 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18659 if (pir != null) { 18660 // Get all of the existing entries that exactly match this filter. 18661 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18662 if (existing != null && existing.size() == 1) { 18663 PreferredActivity cur = existing.get(0); 18664 if (DEBUG_PREFERRED) { 18665 Slog.i(TAG, "Checking replace of preferred:"); 18666 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18667 if (!cur.mPref.mAlways) { 18668 Slog.i(TAG, " -- CUR; not mAlways!"); 18669 } else { 18670 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18671 Slog.i(TAG, " -- CUR: mSet=" 18672 + Arrays.toString(cur.mPref.mSetComponents)); 18673 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18674 Slog.i(TAG, " -- NEW: mMatch=" 18675 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18676 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18677 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18678 } 18679 } 18680 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18681 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18682 && cur.mPref.sameSet(set)) { 18683 // Setting the preferred activity to what it happens to be already 18684 if (DEBUG_PREFERRED) { 18685 Slog.i(TAG, "Replacing with same preferred activity " 18686 + cur.mPref.mShortComponent + " for user " 18687 + userId + ":"); 18688 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18689 } 18690 return; 18691 } 18692 } 18693 18694 if (existing != null) { 18695 if (DEBUG_PREFERRED) { 18696 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18697 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18698 } 18699 for (int i = 0; i < existing.size(); i++) { 18700 PreferredActivity pa = existing.get(i); 18701 if (DEBUG_PREFERRED) { 18702 Slog.i(TAG, "Removing existing preferred activity " 18703 + pa.mPref.mComponent + ":"); 18704 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18705 } 18706 pir.removeFilter(pa); 18707 } 18708 } 18709 } 18710 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18711 "Replacing preferred"); 18712 } 18713 } 18714 18715 @Override 18716 public void clearPackagePreferredActivities(String packageName) { 18717 final int uid = Binder.getCallingUid(); 18718 // writer 18719 synchronized (mPackages) { 18720 PackageParser.Package pkg = mPackages.get(packageName); 18721 if (pkg == null || pkg.applicationInfo.uid != uid) { 18722 if (mContext.checkCallingOrSelfPermission( 18723 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18724 != PackageManager.PERMISSION_GRANTED) { 18725 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18726 < Build.VERSION_CODES.FROYO) { 18727 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18728 + Binder.getCallingUid()); 18729 return; 18730 } 18731 mContext.enforceCallingOrSelfPermission( 18732 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18733 } 18734 } 18735 18736 int user = UserHandle.getCallingUserId(); 18737 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18738 scheduleWritePackageRestrictionsLocked(user); 18739 } 18740 } 18741 } 18742 18743 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18744 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18745 ArrayList<PreferredActivity> removed = null; 18746 boolean changed = false; 18747 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18748 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18749 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18750 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18751 continue; 18752 } 18753 Iterator<PreferredActivity> it = pir.filterIterator(); 18754 while (it.hasNext()) { 18755 PreferredActivity pa = it.next(); 18756 // Mark entry for removal only if it matches the package name 18757 // and the entry is of type "always". 18758 if (packageName == null || 18759 (pa.mPref.mComponent.getPackageName().equals(packageName) 18760 && pa.mPref.mAlways)) { 18761 if (removed == null) { 18762 removed = new ArrayList<PreferredActivity>(); 18763 } 18764 removed.add(pa); 18765 } 18766 } 18767 if (removed != null) { 18768 for (int j=0; j<removed.size(); j++) { 18769 PreferredActivity pa = removed.get(j); 18770 pir.removeFilter(pa); 18771 } 18772 changed = true; 18773 } 18774 } 18775 if (changed) { 18776 postPreferredActivityChangedBroadcast(userId); 18777 } 18778 return changed; 18779 } 18780 18781 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18782 private void clearIntentFilterVerificationsLPw(int userId) { 18783 final int packageCount = mPackages.size(); 18784 for (int i = 0; i < packageCount; i++) { 18785 PackageParser.Package pkg = mPackages.valueAt(i); 18786 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18787 } 18788 } 18789 18790 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18791 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18792 if (userId == UserHandle.USER_ALL) { 18793 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18794 sUserManager.getUserIds())) { 18795 for (int oneUserId : sUserManager.getUserIds()) { 18796 scheduleWritePackageRestrictionsLocked(oneUserId); 18797 } 18798 } 18799 } else { 18800 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18801 scheduleWritePackageRestrictionsLocked(userId); 18802 } 18803 } 18804 } 18805 18806 void clearDefaultBrowserIfNeeded(String packageName) { 18807 for (int oneUserId : sUserManager.getUserIds()) { 18808 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18809 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18810 if (packageName.equals(defaultBrowserPackageName)) { 18811 setDefaultBrowserPackageName(null, oneUserId); 18812 } 18813 } 18814 } 18815 18816 @Override 18817 public void resetApplicationPreferences(int userId) { 18818 mContext.enforceCallingOrSelfPermission( 18819 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18820 final long identity = Binder.clearCallingIdentity(); 18821 // writer 18822 try { 18823 synchronized (mPackages) { 18824 clearPackagePreferredActivitiesLPw(null, userId); 18825 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18826 // TODO: We have to reset the default SMS and Phone. This requires 18827 // significant refactoring to keep all default apps in the package 18828 // manager (cleaner but more work) or have the services provide 18829 // callbacks to the package manager to request a default app reset. 18830 applyFactoryDefaultBrowserLPw(userId); 18831 clearIntentFilterVerificationsLPw(userId); 18832 primeDomainVerificationsLPw(userId); 18833 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18834 scheduleWritePackageRestrictionsLocked(userId); 18835 } 18836 resetNetworkPolicies(userId); 18837 } finally { 18838 Binder.restoreCallingIdentity(identity); 18839 } 18840 } 18841 18842 @Override 18843 public int getPreferredActivities(List<IntentFilter> outFilters, 18844 List<ComponentName> outActivities, String packageName) { 18845 18846 int num = 0; 18847 final int userId = UserHandle.getCallingUserId(); 18848 // reader 18849 synchronized (mPackages) { 18850 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18851 if (pir != null) { 18852 final Iterator<PreferredActivity> it = pir.filterIterator(); 18853 while (it.hasNext()) { 18854 final PreferredActivity pa = it.next(); 18855 if (packageName == null 18856 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18857 && pa.mPref.mAlways)) { 18858 if (outFilters != null) { 18859 outFilters.add(new IntentFilter(pa)); 18860 } 18861 if (outActivities != null) { 18862 outActivities.add(pa.mPref.mComponent); 18863 } 18864 } 18865 } 18866 } 18867 } 18868 18869 return num; 18870 } 18871 18872 @Override 18873 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 18874 int userId) { 18875 int callingUid = Binder.getCallingUid(); 18876 if (callingUid != Process.SYSTEM_UID) { 18877 throw new SecurityException( 18878 "addPersistentPreferredActivity can only be run by the system"); 18879 } 18880 if (filter.countActions() == 0) { 18881 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18882 return; 18883 } 18884 synchronized (mPackages) { 18885 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 18886 ":"); 18887 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18888 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 18889 new PersistentPreferredActivity(filter, activity)); 18890 scheduleWritePackageRestrictionsLocked(userId); 18891 postPreferredActivityChangedBroadcast(userId); 18892 } 18893 } 18894 18895 @Override 18896 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 18897 int callingUid = Binder.getCallingUid(); 18898 if (callingUid != Process.SYSTEM_UID) { 18899 throw new SecurityException( 18900 "clearPackagePersistentPreferredActivities can only be run by the system"); 18901 } 18902 ArrayList<PersistentPreferredActivity> removed = null; 18903 boolean changed = false; 18904 synchronized (mPackages) { 18905 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 18906 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 18907 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 18908 .valueAt(i); 18909 if (userId != thisUserId) { 18910 continue; 18911 } 18912 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 18913 while (it.hasNext()) { 18914 PersistentPreferredActivity ppa = it.next(); 18915 // Mark entry for removal only if it matches the package name. 18916 if (ppa.mComponent.getPackageName().equals(packageName)) { 18917 if (removed == null) { 18918 removed = new ArrayList<PersistentPreferredActivity>(); 18919 } 18920 removed.add(ppa); 18921 } 18922 } 18923 if (removed != null) { 18924 for (int j=0; j<removed.size(); j++) { 18925 PersistentPreferredActivity ppa = removed.get(j); 18926 ppir.removeFilter(ppa); 18927 } 18928 changed = true; 18929 } 18930 } 18931 18932 if (changed) { 18933 scheduleWritePackageRestrictionsLocked(userId); 18934 postPreferredActivityChangedBroadcast(userId); 18935 } 18936 } 18937 } 18938 18939 /** 18940 * Common machinery for picking apart a restored XML blob and passing 18941 * it to a caller-supplied functor to be applied to the running system. 18942 */ 18943 private void restoreFromXml(XmlPullParser parser, int userId, 18944 String expectedStartTag, BlobXmlRestorer functor) 18945 throws IOException, XmlPullParserException { 18946 int type; 18947 while ((type = parser.next()) != XmlPullParser.START_TAG 18948 && type != XmlPullParser.END_DOCUMENT) { 18949 } 18950 if (type != XmlPullParser.START_TAG) { 18951 // oops didn't find a start tag?! 18952 if (DEBUG_BACKUP) { 18953 Slog.e(TAG, "Didn't find start tag during restore"); 18954 } 18955 return; 18956 } 18957Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 18958 // this is supposed to be TAG_PREFERRED_BACKUP 18959 if (!expectedStartTag.equals(parser.getName())) { 18960 if (DEBUG_BACKUP) { 18961 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 18962 } 18963 return; 18964 } 18965 18966 // skip interfering stuff, then we're aligned with the backing implementation 18967 while ((type = parser.next()) == XmlPullParser.TEXT) { } 18968Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 18969 functor.apply(parser, userId); 18970 } 18971 18972 private interface BlobXmlRestorer { 18973 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 18974 } 18975 18976 /** 18977 * Non-Binder method, support for the backup/restore mechanism: write the 18978 * full set of preferred activities in its canonical XML format. Returns the 18979 * XML output as a byte array, or null if there is none. 18980 */ 18981 @Override 18982 public byte[] getPreferredActivityBackup(int userId) { 18983 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18984 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 18985 } 18986 18987 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18988 try { 18989 final XmlSerializer serializer = new FastXmlSerializer(); 18990 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18991 serializer.startDocument(null, true); 18992 serializer.startTag(null, TAG_PREFERRED_BACKUP); 18993 18994 synchronized (mPackages) { 18995 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 18996 } 18997 18998 serializer.endTag(null, TAG_PREFERRED_BACKUP); 18999 serializer.endDocument(); 19000 serializer.flush(); 19001 } catch (Exception e) { 19002 if (DEBUG_BACKUP) { 19003 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19004 } 19005 return null; 19006 } 19007 19008 return dataStream.toByteArray(); 19009 } 19010 19011 @Override 19012 public void restorePreferredActivities(byte[] backup, int userId) { 19013 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19014 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19015 } 19016 19017 try { 19018 final XmlPullParser parser = Xml.newPullParser(); 19019 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19020 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19021 new BlobXmlRestorer() { 19022 @Override 19023 public void apply(XmlPullParser parser, int userId) 19024 throws XmlPullParserException, IOException { 19025 synchronized (mPackages) { 19026 mSettings.readPreferredActivitiesLPw(parser, userId); 19027 } 19028 } 19029 } ); 19030 } catch (Exception e) { 19031 if (DEBUG_BACKUP) { 19032 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19033 } 19034 } 19035 } 19036 19037 /** 19038 * Non-Binder method, support for the backup/restore mechanism: write the 19039 * default browser (etc) settings in its canonical XML format. Returns the default 19040 * browser XML representation as a byte array, or null if there is none. 19041 */ 19042 @Override 19043 public byte[] getDefaultAppsBackup(int userId) { 19044 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19045 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19046 } 19047 19048 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19049 try { 19050 final XmlSerializer serializer = new FastXmlSerializer(); 19051 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19052 serializer.startDocument(null, true); 19053 serializer.startTag(null, TAG_DEFAULT_APPS); 19054 19055 synchronized (mPackages) { 19056 mSettings.writeDefaultAppsLPr(serializer, userId); 19057 } 19058 19059 serializer.endTag(null, TAG_DEFAULT_APPS); 19060 serializer.endDocument(); 19061 serializer.flush(); 19062 } catch (Exception e) { 19063 if (DEBUG_BACKUP) { 19064 Slog.e(TAG, "Unable to write default apps for backup", e); 19065 } 19066 return null; 19067 } 19068 19069 return dataStream.toByteArray(); 19070 } 19071 19072 @Override 19073 public void restoreDefaultApps(byte[] backup, int userId) { 19074 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19075 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19076 } 19077 19078 try { 19079 final XmlPullParser parser = Xml.newPullParser(); 19080 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19081 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19082 new BlobXmlRestorer() { 19083 @Override 19084 public void apply(XmlPullParser parser, int userId) 19085 throws XmlPullParserException, IOException { 19086 synchronized (mPackages) { 19087 mSettings.readDefaultAppsLPw(parser, userId); 19088 } 19089 } 19090 } ); 19091 } catch (Exception e) { 19092 if (DEBUG_BACKUP) { 19093 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19094 } 19095 } 19096 } 19097 19098 @Override 19099 public byte[] getIntentFilterVerificationBackup(int userId) { 19100 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19101 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19102 } 19103 19104 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19105 try { 19106 final XmlSerializer serializer = new FastXmlSerializer(); 19107 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19108 serializer.startDocument(null, true); 19109 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19110 19111 synchronized (mPackages) { 19112 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19113 } 19114 19115 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19116 serializer.endDocument(); 19117 serializer.flush(); 19118 } catch (Exception e) { 19119 if (DEBUG_BACKUP) { 19120 Slog.e(TAG, "Unable to write default apps for backup", e); 19121 } 19122 return null; 19123 } 19124 19125 return dataStream.toByteArray(); 19126 } 19127 19128 @Override 19129 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19130 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19131 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19132 } 19133 19134 try { 19135 final XmlPullParser parser = Xml.newPullParser(); 19136 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19137 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19138 new BlobXmlRestorer() { 19139 @Override 19140 public void apply(XmlPullParser parser, int userId) 19141 throws XmlPullParserException, IOException { 19142 synchronized (mPackages) { 19143 mSettings.readAllDomainVerificationsLPr(parser, userId); 19144 mSettings.writeLPr(); 19145 } 19146 } 19147 } ); 19148 } catch (Exception e) { 19149 if (DEBUG_BACKUP) { 19150 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19151 } 19152 } 19153 } 19154 19155 @Override 19156 public byte[] getPermissionGrantBackup(int userId) { 19157 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19158 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19159 } 19160 19161 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19162 try { 19163 final XmlSerializer serializer = new FastXmlSerializer(); 19164 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19165 serializer.startDocument(null, true); 19166 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19167 19168 synchronized (mPackages) { 19169 serializeRuntimePermissionGrantsLPr(serializer, userId); 19170 } 19171 19172 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19173 serializer.endDocument(); 19174 serializer.flush(); 19175 } catch (Exception e) { 19176 if (DEBUG_BACKUP) { 19177 Slog.e(TAG, "Unable to write default apps for backup", e); 19178 } 19179 return null; 19180 } 19181 19182 return dataStream.toByteArray(); 19183 } 19184 19185 @Override 19186 public void restorePermissionGrants(byte[] backup, int userId) { 19187 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19188 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19189 } 19190 19191 try { 19192 final XmlPullParser parser = Xml.newPullParser(); 19193 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19194 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19195 new BlobXmlRestorer() { 19196 @Override 19197 public void apply(XmlPullParser parser, int userId) 19198 throws XmlPullParserException, IOException { 19199 synchronized (mPackages) { 19200 processRestoredPermissionGrantsLPr(parser, userId); 19201 } 19202 } 19203 } ); 19204 } catch (Exception e) { 19205 if (DEBUG_BACKUP) { 19206 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19207 } 19208 } 19209 } 19210 19211 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19212 throws IOException { 19213 serializer.startTag(null, TAG_ALL_GRANTS); 19214 19215 final int N = mSettings.mPackages.size(); 19216 for (int i = 0; i < N; i++) { 19217 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19218 boolean pkgGrantsKnown = false; 19219 19220 PermissionsState packagePerms = ps.getPermissionsState(); 19221 19222 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19223 final int grantFlags = state.getFlags(); 19224 // only look at grants that are not system/policy fixed 19225 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19226 final boolean isGranted = state.isGranted(); 19227 // And only back up the user-twiddled state bits 19228 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19229 final String packageName = mSettings.mPackages.keyAt(i); 19230 if (!pkgGrantsKnown) { 19231 serializer.startTag(null, TAG_GRANT); 19232 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19233 pkgGrantsKnown = true; 19234 } 19235 19236 final boolean userSet = 19237 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19238 final boolean userFixed = 19239 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19240 final boolean revoke = 19241 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19242 19243 serializer.startTag(null, TAG_PERMISSION); 19244 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19245 if (isGranted) { 19246 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19247 } 19248 if (userSet) { 19249 serializer.attribute(null, ATTR_USER_SET, "true"); 19250 } 19251 if (userFixed) { 19252 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19253 } 19254 if (revoke) { 19255 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19256 } 19257 serializer.endTag(null, TAG_PERMISSION); 19258 } 19259 } 19260 } 19261 19262 if (pkgGrantsKnown) { 19263 serializer.endTag(null, TAG_GRANT); 19264 } 19265 } 19266 19267 serializer.endTag(null, TAG_ALL_GRANTS); 19268 } 19269 19270 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19271 throws XmlPullParserException, IOException { 19272 String pkgName = null; 19273 int outerDepth = parser.getDepth(); 19274 int type; 19275 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19276 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19277 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19278 continue; 19279 } 19280 19281 final String tagName = parser.getName(); 19282 if (tagName.equals(TAG_GRANT)) { 19283 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19284 if (DEBUG_BACKUP) { 19285 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19286 } 19287 } else if (tagName.equals(TAG_PERMISSION)) { 19288 19289 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19290 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19291 19292 int newFlagSet = 0; 19293 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19294 newFlagSet |= FLAG_PERMISSION_USER_SET; 19295 } 19296 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19297 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19298 } 19299 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19300 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19301 } 19302 if (DEBUG_BACKUP) { 19303 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19304 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19305 } 19306 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19307 if (ps != null) { 19308 // Already installed so we apply the grant immediately 19309 if (DEBUG_BACKUP) { 19310 Slog.v(TAG, " + already installed; applying"); 19311 } 19312 PermissionsState perms = ps.getPermissionsState(); 19313 BasePermission bp = mSettings.mPermissions.get(permName); 19314 if (bp != null) { 19315 if (isGranted) { 19316 perms.grantRuntimePermission(bp, userId); 19317 } 19318 if (newFlagSet != 0) { 19319 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19320 } 19321 } 19322 } else { 19323 // Need to wait for post-restore install to apply the grant 19324 if (DEBUG_BACKUP) { 19325 Slog.v(TAG, " - not yet installed; saving for later"); 19326 } 19327 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19328 isGranted, newFlagSet, userId); 19329 } 19330 } else { 19331 PackageManagerService.reportSettingsProblem(Log.WARN, 19332 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19333 XmlUtils.skipCurrentTag(parser); 19334 } 19335 } 19336 19337 scheduleWriteSettingsLocked(); 19338 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19339 } 19340 19341 @Override 19342 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19343 int sourceUserId, int targetUserId, int flags) { 19344 mContext.enforceCallingOrSelfPermission( 19345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19346 int callingUid = Binder.getCallingUid(); 19347 enforceOwnerRights(ownerPackage, callingUid); 19348 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19349 if (intentFilter.countActions() == 0) { 19350 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19351 return; 19352 } 19353 synchronized (mPackages) { 19354 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19355 ownerPackage, targetUserId, flags); 19356 CrossProfileIntentResolver resolver = 19357 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19358 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19359 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19360 if (existing != null) { 19361 int size = existing.size(); 19362 for (int i = 0; i < size; i++) { 19363 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19364 return; 19365 } 19366 } 19367 } 19368 resolver.addFilter(newFilter); 19369 scheduleWritePackageRestrictionsLocked(sourceUserId); 19370 } 19371 } 19372 19373 @Override 19374 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19375 mContext.enforceCallingOrSelfPermission( 19376 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19377 int callingUid = Binder.getCallingUid(); 19378 enforceOwnerRights(ownerPackage, callingUid); 19379 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19380 synchronized (mPackages) { 19381 CrossProfileIntentResolver resolver = 19382 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19383 ArraySet<CrossProfileIntentFilter> set = 19384 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19385 for (CrossProfileIntentFilter filter : set) { 19386 if (filter.getOwnerPackage().equals(ownerPackage)) { 19387 resolver.removeFilter(filter); 19388 } 19389 } 19390 scheduleWritePackageRestrictionsLocked(sourceUserId); 19391 } 19392 } 19393 19394 // Enforcing that callingUid is owning pkg on userId 19395 private void enforceOwnerRights(String pkg, int callingUid) { 19396 // The system owns everything. 19397 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19398 return; 19399 } 19400 int callingUserId = UserHandle.getUserId(callingUid); 19401 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19402 if (pi == null) { 19403 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19404 + callingUserId); 19405 } 19406 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19407 throw new SecurityException("Calling uid " + callingUid 19408 + " does not own package " + pkg); 19409 } 19410 } 19411 19412 @Override 19413 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19414 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19415 } 19416 19417 private Intent getHomeIntent() { 19418 Intent intent = new Intent(Intent.ACTION_MAIN); 19419 intent.addCategory(Intent.CATEGORY_HOME); 19420 intent.addCategory(Intent.CATEGORY_DEFAULT); 19421 return intent; 19422 } 19423 19424 private IntentFilter getHomeFilter() { 19425 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19426 filter.addCategory(Intent.CATEGORY_HOME); 19427 filter.addCategory(Intent.CATEGORY_DEFAULT); 19428 return filter; 19429 } 19430 19431 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19432 int userId) { 19433 Intent intent = getHomeIntent(); 19434 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19435 PackageManager.GET_META_DATA, userId); 19436 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19437 true, false, false, userId); 19438 19439 allHomeCandidates.clear(); 19440 if (list != null) { 19441 for (ResolveInfo ri : list) { 19442 allHomeCandidates.add(ri); 19443 } 19444 } 19445 return (preferred == null || preferred.activityInfo == null) 19446 ? null 19447 : new ComponentName(preferred.activityInfo.packageName, 19448 preferred.activityInfo.name); 19449 } 19450 19451 @Override 19452 public void setHomeActivity(ComponentName comp, int userId) { 19453 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19454 getHomeActivitiesAsUser(homeActivities, userId); 19455 19456 boolean found = false; 19457 19458 final int size = homeActivities.size(); 19459 final ComponentName[] set = new ComponentName[size]; 19460 for (int i = 0; i < size; i++) { 19461 final ResolveInfo candidate = homeActivities.get(i); 19462 final ActivityInfo info = candidate.activityInfo; 19463 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19464 set[i] = activityName; 19465 if (!found && activityName.equals(comp)) { 19466 found = true; 19467 } 19468 } 19469 if (!found) { 19470 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19471 + userId); 19472 } 19473 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19474 set, comp, userId); 19475 } 19476 19477 private @Nullable String getSetupWizardPackageName() { 19478 final Intent intent = new Intent(Intent.ACTION_MAIN); 19479 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19480 19481 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19482 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19483 | MATCH_DISABLED_COMPONENTS, 19484 UserHandle.myUserId()); 19485 if (matches.size() == 1) { 19486 return matches.get(0).getComponentInfo().packageName; 19487 } else { 19488 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19489 + ": matches=" + matches); 19490 return null; 19491 } 19492 } 19493 19494 private @Nullable String getStorageManagerPackageName() { 19495 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19496 19497 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19498 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19499 | MATCH_DISABLED_COMPONENTS, 19500 UserHandle.myUserId()); 19501 if (matches.size() == 1) { 19502 return matches.get(0).getComponentInfo().packageName; 19503 } else { 19504 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19505 + matches.size() + ": matches=" + matches); 19506 return null; 19507 } 19508 } 19509 19510 @Override 19511 public void setApplicationEnabledSetting(String appPackageName, 19512 int newState, int flags, int userId, String callingPackage) { 19513 if (!sUserManager.exists(userId)) return; 19514 if (callingPackage == null) { 19515 callingPackage = Integer.toString(Binder.getCallingUid()); 19516 } 19517 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19518 } 19519 19520 @Override 19521 public void setComponentEnabledSetting(ComponentName componentName, 19522 int newState, int flags, int userId) { 19523 if (!sUserManager.exists(userId)) return; 19524 setEnabledSetting(componentName.getPackageName(), 19525 componentName.getClassName(), newState, flags, userId, null); 19526 } 19527 19528 private void setEnabledSetting(final String packageName, String className, int newState, 19529 final int flags, int userId, String callingPackage) { 19530 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19531 || newState == COMPONENT_ENABLED_STATE_ENABLED 19532 || newState == COMPONENT_ENABLED_STATE_DISABLED 19533 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19534 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19535 throw new IllegalArgumentException("Invalid new component state: " 19536 + newState); 19537 } 19538 PackageSetting pkgSetting; 19539 final int uid = Binder.getCallingUid(); 19540 final int permission; 19541 if (uid == Process.SYSTEM_UID) { 19542 permission = PackageManager.PERMISSION_GRANTED; 19543 } else { 19544 permission = mContext.checkCallingOrSelfPermission( 19545 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19546 } 19547 enforceCrossUserPermission(uid, userId, 19548 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19549 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19550 boolean sendNow = false; 19551 boolean isApp = (className == null); 19552 String componentName = isApp ? packageName : className; 19553 int packageUid = -1; 19554 ArrayList<String> components; 19555 19556 // writer 19557 synchronized (mPackages) { 19558 pkgSetting = mSettings.mPackages.get(packageName); 19559 if (pkgSetting == null) { 19560 if (className == null) { 19561 throw new IllegalArgumentException("Unknown package: " + packageName); 19562 } 19563 throw new IllegalArgumentException( 19564 "Unknown component: " + packageName + "/" + className); 19565 } 19566 } 19567 19568 // Limit who can change which apps 19569 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19570 // Don't allow apps that don't have permission to modify other apps 19571 if (!allowedByPermission) { 19572 throw new SecurityException( 19573 "Permission Denial: attempt to change component state from pid=" 19574 + Binder.getCallingPid() 19575 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19576 } 19577 // Don't allow changing protected packages. 19578 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19579 throw new SecurityException("Cannot disable a protected package: " + packageName); 19580 } 19581 } 19582 19583 synchronized (mPackages) { 19584 if (uid == Process.SHELL_UID 19585 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19586 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19587 // unless it is a test package. 19588 int oldState = pkgSetting.getEnabled(userId); 19589 if (className == null 19590 && 19591 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19592 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19593 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19594 && 19595 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19596 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19597 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19598 // ok 19599 } else { 19600 throw new SecurityException( 19601 "Shell cannot change component state for " + packageName + "/" 19602 + className + " to " + newState); 19603 } 19604 } 19605 if (className == null) { 19606 // We're dealing with an application/package level state change 19607 if (pkgSetting.getEnabled(userId) == newState) { 19608 // Nothing to do 19609 return; 19610 } 19611 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19612 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19613 // Don't care about who enables an app. 19614 callingPackage = null; 19615 } 19616 pkgSetting.setEnabled(newState, userId, callingPackage); 19617 // pkgSetting.pkg.mSetEnabled = newState; 19618 } else { 19619 // We're dealing with a component level state change 19620 // First, verify that this is a valid class name. 19621 PackageParser.Package pkg = pkgSetting.pkg; 19622 if (pkg == null || !pkg.hasComponentClassName(className)) { 19623 if (pkg != null && 19624 pkg.applicationInfo.targetSdkVersion >= 19625 Build.VERSION_CODES.JELLY_BEAN) { 19626 throw new IllegalArgumentException("Component class " + className 19627 + " does not exist in " + packageName); 19628 } else { 19629 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19630 + className + " does not exist in " + packageName); 19631 } 19632 } 19633 switch (newState) { 19634 case COMPONENT_ENABLED_STATE_ENABLED: 19635 if (!pkgSetting.enableComponentLPw(className, userId)) { 19636 return; 19637 } 19638 break; 19639 case COMPONENT_ENABLED_STATE_DISABLED: 19640 if (!pkgSetting.disableComponentLPw(className, userId)) { 19641 return; 19642 } 19643 break; 19644 case COMPONENT_ENABLED_STATE_DEFAULT: 19645 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19646 return; 19647 } 19648 break; 19649 default: 19650 Slog.e(TAG, "Invalid new component state: " + newState); 19651 return; 19652 } 19653 } 19654 scheduleWritePackageRestrictionsLocked(userId); 19655 components = mPendingBroadcasts.get(userId, packageName); 19656 final boolean newPackage = components == null; 19657 if (newPackage) { 19658 components = new ArrayList<String>(); 19659 } 19660 if (!components.contains(componentName)) { 19661 components.add(componentName); 19662 } 19663 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19664 sendNow = true; 19665 // Purge entry from pending broadcast list if another one exists already 19666 // since we are sending one right away. 19667 mPendingBroadcasts.remove(userId, packageName); 19668 } else { 19669 if (newPackage) { 19670 mPendingBroadcasts.put(userId, packageName, components); 19671 } 19672 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19673 // Schedule a message 19674 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19675 } 19676 } 19677 } 19678 19679 long callingId = Binder.clearCallingIdentity(); 19680 try { 19681 if (sendNow) { 19682 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19683 sendPackageChangedBroadcast(packageName, 19684 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19685 } 19686 } finally { 19687 Binder.restoreCallingIdentity(callingId); 19688 } 19689 } 19690 19691 @Override 19692 public void flushPackageRestrictionsAsUser(int userId) { 19693 if (!sUserManager.exists(userId)) { 19694 return; 19695 } 19696 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19697 false /* checkShell */, "flushPackageRestrictions"); 19698 synchronized (mPackages) { 19699 mSettings.writePackageRestrictionsLPr(userId); 19700 mDirtyUsers.remove(userId); 19701 if (mDirtyUsers.isEmpty()) { 19702 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19703 } 19704 } 19705 } 19706 19707 private void sendPackageChangedBroadcast(String packageName, 19708 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19709 if (DEBUG_INSTALL) 19710 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19711 + componentNames); 19712 Bundle extras = new Bundle(4); 19713 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19714 String nameList[] = new String[componentNames.size()]; 19715 componentNames.toArray(nameList); 19716 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19717 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19718 extras.putInt(Intent.EXTRA_UID, packageUid); 19719 // If this is not reporting a change of the overall package, then only send it 19720 // to registered receivers. We don't want to launch a swath of apps for every 19721 // little component state change. 19722 final int flags = !componentNames.contains(packageName) 19723 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19724 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19725 new int[] {UserHandle.getUserId(packageUid)}); 19726 } 19727 19728 @Override 19729 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19730 if (!sUserManager.exists(userId)) return; 19731 final int uid = Binder.getCallingUid(); 19732 final int permission = mContext.checkCallingOrSelfPermission( 19733 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19734 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19735 enforceCrossUserPermission(uid, userId, 19736 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19737 // writer 19738 synchronized (mPackages) { 19739 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19740 allowedByPermission, uid, userId)) { 19741 scheduleWritePackageRestrictionsLocked(userId); 19742 } 19743 } 19744 } 19745 19746 @Override 19747 public String getInstallerPackageName(String packageName) { 19748 // reader 19749 synchronized (mPackages) { 19750 return mSettings.getInstallerPackageNameLPr(packageName); 19751 } 19752 } 19753 19754 public boolean isOrphaned(String packageName) { 19755 // reader 19756 synchronized (mPackages) { 19757 return mSettings.isOrphaned(packageName); 19758 } 19759 } 19760 19761 @Override 19762 public int getApplicationEnabledSetting(String packageName, int userId) { 19763 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19764 int uid = Binder.getCallingUid(); 19765 enforceCrossUserPermission(uid, userId, 19766 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19767 // reader 19768 synchronized (mPackages) { 19769 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19770 } 19771 } 19772 19773 @Override 19774 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19775 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19776 int uid = Binder.getCallingUid(); 19777 enforceCrossUserPermission(uid, userId, 19778 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19779 // reader 19780 synchronized (mPackages) { 19781 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19782 } 19783 } 19784 19785 @Override 19786 public void enterSafeMode() { 19787 enforceSystemOrRoot("Only the system can request entering safe mode"); 19788 19789 if (!mSystemReady) { 19790 mSafeMode = true; 19791 } 19792 } 19793 19794 @Override 19795 public void systemReady() { 19796 mSystemReady = true; 19797 19798 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19799 // disabled after already being started. 19800 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19801 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19802 19803 // Read the compatibilty setting when the system is ready. 19804 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19805 mContext.getContentResolver(), 19806 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19807 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19808 if (DEBUG_SETTINGS) { 19809 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19810 } 19811 19812 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19813 19814 synchronized (mPackages) { 19815 // Verify that all of the preferred activity components actually 19816 // exist. It is possible for applications to be updated and at 19817 // that point remove a previously declared activity component that 19818 // had been set as a preferred activity. We try to clean this up 19819 // the next time we encounter that preferred activity, but it is 19820 // possible for the user flow to never be able to return to that 19821 // situation so here we do a sanity check to make sure we haven't 19822 // left any junk around. 19823 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 19824 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19825 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19826 removed.clear(); 19827 for (PreferredActivity pa : pir.filterSet()) { 19828 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 19829 removed.add(pa); 19830 } 19831 } 19832 if (removed.size() > 0) { 19833 for (int r=0; r<removed.size(); r++) { 19834 PreferredActivity pa = removed.get(r); 19835 Slog.w(TAG, "Removing dangling preferred activity: " 19836 + pa.mPref.mComponent); 19837 pir.removeFilter(pa); 19838 } 19839 mSettings.writePackageRestrictionsLPr( 19840 mSettings.mPreferredActivities.keyAt(i)); 19841 } 19842 } 19843 19844 for (int userId : UserManagerService.getInstance().getUserIds()) { 19845 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 19846 grantPermissionsUserIds = ArrayUtils.appendInt( 19847 grantPermissionsUserIds, userId); 19848 } 19849 } 19850 } 19851 sUserManager.systemReady(); 19852 19853 // If we upgraded grant all default permissions before kicking off. 19854 for (int userId : grantPermissionsUserIds) { 19855 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 19856 } 19857 19858 // If we did not grant default permissions, we preload from this the 19859 // default permission exceptions lazily to ensure we don't hit the 19860 // disk on a new user creation. 19861 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 19862 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 19863 } 19864 19865 // Kick off any messages waiting for system ready 19866 if (mPostSystemReadyMessages != null) { 19867 for (Message msg : mPostSystemReadyMessages) { 19868 msg.sendToTarget(); 19869 } 19870 mPostSystemReadyMessages = null; 19871 } 19872 19873 // Watch for external volumes that come and go over time 19874 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19875 storage.registerListener(mStorageListener); 19876 19877 mInstallerService.systemReady(); 19878 mPackageDexOptimizer.systemReady(); 19879 19880 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 19881 StorageManagerInternal.class); 19882 StorageManagerInternal.addExternalStoragePolicy( 19883 new StorageManagerInternal.ExternalStorageMountPolicy() { 19884 @Override 19885 public int getMountMode(int uid, String packageName) { 19886 if (Process.isIsolated(uid)) { 19887 return Zygote.MOUNT_EXTERNAL_NONE; 19888 } 19889 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 19890 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19891 } 19892 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19893 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19894 } 19895 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19896 return Zygote.MOUNT_EXTERNAL_READ; 19897 } 19898 return Zygote.MOUNT_EXTERNAL_WRITE; 19899 } 19900 19901 @Override 19902 public boolean hasExternalStorage(int uid, String packageName) { 19903 return true; 19904 } 19905 }); 19906 19907 // Now that we're mostly running, clean up stale users and apps 19908 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 19909 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 19910 } 19911 19912 @Override 19913 public boolean isSafeMode() { 19914 return mSafeMode; 19915 } 19916 19917 @Override 19918 public boolean hasSystemUidErrors() { 19919 return mHasSystemUidErrors; 19920 } 19921 19922 static String arrayToString(int[] array) { 19923 StringBuffer buf = new StringBuffer(128); 19924 buf.append('['); 19925 if (array != null) { 19926 for (int i=0; i<array.length; i++) { 19927 if (i > 0) buf.append(", "); 19928 buf.append(array[i]); 19929 } 19930 } 19931 buf.append(']'); 19932 return buf.toString(); 19933 } 19934 19935 static class DumpState { 19936 public static final int DUMP_LIBS = 1 << 0; 19937 public static final int DUMP_FEATURES = 1 << 1; 19938 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 19939 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 19940 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 19941 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 19942 public static final int DUMP_PERMISSIONS = 1 << 6; 19943 public static final int DUMP_PACKAGES = 1 << 7; 19944 public static final int DUMP_SHARED_USERS = 1 << 8; 19945 public static final int DUMP_MESSAGES = 1 << 9; 19946 public static final int DUMP_PROVIDERS = 1 << 10; 19947 public static final int DUMP_VERIFIERS = 1 << 11; 19948 public static final int DUMP_PREFERRED = 1 << 12; 19949 public static final int DUMP_PREFERRED_XML = 1 << 13; 19950 public static final int DUMP_KEYSETS = 1 << 14; 19951 public static final int DUMP_VERSION = 1 << 15; 19952 public static final int DUMP_INSTALLS = 1 << 16; 19953 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 19954 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 19955 public static final int DUMP_FROZEN = 1 << 19; 19956 public static final int DUMP_DEXOPT = 1 << 20; 19957 public static final int DUMP_COMPILER_STATS = 1 << 21; 19958 19959 public static final int OPTION_SHOW_FILTERS = 1 << 0; 19960 19961 private int mTypes; 19962 19963 private int mOptions; 19964 19965 private boolean mTitlePrinted; 19966 19967 private SharedUserSetting mSharedUser; 19968 19969 public boolean isDumping(int type) { 19970 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 19971 return true; 19972 } 19973 19974 return (mTypes & type) != 0; 19975 } 19976 19977 public void setDump(int type) { 19978 mTypes |= type; 19979 } 19980 19981 public boolean isOptionEnabled(int option) { 19982 return (mOptions & option) != 0; 19983 } 19984 19985 public void setOptionEnabled(int option) { 19986 mOptions |= option; 19987 } 19988 19989 public boolean onTitlePrinted() { 19990 final boolean printed = mTitlePrinted; 19991 mTitlePrinted = true; 19992 return printed; 19993 } 19994 19995 public boolean getTitlePrinted() { 19996 return mTitlePrinted; 19997 } 19998 19999 public void setTitlePrinted(boolean enabled) { 20000 mTitlePrinted = enabled; 20001 } 20002 20003 public SharedUserSetting getSharedUser() { 20004 return mSharedUser; 20005 } 20006 20007 public void setSharedUser(SharedUserSetting user) { 20008 mSharedUser = user; 20009 } 20010 } 20011 20012 @Override 20013 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20014 FileDescriptor err, String[] args, ShellCallback callback, 20015 ResultReceiver resultReceiver) { 20016 (new PackageManagerShellCommand(this)).exec( 20017 this, in, out, err, args, callback, resultReceiver); 20018 } 20019 20020 @Override 20021 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20022 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20023 != PackageManager.PERMISSION_GRANTED) { 20024 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20025 + Binder.getCallingPid() 20026 + ", uid=" + Binder.getCallingUid() 20027 + " without permission " 20028 + android.Manifest.permission.DUMP); 20029 return; 20030 } 20031 20032 DumpState dumpState = new DumpState(); 20033 boolean fullPreferred = false; 20034 boolean checkin = false; 20035 20036 String packageName = null; 20037 ArraySet<String> permissionNames = null; 20038 20039 int opti = 0; 20040 while (opti < args.length) { 20041 String opt = args[opti]; 20042 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20043 break; 20044 } 20045 opti++; 20046 20047 if ("-a".equals(opt)) { 20048 // Right now we only know how to print all. 20049 } else if ("-h".equals(opt)) { 20050 pw.println("Package manager dump options:"); 20051 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20052 pw.println(" --checkin: dump for a checkin"); 20053 pw.println(" -f: print details of intent filters"); 20054 pw.println(" -h: print this help"); 20055 pw.println(" cmd may be one of:"); 20056 pw.println(" l[ibraries]: list known shared libraries"); 20057 pw.println(" f[eatures]: list device features"); 20058 pw.println(" k[eysets]: print known keysets"); 20059 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20060 pw.println(" perm[issions]: dump permissions"); 20061 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20062 pw.println(" pref[erred]: print preferred package settings"); 20063 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20064 pw.println(" prov[iders]: dump content providers"); 20065 pw.println(" p[ackages]: dump installed packages"); 20066 pw.println(" s[hared-users]: dump shared user IDs"); 20067 pw.println(" m[essages]: print collected runtime messages"); 20068 pw.println(" v[erifiers]: print package verifier info"); 20069 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20070 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20071 pw.println(" version: print database version info"); 20072 pw.println(" write: write current settings now"); 20073 pw.println(" installs: details about install sessions"); 20074 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20075 pw.println(" dexopt: dump dexopt state"); 20076 pw.println(" compiler-stats: dump compiler statistics"); 20077 pw.println(" <package.name>: info about given package"); 20078 return; 20079 } else if ("--checkin".equals(opt)) { 20080 checkin = true; 20081 } else if ("-f".equals(opt)) { 20082 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20083 } else { 20084 pw.println("Unknown argument: " + opt + "; use -h for help"); 20085 } 20086 } 20087 20088 // Is the caller requesting to dump a particular piece of data? 20089 if (opti < args.length) { 20090 String cmd = args[opti]; 20091 opti++; 20092 // Is this a package name? 20093 if ("android".equals(cmd) || cmd.contains(".")) { 20094 packageName = cmd; 20095 // When dumping a single package, we always dump all of its 20096 // filter information since the amount of data will be reasonable. 20097 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20098 } else if ("check-permission".equals(cmd)) { 20099 if (opti >= args.length) { 20100 pw.println("Error: check-permission missing permission argument"); 20101 return; 20102 } 20103 String perm = args[opti]; 20104 opti++; 20105 if (opti >= args.length) { 20106 pw.println("Error: check-permission missing package argument"); 20107 return; 20108 } 20109 20110 String pkg = args[opti]; 20111 opti++; 20112 int user = UserHandle.getUserId(Binder.getCallingUid()); 20113 if (opti < args.length) { 20114 try { 20115 user = Integer.parseInt(args[opti]); 20116 } catch (NumberFormatException e) { 20117 pw.println("Error: check-permission user argument is not a number: " 20118 + args[opti]); 20119 return; 20120 } 20121 } 20122 20123 // Normalize package name to handle renamed packages and static libs 20124 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20125 20126 pw.println(checkPermission(perm, pkg, user)); 20127 return; 20128 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20129 dumpState.setDump(DumpState.DUMP_LIBS); 20130 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20131 dumpState.setDump(DumpState.DUMP_FEATURES); 20132 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20133 if (opti >= args.length) { 20134 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20135 | DumpState.DUMP_SERVICE_RESOLVERS 20136 | DumpState.DUMP_RECEIVER_RESOLVERS 20137 | DumpState.DUMP_CONTENT_RESOLVERS); 20138 } else { 20139 while (opti < args.length) { 20140 String name = args[opti]; 20141 if ("a".equals(name) || "activity".equals(name)) { 20142 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20143 } else if ("s".equals(name) || "service".equals(name)) { 20144 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20145 } else if ("r".equals(name) || "receiver".equals(name)) { 20146 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20147 } else if ("c".equals(name) || "content".equals(name)) { 20148 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20149 } else { 20150 pw.println("Error: unknown resolver table type: " + name); 20151 return; 20152 } 20153 opti++; 20154 } 20155 } 20156 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20157 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20158 } else if ("permission".equals(cmd)) { 20159 if (opti >= args.length) { 20160 pw.println("Error: permission requires permission name"); 20161 return; 20162 } 20163 permissionNames = new ArraySet<>(); 20164 while (opti < args.length) { 20165 permissionNames.add(args[opti]); 20166 opti++; 20167 } 20168 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20169 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20170 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20171 dumpState.setDump(DumpState.DUMP_PREFERRED); 20172 } else if ("preferred-xml".equals(cmd)) { 20173 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20174 if (opti < args.length && "--full".equals(args[opti])) { 20175 fullPreferred = true; 20176 opti++; 20177 } 20178 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20179 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20180 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20181 dumpState.setDump(DumpState.DUMP_PACKAGES); 20182 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20183 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20184 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20185 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20186 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20187 dumpState.setDump(DumpState.DUMP_MESSAGES); 20188 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20189 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20190 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20191 || "intent-filter-verifiers".equals(cmd)) { 20192 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20193 } else if ("version".equals(cmd)) { 20194 dumpState.setDump(DumpState.DUMP_VERSION); 20195 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20196 dumpState.setDump(DumpState.DUMP_KEYSETS); 20197 } else if ("installs".equals(cmd)) { 20198 dumpState.setDump(DumpState.DUMP_INSTALLS); 20199 } else if ("frozen".equals(cmd)) { 20200 dumpState.setDump(DumpState.DUMP_FROZEN); 20201 } else if ("dexopt".equals(cmd)) { 20202 dumpState.setDump(DumpState.DUMP_DEXOPT); 20203 } else if ("compiler-stats".equals(cmd)) { 20204 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20205 } else if ("write".equals(cmd)) { 20206 synchronized (mPackages) { 20207 mSettings.writeLPr(); 20208 pw.println("Settings written."); 20209 return; 20210 } 20211 } 20212 } 20213 20214 if (checkin) { 20215 pw.println("vers,1"); 20216 } 20217 20218 // reader 20219 synchronized (mPackages) { 20220 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20221 if (!checkin) { 20222 if (dumpState.onTitlePrinted()) 20223 pw.println(); 20224 pw.println("Database versions:"); 20225 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20226 } 20227 } 20228 20229 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20230 if (!checkin) { 20231 if (dumpState.onTitlePrinted()) 20232 pw.println(); 20233 pw.println("Verifiers:"); 20234 pw.print(" Required: "); 20235 pw.print(mRequiredVerifierPackage); 20236 pw.print(" (uid="); 20237 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20238 UserHandle.USER_SYSTEM)); 20239 pw.println(")"); 20240 } else if (mRequiredVerifierPackage != null) { 20241 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20242 pw.print(","); 20243 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20244 UserHandle.USER_SYSTEM)); 20245 } 20246 } 20247 20248 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20249 packageName == null) { 20250 if (mIntentFilterVerifierComponent != null) { 20251 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20252 if (!checkin) { 20253 if (dumpState.onTitlePrinted()) 20254 pw.println(); 20255 pw.println("Intent Filter Verifier:"); 20256 pw.print(" Using: "); 20257 pw.print(verifierPackageName); 20258 pw.print(" (uid="); 20259 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20260 UserHandle.USER_SYSTEM)); 20261 pw.println(")"); 20262 } else if (verifierPackageName != null) { 20263 pw.print("ifv,"); pw.print(verifierPackageName); 20264 pw.print(","); 20265 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20266 UserHandle.USER_SYSTEM)); 20267 } 20268 } else { 20269 pw.println(); 20270 pw.println("No Intent Filter Verifier available!"); 20271 } 20272 } 20273 20274 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20275 boolean printedHeader = false; 20276 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20277 while (it.hasNext()) { 20278 String libName = it.next(); 20279 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20280 if (versionedLib == null) { 20281 continue; 20282 } 20283 final int versionCount = versionedLib.size(); 20284 for (int i = 0; i < versionCount; i++) { 20285 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20286 if (!checkin) { 20287 if (!printedHeader) { 20288 if (dumpState.onTitlePrinted()) 20289 pw.println(); 20290 pw.println("Libraries:"); 20291 printedHeader = true; 20292 } 20293 pw.print(" "); 20294 } else { 20295 pw.print("lib,"); 20296 } 20297 pw.print(libEntry.info.getName()); 20298 if (libEntry.info.isStatic()) { 20299 pw.print(" version=" + libEntry.info.getVersion()); 20300 } 20301 if (!checkin) { 20302 pw.print(" -> "); 20303 } 20304 if (libEntry.path != null) { 20305 pw.print(" (jar) "); 20306 pw.print(libEntry.path); 20307 } else { 20308 pw.print(" (apk) "); 20309 pw.print(libEntry.apk); 20310 } 20311 pw.println(); 20312 } 20313 } 20314 } 20315 20316 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20317 if (dumpState.onTitlePrinted()) 20318 pw.println(); 20319 if (!checkin) { 20320 pw.println("Features:"); 20321 } 20322 20323 for (FeatureInfo feat : mAvailableFeatures.values()) { 20324 if (checkin) { 20325 pw.print("feat,"); 20326 pw.print(feat.name); 20327 pw.print(","); 20328 pw.println(feat.version); 20329 } else { 20330 pw.print(" "); 20331 pw.print(feat.name); 20332 if (feat.version > 0) { 20333 pw.print(" version="); 20334 pw.print(feat.version); 20335 } 20336 pw.println(); 20337 } 20338 } 20339 } 20340 20341 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20342 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20343 : "Activity Resolver Table:", " ", packageName, 20344 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20345 dumpState.setTitlePrinted(true); 20346 } 20347 } 20348 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20349 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20350 : "Receiver Resolver Table:", " ", packageName, 20351 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20352 dumpState.setTitlePrinted(true); 20353 } 20354 } 20355 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20356 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20357 : "Service Resolver Table:", " ", packageName, 20358 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20359 dumpState.setTitlePrinted(true); 20360 } 20361 } 20362 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20363 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20364 : "Provider Resolver Table:", " ", packageName, 20365 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20366 dumpState.setTitlePrinted(true); 20367 } 20368 } 20369 20370 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20371 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20372 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20373 int user = mSettings.mPreferredActivities.keyAt(i); 20374 if (pir.dump(pw, 20375 dumpState.getTitlePrinted() 20376 ? "\nPreferred Activities User " + user + ":" 20377 : "Preferred Activities User " + user + ":", " ", 20378 packageName, true, false)) { 20379 dumpState.setTitlePrinted(true); 20380 } 20381 } 20382 } 20383 20384 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20385 pw.flush(); 20386 FileOutputStream fout = new FileOutputStream(fd); 20387 BufferedOutputStream str = new BufferedOutputStream(fout); 20388 XmlSerializer serializer = new FastXmlSerializer(); 20389 try { 20390 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20391 serializer.startDocument(null, true); 20392 serializer.setFeature( 20393 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20394 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20395 serializer.endDocument(); 20396 serializer.flush(); 20397 } catch (IllegalArgumentException e) { 20398 pw.println("Failed writing: " + e); 20399 } catch (IllegalStateException e) { 20400 pw.println("Failed writing: " + e); 20401 } catch (IOException e) { 20402 pw.println("Failed writing: " + e); 20403 } 20404 } 20405 20406 if (!checkin 20407 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20408 && packageName == null) { 20409 pw.println(); 20410 int count = mSettings.mPackages.size(); 20411 if (count == 0) { 20412 pw.println("No applications!"); 20413 pw.println(); 20414 } else { 20415 final String prefix = " "; 20416 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20417 if (allPackageSettings.size() == 0) { 20418 pw.println("No domain preferred apps!"); 20419 pw.println(); 20420 } else { 20421 pw.println("App verification status:"); 20422 pw.println(); 20423 count = 0; 20424 for (PackageSetting ps : allPackageSettings) { 20425 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20426 if (ivi == null || ivi.getPackageName() == null) continue; 20427 pw.println(prefix + "Package: " + ivi.getPackageName()); 20428 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20429 pw.println(prefix + "Status: " + ivi.getStatusString()); 20430 pw.println(); 20431 count++; 20432 } 20433 if (count == 0) { 20434 pw.println(prefix + "No app verification established."); 20435 pw.println(); 20436 } 20437 for (int userId : sUserManager.getUserIds()) { 20438 pw.println("App linkages for user " + userId + ":"); 20439 pw.println(); 20440 count = 0; 20441 for (PackageSetting ps : allPackageSettings) { 20442 final long status = ps.getDomainVerificationStatusForUser(userId); 20443 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20444 && !DEBUG_DOMAIN_VERIFICATION) { 20445 continue; 20446 } 20447 pw.println(prefix + "Package: " + ps.name); 20448 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20449 String statusStr = IntentFilterVerificationInfo. 20450 getStatusStringFromValue(status); 20451 pw.println(prefix + "Status: " + statusStr); 20452 pw.println(); 20453 count++; 20454 } 20455 if (count == 0) { 20456 pw.println(prefix + "No configured app linkages."); 20457 pw.println(); 20458 } 20459 } 20460 } 20461 } 20462 } 20463 20464 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20465 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20466 if (packageName == null && permissionNames == null) { 20467 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20468 if (iperm == 0) { 20469 if (dumpState.onTitlePrinted()) 20470 pw.println(); 20471 pw.println("AppOp Permissions:"); 20472 } 20473 pw.print(" AppOp Permission "); 20474 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20475 pw.println(":"); 20476 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20477 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20478 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20479 } 20480 } 20481 } 20482 } 20483 20484 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20485 boolean printedSomething = false; 20486 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20487 if (packageName != null && !packageName.equals(p.info.packageName)) { 20488 continue; 20489 } 20490 if (!printedSomething) { 20491 if (dumpState.onTitlePrinted()) 20492 pw.println(); 20493 pw.println("Registered ContentProviders:"); 20494 printedSomething = true; 20495 } 20496 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20497 pw.print(" "); pw.println(p.toString()); 20498 } 20499 printedSomething = false; 20500 for (Map.Entry<String, PackageParser.Provider> entry : 20501 mProvidersByAuthority.entrySet()) { 20502 PackageParser.Provider p = entry.getValue(); 20503 if (packageName != null && !packageName.equals(p.info.packageName)) { 20504 continue; 20505 } 20506 if (!printedSomething) { 20507 if (dumpState.onTitlePrinted()) 20508 pw.println(); 20509 pw.println("ContentProvider Authorities:"); 20510 printedSomething = true; 20511 } 20512 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20513 pw.print(" "); pw.println(p.toString()); 20514 if (p.info != null && p.info.applicationInfo != null) { 20515 final String appInfo = p.info.applicationInfo.toString(); 20516 pw.print(" applicationInfo="); pw.println(appInfo); 20517 } 20518 } 20519 } 20520 20521 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20522 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20523 } 20524 20525 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20526 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20527 } 20528 20529 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20530 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20531 } 20532 20533 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20534 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20535 } 20536 20537 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20538 // XXX should handle packageName != null by dumping only install data that 20539 // the given package is involved with. 20540 if (dumpState.onTitlePrinted()) pw.println(); 20541 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20542 } 20543 20544 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20545 // XXX should handle packageName != null by dumping only install data that 20546 // the given package is involved with. 20547 if (dumpState.onTitlePrinted()) pw.println(); 20548 20549 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20550 ipw.println(); 20551 ipw.println("Frozen packages:"); 20552 ipw.increaseIndent(); 20553 if (mFrozenPackages.size() == 0) { 20554 ipw.println("(none)"); 20555 } else { 20556 for (int i = 0; i < mFrozenPackages.size(); i++) { 20557 ipw.println(mFrozenPackages.valueAt(i)); 20558 } 20559 } 20560 ipw.decreaseIndent(); 20561 } 20562 20563 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20564 if (dumpState.onTitlePrinted()) pw.println(); 20565 dumpDexoptStateLPr(pw, packageName); 20566 } 20567 20568 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20569 if (dumpState.onTitlePrinted()) pw.println(); 20570 dumpCompilerStatsLPr(pw, packageName); 20571 } 20572 20573 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20574 if (dumpState.onTitlePrinted()) pw.println(); 20575 mSettings.dumpReadMessagesLPr(pw, dumpState); 20576 20577 pw.println(); 20578 pw.println("Package warning messages:"); 20579 BufferedReader in = null; 20580 String line = null; 20581 try { 20582 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20583 while ((line = in.readLine()) != null) { 20584 if (line.contains("ignored: updated version")) continue; 20585 pw.println(line); 20586 } 20587 } catch (IOException ignored) { 20588 } finally { 20589 IoUtils.closeQuietly(in); 20590 } 20591 } 20592 20593 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20594 BufferedReader in = null; 20595 String line = null; 20596 try { 20597 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20598 while ((line = in.readLine()) != null) { 20599 if (line.contains("ignored: updated version")) continue; 20600 pw.print("msg,"); 20601 pw.println(line); 20602 } 20603 } catch (IOException ignored) { 20604 } finally { 20605 IoUtils.closeQuietly(in); 20606 } 20607 } 20608 } 20609 } 20610 20611 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20612 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20613 ipw.println(); 20614 ipw.println("Dexopt state:"); 20615 ipw.increaseIndent(); 20616 Collection<PackageParser.Package> packages = null; 20617 if (packageName != null) { 20618 PackageParser.Package targetPackage = mPackages.get(packageName); 20619 if (targetPackage != null) { 20620 packages = Collections.singletonList(targetPackage); 20621 } else { 20622 ipw.println("Unable to find package: " + packageName); 20623 return; 20624 } 20625 } else { 20626 packages = mPackages.values(); 20627 } 20628 20629 for (PackageParser.Package pkg : packages) { 20630 ipw.println("[" + pkg.packageName + "]"); 20631 ipw.increaseIndent(); 20632 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20633 ipw.decreaseIndent(); 20634 } 20635 } 20636 20637 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20638 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20639 ipw.println(); 20640 ipw.println("Compiler stats:"); 20641 ipw.increaseIndent(); 20642 Collection<PackageParser.Package> packages = null; 20643 if (packageName != null) { 20644 PackageParser.Package targetPackage = mPackages.get(packageName); 20645 if (targetPackage != null) { 20646 packages = Collections.singletonList(targetPackage); 20647 } else { 20648 ipw.println("Unable to find package: " + packageName); 20649 return; 20650 } 20651 } else { 20652 packages = mPackages.values(); 20653 } 20654 20655 for (PackageParser.Package pkg : packages) { 20656 ipw.println("[" + pkg.packageName + "]"); 20657 ipw.increaseIndent(); 20658 20659 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20660 if (stats == null) { 20661 ipw.println("(No recorded stats)"); 20662 } else { 20663 stats.dump(ipw); 20664 } 20665 ipw.decreaseIndent(); 20666 } 20667 } 20668 20669 private String dumpDomainString(String packageName) { 20670 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20671 .getList(); 20672 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20673 20674 ArraySet<String> result = new ArraySet<>(); 20675 if (iviList.size() > 0) { 20676 for (IntentFilterVerificationInfo ivi : iviList) { 20677 for (String host : ivi.getDomains()) { 20678 result.add(host); 20679 } 20680 } 20681 } 20682 if (filters != null && filters.size() > 0) { 20683 for (IntentFilter filter : filters) { 20684 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20685 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20686 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20687 result.addAll(filter.getHostsList()); 20688 } 20689 } 20690 } 20691 20692 StringBuilder sb = new StringBuilder(result.size() * 16); 20693 for (String domain : result) { 20694 if (sb.length() > 0) sb.append(" "); 20695 sb.append(domain); 20696 } 20697 return sb.toString(); 20698 } 20699 20700 // ------- apps on sdcard specific code ------- 20701 static final boolean DEBUG_SD_INSTALL = false; 20702 20703 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20704 20705 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20706 20707 private boolean mMediaMounted = false; 20708 20709 static String getEncryptKey() { 20710 try { 20711 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20712 SD_ENCRYPTION_KEYSTORE_NAME); 20713 if (sdEncKey == null) { 20714 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20715 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20716 if (sdEncKey == null) { 20717 Slog.e(TAG, "Failed to create encryption keys"); 20718 return null; 20719 } 20720 } 20721 return sdEncKey; 20722 } catch (NoSuchAlgorithmException nsae) { 20723 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20724 return null; 20725 } catch (IOException ioe) { 20726 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20727 return null; 20728 } 20729 } 20730 20731 /* 20732 * Update media status on PackageManager. 20733 */ 20734 @Override 20735 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20736 int callingUid = Binder.getCallingUid(); 20737 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20738 throw new SecurityException("Media status can only be updated by the system"); 20739 } 20740 // reader; this apparently protects mMediaMounted, but should probably 20741 // be a different lock in that case. 20742 synchronized (mPackages) { 20743 Log.i(TAG, "Updating external media status from " 20744 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20745 + (mediaStatus ? "mounted" : "unmounted")); 20746 if (DEBUG_SD_INSTALL) 20747 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20748 + ", mMediaMounted=" + mMediaMounted); 20749 if (mediaStatus == mMediaMounted) { 20750 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20751 : 0, -1); 20752 mHandler.sendMessage(msg); 20753 return; 20754 } 20755 mMediaMounted = mediaStatus; 20756 } 20757 // Queue up an async operation since the package installation may take a 20758 // little while. 20759 mHandler.post(new Runnable() { 20760 public void run() { 20761 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 20762 } 20763 }); 20764 } 20765 20766 /** 20767 * Called by StorageManagerService when the initial ASECs to scan are available. 20768 * Should block until all the ASEC containers are finished being scanned. 20769 */ 20770 public void scanAvailableAsecs() { 20771 updateExternalMediaStatusInner(true, false, false); 20772 } 20773 20774 /* 20775 * Collect information of applications on external media, map them against 20776 * existing containers and update information based on current mount status. 20777 * Please note that we always have to report status if reportStatus has been 20778 * set to true especially when unloading packages. 20779 */ 20780 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 20781 boolean externalStorage) { 20782 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 20783 int[] uidArr = EmptyArray.INT; 20784 20785 final String[] list = PackageHelper.getSecureContainerList(); 20786 if (ArrayUtils.isEmpty(list)) { 20787 Log.i(TAG, "No secure containers found"); 20788 } else { 20789 // Process list of secure containers and categorize them 20790 // as active or stale based on their package internal state. 20791 20792 // reader 20793 synchronized (mPackages) { 20794 for (String cid : list) { 20795 // Leave stages untouched for now; installer service owns them 20796 if (PackageInstallerService.isStageName(cid)) continue; 20797 20798 if (DEBUG_SD_INSTALL) 20799 Log.i(TAG, "Processing container " + cid); 20800 String pkgName = getAsecPackageName(cid); 20801 if (pkgName == null) { 20802 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 20803 continue; 20804 } 20805 if (DEBUG_SD_INSTALL) 20806 Log.i(TAG, "Looking for pkg : " + pkgName); 20807 20808 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20809 if (ps == null) { 20810 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 20811 continue; 20812 } 20813 20814 /* 20815 * Skip packages that are not external if we're unmounting 20816 * external storage. 20817 */ 20818 if (externalStorage && !isMounted && !isExternal(ps)) { 20819 continue; 20820 } 20821 20822 final AsecInstallArgs args = new AsecInstallArgs(cid, 20823 getAppDexInstructionSets(ps), ps.isForwardLocked()); 20824 // The package status is changed only if the code path 20825 // matches between settings and the container id. 20826 if (ps.codePathString != null 20827 && ps.codePathString.startsWith(args.getCodePath())) { 20828 if (DEBUG_SD_INSTALL) { 20829 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 20830 + " at code path: " + ps.codePathString); 20831 } 20832 20833 // We do have a valid package installed on sdcard 20834 processCids.put(args, ps.codePathString); 20835 final int uid = ps.appId; 20836 if (uid != -1) { 20837 uidArr = ArrayUtils.appendInt(uidArr, uid); 20838 } 20839 } else { 20840 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 20841 + ps.codePathString); 20842 } 20843 } 20844 } 20845 20846 Arrays.sort(uidArr); 20847 } 20848 20849 // Process packages with valid entries. 20850 if (isMounted) { 20851 if (DEBUG_SD_INSTALL) 20852 Log.i(TAG, "Loading packages"); 20853 loadMediaPackages(processCids, uidArr, externalStorage); 20854 startCleaningPackages(); 20855 mInstallerService.onSecureContainersAvailable(); 20856 } else { 20857 if (DEBUG_SD_INSTALL) 20858 Log.i(TAG, "Unloading packages"); 20859 unloadMediaPackages(processCids, uidArr, reportStatus); 20860 } 20861 } 20862 20863 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20864 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 20865 final int size = infos.size(); 20866 final String[] packageNames = new String[size]; 20867 final int[] packageUids = new int[size]; 20868 for (int i = 0; i < size; i++) { 20869 final ApplicationInfo info = infos.get(i); 20870 packageNames[i] = info.packageName; 20871 packageUids[i] = info.uid; 20872 } 20873 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 20874 finishedReceiver); 20875 } 20876 20877 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20878 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20879 sendResourcesChangedBroadcast(mediaStatus, replacing, 20880 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 20881 } 20882 20883 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20884 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20885 int size = pkgList.length; 20886 if (size > 0) { 20887 // Send broadcasts here 20888 Bundle extras = new Bundle(); 20889 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 20890 if (uidArr != null) { 20891 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 20892 } 20893 if (replacing) { 20894 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 20895 } 20896 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 20897 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 20898 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 20899 } 20900 } 20901 20902 /* 20903 * Look at potentially valid container ids from processCids If package 20904 * information doesn't match the one on record or package scanning fails, 20905 * the cid is added to list of removeCids. We currently don't delete stale 20906 * containers. 20907 */ 20908 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 20909 boolean externalStorage) { 20910 ArrayList<String> pkgList = new ArrayList<String>(); 20911 Set<AsecInstallArgs> keys = processCids.keySet(); 20912 20913 for (AsecInstallArgs args : keys) { 20914 String codePath = processCids.get(args); 20915 if (DEBUG_SD_INSTALL) 20916 Log.i(TAG, "Loading container : " + args.cid); 20917 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 20918 try { 20919 // Make sure there are no container errors first. 20920 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 20921 Slog.e(TAG, "Failed to mount cid : " + args.cid 20922 + " when installing from sdcard"); 20923 continue; 20924 } 20925 // Check code path here. 20926 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 20927 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 20928 + " does not match one in settings " + codePath); 20929 continue; 20930 } 20931 // Parse package 20932 int parseFlags = mDefParseFlags; 20933 if (args.isExternalAsec()) { 20934 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 20935 } 20936 if (args.isFwdLocked()) { 20937 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 20938 } 20939 20940 synchronized (mInstallLock) { 20941 PackageParser.Package pkg = null; 20942 try { 20943 // Sadly we don't know the package name yet to freeze it 20944 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 20945 SCAN_IGNORE_FROZEN, 0, null); 20946 } catch (PackageManagerException e) { 20947 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 20948 } 20949 // Scan the package 20950 if (pkg != null) { 20951 /* 20952 * TODO why is the lock being held? doPostInstall is 20953 * called in other places without the lock. This needs 20954 * to be straightened out. 20955 */ 20956 // writer 20957 synchronized (mPackages) { 20958 retCode = PackageManager.INSTALL_SUCCEEDED; 20959 pkgList.add(pkg.packageName); 20960 // Post process args 20961 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 20962 pkg.applicationInfo.uid); 20963 } 20964 } else { 20965 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 20966 } 20967 } 20968 20969 } finally { 20970 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 20971 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 20972 } 20973 } 20974 } 20975 // writer 20976 synchronized (mPackages) { 20977 // If the platform SDK has changed since the last time we booted, 20978 // we need to re-grant app permission to catch any new ones that 20979 // appear. This is really a hack, and means that apps can in some 20980 // cases get permissions that the user didn't initially explicitly 20981 // allow... it would be nice to have some better way to handle 20982 // this situation. 20983 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 20984 : mSettings.getInternalVersion(); 20985 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 20986 : StorageManager.UUID_PRIVATE_INTERNAL; 20987 20988 int updateFlags = UPDATE_PERMISSIONS_ALL; 20989 if (ver.sdkVersion != mSdkVersion) { 20990 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20991 + mSdkVersion + "; regranting permissions for external"); 20992 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20993 } 20994 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20995 20996 // Yay, everything is now upgraded 20997 ver.forceCurrent(); 20998 20999 // can downgrade to reader 21000 // Persist settings 21001 mSettings.writeLPr(); 21002 } 21003 // Send a broadcast to let everyone know we are done processing 21004 if (pkgList.size() > 0) { 21005 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21006 } 21007 } 21008 21009 /* 21010 * Utility method to unload a list of specified containers 21011 */ 21012 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21013 // Just unmount all valid containers. 21014 for (AsecInstallArgs arg : cidArgs) { 21015 synchronized (mInstallLock) { 21016 arg.doPostDeleteLI(false); 21017 } 21018 } 21019 } 21020 21021 /* 21022 * Unload packages mounted on external media. This involves deleting package 21023 * data from internal structures, sending broadcasts about disabled packages, 21024 * gc'ing to free up references, unmounting all secure containers 21025 * corresponding to packages on external media, and posting a 21026 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21027 * that we always have to post this message if status has been requested no 21028 * matter what. 21029 */ 21030 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21031 final boolean reportStatus) { 21032 if (DEBUG_SD_INSTALL) 21033 Log.i(TAG, "unloading media packages"); 21034 ArrayList<String> pkgList = new ArrayList<String>(); 21035 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21036 final Set<AsecInstallArgs> keys = processCids.keySet(); 21037 for (AsecInstallArgs args : keys) { 21038 String pkgName = args.getPackageName(); 21039 if (DEBUG_SD_INSTALL) 21040 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21041 // Delete package internally 21042 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21043 synchronized (mInstallLock) { 21044 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21045 final boolean res; 21046 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21047 "unloadMediaPackages")) { 21048 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21049 null); 21050 } 21051 if (res) { 21052 pkgList.add(pkgName); 21053 } else { 21054 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21055 failedList.add(args); 21056 } 21057 } 21058 } 21059 21060 // reader 21061 synchronized (mPackages) { 21062 // We didn't update the settings after removing each package; 21063 // write them now for all packages. 21064 mSettings.writeLPr(); 21065 } 21066 21067 // We have to absolutely send UPDATED_MEDIA_STATUS only 21068 // after confirming that all the receivers processed the ordered 21069 // broadcast when packages get disabled, force a gc to clean things up. 21070 // and unload all the containers. 21071 if (pkgList.size() > 0) { 21072 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21073 new IIntentReceiver.Stub() { 21074 public void performReceive(Intent intent, int resultCode, String data, 21075 Bundle extras, boolean ordered, boolean sticky, 21076 int sendingUser) throws RemoteException { 21077 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21078 reportStatus ? 1 : 0, 1, keys); 21079 mHandler.sendMessage(msg); 21080 } 21081 }); 21082 } else { 21083 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21084 keys); 21085 mHandler.sendMessage(msg); 21086 } 21087 } 21088 21089 private void loadPrivatePackages(final VolumeInfo vol) { 21090 mHandler.post(new Runnable() { 21091 @Override 21092 public void run() { 21093 loadPrivatePackagesInner(vol); 21094 } 21095 }); 21096 } 21097 21098 private void loadPrivatePackagesInner(VolumeInfo vol) { 21099 final String volumeUuid = vol.fsUuid; 21100 if (TextUtils.isEmpty(volumeUuid)) { 21101 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21102 return; 21103 } 21104 21105 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21106 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21107 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21108 21109 final VersionInfo ver; 21110 final List<PackageSetting> packages; 21111 synchronized (mPackages) { 21112 ver = mSettings.findOrCreateVersion(volumeUuid); 21113 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21114 } 21115 21116 for (PackageSetting ps : packages) { 21117 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21118 synchronized (mInstallLock) { 21119 final PackageParser.Package pkg; 21120 try { 21121 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21122 loaded.add(pkg.applicationInfo); 21123 21124 } catch (PackageManagerException e) { 21125 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21126 } 21127 21128 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21129 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21130 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21131 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21132 } 21133 } 21134 } 21135 21136 // Reconcile app data for all started/unlocked users 21137 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21138 final UserManager um = mContext.getSystemService(UserManager.class); 21139 UserManagerInternal umInternal = getUserManagerInternal(); 21140 for (UserInfo user : um.getUsers()) { 21141 final int flags; 21142 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21143 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21144 } else if (umInternal.isUserRunning(user.id)) { 21145 flags = StorageManager.FLAG_STORAGE_DE; 21146 } else { 21147 continue; 21148 } 21149 21150 try { 21151 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21152 synchronized (mInstallLock) { 21153 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21154 } 21155 } catch (IllegalStateException e) { 21156 // Device was probably ejected, and we'll process that event momentarily 21157 Slog.w(TAG, "Failed to prepare storage: " + e); 21158 } 21159 } 21160 21161 synchronized (mPackages) { 21162 int updateFlags = UPDATE_PERMISSIONS_ALL; 21163 if (ver.sdkVersion != mSdkVersion) { 21164 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21165 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21166 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21167 } 21168 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21169 21170 // Yay, everything is now upgraded 21171 ver.forceCurrent(); 21172 21173 mSettings.writeLPr(); 21174 } 21175 21176 for (PackageFreezer freezer : freezers) { 21177 freezer.close(); 21178 } 21179 21180 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21181 sendResourcesChangedBroadcast(true, false, loaded, null); 21182 } 21183 21184 private void unloadPrivatePackages(final VolumeInfo vol) { 21185 mHandler.post(new Runnable() { 21186 @Override 21187 public void run() { 21188 unloadPrivatePackagesInner(vol); 21189 } 21190 }); 21191 } 21192 21193 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21194 final String volumeUuid = vol.fsUuid; 21195 if (TextUtils.isEmpty(volumeUuid)) { 21196 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21197 return; 21198 } 21199 21200 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21201 synchronized (mInstallLock) { 21202 synchronized (mPackages) { 21203 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21204 for (PackageSetting ps : packages) { 21205 if (ps.pkg == null) continue; 21206 21207 final ApplicationInfo info = ps.pkg.applicationInfo; 21208 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21209 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21210 21211 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21212 "unloadPrivatePackagesInner")) { 21213 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21214 false, null)) { 21215 unloaded.add(info); 21216 } else { 21217 Slog.w(TAG, "Failed to unload " + ps.codePath); 21218 } 21219 } 21220 21221 // Try very hard to release any references to this package 21222 // so we don't risk the system server being killed due to 21223 // open FDs 21224 AttributeCache.instance().removePackage(ps.name); 21225 } 21226 21227 mSettings.writeLPr(); 21228 } 21229 } 21230 21231 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21232 sendResourcesChangedBroadcast(false, false, unloaded, null); 21233 21234 // Try very hard to release any references to this path so we don't risk 21235 // the system server being killed due to open FDs 21236 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21237 21238 for (int i = 0; i < 3; i++) { 21239 System.gc(); 21240 System.runFinalization(); 21241 } 21242 } 21243 21244 /** 21245 * Prepare storage areas for given user on all mounted devices. 21246 */ 21247 void prepareUserData(int userId, int userSerial, int flags) { 21248 synchronized (mInstallLock) { 21249 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21250 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21251 final String volumeUuid = vol.getFsUuid(); 21252 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 21253 } 21254 } 21255 } 21256 21257 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 21258 boolean allowRecover) { 21259 // Prepare storage and verify that serial numbers are consistent; if 21260 // there's a mismatch we need to destroy to avoid leaking data 21261 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21262 try { 21263 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 21264 21265 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 21266 UserManagerService.enforceSerialNumber( 21267 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 21268 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 21269 UserManagerService.enforceSerialNumber( 21270 Environment.getDataSystemDeDirectory(userId), userSerial); 21271 } 21272 } 21273 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 21274 UserManagerService.enforceSerialNumber( 21275 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 21276 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 21277 UserManagerService.enforceSerialNumber( 21278 Environment.getDataSystemCeDirectory(userId), userSerial); 21279 } 21280 } 21281 21282 synchronized (mInstallLock) { 21283 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 21284 } 21285 } catch (Exception e) { 21286 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 21287 + " because we failed to prepare: " + e); 21288 destroyUserDataLI(volumeUuid, userId, 21289 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 21290 21291 if (allowRecover) { 21292 // Try one last time; if we fail again we're really in trouble 21293 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 21294 } 21295 } 21296 } 21297 21298 /** 21299 * Destroy storage areas for given user on all mounted devices. 21300 */ 21301 void destroyUserData(int userId, int flags) { 21302 synchronized (mInstallLock) { 21303 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21304 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21305 final String volumeUuid = vol.getFsUuid(); 21306 destroyUserDataLI(volumeUuid, userId, flags); 21307 } 21308 } 21309 } 21310 21311 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 21312 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21313 try { 21314 // Clean up app data, profile data, and media data 21315 mInstaller.destroyUserData(volumeUuid, userId, flags); 21316 21317 // Clean up system data 21318 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 21319 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21320 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 21321 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 21322 } 21323 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21324 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 21325 } 21326 } 21327 21328 // Data with special labels is now gone, so finish the job 21329 storage.destroyUserStorage(volumeUuid, userId, flags); 21330 21331 } catch (Exception e) { 21332 logCriticalInfo(Log.WARN, 21333 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 21334 } 21335 } 21336 21337 /** 21338 * Examine all users present on given mounted volume, and destroy data 21339 * belonging to users that are no longer valid, or whose user ID has been 21340 * recycled. 21341 */ 21342 private void reconcileUsers(String volumeUuid) { 21343 final List<File> files = new ArrayList<>(); 21344 Collections.addAll(files, FileUtils 21345 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 21346 Collections.addAll(files, FileUtils 21347 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 21348 Collections.addAll(files, FileUtils 21349 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 21350 Collections.addAll(files, FileUtils 21351 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 21352 for (File file : files) { 21353 if (!file.isDirectory()) continue; 21354 21355 final int userId; 21356 final UserInfo info; 21357 try { 21358 userId = Integer.parseInt(file.getName()); 21359 info = sUserManager.getUserInfo(userId); 21360 } catch (NumberFormatException e) { 21361 Slog.w(TAG, "Invalid user directory " + file); 21362 continue; 21363 } 21364 21365 boolean destroyUser = false; 21366 if (info == null) { 21367 logCriticalInfo(Log.WARN, "Destroying user directory " + file 21368 + " because no matching user was found"); 21369 destroyUser = true; 21370 } else if (!mOnlyCore) { 21371 try { 21372 UserManagerService.enforceSerialNumber(file, info.serialNumber); 21373 } catch (IOException e) { 21374 logCriticalInfo(Log.WARN, "Destroying user directory " + file 21375 + " because we failed to enforce serial number: " + e); 21376 destroyUser = true; 21377 } 21378 } 21379 21380 if (destroyUser) { 21381 synchronized (mInstallLock) { 21382 destroyUserDataLI(volumeUuid, userId, 21383 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 21384 } 21385 } 21386 } 21387 } 21388 21389 private void assertPackageKnown(String volumeUuid, String packageName) 21390 throws PackageManagerException { 21391 synchronized (mPackages) { 21392 // Normalize package name to handle renamed packages 21393 packageName = normalizePackageNameLPr(packageName); 21394 21395 final PackageSetting ps = mSettings.mPackages.get(packageName); 21396 if (ps == null) { 21397 throw new PackageManagerException("Package " + packageName + " is unknown"); 21398 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21399 throw new PackageManagerException( 21400 "Package " + packageName + " found on unknown volume " + volumeUuid 21401 + "; expected volume " + ps.volumeUuid); 21402 } 21403 } 21404 } 21405 21406 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21407 throws PackageManagerException { 21408 synchronized (mPackages) { 21409 // Normalize package name to handle renamed packages 21410 packageName = normalizePackageNameLPr(packageName); 21411 21412 final PackageSetting ps = mSettings.mPackages.get(packageName); 21413 if (ps == null) { 21414 throw new PackageManagerException("Package " + packageName + " is unknown"); 21415 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21416 throw new PackageManagerException( 21417 "Package " + packageName + " found on unknown volume " + volumeUuid 21418 + "; expected volume " + ps.volumeUuid); 21419 } else if (!ps.getInstalled(userId)) { 21420 throw new PackageManagerException( 21421 "Package " + packageName + " not installed for user " + userId); 21422 } 21423 } 21424 } 21425 21426 private List<String> collectAbsoluteCodePaths() { 21427 synchronized (mPackages) { 21428 List<String> codePaths = new ArrayList<>(); 21429 final int packageCount = mSettings.mPackages.size(); 21430 for (int i = 0; i < packageCount; i++) { 21431 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21432 codePaths.add(ps.codePath.getAbsolutePath()); 21433 } 21434 return codePaths; 21435 } 21436 } 21437 21438 /** 21439 * Examine all apps present on given mounted volume, and destroy apps that 21440 * aren't expected, either due to uninstallation or reinstallation on 21441 * another volume. 21442 */ 21443 private void reconcileApps(String volumeUuid) { 21444 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21445 List<File> filesToDelete = null; 21446 21447 final File[] files = FileUtils.listFilesOrEmpty( 21448 Environment.getDataAppDirectory(volumeUuid)); 21449 for (File file : files) { 21450 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21451 && !PackageInstallerService.isStageName(file.getName()); 21452 if (!isPackage) { 21453 // Ignore entries which are not packages 21454 continue; 21455 } 21456 21457 String absolutePath = file.getAbsolutePath(); 21458 21459 boolean pathValid = false; 21460 final int absoluteCodePathCount = absoluteCodePaths.size(); 21461 for (int i = 0; i < absoluteCodePathCount; i++) { 21462 String absoluteCodePath = absoluteCodePaths.get(i); 21463 if (absolutePath.startsWith(absoluteCodePath)) { 21464 pathValid = true; 21465 break; 21466 } 21467 } 21468 21469 if (!pathValid) { 21470 if (filesToDelete == null) { 21471 filesToDelete = new ArrayList<>(); 21472 } 21473 filesToDelete.add(file); 21474 } 21475 } 21476 21477 if (filesToDelete != null) { 21478 final int fileToDeleteCount = filesToDelete.size(); 21479 for (int i = 0; i < fileToDeleteCount; i++) { 21480 File fileToDelete = filesToDelete.get(i); 21481 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21482 synchronized (mInstallLock) { 21483 removeCodePathLI(fileToDelete); 21484 } 21485 } 21486 } 21487 } 21488 21489 /** 21490 * Reconcile all app data for the given user. 21491 * <p> 21492 * Verifies that directories exist and that ownership and labeling is 21493 * correct for all installed apps on all mounted volumes. 21494 */ 21495 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21496 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21497 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21498 final String volumeUuid = vol.getFsUuid(); 21499 synchronized (mInstallLock) { 21500 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21501 } 21502 } 21503 } 21504 21505 /** 21506 * Reconcile all app data on given mounted volume. 21507 * <p> 21508 * Destroys app data that isn't expected, either due to uninstallation or 21509 * reinstallation on another volume. 21510 * <p> 21511 * Verifies that directories exist and that ownership and labeling is 21512 * correct for all installed apps. 21513 */ 21514 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21515 boolean migrateAppData) { 21516 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21517 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21518 21519 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21520 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21521 21522 // First look for stale data that doesn't belong, and check if things 21523 // have changed since we did our last restorecon 21524 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21525 if (StorageManager.isFileEncryptedNativeOrEmulated() 21526 && !StorageManager.isUserKeyUnlocked(userId)) { 21527 throw new RuntimeException( 21528 "Yikes, someone asked us to reconcile CE storage while " + userId 21529 + " was still locked; this would have caused massive data loss!"); 21530 } 21531 21532 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21533 for (File file : files) { 21534 final String packageName = file.getName(); 21535 try { 21536 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21537 } catch (PackageManagerException e) { 21538 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21539 try { 21540 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21541 StorageManager.FLAG_STORAGE_CE, 0); 21542 } catch (InstallerException e2) { 21543 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21544 } 21545 } 21546 } 21547 } 21548 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21549 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21550 for (File file : files) { 21551 final String packageName = file.getName(); 21552 try { 21553 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21554 } catch (PackageManagerException e) { 21555 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21556 try { 21557 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21558 StorageManager.FLAG_STORAGE_DE, 0); 21559 } catch (InstallerException e2) { 21560 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21561 } 21562 } 21563 } 21564 } 21565 21566 // Ensure that data directories are ready to roll for all packages 21567 // installed for this volume and user 21568 final List<PackageSetting> packages; 21569 synchronized (mPackages) { 21570 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21571 } 21572 int preparedCount = 0; 21573 for (PackageSetting ps : packages) { 21574 final String packageName = ps.name; 21575 if (ps.pkg == null) { 21576 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21577 // TODO: might be due to legacy ASEC apps; we should circle back 21578 // and reconcile again once they're scanned 21579 continue; 21580 } 21581 21582 if (ps.getInstalled(userId)) { 21583 prepareAppDataLIF(ps.pkg, userId, flags); 21584 21585 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 21586 // We may have just shuffled around app data directories, so 21587 // prepare them one more time 21588 prepareAppDataLIF(ps.pkg, userId, flags); 21589 } 21590 21591 preparedCount++; 21592 } 21593 } 21594 21595 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21596 } 21597 21598 /** 21599 * Prepare app data for the given app just after it was installed or 21600 * upgraded. This method carefully only touches users that it's installed 21601 * for, and it forces a restorecon to handle any seinfo changes. 21602 * <p> 21603 * Verifies that directories exist and that ownership and labeling is 21604 * correct for all installed apps. If there is an ownership mismatch, it 21605 * will try recovering system apps by wiping data; third-party app data is 21606 * left intact. 21607 * <p> 21608 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21609 */ 21610 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21611 final PackageSetting ps; 21612 synchronized (mPackages) { 21613 ps = mSettings.mPackages.get(pkg.packageName); 21614 mSettings.writeKernelMappingLPr(ps); 21615 } 21616 21617 final UserManager um = mContext.getSystemService(UserManager.class); 21618 UserManagerInternal umInternal = getUserManagerInternal(); 21619 for (UserInfo user : um.getUsers()) { 21620 final int flags; 21621 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21622 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21623 } else if (umInternal.isUserRunning(user.id)) { 21624 flags = StorageManager.FLAG_STORAGE_DE; 21625 } else { 21626 continue; 21627 } 21628 21629 if (ps.getInstalled(user.id)) { 21630 // TODO: when user data is locked, mark that we're still dirty 21631 prepareAppDataLIF(pkg, user.id, flags); 21632 } 21633 } 21634 } 21635 21636 /** 21637 * Prepare app data for the given app. 21638 * <p> 21639 * Verifies that directories exist and that ownership and labeling is 21640 * correct for all installed apps. If there is an ownership mismatch, this 21641 * will try recovering system apps by wiping data; third-party app data is 21642 * left intact. 21643 */ 21644 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21645 if (pkg == null) { 21646 Slog.wtf(TAG, "Package was null!", new Throwable()); 21647 return; 21648 } 21649 prepareAppDataLeafLIF(pkg, userId, flags); 21650 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21651 for (int i = 0; i < childCount; i++) { 21652 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21653 } 21654 } 21655 21656 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21657 if (DEBUG_APP_DATA) { 21658 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21659 + Integer.toHexString(flags)); 21660 } 21661 21662 final String volumeUuid = pkg.volumeUuid; 21663 final String packageName = pkg.packageName; 21664 final ApplicationInfo app = pkg.applicationInfo; 21665 final int appId = UserHandle.getAppId(app.uid); 21666 21667 Preconditions.checkNotNull(app.seinfo); 21668 21669 long ceDataInode = -1; 21670 try { 21671 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21672 appId, app.seinfo, app.targetSdkVersion); 21673 } catch (InstallerException e) { 21674 if (app.isSystemApp()) { 21675 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21676 + ", but trying to recover: " + e); 21677 destroyAppDataLeafLIF(pkg, userId, flags); 21678 try { 21679 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21680 appId, app.seinfo, app.targetSdkVersion); 21681 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21682 } catch (InstallerException e2) { 21683 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21684 } 21685 } else { 21686 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21687 } 21688 } 21689 21690 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21691 // TODO: mark this structure as dirty so we persist it! 21692 synchronized (mPackages) { 21693 final PackageSetting ps = mSettings.mPackages.get(packageName); 21694 if (ps != null) { 21695 ps.setCeDataInode(ceDataInode, userId); 21696 } 21697 } 21698 } 21699 21700 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21701 } 21702 21703 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21704 if (pkg == null) { 21705 Slog.wtf(TAG, "Package was null!", new Throwable()); 21706 return; 21707 } 21708 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21709 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21710 for (int i = 0; i < childCount; i++) { 21711 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21712 } 21713 } 21714 21715 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21716 final String volumeUuid = pkg.volumeUuid; 21717 final String packageName = pkg.packageName; 21718 final ApplicationInfo app = pkg.applicationInfo; 21719 21720 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21721 // Create a native library symlink only if we have native libraries 21722 // and if the native libraries are 32 bit libraries. We do not provide 21723 // this symlink for 64 bit libraries. 21724 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21725 final String nativeLibPath = app.nativeLibraryDir; 21726 try { 21727 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21728 nativeLibPath, userId); 21729 } catch (InstallerException e) { 21730 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21731 } 21732 } 21733 } 21734 } 21735 21736 /** 21737 * For system apps on non-FBE devices, this method migrates any existing 21738 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21739 * requested by the app. 21740 */ 21741 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21742 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21743 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21744 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21745 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21746 try { 21747 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21748 storageTarget); 21749 } catch (InstallerException e) { 21750 logCriticalInfo(Log.WARN, 21751 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21752 } 21753 return true; 21754 } else { 21755 return false; 21756 } 21757 } 21758 21759 public PackageFreezer freezePackage(String packageName, String killReason) { 21760 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21761 } 21762 21763 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21764 return new PackageFreezer(packageName, userId, killReason); 21765 } 21766 21767 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21768 String killReason) { 21769 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21770 } 21771 21772 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21773 String killReason) { 21774 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21775 return new PackageFreezer(); 21776 } else { 21777 return freezePackage(packageName, userId, killReason); 21778 } 21779 } 21780 21781 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21782 String killReason) { 21783 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21784 } 21785 21786 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21787 String killReason) { 21788 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21789 return new PackageFreezer(); 21790 } else { 21791 return freezePackage(packageName, userId, killReason); 21792 } 21793 } 21794 21795 /** 21796 * Class that freezes and kills the given package upon creation, and 21797 * unfreezes it upon closing. This is typically used when doing surgery on 21798 * app code/data to prevent the app from running while you're working. 21799 */ 21800 private class PackageFreezer implements AutoCloseable { 21801 private final String mPackageName; 21802 private final PackageFreezer[] mChildren; 21803 21804 private final boolean mWeFroze; 21805 21806 private final AtomicBoolean mClosed = new AtomicBoolean(); 21807 private final CloseGuard mCloseGuard = CloseGuard.get(); 21808 21809 /** 21810 * Create and return a stub freezer that doesn't actually do anything, 21811 * typically used when someone requested 21812 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21813 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21814 */ 21815 public PackageFreezer() { 21816 mPackageName = null; 21817 mChildren = null; 21818 mWeFroze = false; 21819 mCloseGuard.open("close"); 21820 } 21821 21822 public PackageFreezer(String packageName, int userId, String killReason) { 21823 synchronized (mPackages) { 21824 mPackageName = packageName; 21825 mWeFroze = mFrozenPackages.add(mPackageName); 21826 21827 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21828 if (ps != null) { 21829 killApplication(ps.name, ps.appId, userId, killReason); 21830 } 21831 21832 final PackageParser.Package p = mPackages.get(packageName); 21833 if (p != null && p.childPackages != null) { 21834 final int N = p.childPackages.size(); 21835 mChildren = new PackageFreezer[N]; 21836 for (int i = 0; i < N; i++) { 21837 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21838 userId, killReason); 21839 } 21840 } else { 21841 mChildren = null; 21842 } 21843 } 21844 mCloseGuard.open("close"); 21845 } 21846 21847 @Override 21848 protected void finalize() throws Throwable { 21849 try { 21850 mCloseGuard.warnIfOpen(); 21851 close(); 21852 } finally { 21853 super.finalize(); 21854 } 21855 } 21856 21857 @Override 21858 public void close() { 21859 mCloseGuard.close(); 21860 if (mClosed.compareAndSet(false, true)) { 21861 synchronized (mPackages) { 21862 if (mWeFroze) { 21863 mFrozenPackages.remove(mPackageName); 21864 } 21865 21866 if (mChildren != null) { 21867 for (PackageFreezer freezer : mChildren) { 21868 freezer.close(); 21869 } 21870 } 21871 } 21872 } 21873 } 21874 } 21875 21876 /** 21877 * Verify that given package is currently frozen. 21878 */ 21879 private void checkPackageFrozen(String packageName) { 21880 synchronized (mPackages) { 21881 if (!mFrozenPackages.contains(packageName)) { 21882 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21883 } 21884 } 21885 } 21886 21887 @Override 21888 public int movePackage(final String packageName, final String volumeUuid) { 21889 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21890 21891 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21892 final int moveId = mNextMoveId.getAndIncrement(); 21893 mHandler.post(new Runnable() { 21894 @Override 21895 public void run() { 21896 try { 21897 movePackageInternal(packageName, volumeUuid, moveId, user); 21898 } catch (PackageManagerException e) { 21899 Slog.w(TAG, "Failed to move " + packageName, e); 21900 mMoveCallbacks.notifyStatusChanged(moveId, 21901 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21902 } 21903 } 21904 }); 21905 return moveId; 21906 } 21907 21908 private void movePackageInternal(final String packageName, final String volumeUuid, 21909 final int moveId, UserHandle user) throws PackageManagerException { 21910 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21911 final PackageManager pm = mContext.getPackageManager(); 21912 21913 final boolean currentAsec; 21914 final String currentVolumeUuid; 21915 final File codeFile; 21916 final String installerPackageName; 21917 final String packageAbiOverride; 21918 final int appId; 21919 final String seinfo; 21920 final String label; 21921 final int targetSdkVersion; 21922 final PackageFreezer freezer; 21923 final int[] installedUserIds; 21924 21925 // reader 21926 synchronized (mPackages) { 21927 final PackageParser.Package pkg = mPackages.get(packageName); 21928 final PackageSetting ps = mSettings.mPackages.get(packageName); 21929 if (pkg == null || ps == null) { 21930 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21931 } 21932 21933 if (pkg.applicationInfo.isSystemApp()) { 21934 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 21935 "Cannot move system application"); 21936 } 21937 21938 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 21939 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 21940 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 21941 if (isInternalStorage && !allow3rdPartyOnInternal) { 21942 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 21943 "3rd party apps are not allowed on internal storage"); 21944 } 21945 21946 if (pkg.applicationInfo.isExternalAsec()) { 21947 currentAsec = true; 21948 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 21949 } else if (pkg.applicationInfo.isForwardLocked()) { 21950 currentAsec = true; 21951 currentVolumeUuid = "forward_locked"; 21952 } else { 21953 currentAsec = false; 21954 currentVolumeUuid = ps.volumeUuid; 21955 21956 final File probe = new File(pkg.codePath); 21957 final File probeOat = new File(probe, "oat"); 21958 if (!probe.isDirectory() || !probeOat.isDirectory()) { 21959 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21960 "Move only supported for modern cluster style installs"); 21961 } 21962 } 21963 21964 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 21965 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21966 "Package already moved to " + volumeUuid); 21967 } 21968 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 21969 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 21970 "Device admin cannot be moved"); 21971 } 21972 21973 if (mFrozenPackages.contains(packageName)) { 21974 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 21975 "Failed to move already frozen package"); 21976 } 21977 21978 codeFile = new File(pkg.codePath); 21979 installerPackageName = ps.installerPackageName; 21980 packageAbiOverride = ps.cpuAbiOverrideString; 21981 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 21982 seinfo = pkg.applicationInfo.seinfo; 21983 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 21984 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 21985 freezer = freezePackage(packageName, "movePackageInternal"); 21986 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 21987 } 21988 21989 final Bundle extras = new Bundle(); 21990 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 21991 extras.putString(Intent.EXTRA_TITLE, label); 21992 mMoveCallbacks.notifyCreated(moveId, extras); 21993 21994 int installFlags; 21995 final boolean moveCompleteApp; 21996 final File measurePath; 21997 21998 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 21999 installFlags = INSTALL_INTERNAL; 22000 moveCompleteApp = !currentAsec; 22001 measurePath = Environment.getDataAppDirectory(volumeUuid); 22002 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22003 installFlags = INSTALL_EXTERNAL; 22004 moveCompleteApp = false; 22005 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22006 } else { 22007 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22008 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22009 || !volume.isMountedWritable()) { 22010 freezer.close(); 22011 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22012 "Move location not mounted private volume"); 22013 } 22014 22015 Preconditions.checkState(!currentAsec); 22016 22017 installFlags = INSTALL_INTERNAL; 22018 moveCompleteApp = true; 22019 measurePath = Environment.getDataAppDirectory(volumeUuid); 22020 } 22021 22022 final PackageStats stats = new PackageStats(null, -1); 22023 synchronized (mInstaller) { 22024 for (int userId : installedUserIds) { 22025 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22026 freezer.close(); 22027 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22028 "Failed to measure package size"); 22029 } 22030 } 22031 } 22032 22033 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22034 + stats.dataSize); 22035 22036 final long startFreeBytes = measurePath.getFreeSpace(); 22037 final long sizeBytes; 22038 if (moveCompleteApp) { 22039 sizeBytes = stats.codeSize + stats.dataSize; 22040 } else { 22041 sizeBytes = stats.codeSize; 22042 } 22043 22044 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22045 freezer.close(); 22046 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22047 "Not enough free space to move"); 22048 } 22049 22050 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22051 22052 final CountDownLatch installedLatch = new CountDownLatch(1); 22053 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22054 @Override 22055 public void onUserActionRequired(Intent intent) throws RemoteException { 22056 throw new IllegalStateException(); 22057 } 22058 22059 @Override 22060 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22061 Bundle extras) throws RemoteException { 22062 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22063 + PackageManager.installStatusToString(returnCode, msg)); 22064 22065 installedLatch.countDown(); 22066 freezer.close(); 22067 22068 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22069 switch (status) { 22070 case PackageInstaller.STATUS_SUCCESS: 22071 mMoveCallbacks.notifyStatusChanged(moveId, 22072 PackageManager.MOVE_SUCCEEDED); 22073 break; 22074 case PackageInstaller.STATUS_FAILURE_STORAGE: 22075 mMoveCallbacks.notifyStatusChanged(moveId, 22076 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22077 break; 22078 default: 22079 mMoveCallbacks.notifyStatusChanged(moveId, 22080 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22081 break; 22082 } 22083 } 22084 }; 22085 22086 final MoveInfo move; 22087 if (moveCompleteApp) { 22088 // Kick off a thread to report progress estimates 22089 new Thread() { 22090 @Override 22091 public void run() { 22092 while (true) { 22093 try { 22094 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22095 break; 22096 } 22097 } catch (InterruptedException ignored) { 22098 } 22099 22100 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22101 final int progress = 10 + (int) MathUtils.constrain( 22102 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22103 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22104 } 22105 } 22106 }.start(); 22107 22108 final String dataAppName = codeFile.getName(); 22109 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22110 dataAppName, appId, seinfo, targetSdkVersion); 22111 } else { 22112 move = null; 22113 } 22114 22115 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22116 22117 final Message msg = mHandler.obtainMessage(INIT_COPY); 22118 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22119 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22120 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22121 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22122 PackageManager.INSTALL_REASON_UNKNOWN); 22123 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22124 msg.obj = params; 22125 22126 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22127 System.identityHashCode(msg.obj)); 22128 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22129 System.identityHashCode(msg.obj)); 22130 22131 mHandler.sendMessage(msg); 22132 } 22133 22134 @Override 22135 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22136 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22137 22138 final int realMoveId = mNextMoveId.getAndIncrement(); 22139 final Bundle extras = new Bundle(); 22140 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22141 mMoveCallbacks.notifyCreated(realMoveId, extras); 22142 22143 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22144 @Override 22145 public void onCreated(int moveId, Bundle extras) { 22146 // Ignored 22147 } 22148 22149 @Override 22150 public void onStatusChanged(int moveId, int status, long estMillis) { 22151 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22152 } 22153 }; 22154 22155 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22156 storage.setPrimaryStorageUuid(volumeUuid, callback); 22157 return realMoveId; 22158 } 22159 22160 @Override 22161 public int getMoveStatus(int moveId) { 22162 mContext.enforceCallingOrSelfPermission( 22163 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22164 return mMoveCallbacks.mLastStatus.get(moveId); 22165 } 22166 22167 @Override 22168 public void registerMoveCallback(IPackageMoveObserver callback) { 22169 mContext.enforceCallingOrSelfPermission( 22170 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22171 mMoveCallbacks.register(callback); 22172 } 22173 22174 @Override 22175 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22176 mContext.enforceCallingOrSelfPermission( 22177 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22178 mMoveCallbacks.unregister(callback); 22179 } 22180 22181 @Override 22182 public boolean setInstallLocation(int loc) { 22183 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22184 null); 22185 if (getInstallLocation() == loc) { 22186 return true; 22187 } 22188 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22189 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22190 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22191 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22192 return true; 22193 } 22194 return false; 22195 } 22196 22197 @Override 22198 public int getInstallLocation() { 22199 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22200 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22201 PackageHelper.APP_INSTALL_AUTO); 22202 } 22203 22204 /** Called by UserManagerService */ 22205 void cleanUpUser(UserManagerService userManager, int userHandle) { 22206 synchronized (mPackages) { 22207 mDirtyUsers.remove(userHandle); 22208 mUserNeedsBadging.delete(userHandle); 22209 mSettings.removeUserLPw(userHandle); 22210 mPendingBroadcasts.remove(userHandle); 22211 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 22212 removeUnusedPackagesLPw(userManager, userHandle); 22213 } 22214 } 22215 22216 /** 22217 * We're removing userHandle and would like to remove any downloaded packages 22218 * that are no longer in use by any other user. 22219 * @param userHandle the user being removed 22220 */ 22221 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22222 final boolean DEBUG_CLEAN_APKS = false; 22223 int [] users = userManager.getUserIds(); 22224 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22225 while (psit.hasNext()) { 22226 PackageSetting ps = psit.next(); 22227 if (ps.pkg == null) { 22228 continue; 22229 } 22230 final String packageName = ps.pkg.packageName; 22231 // Skip over if system app 22232 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22233 continue; 22234 } 22235 if (DEBUG_CLEAN_APKS) { 22236 Slog.i(TAG, "Checking package " + packageName); 22237 } 22238 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22239 if (keep) { 22240 if (DEBUG_CLEAN_APKS) { 22241 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22242 } 22243 } else { 22244 for (int i = 0; i < users.length; i++) { 22245 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22246 keep = true; 22247 if (DEBUG_CLEAN_APKS) { 22248 Slog.i(TAG, " Keeping package " + packageName + " for user " 22249 + users[i]); 22250 } 22251 break; 22252 } 22253 } 22254 } 22255 if (!keep) { 22256 if (DEBUG_CLEAN_APKS) { 22257 Slog.i(TAG, " Removing package " + packageName); 22258 } 22259 mHandler.post(new Runnable() { 22260 public void run() { 22261 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22262 userHandle, 0); 22263 } //end run 22264 }); 22265 } 22266 } 22267 } 22268 22269 /** Called by UserManagerService */ 22270 void createNewUser(int userId, String[] disallowedPackages) { 22271 synchronized (mInstallLock) { 22272 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22273 } 22274 synchronized (mPackages) { 22275 scheduleWritePackageRestrictionsLocked(userId); 22276 scheduleWritePackageListLocked(userId); 22277 applyFactoryDefaultBrowserLPw(userId); 22278 primeDomainVerificationsLPw(userId); 22279 } 22280 } 22281 22282 void onNewUserCreated(final int userId) { 22283 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22284 // If permission review for legacy apps is required, we represent 22285 // dagerous permissions for such apps as always granted runtime 22286 // permissions to keep per user flag state whether review is needed. 22287 // Hence, if a new user is added we have to propagate dangerous 22288 // permission grants for these legacy apps. 22289 if (mPermissionReviewRequired) { 22290 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22291 | UPDATE_PERMISSIONS_REPLACE_ALL); 22292 } 22293 } 22294 22295 @Override 22296 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22297 mContext.enforceCallingOrSelfPermission( 22298 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22299 "Only package verification agents can read the verifier device identity"); 22300 22301 synchronized (mPackages) { 22302 return mSettings.getVerifierDeviceIdentityLPw(); 22303 } 22304 } 22305 22306 @Override 22307 public void setPermissionEnforced(String permission, boolean enforced) { 22308 // TODO: Now that we no longer change GID for storage, this should to away. 22309 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22310 "setPermissionEnforced"); 22311 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22312 synchronized (mPackages) { 22313 if (mSettings.mReadExternalStorageEnforced == null 22314 || mSettings.mReadExternalStorageEnforced != enforced) { 22315 mSettings.mReadExternalStorageEnforced = enforced; 22316 mSettings.writeLPr(); 22317 } 22318 } 22319 // kill any non-foreground processes so we restart them and 22320 // grant/revoke the GID. 22321 final IActivityManager am = ActivityManager.getService(); 22322 if (am != null) { 22323 final long token = Binder.clearCallingIdentity(); 22324 try { 22325 am.killProcessesBelowForeground("setPermissionEnforcement"); 22326 } catch (RemoteException e) { 22327 } finally { 22328 Binder.restoreCallingIdentity(token); 22329 } 22330 } 22331 } else { 22332 throw new IllegalArgumentException("No selective enforcement for " + permission); 22333 } 22334 } 22335 22336 @Override 22337 @Deprecated 22338 public boolean isPermissionEnforced(String permission) { 22339 return true; 22340 } 22341 22342 @Override 22343 public boolean isStorageLow() { 22344 final long token = Binder.clearCallingIdentity(); 22345 try { 22346 final DeviceStorageMonitorInternal 22347 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22348 if (dsm != null) { 22349 return dsm.isMemoryLow(); 22350 } else { 22351 return false; 22352 } 22353 } finally { 22354 Binder.restoreCallingIdentity(token); 22355 } 22356 } 22357 22358 @Override 22359 public IPackageInstaller getPackageInstaller() { 22360 return mInstallerService; 22361 } 22362 22363 private boolean userNeedsBadging(int userId) { 22364 int index = mUserNeedsBadging.indexOfKey(userId); 22365 if (index < 0) { 22366 final UserInfo userInfo; 22367 final long token = Binder.clearCallingIdentity(); 22368 try { 22369 userInfo = sUserManager.getUserInfo(userId); 22370 } finally { 22371 Binder.restoreCallingIdentity(token); 22372 } 22373 final boolean b; 22374 if (userInfo != null && userInfo.isManagedProfile()) { 22375 b = true; 22376 } else { 22377 b = false; 22378 } 22379 mUserNeedsBadging.put(userId, b); 22380 return b; 22381 } 22382 return mUserNeedsBadging.valueAt(index); 22383 } 22384 22385 @Override 22386 public KeySet getKeySetByAlias(String packageName, String alias) { 22387 if (packageName == null || alias == null) { 22388 return null; 22389 } 22390 synchronized(mPackages) { 22391 final PackageParser.Package pkg = mPackages.get(packageName); 22392 if (pkg == null) { 22393 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22394 throw new IllegalArgumentException("Unknown package: " + packageName); 22395 } 22396 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22397 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22398 } 22399 } 22400 22401 @Override 22402 public KeySet getSigningKeySet(String packageName) { 22403 if (packageName == null) { 22404 return null; 22405 } 22406 synchronized(mPackages) { 22407 final PackageParser.Package pkg = mPackages.get(packageName); 22408 if (pkg == null) { 22409 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22410 throw new IllegalArgumentException("Unknown package: " + packageName); 22411 } 22412 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22413 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22414 throw new SecurityException("May not access signing KeySet of other apps."); 22415 } 22416 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22417 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22418 } 22419 } 22420 22421 @Override 22422 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22423 if (packageName == null || ks == null) { 22424 return false; 22425 } 22426 synchronized(mPackages) { 22427 final PackageParser.Package pkg = mPackages.get(packageName); 22428 if (pkg == null) { 22429 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22430 throw new IllegalArgumentException("Unknown package: " + packageName); 22431 } 22432 IBinder ksh = ks.getToken(); 22433 if (ksh instanceof KeySetHandle) { 22434 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22435 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22436 } 22437 return false; 22438 } 22439 } 22440 22441 @Override 22442 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22443 if (packageName == null || ks == null) { 22444 return false; 22445 } 22446 synchronized(mPackages) { 22447 final PackageParser.Package pkg = mPackages.get(packageName); 22448 if (pkg == null) { 22449 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22450 throw new IllegalArgumentException("Unknown package: " + packageName); 22451 } 22452 IBinder ksh = ks.getToken(); 22453 if (ksh instanceof KeySetHandle) { 22454 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22455 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22456 } 22457 return false; 22458 } 22459 } 22460 22461 private void deletePackageIfUnusedLPr(final String packageName) { 22462 PackageSetting ps = mSettings.mPackages.get(packageName); 22463 if (ps == null) { 22464 return; 22465 } 22466 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22467 // TODO Implement atomic delete if package is unused 22468 // It is currently possible that the package will be deleted even if it is installed 22469 // after this method returns. 22470 mHandler.post(new Runnable() { 22471 public void run() { 22472 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22473 0, PackageManager.DELETE_ALL_USERS); 22474 } 22475 }); 22476 } 22477 } 22478 22479 /** 22480 * Check and throw if the given before/after packages would be considered a 22481 * downgrade. 22482 */ 22483 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22484 throws PackageManagerException { 22485 if (after.versionCode < before.mVersionCode) { 22486 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22487 "Update version code " + after.versionCode + " is older than current " 22488 + before.mVersionCode); 22489 } else if (after.versionCode == before.mVersionCode) { 22490 if (after.baseRevisionCode < before.baseRevisionCode) { 22491 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22492 "Update base revision code " + after.baseRevisionCode 22493 + " is older than current " + before.baseRevisionCode); 22494 } 22495 22496 if (!ArrayUtils.isEmpty(after.splitNames)) { 22497 for (int i = 0; i < after.splitNames.length; i++) { 22498 final String splitName = after.splitNames[i]; 22499 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22500 if (j != -1) { 22501 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22502 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22503 "Update split " + splitName + " revision code " 22504 + after.splitRevisionCodes[i] + " is older than current " 22505 + before.splitRevisionCodes[j]); 22506 } 22507 } 22508 } 22509 } 22510 } 22511 } 22512 22513 private static class MoveCallbacks extends Handler { 22514 private static final int MSG_CREATED = 1; 22515 private static final int MSG_STATUS_CHANGED = 2; 22516 22517 private final RemoteCallbackList<IPackageMoveObserver> 22518 mCallbacks = new RemoteCallbackList<>(); 22519 22520 private final SparseIntArray mLastStatus = new SparseIntArray(); 22521 22522 public MoveCallbacks(Looper looper) { 22523 super(looper); 22524 } 22525 22526 public void register(IPackageMoveObserver callback) { 22527 mCallbacks.register(callback); 22528 } 22529 22530 public void unregister(IPackageMoveObserver callback) { 22531 mCallbacks.unregister(callback); 22532 } 22533 22534 @Override 22535 public void handleMessage(Message msg) { 22536 final SomeArgs args = (SomeArgs) msg.obj; 22537 final int n = mCallbacks.beginBroadcast(); 22538 for (int i = 0; i < n; i++) { 22539 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22540 try { 22541 invokeCallback(callback, msg.what, args); 22542 } catch (RemoteException ignored) { 22543 } 22544 } 22545 mCallbacks.finishBroadcast(); 22546 args.recycle(); 22547 } 22548 22549 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22550 throws RemoteException { 22551 switch (what) { 22552 case MSG_CREATED: { 22553 callback.onCreated(args.argi1, (Bundle) args.arg2); 22554 break; 22555 } 22556 case MSG_STATUS_CHANGED: { 22557 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22558 break; 22559 } 22560 } 22561 } 22562 22563 private void notifyCreated(int moveId, Bundle extras) { 22564 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22565 22566 final SomeArgs args = SomeArgs.obtain(); 22567 args.argi1 = moveId; 22568 args.arg2 = extras; 22569 obtainMessage(MSG_CREATED, args).sendToTarget(); 22570 } 22571 22572 private void notifyStatusChanged(int moveId, int status) { 22573 notifyStatusChanged(moveId, status, -1); 22574 } 22575 22576 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22577 Slog.v(TAG, "Move " + moveId + " status " + status); 22578 22579 final SomeArgs args = SomeArgs.obtain(); 22580 args.argi1 = moveId; 22581 args.argi2 = status; 22582 args.arg3 = estMillis; 22583 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22584 22585 synchronized (mLastStatus) { 22586 mLastStatus.put(moveId, status); 22587 } 22588 } 22589 } 22590 22591 private final static class OnPermissionChangeListeners extends Handler { 22592 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22593 22594 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22595 new RemoteCallbackList<>(); 22596 22597 public OnPermissionChangeListeners(Looper looper) { 22598 super(looper); 22599 } 22600 22601 @Override 22602 public void handleMessage(Message msg) { 22603 switch (msg.what) { 22604 case MSG_ON_PERMISSIONS_CHANGED: { 22605 final int uid = msg.arg1; 22606 handleOnPermissionsChanged(uid); 22607 } break; 22608 } 22609 } 22610 22611 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22612 mPermissionListeners.register(listener); 22613 22614 } 22615 22616 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22617 mPermissionListeners.unregister(listener); 22618 } 22619 22620 public void onPermissionsChanged(int uid) { 22621 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22622 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22623 } 22624 } 22625 22626 private void handleOnPermissionsChanged(int uid) { 22627 final int count = mPermissionListeners.beginBroadcast(); 22628 try { 22629 for (int i = 0; i < count; i++) { 22630 IOnPermissionsChangeListener callback = mPermissionListeners 22631 .getBroadcastItem(i); 22632 try { 22633 callback.onPermissionsChanged(uid); 22634 } catch (RemoteException e) { 22635 Log.e(TAG, "Permission listener is dead", e); 22636 } 22637 } 22638 } finally { 22639 mPermissionListeners.finishBroadcast(); 22640 } 22641 } 22642 } 22643 22644 private class PackageManagerInternalImpl extends PackageManagerInternal { 22645 @Override 22646 public void setLocationPackagesProvider(PackagesProvider provider) { 22647 synchronized (mPackages) { 22648 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22649 } 22650 } 22651 22652 @Override 22653 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22654 synchronized (mPackages) { 22655 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22656 } 22657 } 22658 22659 @Override 22660 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22661 synchronized (mPackages) { 22662 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22663 } 22664 } 22665 22666 @Override 22667 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22668 synchronized (mPackages) { 22669 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22670 } 22671 } 22672 22673 @Override 22674 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22675 synchronized (mPackages) { 22676 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22677 } 22678 } 22679 22680 @Override 22681 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22682 synchronized (mPackages) { 22683 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22684 } 22685 } 22686 22687 @Override 22688 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22689 synchronized (mPackages) { 22690 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22691 packageName, userId); 22692 } 22693 } 22694 22695 @Override 22696 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22697 synchronized (mPackages) { 22698 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22699 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22700 packageName, userId); 22701 } 22702 } 22703 22704 @Override 22705 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22706 synchronized (mPackages) { 22707 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22708 packageName, userId); 22709 } 22710 } 22711 22712 @Override 22713 public void setKeepUninstalledPackages(final List<String> packageList) { 22714 Preconditions.checkNotNull(packageList); 22715 List<String> removedFromList = null; 22716 synchronized (mPackages) { 22717 if (mKeepUninstalledPackages != null) { 22718 final int packagesCount = mKeepUninstalledPackages.size(); 22719 for (int i = 0; i < packagesCount; i++) { 22720 String oldPackage = mKeepUninstalledPackages.get(i); 22721 if (packageList != null && packageList.contains(oldPackage)) { 22722 continue; 22723 } 22724 if (removedFromList == null) { 22725 removedFromList = new ArrayList<>(); 22726 } 22727 removedFromList.add(oldPackage); 22728 } 22729 } 22730 mKeepUninstalledPackages = new ArrayList<>(packageList); 22731 if (removedFromList != null) { 22732 final int removedCount = removedFromList.size(); 22733 for (int i = 0; i < removedCount; i++) { 22734 deletePackageIfUnusedLPr(removedFromList.get(i)); 22735 } 22736 } 22737 } 22738 } 22739 22740 @Override 22741 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22742 synchronized (mPackages) { 22743 // If we do not support permission review, done. 22744 if (!mPermissionReviewRequired) { 22745 return false; 22746 } 22747 22748 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22749 if (packageSetting == null) { 22750 return false; 22751 } 22752 22753 // Permission review applies only to apps not supporting the new permission model. 22754 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22755 return false; 22756 } 22757 22758 // Legacy apps have the permission and get user consent on launch. 22759 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22760 return permissionsState.isPermissionReviewRequired(userId); 22761 } 22762 } 22763 22764 @Override 22765 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22766 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22767 } 22768 22769 @Override 22770 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22771 int userId) { 22772 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22773 } 22774 22775 @Override 22776 public void setDeviceAndProfileOwnerPackages( 22777 int deviceOwnerUserId, String deviceOwnerPackage, 22778 SparseArray<String> profileOwnerPackages) { 22779 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22780 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22781 } 22782 22783 @Override 22784 public boolean isPackageDataProtected(int userId, String packageName) { 22785 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22786 } 22787 22788 @Override 22789 public boolean isPackageEphemeral(int userId, String packageName) { 22790 synchronized (mPackages) { 22791 PackageParser.Package p = mPackages.get(packageName); 22792 return p != null ? p.applicationInfo.isEphemeralApp() : false; 22793 } 22794 } 22795 22796 @Override 22797 public boolean wasPackageEverLaunched(String packageName, int userId) { 22798 synchronized (mPackages) { 22799 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22800 } 22801 } 22802 22803 @Override 22804 public void grantRuntimePermission(String packageName, String name, int userId, 22805 boolean overridePolicy) { 22806 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22807 overridePolicy); 22808 } 22809 22810 @Override 22811 public void revokeRuntimePermission(String packageName, String name, int userId, 22812 boolean overridePolicy) { 22813 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22814 overridePolicy); 22815 } 22816 22817 @Override 22818 public String getNameForUid(int uid) { 22819 return PackageManagerService.this.getNameForUid(uid); 22820 } 22821 22822 @Override 22823 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 22824 Intent origIntent, String resolvedType, Intent launchIntent, 22825 String callingPackage, int userId) { 22826 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 22827 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 22828 } 22829 22830 @Override 22831 public void grantEphemeralAccess(int userId, Intent intent, 22832 int targetAppId, int ephemeralAppId) { 22833 synchronized (mPackages) { 22834 mEphemeralApplicationRegistry.grantEphemeralAccessLPw(userId, intent, 22835 targetAppId, ephemeralAppId); 22836 } 22837 } 22838 22839 public String getSetupWizardPackageName() { 22840 return mSetupWizardPackage; 22841 } 22842 } 22843 22844 @Override 22845 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 22846 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 22847 synchronized (mPackages) { 22848 final long identity = Binder.clearCallingIdentity(); 22849 try { 22850 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 22851 packageNames, userId); 22852 } finally { 22853 Binder.restoreCallingIdentity(identity); 22854 } 22855 } 22856 } 22857 22858 private static void enforceSystemOrPhoneCaller(String tag) { 22859 int callingUid = Binder.getCallingUid(); 22860 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 22861 throw new SecurityException( 22862 "Cannot call " + tag + " from UID " + callingUid); 22863 } 22864 } 22865 22866 boolean isHistoricalPackageUsageAvailable() { 22867 return mPackageUsage.isHistoricalPackageUsageAvailable(); 22868 } 22869 22870 /** 22871 * Return a <b>copy</b> of the collection of packages known to the package manager. 22872 * @return A copy of the values of mPackages. 22873 */ 22874 Collection<PackageParser.Package> getPackages() { 22875 synchronized (mPackages) { 22876 return new ArrayList<>(mPackages.values()); 22877 } 22878 } 22879 22880 /** 22881 * Logs process start information (including base APK hash) to the security log. 22882 * @hide 22883 */ 22884 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 22885 String apkFile, int pid) { 22886 if (!SecurityLog.isLoggingEnabled()) { 22887 return; 22888 } 22889 Bundle data = new Bundle(); 22890 data.putLong("startTimestamp", System.currentTimeMillis()); 22891 data.putString("processName", processName); 22892 data.putInt("uid", uid); 22893 data.putString("seinfo", seinfo); 22894 data.putString("apkFile", apkFile); 22895 data.putInt("pid", pid); 22896 Message msg = mProcessLoggingHandler.obtainMessage( 22897 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 22898 msg.setData(data); 22899 mProcessLoggingHandler.sendMessage(msg); 22900 } 22901 22902 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 22903 return mCompilerStats.getPackageStats(pkgName); 22904 } 22905 22906 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 22907 return getOrCreateCompilerPackageStats(pkg.packageName); 22908 } 22909 22910 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 22911 return mCompilerStats.getOrCreatePackageStats(pkgName); 22912 } 22913 22914 public void deleteCompilerPackageStats(String pkgName) { 22915 mCompilerStats.deletePackageStats(pkgName); 22916 } 22917 22918 @Override 22919 public int getInstallReason(String packageName, int userId) { 22920 enforceCrossUserPermission(Binder.getCallingUid(), userId, 22921 true /* requireFullPermission */, false /* checkShell */, 22922 "get install reason"); 22923 synchronized (mPackages) { 22924 final PackageSetting ps = mSettings.mPackages.get(packageName); 22925 if (ps != null) { 22926 return ps.getInstallReason(userId); 22927 } 22928 } 22929 return PackageManager.INSTALL_REASON_UNKNOWN; 22930 } 22931} 22932