PackageManagerService.java revision 253984ed8c8f39fa0aa9c5f4addf2f44f334c749
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 104 105import android.Manifest; 106import android.annotation.NonNull; 107import android.annotation.Nullable; 108import android.app.ActivityManager; 109import android.app.AppOpsManager; 110import android.app.IActivityManager; 111import android.app.ResourcesManager; 112import android.app.admin.IDevicePolicyManager; 113import android.app.admin.SecurityLog; 114import android.app.backup.IBackupManager; 115import android.content.BroadcastReceiver; 116import android.content.ComponentName; 117import android.content.ContentResolver; 118import android.content.Context; 119import android.content.IIntentReceiver; 120import android.content.Intent; 121import android.content.IntentFilter; 122import android.content.IntentSender; 123import android.content.IntentSender.SendIntentException; 124import android.content.ServiceConnection; 125import android.content.pm.ActivityInfo; 126import android.content.pm.ApplicationInfo; 127import android.content.pm.AppsQueryHelper; 128import android.content.pm.ChangedPackages; 129import android.content.pm.ComponentInfo; 130import android.content.pm.InstantAppRequest; 131import android.content.pm.AuxiliaryResolveInfo; 132import android.content.pm.FallbackCategoryProvider; 133import android.content.pm.FeatureInfo; 134import android.content.pm.IOnPermissionsChangeListener; 135import android.content.pm.IPackageDataObserver; 136import android.content.pm.IPackageDeleteObserver; 137import android.content.pm.IPackageDeleteObserver2; 138import android.content.pm.IPackageInstallObserver2; 139import android.content.pm.IPackageInstaller; 140import android.content.pm.IPackageManager; 141import android.content.pm.IPackageMoveObserver; 142import android.content.pm.IPackageStatsObserver; 143import android.content.pm.InstantAppInfo; 144import android.content.pm.InstantAppResolveInfo; 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.database.ContentObserver; 175import android.graphics.Bitmap; 176import android.hardware.display.DisplayManager; 177import android.net.Uri; 178import android.os.Binder; 179import android.os.Build; 180import android.os.Bundle; 181import android.os.Debug; 182import android.os.Environment; 183import android.os.Environment.UserEnvironment; 184import android.os.FileUtils; 185import android.os.Handler; 186import android.os.IBinder; 187import android.os.Looper; 188import android.os.Message; 189import android.os.Parcel; 190import android.os.ParcelFileDescriptor; 191import android.os.PatternMatcher; 192import android.os.Process; 193import android.os.RemoteCallbackList; 194import android.os.RemoteException; 195import android.os.ResultReceiver; 196import android.os.SELinux; 197import android.os.ServiceManager; 198import android.os.ShellCallback; 199import android.os.SystemClock; 200import android.os.SystemProperties; 201import android.os.Trace; 202import android.os.UserHandle; 203import android.os.UserManager; 204import android.os.UserManagerInternal; 205import android.os.storage.IStorageManager; 206import android.os.storage.StorageEventListener; 207import android.os.storage.StorageManager; 208import android.os.storage.StorageManagerInternal; 209import android.os.storage.VolumeInfo; 210import android.os.storage.VolumeRecord; 211import android.provider.Settings.Global; 212import android.provider.Settings.Secure; 213import android.security.KeyStore; 214import android.security.SystemKeyStore; 215import android.service.pm.PackageServiceDumpProto; 216import android.system.ErrnoException; 217import android.system.Os; 218import android.text.TextUtils; 219import android.text.format.DateUtils; 220import android.util.ArrayMap; 221import android.util.ArraySet; 222import android.util.Base64; 223import android.util.BootTimingsTraceLog; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.DumpUtils; 258import com.android.internal.util.FastPrintWriter; 259import com.android.internal.util.FastXmlSerializer; 260import com.android.internal.util.IndentingPrintWriter; 261import com.android.internal.util.Preconditions; 262import com.android.internal.util.XmlUtils; 263import com.android.server.AttributeCache; 264import com.android.server.DeviceIdleController; 265import com.android.server.EventLogTags; 266import com.android.server.FgThread; 267import com.android.server.IntentResolver; 268import com.android.server.LocalServices; 269import com.android.server.LockGuard; 270import com.android.server.ServiceThread; 271import com.android.server.SystemConfig; 272import com.android.server.SystemServerInitThreadPool; 273import com.android.server.Watchdog; 274import com.android.server.net.NetworkPolicyManagerInternal; 275import com.android.server.pm.Installer.InstallerException; 276import com.android.server.pm.PermissionsState.PermissionState; 277import com.android.server.pm.Settings.DatabaseVersion; 278import com.android.server.pm.Settings.VersionInfo; 279import com.android.server.pm.dex.DexManager; 280import com.android.server.storage.DeviceStorageMonitorInternal; 281 282import dalvik.system.CloseGuard; 283import dalvik.system.DexFile; 284import dalvik.system.VMRuntime; 285 286import libcore.io.IoUtils; 287import libcore.util.EmptyArray; 288 289import org.xmlpull.v1.XmlPullParser; 290import org.xmlpull.v1.XmlPullParserException; 291import org.xmlpull.v1.XmlSerializer; 292 293import java.io.BufferedOutputStream; 294import java.io.BufferedReader; 295import java.io.ByteArrayInputStream; 296import java.io.ByteArrayOutputStream; 297import java.io.File; 298import java.io.FileDescriptor; 299import java.io.FileInputStream; 300import java.io.FileOutputStream; 301import java.io.FileReader; 302import java.io.FilenameFilter; 303import java.io.IOException; 304import java.io.PrintWriter; 305import java.nio.charset.StandardCharsets; 306import java.security.DigestInputStream; 307import java.security.MessageDigest; 308import java.security.NoSuchAlgorithmException; 309import java.security.PublicKey; 310import java.security.SecureRandom; 311import java.security.cert.Certificate; 312import java.security.cert.CertificateEncodingException; 313import java.security.cert.CertificateException; 314import java.text.SimpleDateFormat; 315import java.util.ArrayList; 316import java.util.Arrays; 317import java.util.Collection; 318import java.util.Collections; 319import java.util.Comparator; 320import java.util.Date; 321import java.util.HashMap; 322import java.util.HashSet; 323import java.util.Iterator; 324import java.util.List; 325import java.util.Map; 326import java.util.Objects; 327import java.util.Set; 328import java.util.concurrent.CountDownLatch; 329import java.util.concurrent.Future; 330import java.util.concurrent.TimeUnit; 331import java.util.concurrent.atomic.AtomicBoolean; 332import java.util.concurrent.atomic.AtomicInteger; 333 334/** 335 * Keep track of all those APKs everywhere. 336 * <p> 337 * Internally there are two important locks: 338 * <ul> 339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 340 * and other related state. It is a fine-grained lock that should only be held 341 * momentarily, as it's one of the most contended locks in the system. 342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 343 * operations typically involve heavy lifting of application data on disk. Since 344 * {@code installd} is single-threaded, and it's operations can often be slow, 345 * this lock should never be acquired while already holding {@link #mPackages}. 346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 347 * holding {@link #mInstallLock}. 348 * </ul> 349 * Many internal methods rely on the caller to hold the appropriate locks, and 350 * this contract is expressed through method name suffixes: 351 * <ul> 352 * <li>fooLI(): the caller must hold {@link #mInstallLock} 353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 354 * being modified must be frozen 355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 357 * </ul> 358 * <p> 359 * Because this class is very central to the platform's security; please run all 360 * CTS and unit tests whenever making modifications: 361 * 362 * <pre> 363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 365 * </pre> 366 */ 367public class PackageManagerService extends IPackageManager.Stub 368 implements PackageSender { 369 static final String TAG = "PackageManager"; 370 static final boolean DEBUG_SETTINGS = false; 371 static final boolean DEBUG_PREFERRED = false; 372 static final boolean DEBUG_UPGRADE = false; 373 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 374 private static final boolean DEBUG_BACKUP = false; 375 private static final boolean DEBUG_INSTALL = false; 376 private static final boolean DEBUG_REMOVE = false; 377 private static final boolean DEBUG_BROADCASTS = false; 378 private static final boolean DEBUG_SHOW_INFO = false; 379 private static final boolean DEBUG_PACKAGE_INFO = false; 380 private static final boolean DEBUG_INTENT_MATCHING = false; 381 private static final boolean DEBUG_PACKAGE_SCANNING = false; 382 private static final boolean DEBUG_VERIFY = false; 383 private static final boolean DEBUG_FILTERS = false; 384 385 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 386 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 387 // user, but by default initialize to this. 388 public static final boolean DEBUG_DEXOPT = false; 389 390 private static final boolean DEBUG_ABI_SELECTION = false; 391 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 392 private static final boolean DEBUG_TRIAGED_MISSING = false; 393 private static final boolean DEBUG_APP_DATA = false; 394 395 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 396 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 397 398 private static final boolean HIDE_EPHEMERAL_APIS = false; 399 400 private static final boolean ENABLE_FREE_CACHE_V2 = 401 SystemProperties.getBoolean("fw.free_cache_v2", true); 402 403 private static final int RADIO_UID = Process.PHONE_UID; 404 private static final int LOG_UID = Process.LOG_UID; 405 private static final int NFC_UID = Process.NFC_UID; 406 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 407 private static final int SHELL_UID = Process.SHELL_UID; 408 409 // Cap the size of permission trees that 3rd party apps can define 410 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 411 412 // Suffix used during package installation when copying/moving 413 // package apks to install directory. 414 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 415 416 static final int SCAN_NO_DEX = 1<<1; 417 static final int SCAN_FORCE_DEX = 1<<2; 418 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 419 static final int SCAN_NEW_INSTALL = 1<<4; 420 static final int SCAN_UPDATE_TIME = 1<<5; 421 static final int SCAN_BOOTING = 1<<6; 422 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 423 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 424 static final int SCAN_REPLACING = 1<<9; 425 static final int SCAN_REQUIRE_KNOWN = 1<<10; 426 static final int SCAN_MOVE = 1<<11; 427 static final int SCAN_INITIAL = 1<<12; 428 static final int SCAN_CHECK_ONLY = 1<<13; 429 static final int SCAN_DONT_KILL_APP = 1<<14; 430 static final int SCAN_IGNORE_FROZEN = 1<<15; 431 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 432 static final int SCAN_AS_INSTANT_APP = 1<<17; 433 static final int SCAN_AS_FULL_APP = 1<<18; 434 /** Should not be with the scan flags */ 435 static final int FLAGS_REMOVE_CHATTY = 1<<31; 436 437 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 438 439 private static final int[] EMPTY_INT_ARRAY = new int[0]; 440 441 /** 442 * Timeout (in milliseconds) after which the watchdog should declare that 443 * our handler thread is wedged. The usual default for such things is one 444 * minute but we sometimes do very lengthy I/O operations on this thread, 445 * such as installing multi-gigabyte applications, so ours needs to be longer. 446 */ 447 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 448 449 /** 450 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 451 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 452 * settings entry if available, otherwise we use the hardcoded default. If it's been 453 * more than this long since the last fstrim, we force one during the boot sequence. 454 * 455 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 456 * one gets run at the next available charging+idle time. This final mandatory 457 * no-fstrim check kicks in only of the other scheduling criteria is never met. 458 */ 459 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 460 461 /** 462 * Whether verification is enabled by default. 463 */ 464 private static final boolean DEFAULT_VERIFY_ENABLE = true; 465 466 /** 467 * The default maximum time to wait for the verification agent to return in 468 * milliseconds. 469 */ 470 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 471 472 /** 473 * The default response for package verification timeout. 474 * 475 * This can be either PackageManager.VERIFICATION_ALLOW or 476 * PackageManager.VERIFICATION_REJECT. 477 */ 478 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 479 480 static final String PLATFORM_PACKAGE_NAME = "android"; 481 482 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 483 484 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 485 DEFAULT_CONTAINER_PACKAGE, 486 "com.android.defcontainer.DefaultContainerService"); 487 488 private static final String KILL_APP_REASON_GIDS_CHANGED = 489 "permission grant or revoke changed gids"; 490 491 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 492 "permissions revoked"; 493 494 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 495 496 private static final String PACKAGE_SCHEME = "package"; 497 498 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 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 540 public static final int REASON_LAST = REASON_AB_OTA; 541 542 /** All dangerous permission names in the same order as the events in MetricsEvent */ 543 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 544 Manifest.permission.READ_CALENDAR, 545 Manifest.permission.WRITE_CALENDAR, 546 Manifest.permission.CAMERA, 547 Manifest.permission.READ_CONTACTS, 548 Manifest.permission.WRITE_CONTACTS, 549 Manifest.permission.GET_ACCOUNTS, 550 Manifest.permission.ACCESS_FINE_LOCATION, 551 Manifest.permission.ACCESS_COARSE_LOCATION, 552 Manifest.permission.RECORD_AUDIO, 553 Manifest.permission.READ_PHONE_STATE, 554 Manifest.permission.CALL_PHONE, 555 Manifest.permission.READ_CALL_LOG, 556 Manifest.permission.WRITE_CALL_LOG, 557 Manifest.permission.ADD_VOICEMAIL, 558 Manifest.permission.USE_SIP, 559 Manifest.permission.PROCESS_OUTGOING_CALLS, 560 Manifest.permission.READ_CELL_BROADCASTS, 561 Manifest.permission.BODY_SENSORS, 562 Manifest.permission.SEND_SMS, 563 Manifest.permission.RECEIVE_SMS, 564 Manifest.permission.READ_SMS, 565 Manifest.permission.RECEIVE_WAP_PUSH, 566 Manifest.permission.RECEIVE_MMS, 567 Manifest.permission.READ_EXTERNAL_STORAGE, 568 Manifest.permission.WRITE_EXTERNAL_STORAGE, 569 Manifest.permission.READ_PHONE_NUMBERS, 570 Manifest.permission.ANSWER_PHONE_CALLS); 571 572 573 /** 574 * Version number for the package parser cache. Increment this whenever the format or 575 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 576 */ 577 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 578 579 /** 580 * Whether the package parser cache is enabled. 581 */ 582 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 583 584 final ServiceThread mHandlerThread; 585 586 final PackageHandler mHandler; 587 588 private final ProcessLoggingHandler mProcessLoggingHandler; 589 590 /** 591 * Messages for {@link #mHandler} that need to wait for system ready before 592 * being dispatched. 593 */ 594 private ArrayList<Message> mPostSystemReadyMessages; 595 596 final int mSdkVersion = Build.VERSION.SDK_INT; 597 598 final Context mContext; 599 final boolean mFactoryTest; 600 final boolean mOnlyCore; 601 final DisplayMetrics mMetrics; 602 final int mDefParseFlags; 603 final String[] mSeparateProcesses; 604 final boolean mIsUpgrade; 605 final boolean mIsPreNUpgrade; 606 final boolean mIsPreNMR1Upgrade; 607 608 // Have we told the Activity Manager to whitelist the default container service by uid yet? 609 @GuardedBy("mPackages") 610 boolean mDefaultContainerWhitelisted = false; 611 612 @GuardedBy("mPackages") 613 private boolean mDexOptDialogShown; 614 615 /** The location for ASEC container files on internal storage. */ 616 final String mAsecInternalPath; 617 618 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 619 // LOCK HELD. Can be called with mInstallLock held. 620 @GuardedBy("mInstallLock") 621 final Installer mInstaller; 622 623 /** Directory where installed third-party apps stored */ 624 final File mAppInstallDir; 625 626 /** 627 * Directory to which applications installed internally have their 628 * 32 bit native libraries copied. 629 */ 630 private File mAppLib32InstallDir; 631 632 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 633 // apps. 634 final File mDrmAppPrivateInstallDir; 635 636 // ---------------------------------------------------------------- 637 638 // Lock for state used when installing and doing other long running 639 // operations. Methods that must be called with this lock held have 640 // the suffix "LI". 641 final Object mInstallLock = new Object(); 642 643 // ---------------------------------------------------------------- 644 645 // Keys are String (package name), values are Package. This also serves 646 // as the lock for the global state. Methods that must be called with 647 // this lock held have the prefix "LP". 648 @GuardedBy("mPackages") 649 final ArrayMap<String, PackageParser.Package> mPackages = 650 new ArrayMap<String, PackageParser.Package>(); 651 652 final ArrayMap<String, Set<String>> mKnownCodebase = 653 new ArrayMap<String, Set<String>>(); 654 655 // Keys are isolated uids and values are the uid of the application 656 // that created the isolated proccess. 657 @GuardedBy("mPackages") 658 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 659 660 // List of APK paths to load for each user and package. This data is never 661 // persisted by the package manager. Instead, the overlay manager will 662 // ensure the data is up-to-date in runtime. 663 @GuardedBy("mPackages") 664 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 665 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 666 667 /** 668 * Tracks new system packages [received in an OTA] that we expect to 669 * find updated user-installed versions. Keys are package name, values 670 * are package location. 671 */ 672 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 673 /** 674 * Tracks high priority intent filters for protected actions. During boot, certain 675 * filter actions are protected and should never be allowed to have a high priority 676 * intent filter for them. However, there is one, and only one exception -- the 677 * setup wizard. It must be able to define a high priority intent filter for these 678 * actions to ensure there are no escapes from the wizard. We need to delay processing 679 * of these during boot as we need to look at all of the system packages in order 680 * to know which component is the setup wizard. 681 */ 682 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 683 /** 684 * Whether or not processing protected filters should be deferred. 685 */ 686 private boolean mDeferProtectedFilters = true; 687 688 /** 689 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 690 */ 691 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 692 /** 693 * Whether or not system app permissions should be promoted from install to runtime. 694 */ 695 boolean mPromoteSystemApps; 696 697 @GuardedBy("mPackages") 698 final Settings mSettings; 699 700 /** 701 * Set of package names that are currently "frozen", which means active 702 * surgery is being done on the code/data for that package. The platform 703 * will refuse to launch frozen packages to avoid race conditions. 704 * 705 * @see PackageFreezer 706 */ 707 @GuardedBy("mPackages") 708 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 709 710 final ProtectedPackages mProtectedPackages; 711 712 boolean mFirstBoot; 713 714 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 715 716 // System configuration read by SystemConfig. 717 final int[] mGlobalGids; 718 final SparseArray<ArraySet<String>> mSystemPermissions; 719 @GuardedBy("mAvailableFeatures") 720 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 721 722 // If mac_permissions.xml was found for seinfo labeling. 723 boolean mFoundPolicyFile; 724 725 private final InstantAppRegistry mInstantAppRegistry; 726 727 @GuardedBy("mPackages") 728 int mChangedPackagesSequenceNumber; 729 /** 730 * List of changed [installed, removed or updated] packages. 731 * mapping from user id -> sequence number -> package name 732 */ 733 @GuardedBy("mPackages") 734 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 735 /** 736 * The sequence number of the last change to a package. 737 * mapping from user id -> package name -> sequence number 738 */ 739 @GuardedBy("mPackages") 740 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 741 742 class PackageParserCallback implements PackageParser.Callback { 743 @Override public final boolean hasFeature(String feature) { 744 return PackageManagerService.this.hasSystemFeature(feature, 0); 745 } 746 747 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 748 Collection<PackageParser.Package> allPackages, String targetPackageName) { 749 List<PackageParser.Package> overlayPackages = null; 750 for (PackageParser.Package p : allPackages) { 751 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 752 if (overlayPackages == null) { 753 overlayPackages = new ArrayList<PackageParser.Package>(); 754 } 755 overlayPackages.add(p); 756 } 757 } 758 if (overlayPackages != null) { 759 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 760 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 761 return p1.mOverlayPriority - p2.mOverlayPriority; 762 } 763 }; 764 Collections.sort(overlayPackages, cmp); 765 } 766 return overlayPackages; 767 } 768 769 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 770 String targetPackageName, String targetPath) { 771 if ("android".equals(targetPackageName)) { 772 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 773 // native AssetManager. 774 return null; 775 } 776 List<PackageParser.Package> overlayPackages = 777 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 778 if (overlayPackages == null || overlayPackages.isEmpty()) { 779 return null; 780 } 781 List<String> overlayPathList = null; 782 for (PackageParser.Package overlayPackage : overlayPackages) { 783 if (targetPath == null) { 784 if (overlayPathList == null) { 785 overlayPathList = new ArrayList<String>(); 786 } 787 overlayPathList.add(overlayPackage.baseCodePath); 788 continue; 789 } 790 791 try { 792 // Creates idmaps for system to parse correctly the Android manifest of the 793 // target package. 794 // 795 // OverlayManagerService will update each of them with a correct gid from its 796 // target package app id. 797 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 798 UserHandle.getSharedAppGid( 799 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 800 if (overlayPathList == null) { 801 overlayPathList = new ArrayList<String>(); 802 } 803 overlayPathList.add(overlayPackage.baseCodePath); 804 } catch (InstallerException e) { 805 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 806 overlayPackage.baseCodePath); 807 } 808 } 809 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 810 } 811 812 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 813 synchronized (mPackages) { 814 return getStaticOverlayPathsLocked( 815 mPackages.values(), targetPackageName, targetPath); 816 } 817 } 818 819 @Override public final String[] getOverlayApks(String targetPackageName) { 820 return getStaticOverlayPaths(targetPackageName, null); 821 } 822 823 @Override public final String[] getOverlayPaths(String targetPackageName, 824 String targetPath) { 825 return getStaticOverlayPaths(targetPackageName, targetPath); 826 } 827 }; 828 829 class ParallelPackageParserCallback extends PackageParserCallback { 830 List<PackageParser.Package> mOverlayPackages = null; 831 832 void findStaticOverlayPackages() { 833 synchronized (mPackages) { 834 for (PackageParser.Package p : mPackages.values()) { 835 if (p.mIsStaticOverlay) { 836 if (mOverlayPackages == null) { 837 mOverlayPackages = new ArrayList<PackageParser.Package>(); 838 } 839 mOverlayPackages.add(p); 840 } 841 } 842 } 843 } 844 845 @Override 846 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 847 // We can trust mOverlayPackages without holding mPackages because package uninstall 848 // can't happen while running parallel parsing. 849 // Moreover holding mPackages on each parsing thread causes dead-lock. 850 return mOverlayPackages == null ? null : 851 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 852 } 853 } 854 855 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 856 final ParallelPackageParserCallback mParallelPackageParserCallback = 857 new ParallelPackageParserCallback(); 858 859 public static final class SharedLibraryEntry { 860 public final String path; 861 public final String apk; 862 public final SharedLibraryInfo info; 863 864 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 865 String declaringPackageName, int declaringPackageVersionCode) { 866 path = _path; 867 apk = _apk; 868 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 869 declaringPackageName, declaringPackageVersionCode), null); 870 } 871 } 872 873 // Currently known shared libraries. 874 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 875 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 876 new ArrayMap<>(); 877 878 // All available activities, for your resolving pleasure. 879 final ActivityIntentResolver mActivities = 880 new ActivityIntentResolver(); 881 882 // All available receivers, for your resolving pleasure. 883 final ActivityIntentResolver mReceivers = 884 new ActivityIntentResolver(); 885 886 // All available services, for your resolving pleasure. 887 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 888 889 // All available providers, for your resolving pleasure. 890 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 891 892 // Mapping from provider base names (first directory in content URI codePath) 893 // to the provider information. 894 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 895 new ArrayMap<String, PackageParser.Provider>(); 896 897 // Mapping from instrumentation class names to info about them. 898 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 899 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 900 901 // Mapping from permission names to info about them. 902 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 903 new ArrayMap<String, PackageParser.PermissionGroup>(); 904 905 // Packages whose data we have transfered into another package, thus 906 // should no longer exist. 907 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 908 909 // Broadcast actions that are only available to the system. 910 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 911 912 /** List of packages waiting for verification. */ 913 final SparseArray<PackageVerificationState> mPendingVerification 914 = new SparseArray<PackageVerificationState>(); 915 916 /** Set of packages associated with each app op permission. */ 917 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 918 919 final PackageInstallerService mInstallerService; 920 921 private final PackageDexOptimizer mPackageDexOptimizer; 922 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 923 // is used by other apps). 924 private final DexManager mDexManager; 925 926 private AtomicInteger mNextMoveId = new AtomicInteger(); 927 private final MoveCallbacks mMoveCallbacks; 928 929 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 930 931 // Cache of users who need badging. 932 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 933 934 /** Token for keys in mPendingVerification. */ 935 private int mPendingVerificationToken = 0; 936 937 volatile boolean mSystemReady; 938 volatile boolean mSafeMode; 939 volatile boolean mHasSystemUidErrors; 940 private volatile boolean mEphemeralAppsDisabled; 941 942 ApplicationInfo mAndroidApplication; 943 final ActivityInfo mResolveActivity = new ActivityInfo(); 944 final ResolveInfo mResolveInfo = new ResolveInfo(); 945 ComponentName mResolveComponentName; 946 PackageParser.Package mPlatformPackage; 947 ComponentName mCustomResolverComponentName; 948 949 boolean mResolverReplaced = false; 950 951 private final @Nullable ComponentName mIntentFilterVerifierComponent; 952 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 953 954 private int mIntentFilterVerificationToken = 0; 955 956 /** The service connection to the ephemeral resolver */ 957 final EphemeralResolverConnection mInstantAppResolverConnection; 958 /** Component used to show resolver settings for Instant Apps */ 959 final ComponentName mInstantAppResolverSettingsComponent; 960 961 /** Activity used to install instant applications */ 962 ActivityInfo mInstantAppInstallerActivity; 963 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 964 965 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 966 = new SparseArray<IntentFilterVerificationState>(); 967 968 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 969 970 // List of packages names to keep cached, even if they are uninstalled for all users 971 private List<String> mKeepUninstalledPackages; 972 973 private UserManagerInternal mUserManagerInternal; 974 975 private DeviceIdleController.LocalService mDeviceIdleController; 976 977 private File mCacheDir; 978 979 private ArraySet<String> mPrivappPermissionsViolations; 980 981 private Future<?> mPrepareAppDataFuture; 982 983 private static class IFVerificationParams { 984 PackageParser.Package pkg; 985 boolean replacing; 986 int userId; 987 int verifierUid; 988 989 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 990 int _userId, int _verifierUid) { 991 pkg = _pkg; 992 replacing = _replacing; 993 userId = _userId; 994 replacing = _replacing; 995 verifierUid = _verifierUid; 996 } 997 } 998 999 private interface IntentFilterVerifier<T extends IntentFilter> { 1000 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1001 T filter, String packageName); 1002 void startVerifications(int userId); 1003 void receiveVerificationResponse(int verificationId); 1004 } 1005 1006 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1007 private Context mContext; 1008 private ComponentName mIntentFilterVerifierComponent; 1009 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1010 1011 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1012 mContext = context; 1013 mIntentFilterVerifierComponent = verifierComponent; 1014 } 1015 1016 private String getDefaultScheme() { 1017 return IntentFilter.SCHEME_HTTPS; 1018 } 1019 1020 @Override 1021 public void startVerifications(int userId) { 1022 // Launch verifications requests 1023 int count = mCurrentIntentFilterVerifications.size(); 1024 for (int n=0; n<count; n++) { 1025 int verificationId = mCurrentIntentFilterVerifications.get(n); 1026 final IntentFilterVerificationState ivs = 1027 mIntentFilterVerificationStates.get(verificationId); 1028 1029 String packageName = ivs.getPackageName(); 1030 1031 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1032 final int filterCount = filters.size(); 1033 ArraySet<String> domainsSet = new ArraySet<>(); 1034 for (int m=0; m<filterCount; m++) { 1035 PackageParser.ActivityIntentInfo filter = filters.get(m); 1036 domainsSet.addAll(filter.getHostsList()); 1037 } 1038 synchronized (mPackages) { 1039 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1040 packageName, domainsSet) != null) { 1041 scheduleWriteSettingsLocked(); 1042 } 1043 } 1044 sendVerificationRequest(userId, verificationId, ivs); 1045 } 1046 mCurrentIntentFilterVerifications.clear(); 1047 } 1048 1049 private void sendVerificationRequest(int userId, int verificationId, 1050 IntentFilterVerificationState ivs) { 1051 1052 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1053 verificationIntent.putExtra( 1054 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1055 verificationId); 1056 verificationIntent.putExtra( 1057 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1058 getDefaultScheme()); 1059 verificationIntent.putExtra( 1060 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1061 ivs.getHostsString()); 1062 verificationIntent.putExtra( 1063 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1064 ivs.getPackageName()); 1065 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1066 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1067 1068 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1069 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1070 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1071 userId, false, "intent filter verifier"); 1072 1073 UserHandle user = new UserHandle(userId); 1074 mContext.sendBroadcastAsUser(verificationIntent, user); 1075 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1076 "Sending IntentFilter verification broadcast"); 1077 } 1078 1079 public void receiveVerificationResponse(int verificationId) { 1080 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1081 1082 final boolean verified = ivs.isVerified(); 1083 1084 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1085 final int count = filters.size(); 1086 if (DEBUG_DOMAIN_VERIFICATION) { 1087 Slog.i(TAG, "Received verification response " + verificationId 1088 + " for " + count + " filters, verified=" + verified); 1089 } 1090 for (int n=0; n<count; n++) { 1091 PackageParser.ActivityIntentInfo filter = filters.get(n); 1092 filter.setVerified(verified); 1093 1094 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1095 + " verified with result:" + verified + " and hosts:" 1096 + ivs.getHostsString()); 1097 } 1098 1099 mIntentFilterVerificationStates.remove(verificationId); 1100 1101 final String packageName = ivs.getPackageName(); 1102 IntentFilterVerificationInfo ivi = null; 1103 1104 synchronized (mPackages) { 1105 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1106 } 1107 if (ivi == null) { 1108 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1109 + verificationId + " packageName:" + packageName); 1110 return; 1111 } 1112 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1113 "Updating IntentFilterVerificationInfo for package " + packageName 1114 +" verificationId:" + verificationId); 1115 1116 synchronized (mPackages) { 1117 if (verified) { 1118 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1119 } else { 1120 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1121 } 1122 scheduleWriteSettingsLocked(); 1123 1124 final int userId = ivs.getUserId(); 1125 if (userId != UserHandle.USER_ALL) { 1126 final int userStatus = 1127 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1128 1129 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1130 boolean needUpdate = false; 1131 1132 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1133 // already been set by the User thru the Disambiguation dialog 1134 switch (userStatus) { 1135 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1136 if (verified) { 1137 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1138 } else { 1139 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1140 } 1141 needUpdate = true; 1142 break; 1143 1144 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1145 if (verified) { 1146 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1147 needUpdate = true; 1148 } 1149 break; 1150 1151 default: 1152 // Nothing to do 1153 } 1154 1155 if (needUpdate) { 1156 mSettings.updateIntentFilterVerificationStatusLPw( 1157 packageName, updatedStatus, userId); 1158 scheduleWritePackageRestrictionsLocked(userId); 1159 } 1160 } 1161 } 1162 } 1163 1164 @Override 1165 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1166 ActivityIntentInfo filter, String packageName) { 1167 if (!hasValidDomains(filter)) { 1168 return false; 1169 } 1170 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1171 if (ivs == null) { 1172 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1173 packageName); 1174 } 1175 if (DEBUG_DOMAIN_VERIFICATION) { 1176 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1177 } 1178 ivs.addFilter(filter); 1179 return true; 1180 } 1181 1182 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1183 int userId, int verificationId, String packageName) { 1184 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1185 verifierUid, userId, packageName); 1186 ivs.setPendingState(); 1187 synchronized (mPackages) { 1188 mIntentFilterVerificationStates.append(verificationId, ivs); 1189 mCurrentIntentFilterVerifications.add(verificationId); 1190 } 1191 return ivs; 1192 } 1193 } 1194 1195 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1196 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1197 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1198 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1199 } 1200 1201 // Set of pending broadcasts for aggregating enable/disable of components. 1202 static class PendingPackageBroadcasts { 1203 // for each user id, a map of <package name -> components within that package> 1204 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1205 1206 public PendingPackageBroadcasts() { 1207 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1208 } 1209 1210 public ArrayList<String> get(int userId, String packageName) { 1211 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1212 return packages.get(packageName); 1213 } 1214 1215 public void put(int userId, String packageName, ArrayList<String> components) { 1216 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1217 packages.put(packageName, components); 1218 } 1219 1220 public void remove(int userId, String packageName) { 1221 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1222 if (packages != null) { 1223 packages.remove(packageName); 1224 } 1225 } 1226 1227 public void remove(int userId) { 1228 mUidMap.remove(userId); 1229 } 1230 1231 public int userIdCount() { 1232 return mUidMap.size(); 1233 } 1234 1235 public int userIdAt(int n) { 1236 return mUidMap.keyAt(n); 1237 } 1238 1239 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1240 return mUidMap.get(userId); 1241 } 1242 1243 public int size() { 1244 // total number of pending broadcast entries across all userIds 1245 int num = 0; 1246 for (int i = 0; i< mUidMap.size(); i++) { 1247 num += mUidMap.valueAt(i).size(); 1248 } 1249 return num; 1250 } 1251 1252 public void clear() { 1253 mUidMap.clear(); 1254 } 1255 1256 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1257 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1258 if (map == null) { 1259 map = new ArrayMap<String, ArrayList<String>>(); 1260 mUidMap.put(userId, map); 1261 } 1262 return map; 1263 } 1264 } 1265 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1266 1267 // Service Connection to remote media container service to copy 1268 // package uri's from external media onto secure containers 1269 // or internal storage. 1270 private IMediaContainerService mContainerService = null; 1271 1272 static final int SEND_PENDING_BROADCAST = 1; 1273 static final int MCS_BOUND = 3; 1274 static final int END_COPY = 4; 1275 static final int INIT_COPY = 5; 1276 static final int MCS_UNBIND = 6; 1277 static final int START_CLEANING_PACKAGE = 7; 1278 static final int FIND_INSTALL_LOC = 8; 1279 static final int POST_INSTALL = 9; 1280 static final int MCS_RECONNECT = 10; 1281 static final int MCS_GIVE_UP = 11; 1282 static final int UPDATED_MEDIA_STATUS = 12; 1283 static final int WRITE_SETTINGS = 13; 1284 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1285 static final int PACKAGE_VERIFIED = 15; 1286 static final int CHECK_PENDING_VERIFICATION = 16; 1287 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1288 static final int INTENT_FILTER_VERIFIED = 18; 1289 static final int WRITE_PACKAGE_LIST = 19; 1290 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1291 1292 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1293 1294 // Delay time in millisecs 1295 static final int BROADCAST_DELAY = 10 * 1000; 1296 1297 static UserManagerService sUserManager; 1298 1299 // Stores a list of users whose package restrictions file needs to be updated 1300 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1301 1302 final private DefaultContainerConnection mDefContainerConn = 1303 new DefaultContainerConnection(); 1304 class DefaultContainerConnection implements ServiceConnection { 1305 public void onServiceConnected(ComponentName name, IBinder service) { 1306 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1307 final IMediaContainerService imcs = IMediaContainerService.Stub 1308 .asInterface(Binder.allowBlocking(service)); 1309 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1310 } 1311 1312 public void onServiceDisconnected(ComponentName name) { 1313 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1314 } 1315 } 1316 1317 // Recordkeeping of restore-after-install operations that are currently in flight 1318 // between the Package Manager and the Backup Manager 1319 static class PostInstallData { 1320 public InstallArgs args; 1321 public PackageInstalledInfo res; 1322 1323 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1324 args = _a; 1325 res = _r; 1326 } 1327 } 1328 1329 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1330 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1331 1332 // XML tags for backup/restore of various bits of state 1333 private static final String TAG_PREFERRED_BACKUP = "pa"; 1334 private static final String TAG_DEFAULT_APPS = "da"; 1335 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1336 1337 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1338 private static final String TAG_ALL_GRANTS = "rt-grants"; 1339 private static final String TAG_GRANT = "grant"; 1340 private static final String ATTR_PACKAGE_NAME = "pkg"; 1341 1342 private static final String TAG_PERMISSION = "perm"; 1343 private static final String ATTR_PERMISSION_NAME = "name"; 1344 private static final String ATTR_IS_GRANTED = "g"; 1345 private static final String ATTR_USER_SET = "set"; 1346 private static final String ATTR_USER_FIXED = "fixed"; 1347 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1348 1349 // System/policy permission grants are not backed up 1350 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1351 FLAG_PERMISSION_POLICY_FIXED 1352 | FLAG_PERMISSION_SYSTEM_FIXED 1353 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1354 1355 // And we back up these user-adjusted states 1356 private static final int USER_RUNTIME_GRANT_MASK = 1357 FLAG_PERMISSION_USER_SET 1358 | FLAG_PERMISSION_USER_FIXED 1359 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1360 1361 final @Nullable String mRequiredVerifierPackage; 1362 final @NonNull String mRequiredInstallerPackage; 1363 final @NonNull String mRequiredUninstallerPackage; 1364 final @Nullable String mSetupWizardPackage; 1365 final @Nullable String mStorageManagerPackage; 1366 final @NonNull String mServicesSystemSharedLibraryPackageName; 1367 final @NonNull String mSharedSystemSharedLibraryPackageName; 1368 1369 final boolean mPermissionReviewRequired; 1370 1371 private final PackageUsage mPackageUsage = new PackageUsage(); 1372 private final CompilerStats mCompilerStats = new CompilerStats(); 1373 1374 class PackageHandler extends Handler { 1375 private boolean mBound = false; 1376 final ArrayList<HandlerParams> mPendingInstalls = 1377 new ArrayList<HandlerParams>(); 1378 1379 private boolean connectToService() { 1380 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1381 " DefaultContainerService"); 1382 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1383 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1384 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1385 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 mBound = true; 1388 return true; 1389 } 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1391 return false; 1392 } 1393 1394 private void disconnectService() { 1395 mContainerService = null; 1396 mBound = false; 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1398 mContext.unbindService(mDefContainerConn); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1400 } 1401 1402 PackageHandler(Looper looper) { 1403 super(looper); 1404 } 1405 1406 public void handleMessage(Message msg) { 1407 try { 1408 doHandleMessage(msg); 1409 } finally { 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } 1412 } 1413 1414 void doHandleMessage(Message msg) { 1415 switch (msg.what) { 1416 case INIT_COPY: { 1417 HandlerParams params = (HandlerParams) msg.obj; 1418 int idx = mPendingInstalls.size(); 1419 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1420 // If a bind was already initiated we dont really 1421 // need to do anything. The pending install 1422 // will be processed later on. 1423 if (!mBound) { 1424 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1425 System.identityHashCode(mHandler)); 1426 // If this is the only one pending we might 1427 // have to bind to the service again. 1428 if (!connectToService()) { 1429 Slog.e(TAG, "Failed to bind to media container service"); 1430 params.serviceError(); 1431 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1432 System.identityHashCode(mHandler)); 1433 if (params.traceMethod != null) { 1434 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1435 params.traceCookie); 1436 } 1437 return; 1438 } else { 1439 // Once we bind to the service, the first 1440 // pending request will be processed. 1441 mPendingInstalls.add(idx, params); 1442 } 1443 } else { 1444 mPendingInstalls.add(idx, params); 1445 // Already bound to the service. Just make 1446 // sure we trigger off processing the first request. 1447 if (idx == 0) { 1448 mHandler.sendEmptyMessage(MCS_BOUND); 1449 } 1450 } 1451 break; 1452 } 1453 case MCS_BOUND: { 1454 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1455 if (msg.obj != null) { 1456 mContainerService = (IMediaContainerService) msg.obj; 1457 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1458 System.identityHashCode(mHandler)); 1459 } 1460 if (mContainerService == null) { 1461 if (!mBound) { 1462 // Something seriously wrong since we are not bound and we are not 1463 // waiting for connection. Bail out. 1464 Slog.e(TAG, "Cannot bind to media container service"); 1465 for (HandlerParams params : mPendingInstalls) { 1466 // Indicate service bind error 1467 params.serviceError(); 1468 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1469 System.identityHashCode(params)); 1470 if (params.traceMethod != null) { 1471 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1472 params.traceMethod, params.traceCookie); 1473 } 1474 return; 1475 } 1476 mPendingInstalls.clear(); 1477 } else { 1478 Slog.w(TAG, "Waiting to connect to media container service"); 1479 } 1480 } else if (mPendingInstalls.size() > 0) { 1481 HandlerParams params = mPendingInstalls.get(0); 1482 if (params != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1484 System.identityHashCode(params)); 1485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1486 if (params.startCopy()) { 1487 // We are done... look for more work or to 1488 // go idle. 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, 1490 "Checking for more work or unbind..."); 1491 // Delete pending install 1492 if (mPendingInstalls.size() > 0) { 1493 mPendingInstalls.remove(0); 1494 } 1495 if (mPendingInstalls.size() == 0) { 1496 if (mBound) { 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, 1498 "Posting delayed MCS_UNBIND"); 1499 removeMessages(MCS_UNBIND); 1500 Message ubmsg = obtainMessage(MCS_UNBIND); 1501 // Unbind after a little delay, to avoid 1502 // continual thrashing. 1503 sendMessageDelayed(ubmsg, 10000); 1504 } 1505 } else { 1506 // There are more pending requests in queue. 1507 // Just post MCS_BOUND message to trigger processing 1508 // of next pending install. 1509 if (DEBUG_SD_INSTALL) Log.i(TAG, 1510 "Posting MCS_BOUND for next work"); 1511 mHandler.sendEmptyMessage(MCS_BOUND); 1512 } 1513 } 1514 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1515 } 1516 } else { 1517 // Should never happen ideally. 1518 Slog.w(TAG, "Empty queue"); 1519 } 1520 break; 1521 } 1522 case MCS_RECONNECT: { 1523 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1524 if (mPendingInstalls.size() > 0) { 1525 if (mBound) { 1526 disconnectService(); 1527 } 1528 if (!connectToService()) { 1529 Slog.e(TAG, "Failed to bind to media container service"); 1530 for (HandlerParams params : mPendingInstalls) { 1531 // Indicate service bind error 1532 params.serviceError(); 1533 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1534 System.identityHashCode(params)); 1535 } 1536 mPendingInstalls.clear(); 1537 } 1538 } 1539 break; 1540 } 1541 case MCS_UNBIND: { 1542 // If there is no actual work left, then time to unbind. 1543 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1544 1545 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1546 if (mBound) { 1547 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1548 1549 disconnectService(); 1550 } 1551 } else if (mPendingInstalls.size() > 0) { 1552 // There are more pending requests in queue. 1553 // Just post MCS_BOUND message to trigger processing 1554 // of next pending install. 1555 mHandler.sendEmptyMessage(MCS_BOUND); 1556 } 1557 1558 break; 1559 } 1560 case MCS_GIVE_UP: { 1561 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1562 HandlerParams params = mPendingInstalls.remove(0); 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1564 System.identityHashCode(params)); 1565 break; 1566 } 1567 case SEND_PENDING_BROADCAST: { 1568 String packages[]; 1569 ArrayList<String> components[]; 1570 int size = 0; 1571 int uids[]; 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 if (mPendingBroadcasts == null) { 1575 return; 1576 } 1577 size = mPendingBroadcasts.size(); 1578 if (size <= 0) { 1579 // Nothing to be done. Just return 1580 return; 1581 } 1582 packages = new String[size]; 1583 components = new ArrayList[size]; 1584 uids = new int[size]; 1585 int i = 0; // filling out the above arrays 1586 1587 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1588 int packageUserId = mPendingBroadcasts.userIdAt(n); 1589 Iterator<Map.Entry<String, ArrayList<String>>> it 1590 = mPendingBroadcasts.packagesForUserId(packageUserId) 1591 .entrySet().iterator(); 1592 while (it.hasNext() && i < size) { 1593 Map.Entry<String, ArrayList<String>> ent = it.next(); 1594 packages[i] = ent.getKey(); 1595 components[i] = ent.getValue(); 1596 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1597 uids[i] = (ps != null) 1598 ? UserHandle.getUid(packageUserId, ps.appId) 1599 : -1; 1600 i++; 1601 } 1602 } 1603 size = i; 1604 mPendingBroadcasts.clear(); 1605 } 1606 // Send broadcasts 1607 for (int i = 0; i < size; i++) { 1608 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1609 } 1610 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1611 break; 1612 } 1613 case START_CLEANING_PACKAGE: { 1614 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1615 final String packageName = (String)msg.obj; 1616 final int userId = msg.arg1; 1617 final boolean andCode = msg.arg2 != 0; 1618 synchronized (mPackages) { 1619 if (userId == UserHandle.USER_ALL) { 1620 int[] users = sUserManager.getUserIds(); 1621 for (int user : users) { 1622 mSettings.addPackageToCleanLPw( 1623 new PackageCleanItem(user, packageName, andCode)); 1624 } 1625 } else { 1626 mSettings.addPackageToCleanLPw( 1627 new PackageCleanItem(userId, packageName, andCode)); 1628 } 1629 } 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1631 startCleaningPackages(); 1632 } break; 1633 case POST_INSTALL: { 1634 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1635 1636 PostInstallData data = mRunningInstalls.get(msg.arg1); 1637 final boolean didRestore = (msg.arg2 != 0); 1638 mRunningInstalls.delete(msg.arg1); 1639 1640 if (data != null) { 1641 InstallArgs args = data.args; 1642 PackageInstalledInfo parentRes = data.res; 1643 1644 final boolean grantPermissions = (args.installFlags 1645 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1646 final boolean killApp = (args.installFlags 1647 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1648 final String[] grantedPermissions = args.installGrantPermissions; 1649 1650 // Handle the parent package 1651 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1652 grantedPermissions, didRestore, args.installerPackageName, 1653 args.observer); 1654 1655 // Handle the child packages 1656 final int childCount = (parentRes.addedChildPackages != null) 1657 ? parentRes.addedChildPackages.size() : 0; 1658 for (int i = 0; i < childCount; i++) { 1659 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1660 handlePackagePostInstall(childRes, grantPermissions, killApp, 1661 grantedPermissions, false, args.installerPackageName, 1662 args.observer); 1663 } 1664 1665 // Log tracing if needed 1666 if (args.traceMethod != null) { 1667 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1668 args.traceCookie); 1669 } 1670 } else { 1671 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1672 } 1673 1674 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1675 } break; 1676 case UPDATED_MEDIA_STATUS: { 1677 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1678 boolean reportStatus = msg.arg1 == 1; 1679 boolean doGc = msg.arg2 == 1; 1680 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1681 if (doGc) { 1682 // Force a gc to clear up stale containers. 1683 Runtime.getRuntime().gc(); 1684 } 1685 if (msg.obj != null) { 1686 @SuppressWarnings("unchecked") 1687 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1688 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1689 // Unload containers 1690 unloadAllContainers(args); 1691 } 1692 if (reportStatus) { 1693 try { 1694 if (DEBUG_SD_INSTALL) Log.i(TAG, 1695 "Invoking StorageManagerService call back"); 1696 PackageHelper.getStorageManager().finishMediaUpdate(); 1697 } catch (RemoteException e) { 1698 Log.e(TAG, "StorageManagerService not running?"); 1699 } 1700 } 1701 } break; 1702 case WRITE_SETTINGS: { 1703 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1704 synchronized (mPackages) { 1705 removeMessages(WRITE_SETTINGS); 1706 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1707 mSettings.writeLPr(); 1708 mDirtyUsers.clear(); 1709 } 1710 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1711 } break; 1712 case WRITE_PACKAGE_RESTRICTIONS: { 1713 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1714 synchronized (mPackages) { 1715 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1716 for (int userId : mDirtyUsers) { 1717 mSettings.writePackageRestrictionsLPr(userId); 1718 } 1719 mDirtyUsers.clear(); 1720 } 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1722 } break; 1723 case WRITE_PACKAGE_LIST: { 1724 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1725 synchronized (mPackages) { 1726 removeMessages(WRITE_PACKAGE_LIST); 1727 mSettings.writePackageListLPr(msg.arg1); 1728 } 1729 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1730 } break; 1731 case CHECK_PENDING_VERIFICATION: { 1732 final int verificationId = msg.arg1; 1733 final PackageVerificationState state = mPendingVerification.get(verificationId); 1734 1735 if ((state != null) && !state.timeoutExtended()) { 1736 final InstallArgs args = state.getInstallArgs(); 1737 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1738 1739 Slog.i(TAG, "Verification timed out for " + originUri); 1740 mPendingVerification.remove(verificationId); 1741 1742 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1743 1744 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1745 Slog.i(TAG, "Continuing with installation of " + originUri); 1746 state.setVerifierResponse(Binder.getCallingUid(), 1747 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1748 broadcastPackageVerified(verificationId, originUri, 1749 PackageManager.VERIFICATION_ALLOW, 1750 state.getInstallArgs().getUser()); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 broadcastPackageVerified(verificationId, originUri, 1758 PackageManager.VERIFICATION_REJECT, 1759 state.getInstallArgs().getUser()); 1760 } 1761 1762 Trace.asyncTraceEnd( 1763 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1764 1765 processPendingInstall(args, ret); 1766 mHandler.sendEmptyMessage(MCS_UNBIND); 1767 } 1768 break; 1769 } 1770 case PACKAGE_VERIFIED: { 1771 final int verificationId = msg.arg1; 1772 1773 final PackageVerificationState state = mPendingVerification.get(verificationId); 1774 if (state == null) { 1775 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1776 break; 1777 } 1778 1779 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1780 1781 state.setVerifierResponse(response.callerUid, response.code); 1782 1783 if (state.isVerificationComplete()) { 1784 mPendingVerification.remove(verificationId); 1785 1786 final InstallArgs args = state.getInstallArgs(); 1787 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1788 1789 int ret; 1790 if (state.isInstallAllowed()) { 1791 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1792 broadcastPackageVerified(verificationId, originUri, 1793 response.code, state.getInstallArgs().getUser()); 1794 try { 1795 ret = args.copyApk(mContainerService, true); 1796 } catch (RemoteException e) { 1797 Slog.e(TAG, "Could not contact the ContainerService"); 1798 } 1799 } else { 1800 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1801 } 1802 1803 Trace.asyncTraceEnd( 1804 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1805 1806 processPendingInstall(args, ret); 1807 mHandler.sendEmptyMessage(MCS_UNBIND); 1808 } 1809 1810 break; 1811 } 1812 case START_INTENT_FILTER_VERIFICATIONS: { 1813 IFVerificationParams params = (IFVerificationParams) msg.obj; 1814 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1815 params.replacing, params.pkg); 1816 break; 1817 } 1818 case INTENT_FILTER_VERIFIED: { 1819 final int verificationId = msg.arg1; 1820 1821 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1822 verificationId); 1823 if (state == null) { 1824 Slog.w(TAG, "Invalid IntentFilter verification token " 1825 + verificationId + " received"); 1826 break; 1827 } 1828 1829 final int userId = state.getUserId(); 1830 1831 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1832 "Processing IntentFilter verification with token:" 1833 + verificationId + " and userId:" + userId); 1834 1835 final IntentFilterVerificationResponse response = 1836 (IntentFilterVerificationResponse) msg.obj; 1837 1838 state.setVerifierResponse(response.callerUid, response.code); 1839 1840 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1841 "IntentFilter verification with token:" + verificationId 1842 + " and userId:" + userId 1843 + " is settings verifier response with response code:" 1844 + response.code); 1845 1846 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1848 + response.getFailedDomainsString()); 1849 } 1850 1851 if (state.isVerificationComplete()) { 1852 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1853 } else { 1854 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1855 "IntentFilter verification with token:" + verificationId 1856 + " was not said to be complete"); 1857 } 1858 1859 break; 1860 } 1861 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1862 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1863 mInstantAppResolverConnection, 1864 (InstantAppRequest) msg.obj, 1865 mInstantAppInstallerActivity, 1866 mHandler); 1867 } 1868 } 1869 } 1870 } 1871 1872 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1873 boolean killApp, String[] grantedPermissions, 1874 boolean launchedForRestore, String installerPackage, 1875 IPackageInstallObserver2 installObserver) { 1876 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1877 // Send the removed broadcasts 1878 if (res.removedInfo != null) { 1879 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1880 } 1881 1882 // Now that we successfully installed the package, grant runtime 1883 // permissions if requested before broadcasting the install. Also 1884 // for legacy apps in permission review mode we clear the permission 1885 // review flag which is used to emulate runtime permissions for 1886 // legacy apps. 1887 if (grantPermissions) { 1888 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1889 } 1890 1891 final boolean update = res.removedInfo != null 1892 && res.removedInfo.removedPackage != null; 1893 final String origInstallerPackageName = res.removedInfo != null 1894 ? res.removedInfo.installerPackageName : null; 1895 1896 // If this is the first time we have child packages for a disabled privileged 1897 // app that had no children, we grant requested runtime permissions to the new 1898 // children if the parent on the system image had them already granted. 1899 if (res.pkg.parentPackage != null) { 1900 synchronized (mPackages) { 1901 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1902 } 1903 } 1904 1905 synchronized (mPackages) { 1906 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1907 } 1908 1909 final String packageName = res.pkg.applicationInfo.packageName; 1910 1911 // Determine the set of users who are adding this package for 1912 // the first time vs. those who are seeing an update. 1913 int[] firstUsers = EMPTY_INT_ARRAY; 1914 int[] updateUsers = EMPTY_INT_ARRAY; 1915 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1916 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1917 for (int newUser : res.newUsers) { 1918 if (ps.getInstantApp(newUser)) { 1919 continue; 1920 } 1921 if (allNewUsers) { 1922 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1923 continue; 1924 } 1925 boolean isNew = true; 1926 for (int origUser : res.origUsers) { 1927 if (origUser == newUser) { 1928 isNew = false; 1929 break; 1930 } 1931 } 1932 if (isNew) { 1933 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1934 } else { 1935 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1936 } 1937 } 1938 1939 // Send installed broadcasts if the package is not a static shared lib. 1940 if (res.pkg.staticSharedLibName == null) { 1941 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1942 1943 // Send added for users that see the package for the first time 1944 // sendPackageAddedForNewUsers also deals with system apps 1945 int appId = UserHandle.getAppId(res.uid); 1946 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1947 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1948 1949 // Send added for users that don't see the package for the first time 1950 Bundle extras = new Bundle(1); 1951 extras.putInt(Intent.EXTRA_UID, res.uid); 1952 if (update) { 1953 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1954 } 1955 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1956 extras, 0 /*flags*/, 1957 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 1958 if (origInstallerPackageName != null) { 1959 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1960 extras, 0 /*flags*/, 1961 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1962 } 1963 1964 // Send replaced for users that don't see the package for the first time 1965 if (update) { 1966 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1967 packageName, extras, 0 /*flags*/, 1968 null /*targetPackage*/, null /*finishedReceiver*/, 1969 updateUsers); 1970 if (origInstallerPackageName != null) { 1971 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1972 extras, 0 /*flags*/, 1973 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1974 } 1975 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1976 null /*package*/, null /*extras*/, 0 /*flags*/, 1977 packageName /*targetPackage*/, 1978 null /*finishedReceiver*/, updateUsers); 1979 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1980 // First-install and we did a restore, so we're responsible for the 1981 // first-launch broadcast. 1982 if (DEBUG_BACKUP) { 1983 Slog.i(TAG, "Post-restore of " + packageName 1984 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1985 } 1986 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1987 } 1988 1989 // Send broadcast package appeared if forward locked/external for all users 1990 // treat asec-hosted packages like removable media on upgrade 1991 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1992 if (DEBUG_INSTALL) { 1993 Slog.i(TAG, "upgrading pkg " + res.pkg 1994 + " is ASEC-hosted -> AVAILABLE"); 1995 } 1996 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1997 ArrayList<String> pkgList = new ArrayList<>(1); 1998 pkgList.add(packageName); 1999 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2000 } 2001 } 2002 2003 // Work that needs to happen on first install within each user 2004 if (firstUsers != null && firstUsers.length > 0) { 2005 synchronized (mPackages) { 2006 for (int userId : firstUsers) { 2007 // If this app is a browser and it's newly-installed for some 2008 // users, clear any default-browser state in those users. The 2009 // app's nature doesn't depend on the user, so we can just check 2010 // its browser nature in any user and generalize. 2011 if (packageIsBrowser(packageName, userId)) { 2012 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2013 } 2014 2015 // We may also need to apply pending (restored) runtime 2016 // permission grants within these users. 2017 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2018 } 2019 } 2020 } 2021 2022 // Log current value of "unknown sources" setting 2023 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2024 getUnknownSourcesSettings()); 2025 2026 // Force a gc to clear up things 2027 Runtime.getRuntime().gc(); 2028 2029 // Remove the replaced package's older resources safely now 2030 // We delete after a gc for applications on sdcard. 2031 if (res.removedInfo != null && res.removedInfo.args != null) { 2032 synchronized (mInstallLock) { 2033 res.removedInfo.args.doPostDeleteLI(true); 2034 } 2035 } 2036 2037 // Notify DexManager that the package was installed for new users. 2038 // The updated users should already be indexed and the package code paths 2039 // should not change. 2040 // Don't notify the manager for ephemeral apps as they are not expected to 2041 // survive long enough to benefit of background optimizations. 2042 for (int userId : firstUsers) { 2043 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2044 // There's a race currently where some install events may interleave with an uninstall. 2045 // This can lead to package info being null (b/36642664). 2046 if (info != null) { 2047 mDexManager.notifyPackageInstalled(info, userId); 2048 } 2049 } 2050 } 2051 2052 // If someone is watching installs - notify them 2053 if (installObserver != null) { 2054 try { 2055 Bundle extras = extrasForInstallResult(res); 2056 installObserver.onPackageInstalled(res.name, res.returnCode, 2057 res.returnMsg, extras); 2058 } catch (RemoteException e) { 2059 Slog.i(TAG, "Observer no longer exists."); 2060 } 2061 } 2062 } 2063 2064 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2065 PackageParser.Package pkg) { 2066 if (pkg.parentPackage == null) { 2067 return; 2068 } 2069 if (pkg.requestedPermissions == null) { 2070 return; 2071 } 2072 final PackageSetting disabledSysParentPs = mSettings 2073 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2074 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2075 || !disabledSysParentPs.isPrivileged() 2076 || (disabledSysParentPs.childPackageNames != null 2077 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2078 return; 2079 } 2080 final int[] allUserIds = sUserManager.getUserIds(); 2081 final int permCount = pkg.requestedPermissions.size(); 2082 for (int i = 0; i < permCount; i++) { 2083 String permission = pkg.requestedPermissions.get(i); 2084 BasePermission bp = mSettings.mPermissions.get(permission); 2085 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2086 continue; 2087 } 2088 for (int userId : allUserIds) { 2089 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2090 permission, userId)) { 2091 grantRuntimePermission(pkg.packageName, permission, userId); 2092 } 2093 } 2094 } 2095 } 2096 2097 private StorageEventListener mStorageListener = new StorageEventListener() { 2098 @Override 2099 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2100 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2101 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2102 final String volumeUuid = vol.getFsUuid(); 2103 2104 // Clean up any users or apps that were removed or recreated 2105 // while this volume was missing 2106 sUserManager.reconcileUsers(volumeUuid); 2107 reconcileApps(volumeUuid); 2108 2109 // Clean up any install sessions that expired or were 2110 // cancelled while this volume was missing 2111 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2112 2113 loadPrivatePackages(vol); 2114 2115 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2116 unloadPrivatePackages(vol); 2117 } 2118 } 2119 2120 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2121 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2122 updateExternalMediaStatus(true, false); 2123 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2124 updateExternalMediaStatus(false, false); 2125 } 2126 } 2127 } 2128 2129 @Override 2130 public void onVolumeForgotten(String fsUuid) { 2131 if (TextUtils.isEmpty(fsUuid)) { 2132 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2133 return; 2134 } 2135 2136 // Remove any apps installed on the forgotten volume 2137 synchronized (mPackages) { 2138 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2139 for (PackageSetting ps : packages) { 2140 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2141 deletePackageVersioned(new VersionedPackage(ps.name, 2142 PackageManager.VERSION_CODE_HIGHEST), 2143 new LegacyPackageDeleteObserver(null).getBinder(), 2144 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2145 // Try very hard to release any references to this package 2146 // so we don't risk the system server being killed due to 2147 // open FDs 2148 AttributeCache.instance().removePackage(ps.name); 2149 } 2150 2151 mSettings.onVolumeForgotten(fsUuid); 2152 mSettings.writeLPr(); 2153 } 2154 } 2155 }; 2156 2157 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2158 String[] grantedPermissions) { 2159 for (int userId : userIds) { 2160 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2161 } 2162 } 2163 2164 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2165 String[] grantedPermissions) { 2166 SettingBase sb = (SettingBase) pkg.mExtras; 2167 if (sb == null) { 2168 return; 2169 } 2170 2171 PermissionsState permissionsState = sb.getPermissionsState(); 2172 2173 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2174 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2175 2176 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2177 >= Build.VERSION_CODES.M; 2178 2179 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2180 2181 for (String permission : pkg.requestedPermissions) { 2182 final BasePermission bp; 2183 synchronized (mPackages) { 2184 bp = mSettings.mPermissions.get(permission); 2185 } 2186 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2187 && (!instantApp || bp.isInstant()) 2188 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2189 && (grantedPermissions == null 2190 || ArrayUtils.contains(grantedPermissions, permission))) { 2191 final int flags = permissionsState.getPermissionFlags(permission, userId); 2192 if (supportsRuntimePermissions) { 2193 // Installer cannot change immutable permissions. 2194 if ((flags & immutableFlags) == 0) { 2195 grantRuntimePermission(pkg.packageName, permission, userId); 2196 } 2197 } else if (mPermissionReviewRequired) { 2198 // In permission review mode we clear the review flag when we 2199 // are asked to install the app with all permissions granted. 2200 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2201 updatePermissionFlags(permission, pkg.packageName, 2202 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2203 } 2204 } 2205 } 2206 } 2207 } 2208 2209 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2210 Bundle extras = null; 2211 switch (res.returnCode) { 2212 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2213 extras = new Bundle(); 2214 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2215 res.origPermission); 2216 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2217 res.origPackage); 2218 break; 2219 } 2220 case PackageManager.INSTALL_SUCCEEDED: { 2221 extras = new Bundle(); 2222 extras.putBoolean(Intent.EXTRA_REPLACING, 2223 res.removedInfo != null && res.removedInfo.removedPackage != null); 2224 break; 2225 } 2226 } 2227 return extras; 2228 } 2229 2230 void scheduleWriteSettingsLocked() { 2231 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2232 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2233 } 2234 } 2235 2236 void scheduleWritePackageListLocked(int userId) { 2237 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2238 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2239 msg.arg1 = userId; 2240 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2241 } 2242 } 2243 2244 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2245 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2246 scheduleWritePackageRestrictionsLocked(userId); 2247 } 2248 2249 void scheduleWritePackageRestrictionsLocked(int userId) { 2250 final int[] userIds = (userId == UserHandle.USER_ALL) 2251 ? sUserManager.getUserIds() : new int[]{userId}; 2252 for (int nextUserId : userIds) { 2253 if (!sUserManager.exists(nextUserId)) return; 2254 mDirtyUsers.add(nextUserId); 2255 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2256 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2257 } 2258 } 2259 } 2260 2261 public static PackageManagerService main(Context context, Installer installer, 2262 boolean factoryTest, boolean onlyCore) { 2263 // Self-check for initial settings. 2264 PackageManagerServiceCompilerMapping.checkProperties(); 2265 2266 PackageManagerService m = new PackageManagerService(context, installer, 2267 factoryTest, onlyCore); 2268 m.enableSystemUserPackages(); 2269 ServiceManager.addService("package", m); 2270 return m; 2271 } 2272 2273 private void enableSystemUserPackages() { 2274 if (!UserManager.isSplitSystemUser()) { 2275 return; 2276 } 2277 // For system user, enable apps based on the following conditions: 2278 // - app is whitelisted or belong to one of these groups: 2279 // -- system app which has no launcher icons 2280 // -- system app which has INTERACT_ACROSS_USERS permission 2281 // -- system IME app 2282 // - app is not in the blacklist 2283 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2284 Set<String> enableApps = new ArraySet<>(); 2285 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2286 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2287 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2288 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2289 enableApps.addAll(wlApps); 2290 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2291 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2292 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2293 enableApps.removeAll(blApps); 2294 Log.i(TAG, "Applications installed for system user: " + enableApps); 2295 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2296 UserHandle.SYSTEM); 2297 final int allAppsSize = allAps.size(); 2298 synchronized (mPackages) { 2299 for (int i = 0; i < allAppsSize; i++) { 2300 String pName = allAps.get(i); 2301 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2302 // Should not happen, but we shouldn't be failing if it does 2303 if (pkgSetting == null) { 2304 continue; 2305 } 2306 boolean install = enableApps.contains(pName); 2307 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2308 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2309 + " for system user"); 2310 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2311 } 2312 } 2313 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2314 } 2315 } 2316 2317 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2318 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2319 Context.DISPLAY_SERVICE); 2320 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2321 } 2322 2323 /** 2324 * Requests that files preopted on a secondary system partition be copied to the data partition 2325 * if possible. Note that the actual copying of the files is accomplished by init for security 2326 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2327 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2328 */ 2329 private static void requestCopyPreoptedFiles() { 2330 final int WAIT_TIME_MS = 100; 2331 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2332 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2333 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2334 // We will wait for up to 100 seconds. 2335 final long timeStart = SystemClock.uptimeMillis(); 2336 final long timeEnd = timeStart + 100 * 1000; 2337 long timeNow = timeStart; 2338 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2339 try { 2340 Thread.sleep(WAIT_TIME_MS); 2341 } catch (InterruptedException e) { 2342 // Do nothing 2343 } 2344 timeNow = SystemClock.uptimeMillis(); 2345 if (timeNow > timeEnd) { 2346 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2347 Slog.wtf(TAG, "cppreopt did not finish!"); 2348 break; 2349 } 2350 } 2351 2352 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2353 } 2354 } 2355 2356 public PackageManagerService(Context context, Installer installer, 2357 boolean factoryTest, boolean onlyCore) { 2358 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2361 SystemClock.uptimeMillis()); 2362 2363 if (mSdkVersion <= 0) { 2364 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2365 } 2366 2367 mContext = context; 2368 2369 mPermissionReviewRequired = context.getResources().getBoolean( 2370 R.bool.config_permissionReviewRequired); 2371 2372 mFactoryTest = factoryTest; 2373 mOnlyCore = onlyCore; 2374 mMetrics = new DisplayMetrics(); 2375 mSettings = new Settings(mPackages); 2376 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2377 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2378 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2379 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2380 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2381 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2382 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2383 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2384 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2385 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2386 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2387 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2388 2389 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2390 if (separateProcesses != null && separateProcesses.length() > 0) { 2391 if ("*".equals(separateProcesses)) { 2392 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2393 mSeparateProcesses = null; 2394 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2395 } else { 2396 mDefParseFlags = 0; 2397 mSeparateProcesses = separateProcesses.split(","); 2398 Slog.w(TAG, "Running with debug.separate_processes: " 2399 + separateProcesses); 2400 } 2401 } else { 2402 mDefParseFlags = 0; 2403 mSeparateProcesses = null; 2404 } 2405 2406 mInstaller = installer; 2407 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2408 "*dexopt*"); 2409 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2410 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2411 2412 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2413 FgThread.get().getLooper()); 2414 2415 getDefaultDisplayMetrics(context, mMetrics); 2416 2417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2418 SystemConfig systemConfig = SystemConfig.getInstance(); 2419 mGlobalGids = systemConfig.getGlobalGids(); 2420 mSystemPermissions = systemConfig.getSystemPermissions(); 2421 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2423 2424 mProtectedPackages = new ProtectedPackages(mContext); 2425 2426 synchronized (mInstallLock) { 2427 // writer 2428 synchronized (mPackages) { 2429 mHandlerThread = new ServiceThread(TAG, 2430 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2431 mHandlerThread.start(); 2432 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2433 mProcessLoggingHandler = new ProcessLoggingHandler(); 2434 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2435 2436 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2437 mInstantAppRegistry = new InstantAppRegistry(this); 2438 2439 File dataDir = Environment.getDataDirectory(); 2440 mAppInstallDir = new File(dataDir, "app"); 2441 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2442 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2443 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2444 sUserManager = new UserManagerService(context, this, 2445 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2446 2447 // Propagate permission configuration in to package manager. 2448 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2449 = systemConfig.getPermissions(); 2450 for (int i=0; i<permConfig.size(); i++) { 2451 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2452 BasePermission bp = mSettings.mPermissions.get(perm.name); 2453 if (bp == null) { 2454 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2455 mSettings.mPermissions.put(perm.name, bp); 2456 } 2457 if (perm.gids != null) { 2458 bp.setGids(perm.gids, perm.perUser); 2459 } 2460 } 2461 2462 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2463 final int builtInLibCount = libConfig.size(); 2464 for (int i = 0; i < builtInLibCount; i++) { 2465 String name = libConfig.keyAt(i); 2466 String path = libConfig.valueAt(i); 2467 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2468 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2469 } 2470 2471 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2472 2473 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2474 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2475 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2476 2477 // Clean up orphaned packages for which the code path doesn't exist 2478 // and they are an update to a system app - caused by bug/32321269 2479 final int packageSettingCount = mSettings.mPackages.size(); 2480 for (int i = packageSettingCount - 1; i >= 0; i--) { 2481 PackageSetting ps = mSettings.mPackages.valueAt(i); 2482 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2483 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2484 mSettings.mPackages.removeAt(i); 2485 mSettings.enableSystemPackageLPw(ps.name); 2486 } 2487 } 2488 2489 if (mFirstBoot) { 2490 requestCopyPreoptedFiles(); 2491 } 2492 2493 String customResolverActivity = Resources.getSystem().getString( 2494 R.string.config_customResolverActivity); 2495 if (TextUtils.isEmpty(customResolverActivity)) { 2496 customResolverActivity = null; 2497 } else { 2498 mCustomResolverComponentName = ComponentName.unflattenFromString( 2499 customResolverActivity); 2500 } 2501 2502 long startTime = SystemClock.uptimeMillis(); 2503 2504 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2505 startTime); 2506 2507 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2508 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2509 2510 if (bootClassPath == null) { 2511 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2512 } 2513 2514 if (systemServerClassPath == null) { 2515 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2516 } 2517 2518 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2519 2520 final VersionInfo ver = mSettings.getInternalVersion(); 2521 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2522 if (mIsUpgrade) { 2523 logCriticalInfo(Log.INFO, 2524 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2525 } 2526 2527 // when upgrading from pre-M, promote system app permissions from install to runtime 2528 mPromoteSystemApps = 2529 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2530 2531 // When upgrading from pre-N, we need to handle package extraction like first boot, 2532 // as there is no profiling data available. 2533 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2534 2535 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2536 2537 // save off the names of pre-existing system packages prior to scanning; we don't 2538 // want to automatically grant runtime permissions for new system apps 2539 if (mPromoteSystemApps) { 2540 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2541 while (pkgSettingIter.hasNext()) { 2542 PackageSetting ps = pkgSettingIter.next(); 2543 if (isSystemApp(ps)) { 2544 mExistingSystemPackages.add(ps.name); 2545 } 2546 } 2547 } 2548 2549 mCacheDir = preparePackageParserCache(mIsUpgrade); 2550 2551 // Set flag to monitor and not change apk file paths when 2552 // scanning install directories. 2553 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2554 2555 if (mIsUpgrade || mFirstBoot) { 2556 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2557 } 2558 2559 // Collect vendor overlay packages. (Do this before scanning any apps.) 2560 // For security and version matching reason, only consider 2561 // overlay packages if they reside in the right directory. 2562 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2563 | PackageParser.PARSE_IS_SYSTEM 2564 | PackageParser.PARSE_IS_SYSTEM_DIR 2565 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2566 2567 mParallelPackageParserCallback.findStaticOverlayPackages(); 2568 2569 // Find base frameworks (resource packages without code). 2570 scanDirTracedLI(frameworkDir, mDefParseFlags 2571 | PackageParser.PARSE_IS_SYSTEM 2572 | PackageParser.PARSE_IS_SYSTEM_DIR 2573 | PackageParser.PARSE_IS_PRIVILEGED, 2574 scanFlags | SCAN_NO_DEX, 0); 2575 2576 // Collected privileged system packages. 2577 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2578 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2579 | PackageParser.PARSE_IS_SYSTEM 2580 | PackageParser.PARSE_IS_SYSTEM_DIR 2581 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2582 2583 // Collect ordinary system packages. 2584 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2585 scanDirTracedLI(systemAppDir, mDefParseFlags 2586 | PackageParser.PARSE_IS_SYSTEM 2587 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2588 2589 // Collect all vendor packages. 2590 File vendorAppDir = new File("/vendor/app"); 2591 try { 2592 vendorAppDir = vendorAppDir.getCanonicalFile(); 2593 } catch (IOException e) { 2594 // failed to look up canonical path, continue with original one 2595 } 2596 scanDirTracedLI(vendorAppDir, mDefParseFlags 2597 | PackageParser.PARSE_IS_SYSTEM 2598 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2599 2600 // Collect all OEM packages. 2601 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2602 scanDirTracedLI(oemAppDir, mDefParseFlags 2603 | PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2605 2606 // Prune any system packages that no longer exist. 2607 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2608 if (!mOnlyCore) { 2609 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2610 while (psit.hasNext()) { 2611 PackageSetting ps = psit.next(); 2612 2613 /* 2614 * If this is not a system app, it can't be a 2615 * disable system app. 2616 */ 2617 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2618 continue; 2619 } 2620 2621 /* 2622 * If the package is scanned, it's not erased. 2623 */ 2624 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2625 if (scannedPkg != null) { 2626 /* 2627 * If the system app is both scanned and in the 2628 * disabled packages list, then it must have been 2629 * added via OTA. Remove it from the currently 2630 * scanned package so the previously user-installed 2631 * application can be scanned. 2632 */ 2633 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2634 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2635 + ps.name + "; removing system app. Last known codePath=" 2636 + ps.codePathString + ", installStatus=" + ps.installStatus 2637 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2638 + scannedPkg.mVersionCode); 2639 removePackageLI(scannedPkg, true); 2640 mExpectingBetter.put(ps.name, ps.codePath); 2641 } 2642 2643 continue; 2644 } 2645 2646 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2647 psit.remove(); 2648 logCriticalInfo(Log.WARN, "System package " + ps.name 2649 + " no longer exists; it's data will be wiped"); 2650 // Actual deletion of code and data will be handled by later 2651 // reconciliation step 2652 } else { 2653 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2654 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2655 possiblyDeletedUpdatedSystemApps.add(ps.name); 2656 } 2657 } 2658 } 2659 } 2660 2661 //look for any incomplete package installations 2662 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2663 for (int i = 0; i < deletePkgsList.size(); i++) { 2664 // Actual deletion of code and data will be handled by later 2665 // reconciliation step 2666 final String packageName = deletePkgsList.get(i).name; 2667 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2668 synchronized (mPackages) { 2669 mSettings.removePackageLPw(packageName); 2670 } 2671 } 2672 2673 //delete tmp files 2674 deleteTempPackageFiles(); 2675 2676 // Remove any shared userIDs that have no associated packages 2677 mSettings.pruneSharedUsersLPw(); 2678 2679 if (!mOnlyCore) { 2680 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2681 SystemClock.uptimeMillis()); 2682 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2683 2684 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2685 | PackageParser.PARSE_FORWARD_LOCK, 2686 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2687 2688 /** 2689 * Remove disable package settings for any updated system 2690 * apps that were removed via an OTA. If they're not a 2691 * previously-updated app, remove them completely. 2692 * Otherwise, just revoke their system-level permissions. 2693 */ 2694 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2695 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2696 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2697 2698 String msg; 2699 if (deletedPkg == null) { 2700 msg = "Updated system package " + deletedAppName 2701 + " no longer exists; it's data will be wiped"; 2702 // Actual deletion of code and data will be handled by later 2703 // reconciliation step 2704 } else { 2705 msg = "Updated system app + " + deletedAppName 2706 + " no longer present; removing system privileges for " 2707 + deletedAppName; 2708 2709 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2710 2711 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2712 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2713 } 2714 logCriticalInfo(Log.WARN, msg); 2715 } 2716 2717 /** 2718 * Make sure all system apps that we expected to appear on 2719 * the userdata partition actually showed up. If they never 2720 * appeared, crawl back and revive the system version. 2721 */ 2722 for (int i = 0; i < mExpectingBetter.size(); i++) { 2723 final String packageName = mExpectingBetter.keyAt(i); 2724 if (!mPackages.containsKey(packageName)) { 2725 final File scanFile = mExpectingBetter.valueAt(i); 2726 2727 logCriticalInfo(Log.WARN, "Expected better " + packageName 2728 + " but never showed up; reverting to system"); 2729 2730 int reparseFlags = mDefParseFlags; 2731 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2732 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2733 | PackageParser.PARSE_IS_SYSTEM_DIR 2734 | PackageParser.PARSE_IS_PRIVILEGED; 2735 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2736 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2737 | PackageParser.PARSE_IS_SYSTEM_DIR; 2738 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2739 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2740 | PackageParser.PARSE_IS_SYSTEM_DIR; 2741 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2742 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2743 | PackageParser.PARSE_IS_SYSTEM_DIR; 2744 } else { 2745 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2746 continue; 2747 } 2748 2749 mSettings.enableSystemPackageLPw(packageName); 2750 2751 try { 2752 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2753 } catch (PackageManagerException e) { 2754 Slog.e(TAG, "Failed to parse original system package: " 2755 + e.getMessage()); 2756 } 2757 } 2758 } 2759 } 2760 mExpectingBetter.clear(); 2761 2762 // Resolve the storage manager. 2763 mStorageManagerPackage = getStorageManagerPackageName(); 2764 2765 // Resolve protected action filters. Only the setup wizard is allowed to 2766 // have a high priority filter for these actions. 2767 mSetupWizardPackage = getSetupWizardPackageName(); 2768 if (mProtectedFilters.size() > 0) { 2769 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2770 Slog.i(TAG, "No setup wizard;" 2771 + " All protected intents capped to priority 0"); 2772 } 2773 for (ActivityIntentInfo filter : mProtectedFilters) { 2774 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2775 if (DEBUG_FILTERS) { 2776 Slog.i(TAG, "Found setup wizard;" 2777 + " allow priority " + filter.getPriority() + ";" 2778 + " package: " + filter.activity.info.packageName 2779 + " activity: " + filter.activity.className 2780 + " priority: " + filter.getPriority()); 2781 } 2782 // skip setup wizard; allow it to keep the high priority filter 2783 continue; 2784 } 2785 Slog.w(TAG, "Protected action; cap priority to 0;" 2786 + " package: " + filter.activity.info.packageName 2787 + " activity: " + filter.activity.className 2788 + " origPrio: " + filter.getPriority()); 2789 filter.setPriority(0); 2790 } 2791 } 2792 mDeferProtectedFilters = false; 2793 mProtectedFilters.clear(); 2794 2795 // Now that we know all of the shared libraries, update all clients to have 2796 // the correct library paths. 2797 updateAllSharedLibrariesLPw(null); 2798 2799 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2800 // NOTE: We ignore potential failures here during a system scan (like 2801 // the rest of the commands above) because there's precious little we 2802 // can do about it. A settings error is reported, though. 2803 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2804 } 2805 2806 // Now that we know all the packages we are keeping, 2807 // read and update their last usage times. 2808 mPackageUsage.read(mPackages); 2809 mCompilerStats.read(); 2810 2811 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2812 SystemClock.uptimeMillis()); 2813 Slog.i(TAG, "Time to scan packages: " 2814 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2815 + " seconds"); 2816 2817 // If the platform SDK has changed since the last time we booted, 2818 // we need to re-grant app permission to catch any new ones that 2819 // appear. This is really a hack, and means that apps can in some 2820 // cases get permissions that the user didn't initially explicitly 2821 // allow... it would be nice to have some better way to handle 2822 // this situation. 2823 int updateFlags = UPDATE_PERMISSIONS_ALL; 2824 if (ver.sdkVersion != mSdkVersion) { 2825 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2826 + mSdkVersion + "; regranting permissions for internal storage"); 2827 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2828 } 2829 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2830 ver.sdkVersion = mSdkVersion; 2831 2832 // If this is the first boot or an update from pre-M, and it is a normal 2833 // boot, then we need to initialize the default preferred apps across 2834 // all defined users. 2835 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2836 for (UserInfo user : sUserManager.getUsers(true)) { 2837 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2838 applyFactoryDefaultBrowserLPw(user.id); 2839 primeDomainVerificationsLPw(user.id); 2840 } 2841 } 2842 2843 // Prepare storage for system user really early during boot, 2844 // since core system apps like SettingsProvider and SystemUI 2845 // can't wait for user to start 2846 final int storageFlags; 2847 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2848 storageFlags = StorageManager.FLAG_STORAGE_DE; 2849 } else { 2850 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2851 } 2852 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2853 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2854 true /* onlyCoreApps */); 2855 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2856 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2857 Trace.TRACE_TAG_PACKAGE_MANAGER); 2858 traceLog.traceBegin("AppDataFixup"); 2859 try { 2860 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2861 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2862 } catch (InstallerException e) { 2863 Slog.w(TAG, "Trouble fixing GIDs", e); 2864 } 2865 traceLog.traceEnd(); 2866 2867 traceLog.traceBegin("AppDataPrepare"); 2868 if (deferPackages == null || deferPackages.isEmpty()) { 2869 return; 2870 } 2871 int count = 0; 2872 for (String pkgName : deferPackages) { 2873 PackageParser.Package pkg = null; 2874 synchronized (mPackages) { 2875 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2876 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2877 pkg = ps.pkg; 2878 } 2879 } 2880 if (pkg != null) { 2881 synchronized (mInstallLock) { 2882 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2883 true /* maybeMigrateAppData */); 2884 } 2885 count++; 2886 } 2887 } 2888 traceLog.traceEnd(); 2889 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2890 }, "prepareAppData"); 2891 2892 // If this is first boot after an OTA, and a normal boot, then 2893 // we need to clear code cache directories. 2894 // Note that we do *not* clear the application profiles. These remain valid 2895 // across OTAs and are used to drive profile verification (post OTA) and 2896 // profile compilation (without waiting to collect a fresh set of profiles). 2897 if (mIsUpgrade && !onlyCore) { 2898 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2899 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2900 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2901 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2902 // No apps are running this early, so no need to freeze 2903 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2904 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2905 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2906 } 2907 } 2908 ver.fingerprint = Build.FINGERPRINT; 2909 } 2910 2911 checkDefaultBrowser(); 2912 2913 // clear only after permissions and other defaults have been updated 2914 mExistingSystemPackages.clear(); 2915 mPromoteSystemApps = false; 2916 2917 // All the changes are done during package scanning. 2918 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2919 2920 // can downgrade to reader 2921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2922 mSettings.writeLPr(); 2923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2924 2925 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2926 SystemClock.uptimeMillis()); 2927 2928 if (!mOnlyCore) { 2929 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2930 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2931 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2932 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2933 if (mIntentFilterVerifierComponent != null) { 2934 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2935 mIntentFilterVerifierComponent); 2936 } else { 2937 mIntentFilterVerifier = null; 2938 } 2939 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2940 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2941 SharedLibraryInfo.VERSION_UNDEFINED); 2942 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2943 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2944 SharedLibraryInfo.VERSION_UNDEFINED); 2945 } else { 2946 mRequiredVerifierPackage = null; 2947 mRequiredInstallerPackage = null; 2948 mRequiredUninstallerPackage = null; 2949 mIntentFilterVerifierComponent = null; 2950 mIntentFilterVerifier = null; 2951 mServicesSystemSharedLibraryPackageName = null; 2952 mSharedSystemSharedLibraryPackageName = null; 2953 } 2954 2955 mInstallerService = new PackageInstallerService(context, this); 2956 final Pair<ComponentName, String> instantAppResolverComponent = 2957 getInstantAppResolverLPr(); 2958 if (instantAppResolverComponent != null) { 2959 if (DEBUG_EPHEMERAL) { 2960 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2961 } 2962 mInstantAppResolverConnection = new EphemeralResolverConnection( 2963 mContext, instantAppResolverComponent.first, 2964 instantAppResolverComponent.second); 2965 mInstantAppResolverSettingsComponent = 2966 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2967 } else { 2968 mInstantAppResolverConnection = null; 2969 mInstantAppResolverSettingsComponent = null; 2970 } 2971 updateInstantAppInstallerLocked(null); 2972 2973 // Read and update the usage of dex files. 2974 // Do this at the end of PM init so that all the packages have their 2975 // data directory reconciled. 2976 // At this point we know the code paths of the packages, so we can validate 2977 // the disk file and build the internal cache. 2978 // The usage file is expected to be small so loading and verifying it 2979 // should take a fairly small time compare to the other activities (e.g. package 2980 // scanning). 2981 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2982 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2983 for (int userId : currentUserIds) { 2984 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2985 } 2986 mDexManager.load(userPackages); 2987 } // synchronized (mPackages) 2988 } // synchronized (mInstallLock) 2989 2990 // Now after opening every single application zip, make sure they 2991 // are all flushed. Not really needed, but keeps things nice and 2992 // tidy. 2993 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2994 Runtime.getRuntime().gc(); 2995 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2996 2997 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2998 FallbackCategoryProvider.loadFallbacks(); 2999 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3000 3001 // The initial scanning above does many calls into installd while 3002 // holding the mPackages lock, but we're mostly interested in yelling 3003 // once we have a booted system. 3004 mInstaller.setWarnIfHeld(mPackages); 3005 3006 // Expose private service for system components to use. 3007 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3008 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3009 } 3010 3011 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3012 // we're only interested in updating the installer appliction when 1) it's not 3013 // already set or 2) the modified package is the installer 3014 if (mInstantAppInstallerActivity != null 3015 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3016 .equals(modifiedPackage)) { 3017 return; 3018 } 3019 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3020 } 3021 3022 private static File preparePackageParserCache(boolean isUpgrade) { 3023 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3024 return null; 3025 } 3026 3027 // Disable package parsing on eng builds to allow for faster incremental development. 3028 if ("eng".equals(Build.TYPE)) { 3029 return null; 3030 } 3031 3032 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3033 Slog.i(TAG, "Disabling package parser cache due to system property."); 3034 return null; 3035 } 3036 3037 // The base directory for the package parser cache lives under /data/system/. 3038 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3039 "package_cache"); 3040 if (cacheBaseDir == null) { 3041 return null; 3042 } 3043 3044 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3045 // This also serves to "GC" unused entries when the package cache version changes (which 3046 // can only happen during upgrades). 3047 if (isUpgrade) { 3048 FileUtils.deleteContents(cacheBaseDir); 3049 } 3050 3051 3052 // Return the versioned package cache directory. This is something like 3053 // "/data/system/package_cache/1" 3054 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3055 3056 // The following is a workaround to aid development on non-numbered userdebug 3057 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3058 // the system partition is newer. 3059 // 3060 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3061 // that starts with "eng." to signify that this is an engineering build and not 3062 // destined for release. 3063 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3064 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3065 3066 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3067 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3068 // in general and should not be used for production changes. In this specific case, 3069 // we know that they will work. 3070 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3071 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3072 FileUtils.deleteContents(cacheBaseDir); 3073 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3074 } 3075 } 3076 3077 return cacheDir; 3078 } 3079 3080 @Override 3081 public boolean isFirstBoot() { 3082 return mFirstBoot; 3083 } 3084 3085 @Override 3086 public boolean isOnlyCoreApps() { 3087 return mOnlyCore; 3088 } 3089 3090 @Override 3091 public boolean isUpgrade() { 3092 return mIsUpgrade; 3093 } 3094 3095 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3096 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3097 3098 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3099 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3100 UserHandle.USER_SYSTEM); 3101 if (matches.size() == 1) { 3102 return matches.get(0).getComponentInfo().packageName; 3103 } else if (matches.size() == 0) { 3104 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3105 return null; 3106 } 3107 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3108 } 3109 3110 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3111 synchronized (mPackages) { 3112 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3113 if (libraryEntry == null) { 3114 throw new IllegalStateException("Missing required shared library:" + name); 3115 } 3116 return libraryEntry.apk; 3117 } 3118 } 3119 3120 private @NonNull String getRequiredInstallerLPr() { 3121 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3122 intent.addCategory(Intent.CATEGORY_DEFAULT); 3123 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3124 3125 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3126 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3127 UserHandle.USER_SYSTEM); 3128 if (matches.size() == 1) { 3129 ResolveInfo resolveInfo = matches.get(0); 3130 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3131 throw new RuntimeException("The installer must be a privileged app"); 3132 } 3133 return matches.get(0).getComponentInfo().packageName; 3134 } else { 3135 throw new RuntimeException("There must be exactly one installer; found " + matches); 3136 } 3137 } 3138 3139 private @NonNull String getRequiredUninstallerLPr() { 3140 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3141 intent.addCategory(Intent.CATEGORY_DEFAULT); 3142 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3143 3144 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3145 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3146 UserHandle.USER_SYSTEM); 3147 if (resolveInfo == null || 3148 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3149 throw new RuntimeException("There must be exactly one uninstaller; found " 3150 + resolveInfo); 3151 } 3152 return resolveInfo.getComponentInfo().packageName; 3153 } 3154 3155 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3156 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3157 3158 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3159 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3160 UserHandle.USER_SYSTEM); 3161 ResolveInfo best = null; 3162 final int N = matches.size(); 3163 for (int i = 0; i < N; i++) { 3164 final ResolveInfo cur = matches.get(i); 3165 final String packageName = cur.getComponentInfo().packageName; 3166 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3167 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3168 continue; 3169 } 3170 3171 if (best == null || cur.priority > best.priority) { 3172 best = cur; 3173 } 3174 } 3175 3176 if (best != null) { 3177 return best.getComponentInfo().getComponentName(); 3178 } 3179 Slog.w(TAG, "Intent filter verifier not found"); 3180 return null; 3181 } 3182 3183 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3184 final String[] packageArray = 3185 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3186 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3187 if (DEBUG_EPHEMERAL) { 3188 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3189 } 3190 return null; 3191 } 3192 3193 final int callingUid = Binder.getCallingUid(); 3194 final int resolveFlags = 3195 MATCH_DIRECT_BOOT_AWARE 3196 | MATCH_DIRECT_BOOT_UNAWARE 3197 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3198 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3199 final Intent resolverIntent = new Intent(actionName); 3200 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3201 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3202 // temporarily look for the old action 3203 if (resolvers.size() == 0) { 3204 if (DEBUG_EPHEMERAL) { 3205 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3206 } 3207 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3208 resolverIntent.setAction(actionName); 3209 resolvers = queryIntentServicesInternal(resolverIntent, null, 3210 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3211 } 3212 final int N = resolvers.size(); 3213 if (N == 0) { 3214 if (DEBUG_EPHEMERAL) { 3215 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3216 } 3217 return null; 3218 } 3219 3220 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3221 for (int i = 0; i < N; i++) { 3222 final ResolveInfo info = resolvers.get(i); 3223 3224 if (info.serviceInfo == null) { 3225 continue; 3226 } 3227 3228 final String packageName = info.serviceInfo.packageName; 3229 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3230 if (DEBUG_EPHEMERAL) { 3231 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3232 + " pkg: " + packageName + ", info:" + info); 3233 } 3234 continue; 3235 } 3236 3237 if (DEBUG_EPHEMERAL) { 3238 Slog.v(TAG, "Ephemeral resolver found;" 3239 + " pkg: " + packageName + ", info:" + info); 3240 } 3241 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3242 } 3243 if (DEBUG_EPHEMERAL) { 3244 Slog.v(TAG, "Ephemeral resolver NOT found"); 3245 } 3246 return null; 3247 } 3248 3249 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3250 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3251 intent.addCategory(Intent.CATEGORY_DEFAULT); 3252 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3253 3254 final int resolveFlags = 3255 MATCH_DIRECT_BOOT_AWARE 3256 | MATCH_DIRECT_BOOT_UNAWARE 3257 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3258 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3259 resolveFlags, UserHandle.USER_SYSTEM); 3260 // temporarily look for the old action 3261 if (matches.isEmpty()) { 3262 if (DEBUG_EPHEMERAL) { 3263 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3264 } 3265 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3266 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3267 resolveFlags, UserHandle.USER_SYSTEM); 3268 } 3269 Iterator<ResolveInfo> iter = matches.iterator(); 3270 while (iter.hasNext()) { 3271 final ResolveInfo rInfo = iter.next(); 3272 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3273 if (ps != null) { 3274 final PermissionsState permissionsState = ps.getPermissionsState(); 3275 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3276 continue; 3277 } 3278 } 3279 iter.remove(); 3280 } 3281 if (matches.size() == 0) { 3282 return null; 3283 } else if (matches.size() == 1) { 3284 return (ActivityInfo) matches.get(0).getComponentInfo(); 3285 } else { 3286 throw new RuntimeException( 3287 "There must be at most one ephemeral installer; found " + matches); 3288 } 3289 } 3290 3291 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3292 @NonNull ComponentName resolver) { 3293 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3294 .addCategory(Intent.CATEGORY_DEFAULT) 3295 .setPackage(resolver.getPackageName()); 3296 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3297 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3298 UserHandle.USER_SYSTEM); 3299 // temporarily look for the old action 3300 if (matches.isEmpty()) { 3301 if (DEBUG_EPHEMERAL) { 3302 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3303 } 3304 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3305 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3306 UserHandle.USER_SYSTEM); 3307 } 3308 if (matches.isEmpty()) { 3309 return null; 3310 } 3311 return matches.get(0).getComponentInfo().getComponentName(); 3312 } 3313 3314 private void primeDomainVerificationsLPw(int userId) { 3315 if (DEBUG_DOMAIN_VERIFICATION) { 3316 Slog.d(TAG, "Priming domain verifications in user " + userId); 3317 } 3318 3319 SystemConfig systemConfig = SystemConfig.getInstance(); 3320 ArraySet<String> packages = systemConfig.getLinkedApps(); 3321 3322 for (String packageName : packages) { 3323 PackageParser.Package pkg = mPackages.get(packageName); 3324 if (pkg != null) { 3325 if (!pkg.isSystemApp()) { 3326 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3327 continue; 3328 } 3329 3330 ArraySet<String> domains = null; 3331 for (PackageParser.Activity a : pkg.activities) { 3332 for (ActivityIntentInfo filter : a.intents) { 3333 if (hasValidDomains(filter)) { 3334 if (domains == null) { 3335 domains = new ArraySet<String>(); 3336 } 3337 domains.addAll(filter.getHostsList()); 3338 } 3339 } 3340 } 3341 3342 if (domains != null && domains.size() > 0) { 3343 if (DEBUG_DOMAIN_VERIFICATION) { 3344 Slog.v(TAG, " + " + packageName); 3345 } 3346 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3347 // state w.r.t. the formal app-linkage "no verification attempted" state; 3348 // and then 'always' in the per-user state actually used for intent resolution. 3349 final IntentFilterVerificationInfo ivi; 3350 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3351 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3352 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3353 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3354 } else { 3355 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3356 + "' does not handle web links"); 3357 } 3358 } else { 3359 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3360 } 3361 } 3362 3363 scheduleWritePackageRestrictionsLocked(userId); 3364 scheduleWriteSettingsLocked(); 3365 } 3366 3367 private void applyFactoryDefaultBrowserLPw(int userId) { 3368 // The default browser app's package name is stored in a string resource, 3369 // with a product-specific overlay used for vendor customization. 3370 String browserPkg = mContext.getResources().getString( 3371 com.android.internal.R.string.default_browser); 3372 if (!TextUtils.isEmpty(browserPkg)) { 3373 // non-empty string => required to be a known package 3374 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3375 if (ps == null) { 3376 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3377 browserPkg = null; 3378 } else { 3379 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3380 } 3381 } 3382 3383 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3384 // default. If there's more than one, just leave everything alone. 3385 if (browserPkg == null) { 3386 calculateDefaultBrowserLPw(userId); 3387 } 3388 } 3389 3390 private void calculateDefaultBrowserLPw(int userId) { 3391 List<String> allBrowsers = resolveAllBrowserApps(userId); 3392 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3393 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3394 } 3395 3396 private List<String> resolveAllBrowserApps(int userId) { 3397 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3398 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3399 PackageManager.MATCH_ALL, userId); 3400 3401 final int count = list.size(); 3402 List<String> result = new ArrayList<String>(count); 3403 for (int i=0; i<count; i++) { 3404 ResolveInfo info = list.get(i); 3405 if (info.activityInfo == null 3406 || !info.handleAllWebDataURI 3407 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3408 || result.contains(info.activityInfo.packageName)) { 3409 continue; 3410 } 3411 result.add(info.activityInfo.packageName); 3412 } 3413 3414 return result; 3415 } 3416 3417 private boolean packageIsBrowser(String packageName, int userId) { 3418 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3419 PackageManager.MATCH_ALL, userId); 3420 final int N = list.size(); 3421 for (int i = 0; i < N; i++) { 3422 ResolveInfo info = list.get(i); 3423 if (packageName.equals(info.activityInfo.packageName)) { 3424 return true; 3425 } 3426 } 3427 return false; 3428 } 3429 3430 private void checkDefaultBrowser() { 3431 final int myUserId = UserHandle.myUserId(); 3432 final String packageName = getDefaultBrowserPackageName(myUserId); 3433 if (packageName != null) { 3434 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3435 if (info == null) { 3436 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3437 synchronized (mPackages) { 3438 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3439 } 3440 } 3441 } 3442 } 3443 3444 @Override 3445 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3446 throws RemoteException { 3447 try { 3448 return super.onTransact(code, data, reply, flags); 3449 } catch (RuntimeException e) { 3450 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3451 Slog.wtf(TAG, "Package Manager Crash", e); 3452 } 3453 throw e; 3454 } 3455 } 3456 3457 static int[] appendInts(int[] cur, int[] add) { 3458 if (add == null) return cur; 3459 if (cur == null) return add; 3460 final int N = add.length; 3461 for (int i=0; i<N; i++) { 3462 cur = appendInt(cur, add[i]); 3463 } 3464 return cur; 3465 } 3466 3467 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3468 if (!sUserManager.exists(userId)) return null; 3469 if (ps == null) { 3470 return null; 3471 } 3472 final PackageParser.Package p = ps.pkg; 3473 if (p == null) { 3474 return null; 3475 } 3476 // Filter out ephemeral app metadata: 3477 // * The system/shell/root can see metadata for any app 3478 // * An installed app can see metadata for 1) other installed apps 3479 // and 2) ephemeral apps that have explicitly interacted with it 3480 // * Ephemeral apps can only see their own data and exposed installed apps 3481 // * Holding a signature permission allows seeing instant apps 3482 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3483 if (callingAppId != Process.SYSTEM_UID 3484 && callingAppId != Process.SHELL_UID 3485 && callingAppId != Process.ROOT_UID 3486 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3487 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3488 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3489 if (instantAppPackageName != null) { 3490 // ephemeral apps can only get information on themselves or 3491 // installed apps that are exposed. 3492 if (!instantAppPackageName.equals(p.packageName) 3493 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3494 return null; 3495 } 3496 } else { 3497 if (ps.getInstantApp(userId)) { 3498 // only get access to the ephemeral app if we've been granted access 3499 if (!mInstantAppRegistry.isInstantAccessGranted( 3500 userId, callingAppId, ps.appId)) { 3501 return null; 3502 } 3503 } 3504 } 3505 } 3506 3507 final PermissionsState permissionsState = ps.getPermissionsState(); 3508 3509 // Compute GIDs only if requested 3510 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3511 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3512 // Compute granted permissions only if package has requested permissions 3513 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3514 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3515 final PackageUserState state = ps.readUserState(userId); 3516 3517 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3518 && ps.isSystem()) { 3519 flags |= MATCH_ANY_USER; 3520 } 3521 3522 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3523 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3524 3525 if (packageInfo == null) { 3526 return null; 3527 } 3528 3529 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3530 3531 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3532 resolveExternalPackageNameLPr(p); 3533 3534 return packageInfo; 3535 } 3536 3537 @Override 3538 public void checkPackageStartable(String packageName, int userId) { 3539 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3540 3541 synchronized (mPackages) { 3542 final PackageSetting ps = mSettings.mPackages.get(packageName); 3543 if (ps == null) { 3544 throw new SecurityException("Package " + packageName + " was not found!"); 3545 } 3546 3547 if (!ps.getInstalled(userId)) { 3548 throw new SecurityException( 3549 "Package " + packageName + " was not installed for user " + userId + "!"); 3550 } 3551 3552 if (mSafeMode && !ps.isSystem()) { 3553 throw new SecurityException("Package " + packageName + " not a system app!"); 3554 } 3555 3556 if (mFrozenPackages.contains(packageName)) { 3557 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3558 } 3559 3560 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3561 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3562 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3563 } 3564 } 3565 } 3566 3567 @Override 3568 public boolean isPackageAvailable(String packageName, int userId) { 3569 if (!sUserManager.exists(userId)) return false; 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3571 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3572 synchronized (mPackages) { 3573 PackageParser.Package p = mPackages.get(packageName); 3574 if (p != null) { 3575 final PackageSetting ps = (PackageSetting) p.mExtras; 3576 if (ps != null) { 3577 final PackageUserState state = ps.readUserState(userId); 3578 if (state != null) { 3579 return PackageParser.isAvailable(state); 3580 } 3581 } 3582 } 3583 } 3584 return false; 3585 } 3586 3587 @Override 3588 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3589 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3590 flags, userId); 3591 } 3592 3593 @Override 3594 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3595 int flags, int userId) { 3596 return getPackageInfoInternal(versionedPackage.getPackageName(), 3597 // TODO: We will change version code to long, so in the new API it is long 3598 (int) versionedPackage.getVersionCode(), flags, userId); 3599 } 3600 3601 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3602 int flags, int userId) { 3603 if (!sUserManager.exists(userId)) return null; 3604 flags = updateFlagsForPackage(flags, userId, packageName); 3605 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3606 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3607 3608 // reader 3609 synchronized (mPackages) { 3610 // Normalize package name to handle renamed packages and static libs 3611 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3612 3613 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3614 if (matchFactoryOnly) { 3615 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3616 if (ps != null) { 3617 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3618 return null; 3619 } 3620 return generatePackageInfo(ps, flags, userId); 3621 } 3622 } 3623 3624 PackageParser.Package p = mPackages.get(packageName); 3625 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3626 return null; 3627 } 3628 if (DEBUG_PACKAGE_INFO) 3629 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3630 if (p != null) { 3631 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3632 Binder.getCallingUid(), userId)) { 3633 return null; 3634 } 3635 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3636 } 3637 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3638 final PackageSetting ps = mSettings.mPackages.get(packageName); 3639 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3640 return null; 3641 } 3642 return generatePackageInfo(ps, flags, userId); 3643 } 3644 } 3645 return null; 3646 } 3647 3648 3649 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3650 // System/shell/root get to see all static libs 3651 final int appId = UserHandle.getAppId(uid); 3652 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3653 || appId == Process.ROOT_UID) { 3654 return false; 3655 } 3656 3657 // No package means no static lib as it is always on internal storage 3658 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3659 return false; 3660 } 3661 3662 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3663 ps.pkg.staticSharedLibVersion); 3664 if (libEntry == null) { 3665 return false; 3666 } 3667 3668 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3669 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3670 if (uidPackageNames == null) { 3671 return true; 3672 } 3673 3674 for (String uidPackageName : uidPackageNames) { 3675 if (ps.name.equals(uidPackageName)) { 3676 return false; 3677 } 3678 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3679 if (uidPs != null) { 3680 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3681 libEntry.info.getName()); 3682 if (index < 0) { 3683 continue; 3684 } 3685 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3686 return false; 3687 } 3688 } 3689 } 3690 return true; 3691 } 3692 3693 @Override 3694 public String[] currentToCanonicalPackageNames(String[] names) { 3695 String[] out = new String[names.length]; 3696 // reader 3697 synchronized (mPackages) { 3698 for (int i=names.length-1; i>=0; i--) { 3699 PackageSetting ps = mSettings.mPackages.get(names[i]); 3700 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3701 } 3702 } 3703 return out; 3704 } 3705 3706 @Override 3707 public String[] canonicalToCurrentPackageNames(String[] names) { 3708 String[] out = new String[names.length]; 3709 // reader 3710 synchronized (mPackages) { 3711 for (int i=names.length-1; i>=0; i--) { 3712 String cur = mSettings.getRenamedPackageLPr(names[i]); 3713 out[i] = cur != null ? cur : names[i]; 3714 } 3715 } 3716 return out; 3717 } 3718 3719 @Override 3720 public int getPackageUid(String packageName, int flags, int userId) { 3721 if (!sUserManager.exists(userId)) return -1; 3722 flags = updateFlagsForPackage(flags, userId, packageName); 3723 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3724 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3725 3726 // reader 3727 synchronized (mPackages) { 3728 final PackageParser.Package p = mPackages.get(packageName); 3729 if (p != null && p.isMatch(flags)) { 3730 return UserHandle.getUid(userId, p.applicationInfo.uid); 3731 } 3732 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3733 final PackageSetting ps = mSettings.mPackages.get(packageName); 3734 if (ps != null && ps.isMatch(flags)) { 3735 return UserHandle.getUid(userId, ps.appId); 3736 } 3737 } 3738 } 3739 3740 return -1; 3741 } 3742 3743 @Override 3744 public int[] getPackageGids(String packageName, int flags, int userId) { 3745 if (!sUserManager.exists(userId)) return null; 3746 flags = updateFlagsForPackage(flags, userId, packageName); 3747 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3748 false /* requireFullPermission */, false /* checkShell */, 3749 "getPackageGids"); 3750 3751 // reader 3752 synchronized (mPackages) { 3753 final PackageParser.Package p = mPackages.get(packageName); 3754 if (p != null && p.isMatch(flags)) { 3755 PackageSetting ps = (PackageSetting) p.mExtras; 3756 // TODO: Shouldn't this be checking for package installed state for userId and 3757 // return null? 3758 return ps.getPermissionsState().computeGids(userId); 3759 } 3760 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3761 final PackageSetting ps = mSettings.mPackages.get(packageName); 3762 if (ps != null && ps.isMatch(flags)) { 3763 return ps.getPermissionsState().computeGids(userId); 3764 } 3765 } 3766 } 3767 3768 return null; 3769 } 3770 3771 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3772 if (bp.perm != null) { 3773 return PackageParser.generatePermissionInfo(bp.perm, flags); 3774 } 3775 PermissionInfo pi = new PermissionInfo(); 3776 pi.name = bp.name; 3777 pi.packageName = bp.sourcePackage; 3778 pi.nonLocalizedLabel = bp.name; 3779 pi.protectionLevel = bp.protectionLevel; 3780 return pi; 3781 } 3782 3783 @Override 3784 public PermissionInfo getPermissionInfo(String name, int flags) { 3785 // reader 3786 synchronized (mPackages) { 3787 final BasePermission p = mSettings.mPermissions.get(name); 3788 if (p != null) { 3789 return generatePermissionInfo(p, flags); 3790 } 3791 return null; 3792 } 3793 } 3794 3795 @Override 3796 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3797 int flags) { 3798 // reader 3799 synchronized (mPackages) { 3800 if (group != null && !mPermissionGroups.containsKey(group)) { 3801 // This is thrown as NameNotFoundException 3802 return null; 3803 } 3804 3805 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3806 for (BasePermission p : mSettings.mPermissions.values()) { 3807 if (group == null) { 3808 if (p.perm == null || p.perm.info.group == null) { 3809 out.add(generatePermissionInfo(p, flags)); 3810 } 3811 } else { 3812 if (p.perm != null && group.equals(p.perm.info.group)) { 3813 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3814 } 3815 } 3816 } 3817 return new ParceledListSlice<>(out); 3818 } 3819 } 3820 3821 @Override 3822 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3823 // reader 3824 synchronized (mPackages) { 3825 return PackageParser.generatePermissionGroupInfo( 3826 mPermissionGroups.get(name), flags); 3827 } 3828 } 3829 3830 @Override 3831 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3832 // reader 3833 synchronized (mPackages) { 3834 final int N = mPermissionGroups.size(); 3835 ArrayList<PermissionGroupInfo> out 3836 = new ArrayList<PermissionGroupInfo>(N); 3837 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3838 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3839 } 3840 return new ParceledListSlice<>(out); 3841 } 3842 } 3843 3844 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3845 int uid, int userId) { 3846 if (!sUserManager.exists(userId)) return null; 3847 PackageSetting ps = mSettings.mPackages.get(packageName); 3848 if (ps != null) { 3849 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3850 return null; 3851 } 3852 if (ps.pkg == null) { 3853 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3854 if (pInfo != null) { 3855 return pInfo.applicationInfo; 3856 } 3857 return null; 3858 } 3859 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3860 ps.readUserState(userId), userId); 3861 if (ai != null) { 3862 rebaseEnabledOverlays(ai, userId); 3863 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3864 } 3865 return ai; 3866 } 3867 return null; 3868 } 3869 3870 @Override 3871 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3872 if (!sUserManager.exists(userId)) return null; 3873 flags = updateFlagsForApplication(flags, userId, packageName); 3874 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3875 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3876 3877 // writer 3878 synchronized (mPackages) { 3879 // Normalize package name to handle renamed packages and static libs 3880 packageName = resolveInternalPackageNameLPr(packageName, 3881 PackageManager.VERSION_CODE_HIGHEST); 3882 3883 PackageParser.Package p = mPackages.get(packageName); 3884 if (DEBUG_PACKAGE_INFO) Log.v( 3885 TAG, "getApplicationInfo " + packageName 3886 + ": " + p); 3887 if (p != null) { 3888 PackageSetting ps = mSettings.mPackages.get(packageName); 3889 if (ps == null) return null; 3890 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3891 return null; 3892 } 3893 // Note: isEnabledLP() does not apply here - always return info 3894 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3895 p, flags, ps.readUserState(userId), userId); 3896 if (ai != null) { 3897 rebaseEnabledOverlays(ai, userId); 3898 ai.packageName = resolveExternalPackageNameLPr(p); 3899 } 3900 return ai; 3901 } 3902 if ("android".equals(packageName)||"system".equals(packageName)) { 3903 return mAndroidApplication; 3904 } 3905 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3906 // Already generates the external package name 3907 return generateApplicationInfoFromSettingsLPw(packageName, 3908 Binder.getCallingUid(), flags, userId); 3909 } 3910 } 3911 return null; 3912 } 3913 3914 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3915 List<String> paths = new ArrayList<>(); 3916 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3917 mEnabledOverlayPaths.get(userId); 3918 if (userSpecificOverlays != null) { 3919 if (!"android".equals(ai.packageName)) { 3920 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3921 if (frameworkOverlays != null) { 3922 paths.addAll(frameworkOverlays); 3923 } 3924 } 3925 3926 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3927 if (appOverlays != null) { 3928 paths.addAll(appOverlays); 3929 } 3930 } 3931 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3932 } 3933 3934 private String normalizePackageNameLPr(String packageName) { 3935 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3936 return normalizedPackageName != null ? normalizedPackageName : packageName; 3937 } 3938 3939 @Override 3940 public void deletePreloadsFileCache() { 3941 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3942 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3943 } 3944 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3945 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3946 FileUtils.deleteContents(dir); 3947 } 3948 3949 @Override 3950 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3951 final IPackageDataObserver observer) { 3952 mContext.enforceCallingOrSelfPermission( 3953 android.Manifest.permission.CLEAR_APP_CACHE, null); 3954 mHandler.post(() -> { 3955 boolean success = false; 3956 try { 3957 freeStorage(volumeUuid, freeStorageSize, 0); 3958 success = true; 3959 } catch (IOException e) { 3960 Slog.w(TAG, e); 3961 } 3962 if (observer != null) { 3963 try { 3964 observer.onRemoveCompleted(null, success); 3965 } catch (RemoteException e) { 3966 Slog.w(TAG, e); 3967 } 3968 } 3969 }); 3970 } 3971 3972 @Override 3973 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3974 final IntentSender pi) { 3975 mContext.enforceCallingOrSelfPermission( 3976 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3977 mHandler.post(() -> { 3978 boolean success = false; 3979 try { 3980 freeStorage(volumeUuid, freeStorageSize, 0); 3981 success = true; 3982 } catch (IOException e) { 3983 Slog.w(TAG, e); 3984 } 3985 if (pi != null) { 3986 try { 3987 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3988 } catch (SendIntentException e) { 3989 Slog.w(TAG, e); 3990 } 3991 } 3992 }); 3993 } 3994 3995 /** 3996 * Blocking call to clear various types of cached data across the system 3997 * until the requested bytes are available. 3998 */ 3999 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4000 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4001 final File file = storage.findPathForUuid(volumeUuid); 4002 if (file.getUsableSpace() >= bytes) return; 4003 4004 if (ENABLE_FREE_CACHE_V2) { 4005 final boolean aggressive = (storageFlags 4006 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4007 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4008 volumeUuid); 4009 4010 // 1. Pre-flight to determine if we have any chance to succeed 4011 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4012 if (internalVolume && (aggressive || SystemProperties 4013 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4014 deletePreloadsFileCache(); 4015 if (file.getUsableSpace() >= bytes) return; 4016 } 4017 4018 // 3. Consider parsed APK data (aggressive only) 4019 if (internalVolume && aggressive) { 4020 FileUtils.deleteContents(mCacheDir); 4021 if (file.getUsableSpace() >= bytes) return; 4022 } 4023 4024 // 4. Consider cached app data (above quotas) 4025 try { 4026 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 4027 } catch (InstallerException ignored) { 4028 } 4029 if (file.getUsableSpace() >= bytes) return; 4030 4031 // 5. Consider shared libraries with refcount=0 and age>2h 4032 // 6. Consider dexopt output (aggressive only) 4033 // 7. Consider ephemeral apps not used in last week 4034 4035 // 8. Consider cached app data (below quotas) 4036 try { 4037 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 4038 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4039 } catch (InstallerException ignored) { 4040 } 4041 if (file.getUsableSpace() >= bytes) return; 4042 4043 // 9. Consider DropBox entries 4044 // 10. Consider ephemeral cookies 4045 4046 } else { 4047 try { 4048 mInstaller.freeCache(volumeUuid, bytes, 0); 4049 } catch (InstallerException ignored) { 4050 } 4051 if (file.getUsableSpace() >= bytes) return; 4052 } 4053 4054 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4055 } 4056 4057 /** 4058 * Update given flags based on encryption status of current user. 4059 */ 4060 private int updateFlags(int flags, int userId) { 4061 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4062 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4063 // Caller expressed an explicit opinion about what encryption 4064 // aware/unaware components they want to see, so fall through and 4065 // give them what they want 4066 } else { 4067 // Caller expressed no opinion, so match based on user state 4068 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4069 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4070 } else { 4071 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4072 } 4073 } 4074 return flags; 4075 } 4076 4077 private UserManagerInternal getUserManagerInternal() { 4078 if (mUserManagerInternal == null) { 4079 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4080 } 4081 return mUserManagerInternal; 4082 } 4083 4084 private DeviceIdleController.LocalService getDeviceIdleController() { 4085 if (mDeviceIdleController == null) { 4086 mDeviceIdleController = 4087 LocalServices.getService(DeviceIdleController.LocalService.class); 4088 } 4089 return mDeviceIdleController; 4090 } 4091 4092 /** 4093 * Update given flags when being used to request {@link PackageInfo}. 4094 */ 4095 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4096 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4097 boolean triaged = true; 4098 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4099 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4100 // Caller is asking for component details, so they'd better be 4101 // asking for specific encryption matching behavior, or be triaged 4102 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4103 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4104 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4105 triaged = false; 4106 } 4107 } 4108 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4109 | PackageManager.MATCH_SYSTEM_ONLY 4110 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4111 triaged = false; 4112 } 4113 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4114 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4115 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4116 + Debug.getCallers(5)); 4117 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4118 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4119 // If the caller wants all packages and has a restricted profile associated with it, 4120 // then match all users. This is to make sure that launchers that need to access work 4121 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4122 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4123 flags |= PackageManager.MATCH_ANY_USER; 4124 } 4125 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4126 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4127 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4128 } 4129 return updateFlags(flags, userId); 4130 } 4131 4132 /** 4133 * Update given flags when being used to request {@link ApplicationInfo}. 4134 */ 4135 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4136 return updateFlagsForPackage(flags, userId, cookie); 4137 } 4138 4139 /** 4140 * Update given flags when being used to request {@link ComponentInfo}. 4141 */ 4142 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4143 if (cookie instanceof Intent) { 4144 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4145 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4146 } 4147 } 4148 4149 boolean triaged = true; 4150 // Caller is asking for component details, so they'd better be 4151 // asking for specific encryption matching behavior, or be triaged 4152 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4153 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4154 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4155 triaged = false; 4156 } 4157 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4158 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4159 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4160 } 4161 4162 return updateFlags(flags, userId); 4163 } 4164 4165 /** 4166 * Update given intent when being used to request {@link ResolveInfo}. 4167 */ 4168 private Intent updateIntentForResolve(Intent intent) { 4169 if (intent.getSelector() != null) { 4170 intent = intent.getSelector(); 4171 } 4172 if (DEBUG_PREFERRED) { 4173 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4174 } 4175 return intent; 4176 } 4177 4178 /** 4179 * Update given flags when being used to request {@link ResolveInfo}. 4180 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4181 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4182 * flag set. However, this flag is only honoured in three circumstances: 4183 * <ul> 4184 * <li>when called from a system process</li> 4185 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4186 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4187 * action and a {@code android.intent.category.BROWSABLE} category</li> 4188 * </ul> 4189 */ 4190 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4191 return updateFlagsForResolve(flags, userId, intent, callingUid, 4192 false /*includeInstantApps*/, false /*onlyExposedExplicitly*/); 4193 } 4194 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4195 boolean includeInstantApps) { 4196 return updateFlagsForResolve(flags, userId, intent, callingUid, 4197 includeInstantApps, false /*onlyExposedExplicitly*/); 4198 } 4199 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4200 boolean includeInstantApps, boolean onlyExposedExplicitly) { 4201 // Safe mode means we shouldn't match any third-party components 4202 if (mSafeMode) { 4203 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4204 } 4205 if (getInstantAppPackageName(callingUid) != null) { 4206 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4207 if (onlyExposedExplicitly) { 4208 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4209 } 4210 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4211 flags |= PackageManager.MATCH_INSTANT; 4212 } else { 4213 // Otherwise, prevent leaking ephemeral components 4214 final boolean isSpecialProcess = 4215 callingUid == Process.SYSTEM_UID 4216 || callingUid == Process.SHELL_UID 4217 || callingUid == 0; 4218 final boolean allowMatchInstant = 4219 (includeInstantApps 4220 && Intent.ACTION_VIEW.equals(intent.getAction()) 4221 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4222 && hasWebURI(intent)) 4223 || isSpecialProcess 4224 || mContext.checkCallingOrSelfPermission( 4225 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4226 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4227 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4228 if (!allowMatchInstant) { 4229 flags &= ~PackageManager.MATCH_INSTANT; 4230 } 4231 } 4232 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4233 } 4234 4235 private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state, 4236 int userId) { 4237 ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId); 4238 if (ret != null) { 4239 rebaseEnabledOverlays(ret.applicationInfo, userId); 4240 } 4241 return ret; 4242 } 4243 4244 private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags, 4245 PackageUserState state, int userId) { 4246 ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId); 4247 if (ai != null) { 4248 rebaseEnabledOverlays(ai.applicationInfo, userId); 4249 } 4250 return ai; 4251 } 4252 4253 @Override 4254 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4255 if (!sUserManager.exists(userId)) return null; 4256 flags = updateFlagsForComponent(flags, userId, component); 4257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4258 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4259 synchronized (mPackages) { 4260 PackageParser.Activity a = mActivities.mActivities.get(component); 4261 4262 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4263 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4264 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4265 if (ps == null) return null; 4266 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4267 } 4268 if (mResolveComponentName.equals(component)) { 4269 return generateActivityInfo(mResolveActivity, flags, new PackageUserState(), 4270 userId); 4271 } 4272 } 4273 return null; 4274 } 4275 4276 @Override 4277 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4278 String resolvedType) { 4279 synchronized (mPackages) { 4280 if (component.equals(mResolveComponentName)) { 4281 // The resolver supports EVERYTHING! 4282 return true; 4283 } 4284 PackageParser.Activity a = mActivities.mActivities.get(component); 4285 if (a == null) { 4286 return false; 4287 } 4288 for (int i=0; i<a.intents.size(); i++) { 4289 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4290 intent.getData(), intent.getCategories(), TAG) >= 0) { 4291 return true; 4292 } 4293 } 4294 return false; 4295 } 4296 } 4297 4298 @Override 4299 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4300 if (!sUserManager.exists(userId)) return null; 4301 flags = updateFlagsForComponent(flags, userId, component); 4302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4303 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4304 synchronized (mPackages) { 4305 PackageParser.Activity a = mReceivers.mActivities.get(component); 4306 if (DEBUG_PACKAGE_INFO) Log.v( 4307 TAG, "getReceiverInfo " + component + ": " + a); 4308 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4309 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4310 if (ps == null) return null; 4311 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4312 } 4313 } 4314 return null; 4315 } 4316 4317 @Override 4318 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4319 if (!sUserManager.exists(userId)) return null; 4320 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4321 4322 flags = updateFlagsForPackage(flags, userId, null); 4323 4324 final boolean canSeeStaticLibraries = 4325 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4326 == PERMISSION_GRANTED 4327 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4328 == PERMISSION_GRANTED 4329 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4330 == PERMISSION_GRANTED 4331 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4332 == PERMISSION_GRANTED; 4333 4334 synchronized (mPackages) { 4335 List<SharedLibraryInfo> result = null; 4336 4337 final int libCount = mSharedLibraries.size(); 4338 for (int i = 0; i < libCount; i++) { 4339 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4340 if (versionedLib == null) { 4341 continue; 4342 } 4343 4344 final int versionCount = versionedLib.size(); 4345 for (int j = 0; j < versionCount; j++) { 4346 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4347 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4348 break; 4349 } 4350 final long identity = Binder.clearCallingIdentity(); 4351 try { 4352 // TODO: We will change version code to long, so in the new API it is long 4353 PackageInfo packageInfo = getPackageInfoVersioned( 4354 libInfo.getDeclaringPackage(), flags, userId); 4355 if (packageInfo == null) { 4356 continue; 4357 } 4358 } finally { 4359 Binder.restoreCallingIdentity(identity); 4360 } 4361 4362 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4363 libInfo.getVersion(), libInfo.getType(), 4364 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4365 flags, userId)); 4366 4367 if (result == null) { 4368 result = new ArrayList<>(); 4369 } 4370 result.add(resLibInfo); 4371 } 4372 } 4373 4374 return result != null ? new ParceledListSlice<>(result) : null; 4375 } 4376 } 4377 4378 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4379 SharedLibraryInfo libInfo, int flags, int userId) { 4380 List<VersionedPackage> versionedPackages = null; 4381 final int packageCount = mSettings.mPackages.size(); 4382 for (int i = 0; i < packageCount; i++) { 4383 PackageSetting ps = mSettings.mPackages.valueAt(i); 4384 4385 if (ps == null) { 4386 continue; 4387 } 4388 4389 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4390 continue; 4391 } 4392 4393 final String libName = libInfo.getName(); 4394 if (libInfo.isStatic()) { 4395 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4396 if (libIdx < 0) { 4397 continue; 4398 } 4399 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4400 continue; 4401 } 4402 if (versionedPackages == null) { 4403 versionedPackages = new ArrayList<>(); 4404 } 4405 // If the dependent is a static shared lib, use the public package name 4406 String dependentPackageName = ps.name; 4407 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4408 dependentPackageName = ps.pkg.manifestPackageName; 4409 } 4410 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4411 } else if (ps.pkg != null) { 4412 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4413 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4414 if (versionedPackages == null) { 4415 versionedPackages = new ArrayList<>(); 4416 } 4417 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4418 } 4419 } 4420 } 4421 4422 return versionedPackages; 4423 } 4424 4425 @Override 4426 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4427 if (!sUserManager.exists(userId)) return null; 4428 flags = updateFlagsForComponent(flags, userId, component); 4429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4430 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4431 synchronized (mPackages) { 4432 PackageParser.Service s = mServices.mServices.get(component); 4433 if (DEBUG_PACKAGE_INFO) Log.v( 4434 TAG, "getServiceInfo " + component + ": " + s); 4435 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4436 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4437 if (ps == null) return null; 4438 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4439 ps.readUserState(userId), userId); 4440 if (si != null) { 4441 rebaseEnabledOverlays(si.applicationInfo, userId); 4442 } 4443 return si; 4444 } 4445 } 4446 return null; 4447 } 4448 4449 @Override 4450 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4451 if (!sUserManager.exists(userId)) return null; 4452 flags = updateFlagsForComponent(flags, userId, component); 4453 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4454 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4455 synchronized (mPackages) { 4456 PackageParser.Provider p = mProviders.mProviders.get(component); 4457 if (DEBUG_PACKAGE_INFO) Log.v( 4458 TAG, "getProviderInfo " + component + ": " + p); 4459 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4460 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4461 if (ps == null) return null; 4462 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4463 ps.readUserState(userId), userId); 4464 if (pi != null) { 4465 rebaseEnabledOverlays(pi.applicationInfo, userId); 4466 } 4467 return pi; 4468 } 4469 } 4470 return null; 4471 } 4472 4473 @Override 4474 public String[] getSystemSharedLibraryNames() { 4475 synchronized (mPackages) { 4476 Set<String> libs = null; 4477 final int libCount = mSharedLibraries.size(); 4478 for (int i = 0; i < libCount; i++) { 4479 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4480 if (versionedLib == null) { 4481 continue; 4482 } 4483 final int versionCount = versionedLib.size(); 4484 for (int j = 0; j < versionCount; j++) { 4485 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4486 if (!libEntry.info.isStatic()) { 4487 if (libs == null) { 4488 libs = new ArraySet<>(); 4489 } 4490 libs.add(libEntry.info.getName()); 4491 break; 4492 } 4493 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4494 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4495 UserHandle.getUserId(Binder.getCallingUid()))) { 4496 if (libs == null) { 4497 libs = new ArraySet<>(); 4498 } 4499 libs.add(libEntry.info.getName()); 4500 break; 4501 } 4502 } 4503 } 4504 4505 if (libs != null) { 4506 String[] libsArray = new String[libs.size()]; 4507 libs.toArray(libsArray); 4508 return libsArray; 4509 } 4510 4511 return null; 4512 } 4513 } 4514 4515 @Override 4516 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4517 synchronized (mPackages) { 4518 return mServicesSystemSharedLibraryPackageName; 4519 } 4520 } 4521 4522 @Override 4523 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4524 synchronized (mPackages) { 4525 return mSharedSystemSharedLibraryPackageName; 4526 } 4527 } 4528 4529 private void updateSequenceNumberLP(String packageName, int[] userList) { 4530 for (int i = userList.length - 1; i >= 0; --i) { 4531 final int userId = userList[i]; 4532 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4533 if (changedPackages == null) { 4534 changedPackages = new SparseArray<>(); 4535 mChangedPackages.put(userId, changedPackages); 4536 } 4537 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4538 if (sequenceNumbers == null) { 4539 sequenceNumbers = new HashMap<>(); 4540 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4541 } 4542 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4543 if (sequenceNumber != null) { 4544 changedPackages.remove(sequenceNumber); 4545 } 4546 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4547 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4548 } 4549 mChangedPackagesSequenceNumber++; 4550 } 4551 4552 @Override 4553 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4554 synchronized (mPackages) { 4555 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4556 return null; 4557 } 4558 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4559 if (changedPackages == null) { 4560 return null; 4561 } 4562 final List<String> packageNames = 4563 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4564 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4565 final String packageName = changedPackages.get(i); 4566 if (packageName != null) { 4567 packageNames.add(packageName); 4568 } 4569 } 4570 return packageNames.isEmpty() 4571 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4572 } 4573 } 4574 4575 @Override 4576 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4577 ArrayList<FeatureInfo> res; 4578 synchronized (mAvailableFeatures) { 4579 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4580 res.addAll(mAvailableFeatures.values()); 4581 } 4582 final FeatureInfo fi = new FeatureInfo(); 4583 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4584 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4585 res.add(fi); 4586 4587 return new ParceledListSlice<>(res); 4588 } 4589 4590 @Override 4591 public boolean hasSystemFeature(String name, int version) { 4592 synchronized (mAvailableFeatures) { 4593 final FeatureInfo feat = mAvailableFeatures.get(name); 4594 if (feat == null) { 4595 return false; 4596 } else { 4597 return feat.version >= version; 4598 } 4599 } 4600 } 4601 4602 @Override 4603 public int checkPermission(String permName, String pkgName, int userId) { 4604 if (!sUserManager.exists(userId)) { 4605 return PackageManager.PERMISSION_DENIED; 4606 } 4607 4608 synchronized (mPackages) { 4609 final PackageParser.Package p = mPackages.get(pkgName); 4610 if (p != null && p.mExtras != null) { 4611 final PackageSetting ps = (PackageSetting) p.mExtras; 4612 final PermissionsState permissionsState = ps.getPermissionsState(); 4613 if (permissionsState.hasPermission(permName, userId)) { 4614 return PackageManager.PERMISSION_GRANTED; 4615 } 4616 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4617 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4618 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4619 return PackageManager.PERMISSION_GRANTED; 4620 } 4621 } 4622 } 4623 4624 return PackageManager.PERMISSION_DENIED; 4625 } 4626 4627 @Override 4628 public int checkUidPermission(String permName, int uid) { 4629 final int userId = UserHandle.getUserId(uid); 4630 4631 if (!sUserManager.exists(userId)) { 4632 return PackageManager.PERMISSION_DENIED; 4633 } 4634 4635 synchronized (mPackages) { 4636 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4637 if (obj != null) { 4638 final SettingBase ps = (SettingBase) obj; 4639 final PermissionsState permissionsState = ps.getPermissionsState(); 4640 if (permissionsState.hasPermission(permName, userId)) { 4641 return PackageManager.PERMISSION_GRANTED; 4642 } 4643 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4644 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4645 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4646 return PackageManager.PERMISSION_GRANTED; 4647 } 4648 } else { 4649 ArraySet<String> perms = mSystemPermissions.get(uid); 4650 if (perms != null) { 4651 if (perms.contains(permName)) { 4652 return PackageManager.PERMISSION_GRANTED; 4653 } 4654 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4655 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4656 return PackageManager.PERMISSION_GRANTED; 4657 } 4658 } 4659 } 4660 } 4661 4662 return PackageManager.PERMISSION_DENIED; 4663 } 4664 4665 @Override 4666 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4667 if (UserHandle.getCallingUserId() != userId) { 4668 mContext.enforceCallingPermission( 4669 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4670 "isPermissionRevokedByPolicy for user " + userId); 4671 } 4672 4673 if (checkPermission(permission, packageName, userId) 4674 == PackageManager.PERMISSION_GRANTED) { 4675 return false; 4676 } 4677 4678 final long identity = Binder.clearCallingIdentity(); 4679 try { 4680 final int flags = getPermissionFlags(permission, packageName, userId); 4681 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4682 } finally { 4683 Binder.restoreCallingIdentity(identity); 4684 } 4685 } 4686 4687 @Override 4688 public String getPermissionControllerPackageName() { 4689 synchronized (mPackages) { 4690 return mRequiredInstallerPackage; 4691 } 4692 } 4693 4694 /** 4695 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4696 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4697 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4698 * @param message the message to log on security exception 4699 */ 4700 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4701 boolean checkShell, String message) { 4702 if (userId < 0) { 4703 throw new IllegalArgumentException("Invalid userId " + userId); 4704 } 4705 if (checkShell) { 4706 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4707 } 4708 if (userId == UserHandle.getUserId(callingUid)) return; 4709 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4710 if (requireFullPermission) { 4711 mContext.enforceCallingOrSelfPermission( 4712 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4713 } else { 4714 try { 4715 mContext.enforceCallingOrSelfPermission( 4716 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4717 } catch (SecurityException se) { 4718 mContext.enforceCallingOrSelfPermission( 4719 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4720 } 4721 } 4722 } 4723 } 4724 4725 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4726 if (callingUid == Process.SHELL_UID) { 4727 if (userHandle >= 0 4728 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4729 throw new SecurityException("Shell does not have permission to access user " 4730 + userHandle); 4731 } else if (userHandle < 0) { 4732 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4733 + Debug.getCallers(3)); 4734 } 4735 } 4736 } 4737 4738 private BasePermission findPermissionTreeLP(String permName) { 4739 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4740 if (permName.startsWith(bp.name) && 4741 permName.length() > bp.name.length() && 4742 permName.charAt(bp.name.length()) == '.') { 4743 return bp; 4744 } 4745 } 4746 return null; 4747 } 4748 4749 private BasePermission checkPermissionTreeLP(String permName) { 4750 if (permName != null) { 4751 BasePermission bp = findPermissionTreeLP(permName); 4752 if (bp != null) { 4753 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4754 return bp; 4755 } 4756 throw new SecurityException("Calling uid " 4757 + Binder.getCallingUid() 4758 + " is not allowed to add to permission tree " 4759 + bp.name + " owned by uid " + bp.uid); 4760 } 4761 } 4762 throw new SecurityException("No permission tree found for " + permName); 4763 } 4764 4765 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4766 if (s1 == null) { 4767 return s2 == null; 4768 } 4769 if (s2 == null) { 4770 return false; 4771 } 4772 if (s1.getClass() != s2.getClass()) { 4773 return false; 4774 } 4775 return s1.equals(s2); 4776 } 4777 4778 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4779 if (pi1.icon != pi2.icon) return false; 4780 if (pi1.logo != pi2.logo) return false; 4781 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4782 if (!compareStrings(pi1.name, pi2.name)) return false; 4783 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4784 // We'll take care of setting this one. 4785 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4786 // These are not currently stored in settings. 4787 //if (!compareStrings(pi1.group, pi2.group)) return false; 4788 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4789 //if (pi1.labelRes != pi2.labelRes) return false; 4790 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4791 return true; 4792 } 4793 4794 int permissionInfoFootprint(PermissionInfo info) { 4795 int size = info.name.length(); 4796 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4797 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4798 return size; 4799 } 4800 4801 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4802 int size = 0; 4803 for (BasePermission perm : mSettings.mPermissions.values()) { 4804 if (perm.uid == tree.uid) { 4805 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4806 } 4807 } 4808 return size; 4809 } 4810 4811 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4812 // We calculate the max size of permissions defined by this uid and throw 4813 // if that plus the size of 'info' would exceed our stated maximum. 4814 if (tree.uid != Process.SYSTEM_UID) { 4815 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4816 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4817 throw new SecurityException("Permission tree size cap exceeded"); 4818 } 4819 } 4820 } 4821 4822 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4823 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4824 throw new SecurityException("Label must be specified in permission"); 4825 } 4826 BasePermission tree = checkPermissionTreeLP(info.name); 4827 BasePermission bp = mSettings.mPermissions.get(info.name); 4828 boolean added = bp == null; 4829 boolean changed = true; 4830 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4831 if (added) { 4832 enforcePermissionCapLocked(info, tree); 4833 bp = new BasePermission(info.name, tree.sourcePackage, 4834 BasePermission.TYPE_DYNAMIC); 4835 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4836 throw new SecurityException( 4837 "Not allowed to modify non-dynamic permission " 4838 + info.name); 4839 } else { 4840 if (bp.protectionLevel == fixedLevel 4841 && bp.perm.owner.equals(tree.perm.owner) 4842 && bp.uid == tree.uid 4843 && comparePermissionInfos(bp.perm.info, info)) { 4844 changed = false; 4845 } 4846 } 4847 bp.protectionLevel = fixedLevel; 4848 info = new PermissionInfo(info); 4849 info.protectionLevel = fixedLevel; 4850 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4851 bp.perm.info.packageName = tree.perm.info.packageName; 4852 bp.uid = tree.uid; 4853 if (added) { 4854 mSettings.mPermissions.put(info.name, bp); 4855 } 4856 if (changed) { 4857 if (!async) { 4858 mSettings.writeLPr(); 4859 } else { 4860 scheduleWriteSettingsLocked(); 4861 } 4862 } 4863 return added; 4864 } 4865 4866 @Override 4867 public boolean addPermission(PermissionInfo info) { 4868 synchronized (mPackages) { 4869 return addPermissionLocked(info, false); 4870 } 4871 } 4872 4873 @Override 4874 public boolean addPermissionAsync(PermissionInfo info) { 4875 synchronized (mPackages) { 4876 return addPermissionLocked(info, true); 4877 } 4878 } 4879 4880 @Override 4881 public void removePermission(String name) { 4882 synchronized (mPackages) { 4883 checkPermissionTreeLP(name); 4884 BasePermission bp = mSettings.mPermissions.get(name); 4885 if (bp != null) { 4886 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4887 throw new SecurityException( 4888 "Not allowed to modify non-dynamic permission " 4889 + name); 4890 } 4891 mSettings.mPermissions.remove(name); 4892 mSettings.writeLPr(); 4893 } 4894 } 4895 } 4896 4897 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4898 BasePermission bp) { 4899 int index = pkg.requestedPermissions.indexOf(bp.name); 4900 if (index == -1) { 4901 throw new SecurityException("Package " + pkg.packageName 4902 + " has not requested permission " + bp.name); 4903 } 4904 if (!bp.isRuntime() && !bp.isDevelopment()) { 4905 throw new SecurityException("Permission " + bp.name 4906 + " is not a changeable permission type"); 4907 } 4908 } 4909 4910 @Override 4911 public void grantRuntimePermission(String packageName, String name, final int userId) { 4912 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4913 } 4914 4915 private void grantRuntimePermission(String packageName, String name, final int userId, 4916 boolean overridePolicy) { 4917 if (!sUserManager.exists(userId)) { 4918 Log.e(TAG, "No such user:" + userId); 4919 return; 4920 } 4921 4922 mContext.enforceCallingOrSelfPermission( 4923 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4924 "grantRuntimePermission"); 4925 4926 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4927 true /* requireFullPermission */, true /* checkShell */, 4928 "grantRuntimePermission"); 4929 4930 final int uid; 4931 final SettingBase sb; 4932 4933 synchronized (mPackages) { 4934 final PackageParser.Package pkg = mPackages.get(packageName); 4935 if (pkg == null) { 4936 throw new IllegalArgumentException("Unknown package: " + packageName); 4937 } 4938 4939 final BasePermission bp = mSettings.mPermissions.get(name); 4940 if (bp == null) { 4941 throw new IllegalArgumentException("Unknown permission: " + name); 4942 } 4943 4944 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4945 4946 // If a permission review is required for legacy apps we represent 4947 // their permissions as always granted runtime ones since we need 4948 // to keep the review required permission flag per user while an 4949 // install permission's state is shared across all users. 4950 if (mPermissionReviewRequired 4951 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4952 && bp.isRuntime()) { 4953 return; 4954 } 4955 4956 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4957 sb = (SettingBase) pkg.mExtras; 4958 if (sb == null) { 4959 throw new IllegalArgumentException("Unknown package: " + packageName); 4960 } 4961 4962 final PermissionsState permissionsState = sb.getPermissionsState(); 4963 4964 final int flags = permissionsState.getPermissionFlags(name, userId); 4965 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4966 throw new SecurityException("Cannot grant system fixed permission " 4967 + name + " for package " + packageName); 4968 } 4969 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4970 throw new SecurityException("Cannot grant policy fixed permission " 4971 + name + " for package " + packageName); 4972 } 4973 4974 if (bp.isDevelopment()) { 4975 // Development permissions must be handled specially, since they are not 4976 // normal runtime permissions. For now they apply to all users. 4977 if (permissionsState.grantInstallPermission(bp) != 4978 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4979 scheduleWriteSettingsLocked(); 4980 } 4981 return; 4982 } 4983 4984 final PackageSetting ps = mSettings.mPackages.get(packageName); 4985 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4986 throw new SecurityException("Cannot grant non-ephemeral permission" 4987 + name + " for package " + packageName); 4988 } 4989 4990 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4991 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4992 return; 4993 } 4994 4995 final int result = permissionsState.grantRuntimePermission(bp, userId); 4996 switch (result) { 4997 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4998 return; 4999 } 5000 5001 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 5002 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5003 mHandler.post(new Runnable() { 5004 @Override 5005 public void run() { 5006 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 5007 } 5008 }); 5009 } 5010 break; 5011 } 5012 5013 if (bp.isRuntime()) { 5014 logPermissionGranted(mContext, name, packageName); 5015 } 5016 5017 mOnPermissionChangeListeners.onPermissionsChanged(uid); 5018 5019 // Not critical if that is lost - app has to request again. 5020 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5021 } 5022 5023 // Only need to do this if user is initialized. Otherwise it's a new user 5024 // and there are no processes running as the user yet and there's no need 5025 // to make an expensive call to remount processes for the changed permissions. 5026 if (READ_EXTERNAL_STORAGE.equals(name) 5027 || WRITE_EXTERNAL_STORAGE.equals(name)) { 5028 final long token = Binder.clearCallingIdentity(); 5029 try { 5030 if (sUserManager.isInitialized(userId)) { 5031 StorageManagerInternal storageManagerInternal = LocalServices.getService( 5032 StorageManagerInternal.class); 5033 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 5034 } 5035 } finally { 5036 Binder.restoreCallingIdentity(token); 5037 } 5038 } 5039 } 5040 5041 @Override 5042 public void revokeRuntimePermission(String packageName, String name, int userId) { 5043 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5044 } 5045 5046 private void revokeRuntimePermission(String packageName, String name, int userId, 5047 boolean overridePolicy) { 5048 if (!sUserManager.exists(userId)) { 5049 Log.e(TAG, "No such user:" + userId); 5050 return; 5051 } 5052 5053 mContext.enforceCallingOrSelfPermission( 5054 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5055 "revokeRuntimePermission"); 5056 5057 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5058 true /* requireFullPermission */, true /* checkShell */, 5059 "revokeRuntimePermission"); 5060 5061 final int appId; 5062 5063 synchronized (mPackages) { 5064 final PackageParser.Package pkg = mPackages.get(packageName); 5065 if (pkg == null) { 5066 throw new IllegalArgumentException("Unknown package: " + packageName); 5067 } 5068 5069 final BasePermission bp = mSettings.mPermissions.get(name); 5070 if (bp == null) { 5071 throw new IllegalArgumentException("Unknown permission: " + name); 5072 } 5073 5074 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5075 5076 // If a permission review is required for legacy apps we represent 5077 // their permissions as always granted runtime ones since we need 5078 // to keep the review required permission flag per user while an 5079 // install permission's state is shared across all users. 5080 if (mPermissionReviewRequired 5081 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5082 && bp.isRuntime()) { 5083 return; 5084 } 5085 5086 SettingBase sb = (SettingBase) pkg.mExtras; 5087 if (sb == null) { 5088 throw new IllegalArgumentException("Unknown package: " + packageName); 5089 } 5090 5091 final PermissionsState permissionsState = sb.getPermissionsState(); 5092 5093 final int flags = permissionsState.getPermissionFlags(name, userId); 5094 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5095 throw new SecurityException("Cannot revoke system fixed permission " 5096 + name + " for package " + packageName); 5097 } 5098 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5099 throw new SecurityException("Cannot revoke policy fixed permission " 5100 + name + " for package " + packageName); 5101 } 5102 5103 if (bp.isDevelopment()) { 5104 // Development permissions must be handled specially, since they are not 5105 // normal runtime permissions. For now they apply to all users. 5106 if (permissionsState.revokeInstallPermission(bp) != 5107 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5108 scheduleWriteSettingsLocked(); 5109 } 5110 return; 5111 } 5112 5113 if (permissionsState.revokeRuntimePermission(bp, userId) == 5114 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5115 return; 5116 } 5117 5118 if (bp.isRuntime()) { 5119 logPermissionRevoked(mContext, name, packageName); 5120 } 5121 5122 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 5123 5124 // Critical, after this call app should never have the permission. 5125 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 5126 5127 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5128 } 5129 5130 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 5131 } 5132 5133 /** 5134 * Get the first event id for the permission. 5135 * 5136 * <p>There are four events for each permission: <ul> 5137 * <li>Request permission: first id + 0</li> 5138 * <li>Grant permission: first id + 1</li> 5139 * <li>Request for permission denied: first id + 2</li> 5140 * <li>Revoke permission: first id + 3</li> 5141 * </ul></p> 5142 * 5143 * @param name name of the permission 5144 * 5145 * @return The first event id for the permission 5146 */ 5147 private static int getBaseEventId(@NonNull String name) { 5148 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5149 5150 if (eventIdIndex == -1) { 5151 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5152 || "user".equals(Build.TYPE)) { 5153 Log.i(TAG, "Unknown permission " + name); 5154 5155 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5156 } else { 5157 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5158 // 5159 // Also update 5160 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5161 // - metrics_constants.proto 5162 throw new IllegalStateException("Unknown permission " + name); 5163 } 5164 } 5165 5166 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5167 } 5168 5169 /** 5170 * Log that a permission was revoked. 5171 * 5172 * @param context Context of the caller 5173 * @param name name of the permission 5174 * @param packageName package permission if for 5175 */ 5176 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5177 @NonNull String packageName) { 5178 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5179 } 5180 5181 /** 5182 * Log that a permission request was granted. 5183 * 5184 * @param context Context of the caller 5185 * @param name name of the permission 5186 * @param packageName package permission if for 5187 */ 5188 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5189 @NonNull String packageName) { 5190 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5191 } 5192 5193 @Override 5194 public void resetRuntimePermissions() { 5195 mContext.enforceCallingOrSelfPermission( 5196 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5197 "revokeRuntimePermission"); 5198 5199 int callingUid = Binder.getCallingUid(); 5200 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5201 mContext.enforceCallingOrSelfPermission( 5202 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5203 "resetRuntimePermissions"); 5204 } 5205 5206 synchronized (mPackages) { 5207 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5208 for (int userId : UserManagerService.getInstance().getUserIds()) { 5209 final int packageCount = mPackages.size(); 5210 for (int i = 0; i < packageCount; i++) { 5211 PackageParser.Package pkg = mPackages.valueAt(i); 5212 if (!(pkg.mExtras instanceof PackageSetting)) { 5213 continue; 5214 } 5215 PackageSetting ps = (PackageSetting) pkg.mExtras; 5216 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5217 } 5218 } 5219 } 5220 } 5221 5222 @Override 5223 public int getPermissionFlags(String name, String packageName, int userId) { 5224 if (!sUserManager.exists(userId)) { 5225 return 0; 5226 } 5227 5228 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5229 5230 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5231 true /* requireFullPermission */, false /* checkShell */, 5232 "getPermissionFlags"); 5233 5234 synchronized (mPackages) { 5235 final PackageParser.Package pkg = mPackages.get(packageName); 5236 if (pkg == null) { 5237 return 0; 5238 } 5239 5240 final BasePermission bp = mSettings.mPermissions.get(name); 5241 if (bp == null) { 5242 return 0; 5243 } 5244 5245 SettingBase sb = (SettingBase) pkg.mExtras; 5246 if (sb == null) { 5247 return 0; 5248 } 5249 5250 PermissionsState permissionsState = sb.getPermissionsState(); 5251 return permissionsState.getPermissionFlags(name, userId); 5252 } 5253 } 5254 5255 @Override 5256 public void updatePermissionFlags(String name, String packageName, int flagMask, 5257 int flagValues, int userId) { 5258 if (!sUserManager.exists(userId)) { 5259 return; 5260 } 5261 5262 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5263 5264 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5265 true /* requireFullPermission */, true /* checkShell */, 5266 "updatePermissionFlags"); 5267 5268 // Only the system can change these flags and nothing else. 5269 if (getCallingUid() != Process.SYSTEM_UID) { 5270 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5271 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5272 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5273 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5274 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5275 } 5276 5277 synchronized (mPackages) { 5278 final PackageParser.Package pkg = mPackages.get(packageName); 5279 if (pkg == null) { 5280 throw new IllegalArgumentException("Unknown package: " + packageName); 5281 } 5282 5283 final BasePermission bp = mSettings.mPermissions.get(name); 5284 if (bp == null) { 5285 throw new IllegalArgumentException("Unknown permission: " + name); 5286 } 5287 5288 SettingBase sb = (SettingBase) pkg.mExtras; 5289 if (sb == null) { 5290 throw new IllegalArgumentException("Unknown package: " + packageName); 5291 } 5292 5293 PermissionsState permissionsState = sb.getPermissionsState(); 5294 5295 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5296 5297 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5298 // Install and runtime permissions are stored in different places, 5299 // so figure out what permission changed and persist the change. 5300 if (permissionsState.getInstallPermissionState(name) != null) { 5301 scheduleWriteSettingsLocked(); 5302 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5303 || hadState) { 5304 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5305 } 5306 } 5307 } 5308 } 5309 5310 /** 5311 * Update the permission flags for all packages and runtime permissions of a user in order 5312 * to allow device or profile owner to remove POLICY_FIXED. 5313 */ 5314 @Override 5315 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5316 if (!sUserManager.exists(userId)) { 5317 return; 5318 } 5319 5320 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5321 5322 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5323 true /* requireFullPermission */, true /* checkShell */, 5324 "updatePermissionFlagsForAllApps"); 5325 5326 // Only the system can change system fixed flags. 5327 if (getCallingUid() != Process.SYSTEM_UID) { 5328 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5329 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5330 } 5331 5332 synchronized (mPackages) { 5333 boolean changed = false; 5334 final int packageCount = mPackages.size(); 5335 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5336 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5337 SettingBase sb = (SettingBase) pkg.mExtras; 5338 if (sb == null) { 5339 continue; 5340 } 5341 PermissionsState permissionsState = sb.getPermissionsState(); 5342 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5343 userId, flagMask, flagValues); 5344 } 5345 if (changed) { 5346 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5347 } 5348 } 5349 } 5350 5351 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5352 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5353 != PackageManager.PERMISSION_GRANTED 5354 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5355 != PackageManager.PERMISSION_GRANTED) { 5356 throw new SecurityException(message + " requires " 5357 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5358 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5359 } 5360 } 5361 5362 @Override 5363 public boolean shouldShowRequestPermissionRationale(String permissionName, 5364 String packageName, int userId) { 5365 if (UserHandle.getCallingUserId() != userId) { 5366 mContext.enforceCallingPermission( 5367 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5368 "canShowRequestPermissionRationale for user " + userId); 5369 } 5370 5371 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5372 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5373 return false; 5374 } 5375 5376 if (checkPermission(permissionName, packageName, userId) 5377 == PackageManager.PERMISSION_GRANTED) { 5378 return false; 5379 } 5380 5381 final int flags; 5382 5383 final long identity = Binder.clearCallingIdentity(); 5384 try { 5385 flags = getPermissionFlags(permissionName, 5386 packageName, userId); 5387 } finally { 5388 Binder.restoreCallingIdentity(identity); 5389 } 5390 5391 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5392 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5393 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5394 5395 if ((flags & fixedFlags) != 0) { 5396 return false; 5397 } 5398 5399 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5400 } 5401 5402 @Override 5403 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5404 mContext.enforceCallingOrSelfPermission( 5405 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5406 "addOnPermissionsChangeListener"); 5407 5408 synchronized (mPackages) { 5409 mOnPermissionChangeListeners.addListenerLocked(listener); 5410 } 5411 } 5412 5413 @Override 5414 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5415 synchronized (mPackages) { 5416 mOnPermissionChangeListeners.removeListenerLocked(listener); 5417 } 5418 } 5419 5420 @Override 5421 public boolean isProtectedBroadcast(String actionName) { 5422 synchronized (mPackages) { 5423 if (mProtectedBroadcasts.contains(actionName)) { 5424 return true; 5425 } else if (actionName != null) { 5426 // TODO: remove these terrible hacks 5427 if (actionName.startsWith("android.net.netmon.lingerExpired") 5428 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5429 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5430 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5431 return true; 5432 } 5433 } 5434 } 5435 return false; 5436 } 5437 5438 @Override 5439 public int checkSignatures(String pkg1, String pkg2) { 5440 synchronized (mPackages) { 5441 final PackageParser.Package p1 = mPackages.get(pkg1); 5442 final PackageParser.Package p2 = mPackages.get(pkg2); 5443 if (p1 == null || p1.mExtras == null 5444 || p2 == null || p2.mExtras == null) { 5445 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5446 } 5447 return compareSignatures(p1.mSignatures, p2.mSignatures); 5448 } 5449 } 5450 5451 @Override 5452 public int checkUidSignatures(int uid1, int uid2) { 5453 // Map to base uids. 5454 uid1 = UserHandle.getAppId(uid1); 5455 uid2 = UserHandle.getAppId(uid2); 5456 // reader 5457 synchronized (mPackages) { 5458 Signature[] s1; 5459 Signature[] s2; 5460 Object obj = mSettings.getUserIdLPr(uid1); 5461 if (obj != null) { 5462 if (obj instanceof SharedUserSetting) { 5463 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5464 } else if (obj instanceof PackageSetting) { 5465 s1 = ((PackageSetting)obj).signatures.mSignatures; 5466 } else { 5467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5468 } 5469 } else { 5470 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5471 } 5472 obj = mSettings.getUserIdLPr(uid2); 5473 if (obj != null) { 5474 if (obj instanceof SharedUserSetting) { 5475 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5476 } else if (obj instanceof PackageSetting) { 5477 s2 = ((PackageSetting)obj).signatures.mSignatures; 5478 } else { 5479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5480 } 5481 } else { 5482 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5483 } 5484 return compareSignatures(s1, s2); 5485 } 5486 } 5487 5488 /** 5489 * This method should typically only be used when granting or revoking 5490 * permissions, since the app may immediately restart after this call. 5491 * <p> 5492 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5493 * guard your work against the app being relaunched. 5494 */ 5495 private void killUid(int appId, int userId, String reason) { 5496 final long identity = Binder.clearCallingIdentity(); 5497 try { 5498 IActivityManager am = ActivityManager.getService(); 5499 if (am != null) { 5500 try { 5501 am.killUid(appId, userId, reason); 5502 } catch (RemoteException e) { 5503 /* ignore - same process */ 5504 } 5505 } 5506 } finally { 5507 Binder.restoreCallingIdentity(identity); 5508 } 5509 } 5510 5511 /** 5512 * Compares two sets of signatures. Returns: 5513 * <br /> 5514 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5515 * <br /> 5516 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5517 * <br /> 5518 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5519 * <br /> 5520 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5521 * <br /> 5522 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5523 */ 5524 static int compareSignatures(Signature[] s1, Signature[] s2) { 5525 if (s1 == null) { 5526 return s2 == null 5527 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5528 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5529 } 5530 5531 if (s2 == null) { 5532 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5533 } 5534 5535 if (s1.length != s2.length) { 5536 return PackageManager.SIGNATURE_NO_MATCH; 5537 } 5538 5539 // Since both signature sets are of size 1, we can compare without HashSets. 5540 if (s1.length == 1) { 5541 return s1[0].equals(s2[0]) ? 5542 PackageManager.SIGNATURE_MATCH : 5543 PackageManager.SIGNATURE_NO_MATCH; 5544 } 5545 5546 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5547 for (Signature sig : s1) { 5548 set1.add(sig); 5549 } 5550 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5551 for (Signature sig : s2) { 5552 set2.add(sig); 5553 } 5554 // Make sure s2 contains all signatures in s1. 5555 if (set1.equals(set2)) { 5556 return PackageManager.SIGNATURE_MATCH; 5557 } 5558 return PackageManager.SIGNATURE_NO_MATCH; 5559 } 5560 5561 /** 5562 * If the database version for this type of package (internal storage or 5563 * external storage) is less than the version where package signatures 5564 * were updated, return true. 5565 */ 5566 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5567 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5568 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5569 } 5570 5571 /** 5572 * Used for backward compatibility to make sure any packages with 5573 * certificate chains get upgraded to the new style. {@code existingSigs} 5574 * will be in the old format (since they were stored on disk from before the 5575 * system upgrade) and {@code scannedSigs} will be in the newer format. 5576 */ 5577 private int compareSignaturesCompat(PackageSignatures existingSigs, 5578 PackageParser.Package scannedPkg) { 5579 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5580 return PackageManager.SIGNATURE_NO_MATCH; 5581 } 5582 5583 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5584 for (Signature sig : existingSigs.mSignatures) { 5585 existingSet.add(sig); 5586 } 5587 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5588 for (Signature sig : scannedPkg.mSignatures) { 5589 try { 5590 Signature[] chainSignatures = sig.getChainSignatures(); 5591 for (Signature chainSig : chainSignatures) { 5592 scannedCompatSet.add(chainSig); 5593 } 5594 } catch (CertificateEncodingException e) { 5595 scannedCompatSet.add(sig); 5596 } 5597 } 5598 /* 5599 * Make sure the expanded scanned set contains all signatures in the 5600 * existing one. 5601 */ 5602 if (scannedCompatSet.equals(existingSet)) { 5603 // Migrate the old signatures to the new scheme. 5604 existingSigs.assignSignatures(scannedPkg.mSignatures); 5605 // The new KeySets will be re-added later in the scanning process. 5606 synchronized (mPackages) { 5607 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5608 } 5609 return PackageManager.SIGNATURE_MATCH; 5610 } 5611 return PackageManager.SIGNATURE_NO_MATCH; 5612 } 5613 5614 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5615 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5616 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5617 } 5618 5619 private int compareSignaturesRecover(PackageSignatures existingSigs, 5620 PackageParser.Package scannedPkg) { 5621 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5622 return PackageManager.SIGNATURE_NO_MATCH; 5623 } 5624 5625 String msg = null; 5626 try { 5627 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5628 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5629 + scannedPkg.packageName); 5630 return PackageManager.SIGNATURE_MATCH; 5631 } 5632 } catch (CertificateException e) { 5633 msg = e.getMessage(); 5634 } 5635 5636 logCriticalInfo(Log.INFO, 5637 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5638 return PackageManager.SIGNATURE_NO_MATCH; 5639 } 5640 5641 @Override 5642 public List<String> getAllPackages() { 5643 synchronized (mPackages) { 5644 return new ArrayList<String>(mPackages.keySet()); 5645 } 5646 } 5647 5648 @Override 5649 public String[] getPackagesForUid(int uid) { 5650 final int userId = UserHandle.getUserId(uid); 5651 uid = UserHandle.getAppId(uid); 5652 // reader 5653 synchronized (mPackages) { 5654 Object obj = mSettings.getUserIdLPr(uid); 5655 if (obj instanceof SharedUserSetting) { 5656 final SharedUserSetting sus = (SharedUserSetting) obj; 5657 final int N = sus.packages.size(); 5658 String[] res = new String[N]; 5659 final Iterator<PackageSetting> it = sus.packages.iterator(); 5660 int i = 0; 5661 while (it.hasNext()) { 5662 PackageSetting ps = it.next(); 5663 if (ps.getInstalled(userId)) { 5664 res[i++] = ps.name; 5665 } else { 5666 res = ArrayUtils.removeElement(String.class, res, res[i]); 5667 } 5668 } 5669 return res; 5670 } else if (obj instanceof PackageSetting) { 5671 final PackageSetting ps = (PackageSetting) obj; 5672 if (ps.getInstalled(userId)) { 5673 return new String[]{ps.name}; 5674 } 5675 } 5676 } 5677 return null; 5678 } 5679 5680 @Override 5681 public String getNameForUid(int uid) { 5682 // reader 5683 synchronized (mPackages) { 5684 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5685 if (obj instanceof SharedUserSetting) { 5686 final SharedUserSetting sus = (SharedUserSetting) obj; 5687 return sus.name + ":" + sus.userId; 5688 } else if (obj instanceof PackageSetting) { 5689 final PackageSetting ps = (PackageSetting) obj; 5690 return ps.name; 5691 } 5692 } 5693 return null; 5694 } 5695 5696 @Override 5697 public int getUidForSharedUser(String sharedUserName) { 5698 if(sharedUserName == null) { 5699 return -1; 5700 } 5701 // reader 5702 synchronized (mPackages) { 5703 SharedUserSetting suid; 5704 try { 5705 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5706 if (suid != null) { 5707 return suid.userId; 5708 } 5709 } catch (PackageManagerException ignore) { 5710 // can't happen, but, still need to catch it 5711 } 5712 return -1; 5713 } 5714 } 5715 5716 @Override 5717 public int getFlagsForUid(int uid) { 5718 synchronized (mPackages) { 5719 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5720 if (obj instanceof SharedUserSetting) { 5721 final SharedUserSetting sus = (SharedUserSetting) obj; 5722 return sus.pkgFlags; 5723 } else if (obj instanceof PackageSetting) { 5724 final PackageSetting ps = (PackageSetting) obj; 5725 return ps.pkgFlags; 5726 } 5727 } 5728 return 0; 5729 } 5730 5731 @Override 5732 public int getPrivateFlagsForUid(int uid) { 5733 synchronized (mPackages) { 5734 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5735 if (obj instanceof SharedUserSetting) { 5736 final SharedUserSetting sus = (SharedUserSetting) obj; 5737 return sus.pkgPrivateFlags; 5738 } else if (obj instanceof PackageSetting) { 5739 final PackageSetting ps = (PackageSetting) obj; 5740 return ps.pkgPrivateFlags; 5741 } 5742 } 5743 return 0; 5744 } 5745 5746 @Override 5747 public boolean isUidPrivileged(int uid) { 5748 uid = UserHandle.getAppId(uid); 5749 // reader 5750 synchronized (mPackages) { 5751 Object obj = mSettings.getUserIdLPr(uid); 5752 if (obj instanceof SharedUserSetting) { 5753 final SharedUserSetting sus = (SharedUserSetting) obj; 5754 final Iterator<PackageSetting> it = sus.packages.iterator(); 5755 while (it.hasNext()) { 5756 if (it.next().isPrivileged()) { 5757 return true; 5758 } 5759 } 5760 } else if (obj instanceof PackageSetting) { 5761 final PackageSetting ps = (PackageSetting) obj; 5762 return ps.isPrivileged(); 5763 } 5764 } 5765 return false; 5766 } 5767 5768 @Override 5769 public String[] getAppOpPermissionPackages(String permissionName) { 5770 synchronized (mPackages) { 5771 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5772 if (pkgs == null) { 5773 return null; 5774 } 5775 return pkgs.toArray(new String[pkgs.size()]); 5776 } 5777 } 5778 5779 @Override 5780 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5781 int flags, int userId) { 5782 return resolveIntentInternal( 5783 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5784 } 5785 5786 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5787 int flags, int userId, boolean resolveForStart) { 5788 try { 5789 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5790 5791 if (!sUserManager.exists(userId)) return null; 5792 final int callingUid = Binder.getCallingUid(); 5793 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5794 enforceCrossUserPermission(callingUid, userId, 5795 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5796 5797 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5798 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5799 flags, userId, resolveForStart); 5800 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5801 5802 final ResolveInfo bestChoice = 5803 chooseBestActivity(intent, resolvedType, flags, query, userId); 5804 return bestChoice; 5805 } finally { 5806 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5807 } 5808 } 5809 5810 @Override 5811 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5812 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5813 throw new SecurityException( 5814 "findPersistentPreferredActivity can only be run by the system"); 5815 } 5816 if (!sUserManager.exists(userId)) { 5817 return null; 5818 } 5819 final int callingUid = Binder.getCallingUid(); 5820 intent = updateIntentForResolve(intent); 5821 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5822 final int flags = updateFlagsForResolve( 5823 0, userId, intent, callingUid, false /*includeInstantApps*/); 5824 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5825 userId); 5826 synchronized (mPackages) { 5827 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5828 userId); 5829 } 5830 } 5831 5832 @Override 5833 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5834 IntentFilter filter, int match, ComponentName activity) { 5835 final int userId = UserHandle.getCallingUserId(); 5836 if (DEBUG_PREFERRED) { 5837 Log.v(TAG, "setLastChosenActivity intent=" + intent 5838 + " resolvedType=" + resolvedType 5839 + " flags=" + flags 5840 + " filter=" + filter 5841 + " match=" + match 5842 + " activity=" + activity); 5843 filter.dump(new PrintStreamPrinter(System.out), " "); 5844 } 5845 intent.setComponent(null); 5846 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5847 userId); 5848 // Find any earlier preferred or last chosen entries and nuke them 5849 findPreferredActivity(intent, resolvedType, 5850 flags, query, 0, false, true, false, userId); 5851 // Add the new activity as the last chosen for this filter 5852 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5853 "Setting last chosen"); 5854 } 5855 5856 @Override 5857 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5858 final int userId = UserHandle.getCallingUserId(); 5859 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5860 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5861 userId); 5862 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5863 false, false, false, userId); 5864 } 5865 5866 /** 5867 * Returns whether or not instant apps have been disabled remotely. 5868 */ 5869 private boolean isEphemeralDisabled() { 5870 return mEphemeralAppsDisabled; 5871 } 5872 5873 private boolean isInstantAppAllowed( 5874 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5875 boolean skipPackageCheck) { 5876 if (mInstantAppResolverConnection == null) { 5877 return false; 5878 } 5879 if (mInstantAppInstallerActivity == null) { 5880 return false; 5881 } 5882 if (intent.getComponent() != null) { 5883 return false; 5884 } 5885 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5886 return false; 5887 } 5888 if (!skipPackageCheck && intent.getPackage() != null) { 5889 return false; 5890 } 5891 final boolean isWebUri = hasWebURI(intent); 5892 if (!isWebUri || intent.getData().getHost() == null) { 5893 return false; 5894 } 5895 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5896 // Or if there's already an ephemeral app installed that handles the action 5897 synchronized (mPackages) { 5898 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5899 for (int n = 0; n < count; n++) { 5900 final ResolveInfo info = resolvedActivities.get(n); 5901 final String packageName = info.activityInfo.packageName; 5902 final PackageSetting ps = mSettings.mPackages.get(packageName); 5903 if (ps != null) { 5904 // only check domain verification status if the app is not a browser 5905 if (!info.handleAllWebDataURI) { 5906 // Try to get the status from User settings first 5907 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5908 final int status = (int) (packedStatus >> 32); 5909 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5910 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5911 if (DEBUG_EPHEMERAL) { 5912 Slog.v(TAG, "DENY instant app;" 5913 + " pkg: " + packageName + ", status: " + status); 5914 } 5915 return false; 5916 } 5917 } 5918 if (ps.getInstantApp(userId)) { 5919 if (DEBUG_EPHEMERAL) { 5920 Slog.v(TAG, "DENY instant app installed;" 5921 + " pkg: " + packageName); 5922 } 5923 return false; 5924 } 5925 } 5926 } 5927 } 5928 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5929 return true; 5930 } 5931 5932 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5933 Intent origIntent, String resolvedType, String callingPackage, 5934 Bundle verificationBundle, int userId) { 5935 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5936 new InstantAppRequest(responseObj, origIntent, resolvedType, 5937 callingPackage, userId, verificationBundle)); 5938 mHandler.sendMessage(msg); 5939 } 5940 5941 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5942 int flags, List<ResolveInfo> query, int userId) { 5943 if (query != null) { 5944 final int N = query.size(); 5945 if (N == 1) { 5946 return query.get(0); 5947 } else if (N > 1) { 5948 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5949 // If there is more than one activity with the same priority, 5950 // then let the user decide between them. 5951 ResolveInfo r0 = query.get(0); 5952 ResolveInfo r1 = query.get(1); 5953 if (DEBUG_INTENT_MATCHING || debug) { 5954 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5955 + r1.activityInfo.name + "=" + r1.priority); 5956 } 5957 // If the first activity has a higher priority, or a different 5958 // default, then it is always desirable to pick it. 5959 if (r0.priority != r1.priority 5960 || r0.preferredOrder != r1.preferredOrder 5961 || r0.isDefault != r1.isDefault) { 5962 return query.get(0); 5963 } 5964 // If we have saved a preference for a preferred activity for 5965 // this Intent, use that. 5966 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5967 flags, query, r0.priority, true, false, debug, userId); 5968 if (ri != null) { 5969 return ri; 5970 } 5971 // If we have an ephemeral app, use it 5972 for (int i = 0; i < N; i++) { 5973 ri = query.get(i); 5974 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5975 final String packageName = ri.activityInfo.packageName; 5976 final PackageSetting ps = mSettings.mPackages.get(packageName); 5977 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5978 final int status = (int)(packedStatus >> 32); 5979 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5980 return ri; 5981 } 5982 } 5983 } 5984 ri = new ResolveInfo(mResolveInfo); 5985 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5986 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5987 // If all of the options come from the same package, show the application's 5988 // label and icon instead of the generic resolver's. 5989 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5990 // and then throw away the ResolveInfo itself, meaning that the caller loses 5991 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5992 // a fallback for this case; we only set the target package's resources on 5993 // the ResolveInfo, not the ActivityInfo. 5994 final String intentPackage = intent.getPackage(); 5995 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5996 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5997 ri.resolvePackageName = intentPackage; 5998 if (userNeedsBadging(userId)) { 5999 ri.noResourceId = true; 6000 } else { 6001 ri.icon = appi.icon; 6002 } 6003 ri.iconResourceId = appi.icon; 6004 ri.labelRes = appi.labelRes; 6005 } 6006 ri.activityInfo.applicationInfo = new ApplicationInfo( 6007 ri.activityInfo.applicationInfo); 6008 if (userId != 0) { 6009 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6010 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6011 } 6012 // Make sure that the resolver is displayable in car mode 6013 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6014 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6015 return ri; 6016 } 6017 } 6018 return null; 6019 } 6020 6021 /** 6022 * Return true if the given list is not empty and all of its contents have 6023 * an activityInfo with the given package name. 6024 */ 6025 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6026 if (ArrayUtils.isEmpty(list)) { 6027 return false; 6028 } 6029 for (int i = 0, N = list.size(); i < N; i++) { 6030 final ResolveInfo ri = list.get(i); 6031 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6032 if (ai == null || !packageName.equals(ai.packageName)) { 6033 return false; 6034 } 6035 } 6036 return true; 6037 } 6038 6039 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6040 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6041 final int N = query.size(); 6042 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6043 .get(userId); 6044 // Get the list of persistent preferred activities that handle the intent 6045 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6046 List<PersistentPreferredActivity> pprefs = ppir != null 6047 ? ppir.queryIntent(intent, resolvedType, 6048 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6049 userId) 6050 : null; 6051 if (pprefs != null && pprefs.size() > 0) { 6052 final int M = pprefs.size(); 6053 for (int i=0; i<M; i++) { 6054 final PersistentPreferredActivity ppa = pprefs.get(i); 6055 if (DEBUG_PREFERRED || debug) { 6056 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6057 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6058 + "\n component=" + ppa.mComponent); 6059 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6060 } 6061 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6062 flags | MATCH_DISABLED_COMPONENTS, userId); 6063 if (DEBUG_PREFERRED || debug) { 6064 Slog.v(TAG, "Found persistent preferred activity:"); 6065 if (ai != null) { 6066 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6067 } else { 6068 Slog.v(TAG, " null"); 6069 } 6070 } 6071 if (ai == null) { 6072 // This previously registered persistent preferred activity 6073 // component is no longer known. Ignore it and do NOT remove it. 6074 continue; 6075 } 6076 for (int j=0; j<N; j++) { 6077 final ResolveInfo ri = query.get(j); 6078 if (!ri.activityInfo.applicationInfo.packageName 6079 .equals(ai.applicationInfo.packageName)) { 6080 continue; 6081 } 6082 if (!ri.activityInfo.name.equals(ai.name)) { 6083 continue; 6084 } 6085 // Found a persistent preference that can handle the intent. 6086 if (DEBUG_PREFERRED || debug) { 6087 Slog.v(TAG, "Returning persistent preferred activity: " + 6088 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6089 } 6090 return ri; 6091 } 6092 } 6093 } 6094 return null; 6095 } 6096 6097 // TODO: handle preferred activities missing while user has amnesia 6098 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6099 List<ResolveInfo> query, int priority, boolean always, 6100 boolean removeMatches, boolean debug, int userId) { 6101 if (!sUserManager.exists(userId)) return null; 6102 final int callingUid = Binder.getCallingUid(); 6103 flags = updateFlagsForResolve( 6104 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6105 intent = updateIntentForResolve(intent); 6106 // writer 6107 synchronized (mPackages) { 6108 // Try to find a matching persistent preferred activity. 6109 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6110 debug, userId); 6111 6112 // If a persistent preferred activity matched, use it. 6113 if (pri != null) { 6114 return pri; 6115 } 6116 6117 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6118 // Get the list of preferred activities that handle the intent 6119 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6120 List<PreferredActivity> prefs = pir != null 6121 ? pir.queryIntent(intent, resolvedType, 6122 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6123 userId) 6124 : null; 6125 if (prefs != null && prefs.size() > 0) { 6126 boolean changed = false; 6127 try { 6128 // First figure out how good the original match set is. 6129 // We will only allow preferred activities that came 6130 // from the same match quality. 6131 int match = 0; 6132 6133 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6134 6135 final int N = query.size(); 6136 for (int j=0; j<N; j++) { 6137 final ResolveInfo ri = query.get(j); 6138 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6139 + ": 0x" + Integer.toHexString(match)); 6140 if (ri.match > match) { 6141 match = ri.match; 6142 } 6143 } 6144 6145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6146 + Integer.toHexString(match)); 6147 6148 match &= IntentFilter.MATCH_CATEGORY_MASK; 6149 final int M = prefs.size(); 6150 for (int i=0; i<M; i++) { 6151 final PreferredActivity pa = prefs.get(i); 6152 if (DEBUG_PREFERRED || debug) { 6153 Slog.v(TAG, "Checking PreferredActivity ds=" 6154 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6155 + "\n component=" + pa.mPref.mComponent); 6156 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6157 } 6158 if (pa.mPref.mMatch != match) { 6159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6160 + Integer.toHexString(pa.mPref.mMatch)); 6161 continue; 6162 } 6163 // If it's not an "always" type preferred activity and that's what we're 6164 // looking for, skip it. 6165 if (always && !pa.mPref.mAlways) { 6166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6167 continue; 6168 } 6169 final ActivityInfo ai = getActivityInfo( 6170 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6171 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6172 userId); 6173 if (DEBUG_PREFERRED || debug) { 6174 Slog.v(TAG, "Found preferred activity:"); 6175 if (ai != null) { 6176 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6177 } else { 6178 Slog.v(TAG, " null"); 6179 } 6180 } 6181 if (ai == null) { 6182 // This previously registered preferred activity 6183 // component is no longer known. Most likely an update 6184 // to the app was installed and in the new version this 6185 // component no longer exists. Clean it up by removing 6186 // it from the preferred activities list, and skip it. 6187 Slog.w(TAG, "Removing dangling preferred activity: " 6188 + pa.mPref.mComponent); 6189 pir.removeFilter(pa); 6190 changed = true; 6191 continue; 6192 } 6193 for (int j=0; j<N; j++) { 6194 final ResolveInfo ri = query.get(j); 6195 if (!ri.activityInfo.applicationInfo.packageName 6196 .equals(ai.applicationInfo.packageName)) { 6197 continue; 6198 } 6199 if (!ri.activityInfo.name.equals(ai.name)) { 6200 continue; 6201 } 6202 6203 if (removeMatches) { 6204 pir.removeFilter(pa); 6205 changed = true; 6206 if (DEBUG_PREFERRED) { 6207 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6208 } 6209 break; 6210 } 6211 6212 // Okay we found a previously set preferred or last chosen app. 6213 // If the result set is different from when this 6214 // was created, we need to clear it and re-ask the 6215 // user their preference, if we're looking for an "always" type entry. 6216 if (always && !pa.mPref.sameSet(query)) { 6217 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6218 + intent + " type " + resolvedType); 6219 if (DEBUG_PREFERRED) { 6220 Slog.v(TAG, "Removing preferred activity since set changed " 6221 + pa.mPref.mComponent); 6222 } 6223 pir.removeFilter(pa); 6224 // Re-add the filter as a "last chosen" entry (!always) 6225 PreferredActivity lastChosen = new PreferredActivity( 6226 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6227 pir.addFilter(lastChosen); 6228 changed = true; 6229 return null; 6230 } 6231 6232 // Yay! Either the set matched or we're looking for the last chosen 6233 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6234 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6235 return ri; 6236 } 6237 } 6238 } finally { 6239 if (changed) { 6240 if (DEBUG_PREFERRED) { 6241 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6242 } 6243 scheduleWritePackageRestrictionsLocked(userId); 6244 } 6245 } 6246 } 6247 } 6248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6249 return null; 6250 } 6251 6252 /* 6253 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6254 */ 6255 @Override 6256 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6257 int targetUserId) { 6258 mContext.enforceCallingOrSelfPermission( 6259 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6260 List<CrossProfileIntentFilter> matches = 6261 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6262 if (matches != null) { 6263 int size = matches.size(); 6264 for (int i = 0; i < size; i++) { 6265 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6266 } 6267 } 6268 if (hasWebURI(intent)) { 6269 // cross-profile app linking works only towards the parent. 6270 final int callingUid = Binder.getCallingUid(); 6271 final UserInfo parent = getProfileParent(sourceUserId); 6272 synchronized(mPackages) { 6273 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6274 false /*includeInstantApps*/); 6275 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6276 intent, resolvedType, flags, sourceUserId, parent.id); 6277 return xpDomainInfo != null; 6278 } 6279 } 6280 return false; 6281 } 6282 6283 private UserInfo getProfileParent(int userId) { 6284 final long identity = Binder.clearCallingIdentity(); 6285 try { 6286 return sUserManager.getProfileParent(userId); 6287 } finally { 6288 Binder.restoreCallingIdentity(identity); 6289 } 6290 } 6291 6292 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6293 String resolvedType, int userId) { 6294 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6295 if (resolver != null) { 6296 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6297 } 6298 return null; 6299 } 6300 6301 @Override 6302 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6303 String resolvedType, int flags, int userId) { 6304 try { 6305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6306 6307 return new ParceledListSlice<>( 6308 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6309 } finally { 6310 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6311 } 6312 } 6313 6314 /** 6315 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6316 * instant, returns {@code null}. 6317 */ 6318 private String getInstantAppPackageName(int callingUid) { 6319 // If the caller is an isolated app use the owner's uid for the lookup. 6320 if (Process.isIsolated(callingUid)) { 6321 callingUid = mIsolatedOwners.get(callingUid); 6322 } 6323 final int appId = UserHandle.getAppId(callingUid); 6324 synchronized (mPackages) { 6325 final Object obj = mSettings.getUserIdLPr(appId); 6326 if (obj instanceof PackageSetting) { 6327 final PackageSetting ps = (PackageSetting) obj; 6328 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6329 return isInstantApp ? ps.pkg.packageName : null; 6330 } 6331 } 6332 return null; 6333 } 6334 6335 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6336 String resolvedType, int flags, int userId) { 6337 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6338 } 6339 6340 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6341 String resolvedType, int flags, int userId, boolean resolveForStart) { 6342 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6343 final int callingUid = Binder.getCallingUid(); 6344 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6345 enforceCrossUserPermission(callingUid, userId, 6346 false /* requireFullPermission */, false /* checkShell */, 6347 "query intent activities"); 6348 final String pkgName = intent.getPackage(); 6349 ComponentName comp = intent.getComponent(); 6350 if (comp == null) { 6351 if (intent.getSelector() != null) { 6352 intent = intent.getSelector(); 6353 comp = intent.getComponent(); 6354 } 6355 } 6356 6357 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart, 6358 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6359 if (comp != null) { 6360 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6361 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6362 if (ai != null) { 6363 // When specifying an explicit component, we prevent the activity from being 6364 // used when either 1) the calling package is normal and the activity is within 6365 // an ephemeral application or 2) the calling package is ephemeral and the 6366 // activity is not visible to ephemeral applications. 6367 final boolean matchInstantApp = 6368 (flags & PackageManager.MATCH_INSTANT) != 0; 6369 final boolean matchVisibleToInstantAppOnly = 6370 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6371 final boolean matchExplicitlyVisibleOnly = 6372 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6373 final boolean isCallerInstantApp = 6374 instantAppPkgName != null; 6375 final boolean isTargetSameInstantApp = 6376 comp.getPackageName().equals(instantAppPkgName); 6377 final boolean isTargetInstantApp = 6378 (ai.applicationInfo.privateFlags 6379 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6380 final boolean isTargetVisibleToInstantApp = 6381 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6382 final boolean isTargetExplicitlyVisibleToInstantApp = 6383 isTargetVisibleToInstantApp 6384 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6385 final boolean isTargetHiddenFromInstantApp = 6386 !isTargetVisibleToInstantApp 6387 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6388 final boolean blockResolution = 6389 !isTargetSameInstantApp 6390 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6391 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6392 && isTargetHiddenFromInstantApp)); 6393 if (!blockResolution) { 6394 final ResolveInfo ri = new ResolveInfo(); 6395 ri.activityInfo = ai; 6396 list.add(ri); 6397 } 6398 } 6399 return applyPostResolutionFilter(list, instantAppPkgName); 6400 } 6401 6402 // reader 6403 boolean sortResult = false; 6404 boolean addEphemeral = false; 6405 List<ResolveInfo> result; 6406 final boolean ephemeralDisabled = isEphemeralDisabled(); 6407 synchronized (mPackages) { 6408 if (pkgName == null) { 6409 List<CrossProfileIntentFilter> matchingFilters = 6410 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6411 // Check for results that need to skip the current profile. 6412 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6413 resolvedType, flags, userId); 6414 if (xpResolveInfo != null) { 6415 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6416 xpResult.add(xpResolveInfo); 6417 return applyPostResolutionFilter( 6418 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6419 } 6420 6421 // Check for results in the current profile. 6422 result = filterIfNotSystemUser(mActivities.queryIntent( 6423 intent, resolvedType, flags, userId), userId); 6424 addEphemeral = !ephemeralDisabled 6425 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6426 // Check for cross profile results. 6427 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6428 xpResolveInfo = queryCrossProfileIntents( 6429 matchingFilters, intent, resolvedType, flags, userId, 6430 hasNonNegativePriorityResult); 6431 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6432 boolean isVisibleToUser = filterIfNotSystemUser( 6433 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6434 if (isVisibleToUser) { 6435 result.add(xpResolveInfo); 6436 sortResult = true; 6437 } 6438 } 6439 if (hasWebURI(intent)) { 6440 CrossProfileDomainInfo xpDomainInfo = null; 6441 final UserInfo parent = getProfileParent(userId); 6442 if (parent != null) { 6443 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6444 flags, userId, parent.id); 6445 } 6446 if (xpDomainInfo != null) { 6447 if (xpResolveInfo != null) { 6448 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6449 // in the result. 6450 result.remove(xpResolveInfo); 6451 } 6452 if (result.size() == 0 && !addEphemeral) { 6453 // No result in current profile, but found candidate in parent user. 6454 // And we are not going to add emphemeral app, so we can return the 6455 // result straight away. 6456 result.add(xpDomainInfo.resolveInfo); 6457 return applyPostResolutionFilter(result, instantAppPkgName); 6458 } 6459 } else if (result.size() <= 1 && !addEphemeral) { 6460 // No result in parent user and <= 1 result in current profile, and we 6461 // are not going to add emphemeral app, so we can return the result without 6462 // further processing. 6463 return applyPostResolutionFilter(result, instantAppPkgName); 6464 } 6465 // We have more than one candidate (combining results from current and parent 6466 // profile), so we need filtering and sorting. 6467 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6468 intent, flags, result, xpDomainInfo, userId); 6469 sortResult = true; 6470 } 6471 } else { 6472 final PackageParser.Package pkg = mPackages.get(pkgName); 6473 if (pkg != null) { 6474 return applyPostResolutionFilter(filterIfNotSystemUser( 6475 mActivities.queryIntentForPackage( 6476 intent, resolvedType, flags, pkg.activities, userId), 6477 userId), instantAppPkgName); 6478 } else { 6479 // the caller wants to resolve for a particular package; however, there 6480 // were no installed results, so, try to find an ephemeral result 6481 addEphemeral = !ephemeralDisabled 6482 && isInstantAppAllowed( 6483 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6484 result = new ArrayList<ResolveInfo>(); 6485 } 6486 } 6487 } 6488 if (addEphemeral) { 6489 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId); 6490 } 6491 if (sortResult) { 6492 Collections.sort(result, mResolvePrioritySorter); 6493 } 6494 return applyPostResolutionFilter(result, instantAppPkgName); 6495 } 6496 6497 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6498 String resolvedType, int flags, int userId) { 6499 // first, check to see if we've got an instant app already installed 6500 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6501 boolean localInstantAppAvailable = false; 6502 boolean blockResolution = false; 6503 if (!alreadyResolvedLocally) { 6504 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6505 flags 6506 | PackageManager.MATCH_INSTANT 6507 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6508 userId); 6509 for (int i = instantApps.size() - 1; i >= 0; --i) { 6510 final ResolveInfo info = instantApps.get(i); 6511 final String packageName = info.activityInfo.packageName; 6512 final PackageSetting ps = mSettings.mPackages.get(packageName); 6513 if (ps.getInstantApp(userId)) { 6514 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6515 final int status = (int)(packedStatus >> 32); 6516 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6517 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6518 // there's a local instant application installed, but, the user has 6519 // chosen to never use it; skip resolution and don't acknowledge 6520 // an instant application is even available 6521 if (DEBUG_EPHEMERAL) { 6522 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6523 } 6524 blockResolution = true; 6525 break; 6526 } else { 6527 // we have a locally installed instant application; skip resolution 6528 // but acknowledge there's an instant application available 6529 if (DEBUG_EPHEMERAL) { 6530 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6531 } 6532 localInstantAppAvailable = true; 6533 break; 6534 } 6535 } 6536 } 6537 } 6538 // no app installed, let's see if one's available 6539 AuxiliaryResolveInfo auxiliaryResponse = null; 6540 if (!localInstantAppAvailable && !blockResolution) { 6541 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6542 final InstantAppRequest requestObject = new InstantAppRequest( 6543 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6544 null /*callingPackage*/, userId, null /*verificationBundle*/); 6545 auxiliaryResponse = 6546 InstantAppResolver.doInstantAppResolutionPhaseOne( 6547 mContext, mInstantAppResolverConnection, requestObject); 6548 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6549 } 6550 if (localInstantAppAvailable || auxiliaryResponse != null) { 6551 if (DEBUG_EPHEMERAL) { 6552 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6553 } 6554 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6555 final PackageSetting ps = 6556 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6557 if (ps != null) { 6558 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6559 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6560 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6561 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6562 // make sure this resolver is the default 6563 ephemeralInstaller.isDefault = true; 6564 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6565 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6566 // add a non-generic filter 6567 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6568 ephemeralInstaller.filter.addDataPath( 6569 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6570 ephemeralInstaller.instantAppAvailable = true; 6571 result.add(ephemeralInstaller); 6572 } 6573 } 6574 return result; 6575 } 6576 6577 private static class CrossProfileDomainInfo { 6578 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6579 ResolveInfo resolveInfo; 6580 /* Best domain verification status of the activities found in the other profile */ 6581 int bestDomainVerificationStatus; 6582 } 6583 6584 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6585 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6586 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6587 sourceUserId)) { 6588 return null; 6589 } 6590 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6591 resolvedType, flags, parentUserId); 6592 6593 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6594 return null; 6595 } 6596 CrossProfileDomainInfo result = null; 6597 int size = resultTargetUser.size(); 6598 for (int i = 0; i < size; i++) { 6599 ResolveInfo riTargetUser = resultTargetUser.get(i); 6600 // Intent filter verification is only for filters that specify a host. So don't return 6601 // those that handle all web uris. 6602 if (riTargetUser.handleAllWebDataURI) { 6603 continue; 6604 } 6605 String packageName = riTargetUser.activityInfo.packageName; 6606 PackageSetting ps = mSettings.mPackages.get(packageName); 6607 if (ps == null) { 6608 continue; 6609 } 6610 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6611 int status = (int)(verificationState >> 32); 6612 if (result == null) { 6613 result = new CrossProfileDomainInfo(); 6614 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6615 sourceUserId, parentUserId); 6616 result.bestDomainVerificationStatus = status; 6617 } else { 6618 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6619 result.bestDomainVerificationStatus); 6620 } 6621 } 6622 // Don't consider matches with status NEVER across profiles. 6623 if (result != null && result.bestDomainVerificationStatus 6624 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6625 return null; 6626 } 6627 return result; 6628 } 6629 6630 /** 6631 * Verification statuses are ordered from the worse to the best, except for 6632 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6633 */ 6634 private int bestDomainVerificationStatus(int status1, int status2) { 6635 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6636 return status2; 6637 } 6638 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6639 return status1; 6640 } 6641 return (int) MathUtils.max(status1, status2); 6642 } 6643 6644 private boolean isUserEnabled(int userId) { 6645 long callingId = Binder.clearCallingIdentity(); 6646 try { 6647 UserInfo userInfo = sUserManager.getUserInfo(userId); 6648 return userInfo != null && userInfo.isEnabled(); 6649 } finally { 6650 Binder.restoreCallingIdentity(callingId); 6651 } 6652 } 6653 6654 /** 6655 * Filter out activities with systemUserOnly flag set, when current user is not System. 6656 * 6657 * @return filtered list 6658 */ 6659 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6660 if (userId == UserHandle.USER_SYSTEM) { 6661 return resolveInfos; 6662 } 6663 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6664 ResolveInfo info = resolveInfos.get(i); 6665 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6666 resolveInfos.remove(i); 6667 } 6668 } 6669 return resolveInfos; 6670 } 6671 6672 /** 6673 * Filters out ephemeral activities. 6674 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6675 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6676 * 6677 * @param resolveInfos The pre-filtered list of resolved activities 6678 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6679 * is performed. 6680 * @return A filtered list of resolved activities. 6681 */ 6682 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6683 String ephemeralPkgName) { 6684 // TODO: When adding on-demand split support for non-instant apps, remove this check 6685 // and always apply post filtering 6686 if (ephemeralPkgName == null) { 6687 return resolveInfos; 6688 } 6689 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6690 final ResolveInfo info = resolveInfos.get(i); 6691 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6692 // allow activities that are defined in the provided package 6693 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6694 if (info.activityInfo.splitName != null 6695 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6696 info.activityInfo.splitName)) { 6697 // requested activity is defined in a split that hasn't been installed yet. 6698 // add the installer to the resolve list 6699 if (DEBUG_EPHEMERAL) { 6700 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6701 } 6702 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6703 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6704 info.activityInfo.packageName, info.activityInfo.splitName, 6705 info.activityInfo.applicationInfo.versionCode); 6706 // make sure this resolver is the default 6707 installerInfo.isDefault = true; 6708 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6709 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6710 // add a non-generic filter 6711 installerInfo.filter = new IntentFilter(); 6712 // load resources from the correct package 6713 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6714 resolveInfos.set(i, installerInfo); 6715 } 6716 continue; 6717 } 6718 // allow activities that have been explicitly exposed to ephemeral apps 6719 if (!isEphemeralApp 6720 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6721 continue; 6722 } 6723 resolveInfos.remove(i); 6724 } 6725 return resolveInfos; 6726 } 6727 6728 /** 6729 * @param resolveInfos list of resolve infos in descending priority order 6730 * @return if the list contains a resolve info with non-negative priority 6731 */ 6732 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6733 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6734 } 6735 6736 private static boolean hasWebURI(Intent intent) { 6737 if (intent.getData() == null) { 6738 return false; 6739 } 6740 final String scheme = intent.getScheme(); 6741 if (TextUtils.isEmpty(scheme)) { 6742 return false; 6743 } 6744 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6745 } 6746 6747 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6748 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6749 int userId) { 6750 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6751 6752 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6753 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6754 candidates.size()); 6755 } 6756 6757 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6758 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6759 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6760 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6761 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6762 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6763 6764 synchronized (mPackages) { 6765 final int count = candidates.size(); 6766 // First, try to use linked apps. Partition the candidates into four lists: 6767 // one for the final results, one for the "do not use ever", one for "undefined status" 6768 // and finally one for "browser app type". 6769 for (int n=0; n<count; n++) { 6770 ResolveInfo info = candidates.get(n); 6771 String packageName = info.activityInfo.packageName; 6772 PackageSetting ps = mSettings.mPackages.get(packageName); 6773 if (ps != null) { 6774 // Add to the special match all list (Browser use case) 6775 if (info.handleAllWebDataURI) { 6776 matchAllList.add(info); 6777 continue; 6778 } 6779 // Try to get the status from User settings first 6780 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6781 int status = (int)(packedStatus >> 32); 6782 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6783 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6784 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6785 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6786 + " : linkgen=" + linkGeneration); 6787 } 6788 // Use link-enabled generation as preferredOrder, i.e. 6789 // prefer newly-enabled over earlier-enabled. 6790 info.preferredOrder = linkGeneration; 6791 alwaysList.add(info); 6792 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6793 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6794 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6795 } 6796 neverList.add(info); 6797 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6798 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6799 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6800 } 6801 alwaysAskList.add(info); 6802 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6803 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6804 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6805 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6806 } 6807 undefinedList.add(info); 6808 } 6809 } 6810 } 6811 6812 // We'll want to include browser possibilities in a few cases 6813 boolean includeBrowser = false; 6814 6815 // First try to add the "always" resolution(s) for the current user, if any 6816 if (alwaysList.size() > 0) { 6817 result.addAll(alwaysList); 6818 } else { 6819 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6820 result.addAll(undefinedList); 6821 // Maybe add one for the other profile. 6822 if (xpDomainInfo != null && ( 6823 xpDomainInfo.bestDomainVerificationStatus 6824 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6825 result.add(xpDomainInfo.resolveInfo); 6826 } 6827 includeBrowser = true; 6828 } 6829 6830 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6831 // If there were 'always' entries their preferred order has been set, so we also 6832 // back that off to make the alternatives equivalent 6833 if (alwaysAskList.size() > 0) { 6834 for (ResolveInfo i : result) { 6835 i.preferredOrder = 0; 6836 } 6837 result.addAll(alwaysAskList); 6838 includeBrowser = true; 6839 } 6840 6841 if (includeBrowser) { 6842 // Also add browsers (all of them or only the default one) 6843 if (DEBUG_DOMAIN_VERIFICATION) { 6844 Slog.v(TAG, " ...including browsers in candidate set"); 6845 } 6846 if ((matchFlags & MATCH_ALL) != 0) { 6847 result.addAll(matchAllList); 6848 } else { 6849 // Browser/generic handling case. If there's a default browser, go straight 6850 // to that (but only if there is no other higher-priority match). 6851 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6852 int maxMatchPrio = 0; 6853 ResolveInfo defaultBrowserMatch = null; 6854 final int numCandidates = matchAllList.size(); 6855 for (int n = 0; n < numCandidates; n++) { 6856 ResolveInfo info = matchAllList.get(n); 6857 // track the highest overall match priority... 6858 if (info.priority > maxMatchPrio) { 6859 maxMatchPrio = info.priority; 6860 } 6861 // ...and the highest-priority default browser match 6862 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6863 if (defaultBrowserMatch == null 6864 || (defaultBrowserMatch.priority < info.priority)) { 6865 if (debug) { 6866 Slog.v(TAG, "Considering default browser match " + info); 6867 } 6868 defaultBrowserMatch = info; 6869 } 6870 } 6871 } 6872 if (defaultBrowserMatch != null 6873 && defaultBrowserMatch.priority >= maxMatchPrio 6874 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6875 { 6876 if (debug) { 6877 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6878 } 6879 result.add(defaultBrowserMatch); 6880 } else { 6881 result.addAll(matchAllList); 6882 } 6883 } 6884 6885 // If there is nothing selected, add all candidates and remove the ones that the user 6886 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6887 if (result.size() == 0) { 6888 result.addAll(candidates); 6889 result.removeAll(neverList); 6890 } 6891 } 6892 } 6893 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6894 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6895 result.size()); 6896 for (ResolveInfo info : result) { 6897 Slog.v(TAG, " + " + info.activityInfo); 6898 } 6899 } 6900 return result; 6901 } 6902 6903 // Returns a packed value as a long: 6904 // 6905 // high 'int'-sized word: link status: undefined/ask/never/always. 6906 // low 'int'-sized word: relative priority among 'always' results. 6907 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6908 long result = ps.getDomainVerificationStatusForUser(userId); 6909 // if none available, get the master status 6910 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6911 if (ps.getIntentFilterVerificationInfo() != null) { 6912 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6913 } 6914 } 6915 return result; 6916 } 6917 6918 private ResolveInfo querySkipCurrentProfileIntents( 6919 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6920 int flags, int sourceUserId) { 6921 if (matchingFilters != null) { 6922 int size = matchingFilters.size(); 6923 for (int i = 0; i < size; i ++) { 6924 CrossProfileIntentFilter filter = matchingFilters.get(i); 6925 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6926 // Checking if there are activities in the target user that can handle the 6927 // intent. 6928 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6929 resolvedType, flags, sourceUserId); 6930 if (resolveInfo != null) { 6931 return resolveInfo; 6932 } 6933 } 6934 } 6935 } 6936 return null; 6937 } 6938 6939 // Return matching ResolveInfo in target user if any. 6940 private ResolveInfo queryCrossProfileIntents( 6941 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6942 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6943 if (matchingFilters != null) { 6944 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6945 // match the same intent. For performance reasons, it is better not to 6946 // run queryIntent twice for the same userId 6947 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6948 int size = matchingFilters.size(); 6949 for (int i = 0; i < size; i++) { 6950 CrossProfileIntentFilter filter = matchingFilters.get(i); 6951 int targetUserId = filter.getTargetUserId(); 6952 boolean skipCurrentProfile = 6953 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6954 boolean skipCurrentProfileIfNoMatchFound = 6955 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6956 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6957 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6958 // Checking if there are activities in the target user that can handle the 6959 // intent. 6960 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6961 resolvedType, flags, sourceUserId); 6962 if (resolveInfo != null) return resolveInfo; 6963 alreadyTriedUserIds.put(targetUserId, true); 6964 } 6965 } 6966 } 6967 return null; 6968 } 6969 6970 /** 6971 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6972 * will forward the intent to the filter's target user. 6973 * Otherwise, returns null. 6974 */ 6975 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6976 String resolvedType, int flags, int sourceUserId) { 6977 int targetUserId = filter.getTargetUserId(); 6978 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6979 resolvedType, flags, targetUserId); 6980 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6981 // If all the matches in the target profile are suspended, return null. 6982 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6983 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6984 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6985 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6986 targetUserId); 6987 } 6988 } 6989 } 6990 return null; 6991 } 6992 6993 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6994 int sourceUserId, int targetUserId) { 6995 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6996 long ident = Binder.clearCallingIdentity(); 6997 boolean targetIsProfile; 6998 try { 6999 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7000 } finally { 7001 Binder.restoreCallingIdentity(ident); 7002 } 7003 String className; 7004 if (targetIsProfile) { 7005 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7006 } else { 7007 className = FORWARD_INTENT_TO_PARENT; 7008 } 7009 ComponentName forwardingActivityComponentName = new ComponentName( 7010 mAndroidApplication.packageName, className); 7011 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7012 sourceUserId); 7013 if (!targetIsProfile) { 7014 forwardingActivityInfo.showUserIcon = targetUserId; 7015 forwardingResolveInfo.noResourceId = true; 7016 } 7017 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7018 forwardingResolveInfo.priority = 0; 7019 forwardingResolveInfo.preferredOrder = 0; 7020 forwardingResolveInfo.match = 0; 7021 forwardingResolveInfo.isDefault = true; 7022 forwardingResolveInfo.filter = filter; 7023 forwardingResolveInfo.targetUserId = targetUserId; 7024 return forwardingResolveInfo; 7025 } 7026 7027 @Override 7028 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7029 Intent[] specifics, String[] specificTypes, Intent intent, 7030 String resolvedType, int flags, int userId) { 7031 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7032 specificTypes, intent, resolvedType, flags, userId)); 7033 } 7034 7035 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7036 Intent[] specifics, String[] specificTypes, Intent intent, 7037 String resolvedType, int flags, int userId) { 7038 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7039 final int callingUid = Binder.getCallingUid(); 7040 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7041 false /*includeInstantApps*/); 7042 enforceCrossUserPermission(callingUid, userId, 7043 false /*requireFullPermission*/, false /*checkShell*/, 7044 "query intent activity options"); 7045 final String resultsAction = intent.getAction(); 7046 7047 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7048 | PackageManager.GET_RESOLVED_FILTER, userId); 7049 7050 if (DEBUG_INTENT_MATCHING) { 7051 Log.v(TAG, "Query " + intent + ": " + results); 7052 } 7053 7054 int specificsPos = 0; 7055 int N; 7056 7057 // todo: note that the algorithm used here is O(N^2). This 7058 // isn't a problem in our current environment, but if we start running 7059 // into situations where we have more than 5 or 10 matches then this 7060 // should probably be changed to something smarter... 7061 7062 // First we go through and resolve each of the specific items 7063 // that were supplied, taking care of removing any corresponding 7064 // duplicate items in the generic resolve list. 7065 if (specifics != null) { 7066 for (int i=0; i<specifics.length; i++) { 7067 final Intent sintent = specifics[i]; 7068 if (sintent == null) { 7069 continue; 7070 } 7071 7072 if (DEBUG_INTENT_MATCHING) { 7073 Log.v(TAG, "Specific #" + i + ": " + sintent); 7074 } 7075 7076 String action = sintent.getAction(); 7077 if (resultsAction != null && resultsAction.equals(action)) { 7078 // If this action was explicitly requested, then don't 7079 // remove things that have it. 7080 action = null; 7081 } 7082 7083 ResolveInfo ri = null; 7084 ActivityInfo ai = null; 7085 7086 ComponentName comp = sintent.getComponent(); 7087 if (comp == null) { 7088 ri = resolveIntent( 7089 sintent, 7090 specificTypes != null ? specificTypes[i] : null, 7091 flags, userId); 7092 if (ri == null) { 7093 continue; 7094 } 7095 if (ri == mResolveInfo) { 7096 // ACK! Must do something better with this. 7097 } 7098 ai = ri.activityInfo; 7099 comp = new ComponentName(ai.applicationInfo.packageName, 7100 ai.name); 7101 } else { 7102 ai = getActivityInfo(comp, flags, userId); 7103 if (ai == null) { 7104 continue; 7105 } 7106 } 7107 7108 // Look for any generic query activities that are duplicates 7109 // of this specific one, and remove them from the results. 7110 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7111 N = results.size(); 7112 int j; 7113 for (j=specificsPos; j<N; j++) { 7114 ResolveInfo sri = results.get(j); 7115 if ((sri.activityInfo.name.equals(comp.getClassName()) 7116 && sri.activityInfo.applicationInfo.packageName.equals( 7117 comp.getPackageName())) 7118 || (action != null && sri.filter.matchAction(action))) { 7119 results.remove(j); 7120 if (DEBUG_INTENT_MATCHING) Log.v( 7121 TAG, "Removing duplicate item from " + j 7122 + " due to specific " + specificsPos); 7123 if (ri == null) { 7124 ri = sri; 7125 } 7126 j--; 7127 N--; 7128 } 7129 } 7130 7131 // Add this specific item to its proper place. 7132 if (ri == null) { 7133 ri = new ResolveInfo(); 7134 ri.activityInfo = ai; 7135 } 7136 results.add(specificsPos, ri); 7137 ri.specificIndex = i; 7138 specificsPos++; 7139 } 7140 } 7141 7142 // Now we go through the remaining generic results and remove any 7143 // duplicate actions that are found here. 7144 N = results.size(); 7145 for (int i=specificsPos; i<N-1; i++) { 7146 final ResolveInfo rii = results.get(i); 7147 if (rii.filter == null) { 7148 continue; 7149 } 7150 7151 // Iterate over all of the actions of this result's intent 7152 // filter... typically this should be just one. 7153 final Iterator<String> it = rii.filter.actionsIterator(); 7154 if (it == null) { 7155 continue; 7156 } 7157 while (it.hasNext()) { 7158 final String action = it.next(); 7159 if (resultsAction != null && resultsAction.equals(action)) { 7160 // If this action was explicitly requested, then don't 7161 // remove things that have it. 7162 continue; 7163 } 7164 for (int j=i+1; j<N; j++) { 7165 final ResolveInfo rij = results.get(j); 7166 if (rij.filter != null && rij.filter.hasAction(action)) { 7167 results.remove(j); 7168 if (DEBUG_INTENT_MATCHING) Log.v( 7169 TAG, "Removing duplicate item from " + j 7170 + " due to action " + action + " at " + i); 7171 j--; 7172 N--; 7173 } 7174 } 7175 } 7176 7177 // If the caller didn't request filter information, drop it now 7178 // so we don't have to marshall/unmarshall it. 7179 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7180 rii.filter = null; 7181 } 7182 } 7183 7184 // Filter out the caller activity if so requested. 7185 if (caller != null) { 7186 N = results.size(); 7187 for (int i=0; i<N; i++) { 7188 ActivityInfo ainfo = results.get(i).activityInfo; 7189 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7190 && caller.getClassName().equals(ainfo.name)) { 7191 results.remove(i); 7192 break; 7193 } 7194 } 7195 } 7196 7197 // If the caller didn't request filter information, 7198 // drop them now so we don't have to 7199 // marshall/unmarshall it. 7200 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7201 N = results.size(); 7202 for (int i=0; i<N; i++) { 7203 results.get(i).filter = null; 7204 } 7205 } 7206 7207 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7208 return results; 7209 } 7210 7211 @Override 7212 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7213 String resolvedType, int flags, int userId) { 7214 return new ParceledListSlice<>( 7215 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7216 } 7217 7218 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7219 String resolvedType, int flags, int userId) { 7220 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7221 final int callingUid = Binder.getCallingUid(); 7222 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7223 false /*includeInstantApps*/); 7224 ComponentName comp = intent.getComponent(); 7225 if (comp == null) { 7226 if (intent.getSelector() != null) { 7227 intent = intent.getSelector(); 7228 comp = intent.getComponent(); 7229 } 7230 } 7231 if (comp != null) { 7232 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7233 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7234 if (ai != null) { 7235 ResolveInfo ri = new ResolveInfo(); 7236 ri.activityInfo = ai; 7237 list.add(ri); 7238 } 7239 return list; 7240 } 7241 7242 // reader 7243 synchronized (mPackages) { 7244 String pkgName = intent.getPackage(); 7245 if (pkgName == null) { 7246 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7247 } 7248 final PackageParser.Package pkg = mPackages.get(pkgName); 7249 if (pkg != null) { 7250 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7251 userId); 7252 } 7253 return Collections.emptyList(); 7254 } 7255 } 7256 7257 @Override 7258 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7259 final int callingUid = Binder.getCallingUid(); 7260 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7261 } 7262 7263 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7264 int userId, int callingUid) { 7265 if (!sUserManager.exists(userId)) return null; 7266 flags = updateFlagsForResolve( 7267 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7268 List<ResolveInfo> query = queryIntentServicesInternal( 7269 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7270 if (query != null) { 7271 if (query.size() >= 1) { 7272 // If there is more than one service with the same priority, 7273 // just arbitrarily pick the first one. 7274 return query.get(0); 7275 } 7276 } 7277 return null; 7278 } 7279 7280 @Override 7281 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7282 String resolvedType, int flags, int userId) { 7283 final int callingUid = Binder.getCallingUid(); 7284 return new ParceledListSlice<>(queryIntentServicesInternal( 7285 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7286 } 7287 7288 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7289 String resolvedType, int flags, int userId, int callingUid, 7290 boolean includeInstantApps) { 7291 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7292 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7293 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7294 ComponentName comp = intent.getComponent(); 7295 if (comp == null) { 7296 if (intent.getSelector() != null) { 7297 intent = intent.getSelector(); 7298 comp = intent.getComponent(); 7299 } 7300 } 7301 if (comp != null) { 7302 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7303 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7304 if (si != null) { 7305 // When specifying an explicit component, we prevent the service from being 7306 // used when either 1) the service is in an instant application and the 7307 // caller is not the same instant application or 2) the calling package is 7308 // ephemeral and the activity is not visible to ephemeral applications. 7309 final boolean matchInstantApp = 7310 (flags & PackageManager.MATCH_INSTANT) != 0; 7311 final boolean matchVisibleToInstantAppOnly = 7312 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7313 final boolean isCallerInstantApp = 7314 instantAppPkgName != null; 7315 final boolean isTargetSameInstantApp = 7316 comp.getPackageName().equals(instantAppPkgName); 7317 final boolean isTargetInstantApp = 7318 (si.applicationInfo.privateFlags 7319 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7320 final boolean isTargetHiddenFromInstantApp = 7321 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7322 final boolean blockResolution = 7323 !isTargetSameInstantApp 7324 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7325 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7326 && isTargetHiddenFromInstantApp)); 7327 if (!blockResolution) { 7328 final ResolveInfo ri = new ResolveInfo(); 7329 ri.serviceInfo = si; 7330 list.add(ri); 7331 } 7332 } 7333 return list; 7334 } 7335 7336 // reader 7337 synchronized (mPackages) { 7338 String pkgName = intent.getPackage(); 7339 if (pkgName == null) { 7340 return applyPostServiceResolutionFilter( 7341 mServices.queryIntent(intent, resolvedType, flags, userId), 7342 instantAppPkgName); 7343 } 7344 final PackageParser.Package pkg = mPackages.get(pkgName); 7345 if (pkg != null) { 7346 return applyPostServiceResolutionFilter( 7347 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7348 userId), 7349 instantAppPkgName); 7350 } 7351 return Collections.emptyList(); 7352 } 7353 } 7354 7355 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7356 String instantAppPkgName) { 7357 // TODO: When adding on-demand split support for non-instant apps, remove this check 7358 // and always apply post filtering 7359 if (instantAppPkgName == null) { 7360 return resolveInfos; 7361 } 7362 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7363 final ResolveInfo info = resolveInfos.get(i); 7364 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7365 // allow services that are defined in the provided package 7366 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7367 if (info.serviceInfo.splitName != null 7368 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7369 info.serviceInfo.splitName)) { 7370 // requested service is defined in a split that hasn't been installed yet. 7371 // add the installer to the resolve list 7372 if (DEBUG_EPHEMERAL) { 7373 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7374 } 7375 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7376 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7377 info.serviceInfo.packageName, info.serviceInfo.splitName, 7378 info.serviceInfo.applicationInfo.versionCode); 7379 // make sure this resolver is the default 7380 installerInfo.isDefault = true; 7381 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7382 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7383 // add a non-generic filter 7384 installerInfo.filter = new IntentFilter(); 7385 // load resources from the correct package 7386 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7387 resolveInfos.set(i, installerInfo); 7388 } 7389 continue; 7390 } 7391 // allow services that have been explicitly exposed to ephemeral apps 7392 if (!isEphemeralApp 7393 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7394 continue; 7395 } 7396 resolveInfos.remove(i); 7397 } 7398 return resolveInfos; 7399 } 7400 7401 @Override 7402 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7403 String resolvedType, int flags, int userId) { 7404 return new ParceledListSlice<>( 7405 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7406 } 7407 7408 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7409 Intent intent, String resolvedType, int flags, int userId) { 7410 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7411 final int callingUid = Binder.getCallingUid(); 7412 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7413 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7414 false /*includeInstantApps*/); 7415 ComponentName comp = intent.getComponent(); 7416 if (comp == null) { 7417 if (intent.getSelector() != null) { 7418 intent = intent.getSelector(); 7419 comp = intent.getComponent(); 7420 } 7421 } 7422 if (comp != null) { 7423 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7424 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7425 if (pi != null) { 7426 // When specifying an explicit component, we prevent the provider from being 7427 // used when either 1) the provider is in an instant application and the 7428 // caller is not the same instant application or 2) the calling package is an 7429 // instant application and the provider is not visible to instant applications. 7430 final boolean matchInstantApp = 7431 (flags & PackageManager.MATCH_INSTANT) != 0; 7432 final boolean matchVisibleToInstantAppOnly = 7433 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7434 final boolean isCallerInstantApp = 7435 instantAppPkgName != null; 7436 final boolean isTargetSameInstantApp = 7437 comp.getPackageName().equals(instantAppPkgName); 7438 final boolean isTargetInstantApp = 7439 (pi.applicationInfo.privateFlags 7440 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7441 final boolean isTargetHiddenFromInstantApp = 7442 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7443 final boolean blockResolution = 7444 !isTargetSameInstantApp 7445 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7446 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7447 && isTargetHiddenFromInstantApp)); 7448 if (!blockResolution) { 7449 final ResolveInfo ri = new ResolveInfo(); 7450 ri.providerInfo = pi; 7451 list.add(ri); 7452 } 7453 } 7454 return list; 7455 } 7456 7457 // reader 7458 synchronized (mPackages) { 7459 String pkgName = intent.getPackage(); 7460 if (pkgName == null) { 7461 return applyPostContentProviderResolutionFilter( 7462 mProviders.queryIntent(intent, resolvedType, flags, userId), 7463 instantAppPkgName); 7464 } 7465 final PackageParser.Package pkg = mPackages.get(pkgName); 7466 if (pkg != null) { 7467 return applyPostContentProviderResolutionFilter( 7468 mProviders.queryIntentForPackage( 7469 intent, resolvedType, flags, pkg.providers, userId), 7470 instantAppPkgName); 7471 } 7472 return Collections.emptyList(); 7473 } 7474 } 7475 7476 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7477 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7478 // TODO: When adding on-demand split support for non-instant applications, remove 7479 // this check and always apply post filtering 7480 if (instantAppPkgName == null) { 7481 return resolveInfos; 7482 } 7483 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7484 final ResolveInfo info = resolveInfos.get(i); 7485 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7486 // allow providers that are defined in the provided package 7487 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7488 if (info.providerInfo.splitName != null 7489 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7490 info.providerInfo.splitName)) { 7491 // requested provider is defined in a split that hasn't been installed yet. 7492 // add the installer to the resolve list 7493 if (DEBUG_EPHEMERAL) { 7494 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7495 } 7496 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7497 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7498 info.providerInfo.packageName, info.providerInfo.splitName, 7499 info.providerInfo.applicationInfo.versionCode); 7500 // make sure this resolver is the default 7501 installerInfo.isDefault = true; 7502 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7503 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7504 // add a non-generic filter 7505 installerInfo.filter = new IntentFilter(); 7506 // load resources from the correct package 7507 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7508 resolveInfos.set(i, installerInfo); 7509 } 7510 continue; 7511 } 7512 // allow providers that have been explicitly exposed to instant applications 7513 if (!isEphemeralApp 7514 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7515 continue; 7516 } 7517 resolveInfos.remove(i); 7518 } 7519 return resolveInfos; 7520 } 7521 7522 @Override 7523 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7524 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7525 flags = updateFlagsForPackage(flags, userId, null); 7526 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7527 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7528 true /* requireFullPermission */, false /* checkShell */, 7529 "get installed packages"); 7530 7531 // writer 7532 synchronized (mPackages) { 7533 ArrayList<PackageInfo> list; 7534 if (listUninstalled) { 7535 list = new ArrayList<>(mSettings.mPackages.size()); 7536 for (PackageSetting ps : mSettings.mPackages.values()) { 7537 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7538 continue; 7539 } 7540 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7541 if (pi != null) { 7542 list.add(pi); 7543 } 7544 } 7545 } else { 7546 list = new ArrayList<>(mPackages.size()); 7547 for (PackageParser.Package p : mPackages.values()) { 7548 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7549 Binder.getCallingUid(), userId)) { 7550 continue; 7551 } 7552 final PackageInfo pi = generatePackageInfo((PackageSetting) 7553 p.mExtras, flags, userId); 7554 if (pi != null) { 7555 list.add(pi); 7556 } 7557 } 7558 } 7559 7560 return new ParceledListSlice<>(list); 7561 } 7562 } 7563 7564 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7565 String[] permissions, boolean[] tmp, int flags, int userId) { 7566 int numMatch = 0; 7567 final PermissionsState permissionsState = ps.getPermissionsState(); 7568 for (int i=0; i<permissions.length; i++) { 7569 final String permission = permissions[i]; 7570 if (permissionsState.hasPermission(permission, userId)) { 7571 tmp[i] = true; 7572 numMatch++; 7573 } else { 7574 tmp[i] = false; 7575 } 7576 } 7577 if (numMatch == 0) { 7578 return; 7579 } 7580 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7581 7582 // The above might return null in cases of uninstalled apps or install-state 7583 // skew across users/profiles. 7584 if (pi != null) { 7585 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7586 if (numMatch == permissions.length) { 7587 pi.requestedPermissions = permissions; 7588 } else { 7589 pi.requestedPermissions = new String[numMatch]; 7590 numMatch = 0; 7591 for (int i=0; i<permissions.length; i++) { 7592 if (tmp[i]) { 7593 pi.requestedPermissions[numMatch] = permissions[i]; 7594 numMatch++; 7595 } 7596 } 7597 } 7598 } 7599 list.add(pi); 7600 } 7601 } 7602 7603 @Override 7604 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7605 String[] permissions, int flags, int userId) { 7606 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7607 flags = updateFlagsForPackage(flags, userId, permissions); 7608 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7609 true /* requireFullPermission */, false /* checkShell */, 7610 "get packages holding permissions"); 7611 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7612 7613 // writer 7614 synchronized (mPackages) { 7615 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7616 boolean[] tmpBools = new boolean[permissions.length]; 7617 if (listUninstalled) { 7618 for (PackageSetting ps : mSettings.mPackages.values()) { 7619 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7620 userId); 7621 } 7622 } else { 7623 for (PackageParser.Package pkg : mPackages.values()) { 7624 PackageSetting ps = (PackageSetting)pkg.mExtras; 7625 if (ps != null) { 7626 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7627 userId); 7628 } 7629 } 7630 } 7631 7632 return new ParceledListSlice<PackageInfo>(list); 7633 } 7634 } 7635 7636 @Override 7637 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7638 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7639 flags = updateFlagsForApplication(flags, userId, null); 7640 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7641 7642 // writer 7643 synchronized (mPackages) { 7644 ArrayList<ApplicationInfo> list; 7645 if (listUninstalled) { 7646 list = new ArrayList<>(mSettings.mPackages.size()); 7647 for (PackageSetting ps : mSettings.mPackages.values()) { 7648 ApplicationInfo ai; 7649 int effectiveFlags = flags; 7650 if (ps.isSystem()) { 7651 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7652 } 7653 if (ps.pkg != null) { 7654 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7655 continue; 7656 } 7657 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7658 ps.readUserState(userId), userId); 7659 if (ai != null) { 7660 rebaseEnabledOverlays(ai, userId); 7661 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7662 } 7663 } else { 7664 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7665 // and already converts to externally visible package name 7666 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7667 Binder.getCallingUid(), effectiveFlags, userId); 7668 } 7669 if (ai != null) { 7670 list.add(ai); 7671 } 7672 } 7673 } else { 7674 list = new ArrayList<>(mPackages.size()); 7675 for (PackageParser.Package p : mPackages.values()) { 7676 if (p.mExtras != null) { 7677 PackageSetting ps = (PackageSetting) p.mExtras; 7678 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7679 continue; 7680 } 7681 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7682 ps.readUserState(userId), userId); 7683 if (ai != null) { 7684 rebaseEnabledOverlays(ai, userId); 7685 ai.packageName = resolveExternalPackageNameLPr(p); 7686 list.add(ai); 7687 } 7688 } 7689 } 7690 } 7691 7692 return new ParceledListSlice<>(list); 7693 } 7694 } 7695 7696 @Override 7697 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7698 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7699 return null; 7700 } 7701 7702 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7703 "getEphemeralApplications"); 7704 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7705 true /* requireFullPermission */, false /* checkShell */, 7706 "getEphemeralApplications"); 7707 synchronized (mPackages) { 7708 List<InstantAppInfo> instantApps = mInstantAppRegistry 7709 .getInstantAppsLPr(userId); 7710 if (instantApps != null) { 7711 return new ParceledListSlice<>(instantApps); 7712 } 7713 } 7714 return null; 7715 } 7716 7717 @Override 7718 public boolean isInstantApp(String packageName, int userId) { 7719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7720 true /* requireFullPermission */, false /* checkShell */, 7721 "isInstantApp"); 7722 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7723 return false; 7724 } 7725 int uid = Binder.getCallingUid(); 7726 if (Process.isIsolated(uid)) { 7727 uid = mIsolatedOwners.get(uid); 7728 } 7729 7730 synchronized (mPackages) { 7731 final PackageSetting ps = mSettings.mPackages.get(packageName); 7732 PackageParser.Package pkg = mPackages.get(packageName); 7733 final boolean returnAllowed = 7734 ps != null 7735 && (isCallerSameApp(packageName, uid) 7736 || mContext.checkCallingOrSelfPermission( 7737 android.Manifest.permission.ACCESS_INSTANT_APPS) 7738 == PERMISSION_GRANTED 7739 || mInstantAppRegistry.isInstantAccessGranted( 7740 userId, UserHandle.getAppId(uid), ps.appId)); 7741 if (returnAllowed) { 7742 return ps.getInstantApp(userId); 7743 } 7744 } 7745 return false; 7746 } 7747 7748 @Override 7749 public byte[] getInstantAppCookie(String packageName, int userId) { 7750 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7751 return null; 7752 } 7753 7754 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7755 true /* requireFullPermission */, false /* checkShell */, 7756 "getInstantAppCookie"); 7757 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7758 return null; 7759 } 7760 synchronized (mPackages) { 7761 return mInstantAppRegistry.getInstantAppCookieLPw( 7762 packageName, userId); 7763 } 7764 } 7765 7766 @Override 7767 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7768 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7769 return true; 7770 } 7771 7772 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7773 true /* requireFullPermission */, true /* checkShell */, 7774 "setInstantAppCookie"); 7775 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7776 return false; 7777 } 7778 synchronized (mPackages) { 7779 return mInstantAppRegistry.setInstantAppCookieLPw( 7780 packageName, cookie, userId); 7781 } 7782 } 7783 7784 @Override 7785 public Bitmap getInstantAppIcon(String packageName, int userId) { 7786 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7787 return null; 7788 } 7789 7790 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7791 "getInstantAppIcon"); 7792 7793 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7794 true /* requireFullPermission */, false /* checkShell */, 7795 "getInstantAppIcon"); 7796 7797 synchronized (mPackages) { 7798 return mInstantAppRegistry.getInstantAppIconLPw( 7799 packageName, userId); 7800 } 7801 } 7802 7803 private boolean isCallerSameApp(String packageName, int uid) { 7804 PackageParser.Package pkg = mPackages.get(packageName); 7805 return pkg != null 7806 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7807 } 7808 7809 @Override 7810 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7811 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7812 } 7813 7814 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7815 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7816 7817 // reader 7818 synchronized (mPackages) { 7819 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7820 final int userId = UserHandle.getCallingUserId(); 7821 while (i.hasNext()) { 7822 final PackageParser.Package p = i.next(); 7823 if (p.applicationInfo == null) continue; 7824 7825 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7826 && !p.applicationInfo.isDirectBootAware(); 7827 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7828 && p.applicationInfo.isDirectBootAware(); 7829 7830 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7831 && (!mSafeMode || isSystemApp(p)) 7832 && (matchesUnaware || matchesAware)) { 7833 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7834 if (ps != null) { 7835 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7836 ps.readUserState(userId), userId); 7837 if (ai != null) { 7838 rebaseEnabledOverlays(ai, userId); 7839 finalList.add(ai); 7840 } 7841 } 7842 } 7843 } 7844 } 7845 7846 return finalList; 7847 } 7848 7849 @Override 7850 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7851 if (!sUserManager.exists(userId)) return null; 7852 flags = updateFlagsForComponent(flags, userId, name); 7853 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 7854 // reader 7855 synchronized (mPackages) { 7856 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7857 PackageSetting ps = provider != null 7858 ? mSettings.mPackages.get(provider.owner.packageName) 7859 : null; 7860 if (ps != null) { 7861 final boolean isInstantApp = ps.getInstantApp(userId); 7862 // normal application; filter out instant application provider 7863 if (instantAppPkgName == null && isInstantApp) { 7864 return null; 7865 } 7866 // instant application; filter out other instant applications 7867 if (instantAppPkgName != null 7868 && isInstantApp 7869 && !provider.owner.packageName.equals(instantAppPkgName)) { 7870 return null; 7871 } 7872 // instant application; filter out non-exposed provider 7873 if (instantAppPkgName != null 7874 && !isInstantApp 7875 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 7876 return null; 7877 } 7878 // provider not enabled 7879 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 7880 return null; 7881 } 7882 return PackageParser.generateProviderInfo( 7883 provider, flags, ps.readUserState(userId), userId); 7884 } 7885 return null; 7886 } 7887 } 7888 7889 /** 7890 * @deprecated 7891 */ 7892 @Deprecated 7893 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7894 // reader 7895 synchronized (mPackages) { 7896 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7897 .entrySet().iterator(); 7898 final int userId = UserHandle.getCallingUserId(); 7899 while (i.hasNext()) { 7900 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7901 PackageParser.Provider p = entry.getValue(); 7902 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7903 7904 if (ps != null && p.syncable 7905 && (!mSafeMode || (p.info.applicationInfo.flags 7906 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7907 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7908 ps.readUserState(userId), userId); 7909 if (info != null) { 7910 outNames.add(entry.getKey()); 7911 outInfo.add(info); 7912 } 7913 } 7914 } 7915 } 7916 } 7917 7918 @Override 7919 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7920 int uid, int flags, String metaDataKey) { 7921 final int userId = processName != null ? UserHandle.getUserId(uid) 7922 : UserHandle.getCallingUserId(); 7923 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7924 flags = updateFlagsForComponent(flags, userId, processName); 7925 7926 ArrayList<ProviderInfo> finalList = null; 7927 // reader 7928 synchronized (mPackages) { 7929 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7930 while (i.hasNext()) { 7931 final PackageParser.Provider p = i.next(); 7932 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7933 if (ps != null && p.info.authority != null 7934 && (processName == null 7935 || (p.info.processName.equals(processName) 7936 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7937 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7938 7939 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7940 // parameter. 7941 if (metaDataKey != null 7942 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7943 continue; 7944 } 7945 7946 if (finalList == null) { 7947 finalList = new ArrayList<ProviderInfo>(3); 7948 } 7949 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7950 ps.readUserState(userId), userId); 7951 if (info != null) { 7952 finalList.add(info); 7953 } 7954 } 7955 } 7956 } 7957 7958 if (finalList != null) { 7959 Collections.sort(finalList, mProviderInitOrderSorter); 7960 return new ParceledListSlice<ProviderInfo>(finalList); 7961 } 7962 7963 return ParceledListSlice.emptyList(); 7964 } 7965 7966 @Override 7967 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7968 // reader 7969 synchronized (mPackages) { 7970 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7971 return PackageParser.generateInstrumentationInfo(i, flags); 7972 } 7973 } 7974 7975 @Override 7976 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7977 String targetPackage, int flags) { 7978 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7979 } 7980 7981 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7982 int flags) { 7983 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7984 7985 // reader 7986 synchronized (mPackages) { 7987 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7988 while (i.hasNext()) { 7989 final PackageParser.Instrumentation p = i.next(); 7990 if (targetPackage == null 7991 || targetPackage.equals(p.info.targetPackage)) { 7992 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7993 flags); 7994 if (ii != null) { 7995 finalList.add(ii); 7996 } 7997 } 7998 } 7999 } 8000 8001 return finalList; 8002 } 8003 8004 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 8005 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 8006 try { 8007 scanDirLI(dir, parseFlags, scanFlags, currentTime); 8008 } finally { 8009 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8010 } 8011 } 8012 8013 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 8014 final File[] files = dir.listFiles(); 8015 if (ArrayUtils.isEmpty(files)) { 8016 Log.d(TAG, "No files in app dir " + dir); 8017 return; 8018 } 8019 8020 if (DEBUG_PACKAGE_SCANNING) { 8021 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 8022 + " flags=0x" + Integer.toHexString(parseFlags)); 8023 } 8024 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8025 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8026 mParallelPackageParserCallback); 8027 8028 // Submit files for parsing in parallel 8029 int fileCount = 0; 8030 for (File file : files) { 8031 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8032 && !PackageInstallerService.isStageName(file.getName()); 8033 if (!isPackage) { 8034 // Ignore entries which are not packages 8035 continue; 8036 } 8037 parallelPackageParser.submit(file, parseFlags); 8038 fileCount++; 8039 } 8040 8041 // Process results one by one 8042 for (; fileCount > 0; fileCount--) { 8043 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8044 Throwable throwable = parseResult.throwable; 8045 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8046 8047 if (throwable == null) { 8048 // Static shared libraries have synthetic package names 8049 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8050 renameStaticSharedLibraryPackage(parseResult.pkg); 8051 } 8052 try { 8053 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8054 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8055 currentTime, null); 8056 } 8057 } catch (PackageManagerException e) { 8058 errorCode = e.error; 8059 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8060 } 8061 } else if (throwable instanceof PackageParser.PackageParserException) { 8062 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8063 throwable; 8064 errorCode = e.error; 8065 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8066 } else { 8067 throw new IllegalStateException("Unexpected exception occurred while parsing " 8068 + parseResult.scanFile, throwable); 8069 } 8070 8071 // Delete invalid userdata apps 8072 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8073 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8074 logCriticalInfo(Log.WARN, 8075 "Deleting invalid package at " + parseResult.scanFile); 8076 removeCodePathLI(parseResult.scanFile); 8077 } 8078 } 8079 parallelPackageParser.close(); 8080 } 8081 8082 private static File getSettingsProblemFile() { 8083 File dataDir = Environment.getDataDirectory(); 8084 File systemDir = new File(dataDir, "system"); 8085 File fname = new File(systemDir, "uiderrors.txt"); 8086 return fname; 8087 } 8088 8089 static void reportSettingsProblem(int priority, String msg) { 8090 logCriticalInfo(priority, msg); 8091 } 8092 8093 public static void logCriticalInfo(int priority, String msg) { 8094 Slog.println(priority, TAG, msg); 8095 EventLogTags.writePmCriticalInfo(msg); 8096 try { 8097 File fname = getSettingsProblemFile(); 8098 FileOutputStream out = new FileOutputStream(fname, true); 8099 PrintWriter pw = new FastPrintWriter(out); 8100 SimpleDateFormat formatter = new SimpleDateFormat(); 8101 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8102 pw.println(dateString + ": " + msg); 8103 pw.close(); 8104 FileUtils.setPermissions( 8105 fname.toString(), 8106 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8107 -1, -1); 8108 } catch (java.io.IOException e) { 8109 } 8110 } 8111 8112 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8113 if (srcFile.isDirectory()) { 8114 final File baseFile = new File(pkg.baseCodePath); 8115 long maxModifiedTime = baseFile.lastModified(); 8116 if (pkg.splitCodePaths != null) { 8117 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8118 final File splitFile = new File(pkg.splitCodePaths[i]); 8119 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8120 } 8121 } 8122 return maxModifiedTime; 8123 } 8124 return srcFile.lastModified(); 8125 } 8126 8127 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8128 final int policyFlags) throws PackageManagerException { 8129 // When upgrading from pre-N MR1, verify the package time stamp using the package 8130 // directory and not the APK file. 8131 final long lastModifiedTime = mIsPreNMR1Upgrade 8132 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8133 if (ps != null 8134 && ps.codePath.equals(srcFile) 8135 && ps.timeStamp == lastModifiedTime 8136 && !isCompatSignatureUpdateNeeded(pkg) 8137 && !isRecoverSignatureUpdateNeeded(pkg)) { 8138 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8139 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8140 ArraySet<PublicKey> signingKs; 8141 synchronized (mPackages) { 8142 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8143 } 8144 if (ps.signatures.mSignatures != null 8145 && ps.signatures.mSignatures.length != 0 8146 && signingKs != null) { 8147 // Optimization: reuse the existing cached certificates 8148 // if the package appears to be unchanged. 8149 pkg.mSignatures = ps.signatures.mSignatures; 8150 pkg.mSigningKeys = signingKs; 8151 return; 8152 } 8153 8154 Slog.w(TAG, "PackageSetting for " + ps.name 8155 + " is missing signatures. Collecting certs again to recover them."); 8156 } else { 8157 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8158 } 8159 8160 try { 8161 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8162 PackageParser.collectCertificates(pkg, policyFlags); 8163 } catch (PackageParserException e) { 8164 throw PackageManagerException.from(e); 8165 } finally { 8166 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8167 } 8168 } 8169 8170 /** 8171 * Traces a package scan. 8172 * @see #scanPackageLI(File, int, int, long, UserHandle) 8173 */ 8174 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8175 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8176 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8177 try { 8178 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8179 } finally { 8180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8181 } 8182 } 8183 8184 /** 8185 * Scans a package and returns the newly parsed package. 8186 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8187 */ 8188 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8189 long currentTime, UserHandle user) throws PackageManagerException { 8190 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8191 PackageParser pp = new PackageParser(); 8192 pp.setSeparateProcesses(mSeparateProcesses); 8193 pp.setOnlyCoreApps(mOnlyCore); 8194 pp.setDisplayMetrics(mMetrics); 8195 pp.setCallback(mPackageParserCallback); 8196 8197 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8198 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8199 } 8200 8201 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8202 final PackageParser.Package pkg; 8203 try { 8204 pkg = pp.parsePackage(scanFile, parseFlags); 8205 } catch (PackageParserException e) { 8206 throw PackageManagerException.from(e); 8207 } finally { 8208 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8209 } 8210 8211 // Static shared libraries have synthetic package names 8212 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8213 renameStaticSharedLibraryPackage(pkg); 8214 } 8215 8216 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8217 } 8218 8219 /** 8220 * Scans a package and returns the newly parsed package. 8221 * @throws PackageManagerException on a parse error. 8222 */ 8223 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8224 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8225 throws PackageManagerException { 8226 // If the package has children and this is the first dive in the function 8227 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8228 // packages (parent and children) would be successfully scanned before the 8229 // actual scan since scanning mutates internal state and we want to atomically 8230 // install the package and its children. 8231 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8232 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8233 scanFlags |= SCAN_CHECK_ONLY; 8234 } 8235 } else { 8236 scanFlags &= ~SCAN_CHECK_ONLY; 8237 } 8238 8239 // Scan the parent 8240 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8241 scanFlags, currentTime, user); 8242 8243 // Scan the children 8244 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8245 for (int i = 0; i < childCount; i++) { 8246 PackageParser.Package childPackage = pkg.childPackages.get(i); 8247 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8248 currentTime, user); 8249 } 8250 8251 8252 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8253 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8254 } 8255 8256 return scannedPkg; 8257 } 8258 8259 /** 8260 * Scans a package and returns the newly parsed package. 8261 * @throws PackageManagerException on a parse error. 8262 */ 8263 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8264 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8265 throws PackageManagerException { 8266 PackageSetting ps = null; 8267 PackageSetting updatedPkg; 8268 // reader 8269 synchronized (mPackages) { 8270 // Look to see if we already know about this package. 8271 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8272 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8273 // This package has been renamed to its original name. Let's 8274 // use that. 8275 ps = mSettings.getPackageLPr(oldName); 8276 } 8277 // If there was no original package, see one for the real package name. 8278 if (ps == null) { 8279 ps = mSettings.getPackageLPr(pkg.packageName); 8280 } 8281 // Check to see if this package could be hiding/updating a system 8282 // package. Must look for it either under the original or real 8283 // package name depending on our state. 8284 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8285 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8286 8287 // If this is a package we don't know about on the system partition, we 8288 // may need to remove disabled child packages on the system partition 8289 // or may need to not add child packages if the parent apk is updated 8290 // on the data partition and no longer defines this child package. 8291 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8292 // If this is a parent package for an updated system app and this system 8293 // app got an OTA update which no longer defines some of the child packages 8294 // we have to prune them from the disabled system packages. 8295 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8296 if (disabledPs != null) { 8297 final int scannedChildCount = (pkg.childPackages != null) 8298 ? pkg.childPackages.size() : 0; 8299 final int disabledChildCount = disabledPs.childPackageNames != null 8300 ? disabledPs.childPackageNames.size() : 0; 8301 for (int i = 0; i < disabledChildCount; i++) { 8302 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8303 boolean disabledPackageAvailable = false; 8304 for (int j = 0; j < scannedChildCount; j++) { 8305 PackageParser.Package childPkg = pkg.childPackages.get(j); 8306 if (childPkg.packageName.equals(disabledChildPackageName)) { 8307 disabledPackageAvailable = true; 8308 break; 8309 } 8310 } 8311 if (!disabledPackageAvailable) { 8312 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8313 } 8314 } 8315 } 8316 } 8317 } 8318 8319 boolean updatedPkgBetter = false; 8320 // First check if this is a system package that may involve an update 8321 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8322 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8323 // it needs to drop FLAG_PRIVILEGED. 8324 if (locationIsPrivileged(scanFile)) { 8325 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8326 } else { 8327 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8328 } 8329 8330 if (ps != null && !ps.codePath.equals(scanFile)) { 8331 // The path has changed from what was last scanned... check the 8332 // version of the new path against what we have stored to determine 8333 // what to do. 8334 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8335 if (pkg.mVersionCode <= ps.versionCode) { 8336 // The system package has been updated and the code path does not match 8337 // Ignore entry. Skip it. 8338 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8339 + " ignored: updated version " + ps.versionCode 8340 + " better than this " + pkg.mVersionCode); 8341 if (!updatedPkg.codePath.equals(scanFile)) { 8342 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8343 + ps.name + " changing from " + updatedPkg.codePathString 8344 + " to " + scanFile); 8345 updatedPkg.codePath = scanFile; 8346 updatedPkg.codePathString = scanFile.toString(); 8347 updatedPkg.resourcePath = scanFile; 8348 updatedPkg.resourcePathString = scanFile.toString(); 8349 } 8350 updatedPkg.pkg = pkg; 8351 updatedPkg.versionCode = pkg.mVersionCode; 8352 8353 // Update the disabled system child packages to point to the package too. 8354 final int childCount = updatedPkg.childPackageNames != null 8355 ? updatedPkg.childPackageNames.size() : 0; 8356 for (int i = 0; i < childCount; i++) { 8357 String childPackageName = updatedPkg.childPackageNames.get(i); 8358 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8359 childPackageName); 8360 if (updatedChildPkg != null) { 8361 updatedChildPkg.pkg = pkg; 8362 updatedChildPkg.versionCode = pkg.mVersionCode; 8363 } 8364 } 8365 8366 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8367 + scanFile + " ignored: updated version " + ps.versionCode 8368 + " better than this " + pkg.mVersionCode); 8369 } else { 8370 // The current app on the system partition is better than 8371 // what we have updated to on the data partition; switch 8372 // back to the system partition version. 8373 // At this point, its safely assumed that package installation for 8374 // apps in system partition will go through. If not there won't be a working 8375 // version of the app 8376 // writer 8377 synchronized (mPackages) { 8378 // Just remove the loaded entries from package lists. 8379 mPackages.remove(ps.name); 8380 } 8381 8382 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8383 + " reverting from " + ps.codePathString 8384 + ": new version " + pkg.mVersionCode 8385 + " better than installed " + ps.versionCode); 8386 8387 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8388 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8389 synchronized (mInstallLock) { 8390 args.cleanUpResourcesLI(); 8391 } 8392 synchronized (mPackages) { 8393 mSettings.enableSystemPackageLPw(ps.name); 8394 } 8395 updatedPkgBetter = true; 8396 } 8397 } 8398 } 8399 8400 if (updatedPkg != null) { 8401 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8402 // initially 8403 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8404 8405 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8406 // flag set initially 8407 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8408 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8409 } 8410 } 8411 8412 // Verify certificates against what was last scanned 8413 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8414 8415 /* 8416 * A new system app appeared, but we already had a non-system one of the 8417 * same name installed earlier. 8418 */ 8419 boolean shouldHideSystemApp = false; 8420 if (updatedPkg == null && ps != null 8421 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8422 /* 8423 * Check to make sure the signatures match first. If they don't, 8424 * wipe the installed application and its data. 8425 */ 8426 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8427 != PackageManager.SIGNATURE_MATCH) { 8428 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8429 + " signatures don't match existing userdata copy; removing"); 8430 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8431 "scanPackageInternalLI")) { 8432 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8433 } 8434 ps = null; 8435 } else { 8436 /* 8437 * If the newly-added system app is an older version than the 8438 * already installed version, hide it. It will be scanned later 8439 * and re-added like an update. 8440 */ 8441 if (pkg.mVersionCode <= ps.versionCode) { 8442 shouldHideSystemApp = true; 8443 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8444 + " but new version " + pkg.mVersionCode + " better than installed " 8445 + ps.versionCode + "; hiding system"); 8446 } else { 8447 /* 8448 * The newly found system app is a newer version that the 8449 * one previously installed. Simply remove the 8450 * already-installed application and replace it with our own 8451 * while keeping the application data. 8452 */ 8453 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8454 + " reverting from " + ps.codePathString + ": new version " 8455 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8456 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8457 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8458 synchronized (mInstallLock) { 8459 args.cleanUpResourcesLI(); 8460 } 8461 } 8462 } 8463 } 8464 8465 // The apk is forward locked (not public) if its code and resources 8466 // are kept in different files. (except for app in either system or 8467 // vendor path). 8468 // TODO grab this value from PackageSettings 8469 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8470 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8471 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8472 } 8473 } 8474 8475 // TODO: extend to support forward-locked splits 8476 String resourcePath = null; 8477 String baseResourcePath = null; 8478 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8479 if (ps != null && ps.resourcePathString != null) { 8480 resourcePath = ps.resourcePathString; 8481 baseResourcePath = ps.resourcePathString; 8482 } else { 8483 // Should not happen at all. Just log an error. 8484 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8485 } 8486 } else { 8487 resourcePath = pkg.codePath; 8488 baseResourcePath = pkg.baseCodePath; 8489 } 8490 8491 // Set application objects path explicitly. 8492 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8493 pkg.setApplicationInfoCodePath(pkg.codePath); 8494 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8495 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8496 pkg.setApplicationInfoResourcePath(resourcePath); 8497 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8498 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8499 8500 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8501 if (ps != null && ps.getInstantApp(userId)) { 8502 scanFlags |= SCAN_AS_INSTANT_APP; 8503 } 8504 8505 // Note that we invoke the following method only if we are about to unpack an application 8506 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8507 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8508 8509 /* 8510 * If the system app should be overridden by a previously installed 8511 * data, hide the system app now and let the /data/app scan pick it up 8512 * again. 8513 */ 8514 if (shouldHideSystemApp) { 8515 synchronized (mPackages) { 8516 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8517 } 8518 } 8519 8520 return scannedPkg; 8521 } 8522 8523 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8524 // Derive the new package synthetic package name 8525 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8526 + pkg.staticSharedLibVersion); 8527 } 8528 8529 private static String fixProcessName(String defProcessName, 8530 String processName) { 8531 if (processName == null) { 8532 return defProcessName; 8533 } 8534 return processName; 8535 } 8536 8537 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8538 throws PackageManagerException { 8539 if (pkgSetting.signatures.mSignatures != null) { 8540 // Already existing package. Make sure signatures match 8541 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8542 == PackageManager.SIGNATURE_MATCH; 8543 if (!match) { 8544 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8545 == PackageManager.SIGNATURE_MATCH; 8546 } 8547 if (!match) { 8548 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8549 == PackageManager.SIGNATURE_MATCH; 8550 } 8551 if (!match) { 8552 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8553 + pkg.packageName + " signatures do not match the " 8554 + "previously installed version; ignoring!"); 8555 } 8556 } 8557 8558 // Check for shared user signatures 8559 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8560 // Already existing package. Make sure signatures match 8561 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8562 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8563 if (!match) { 8564 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8565 == PackageManager.SIGNATURE_MATCH; 8566 } 8567 if (!match) { 8568 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8569 == PackageManager.SIGNATURE_MATCH; 8570 } 8571 if (!match) { 8572 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8573 "Package " + pkg.packageName 8574 + " has no signatures that match those in shared user " 8575 + pkgSetting.sharedUser.name + "; ignoring!"); 8576 } 8577 } 8578 } 8579 8580 /** 8581 * Enforces that only the system UID or root's UID can call a method exposed 8582 * via Binder. 8583 * 8584 * @param message used as message if SecurityException is thrown 8585 * @throws SecurityException if the caller is not system or root 8586 */ 8587 private static final void enforceSystemOrRoot(String message) { 8588 final int uid = Binder.getCallingUid(); 8589 if (uid != Process.SYSTEM_UID && uid != 0) { 8590 throw new SecurityException(message); 8591 } 8592 } 8593 8594 @Override 8595 public void performFstrimIfNeeded() { 8596 enforceSystemOrRoot("Only the system can request fstrim"); 8597 8598 // Before everything else, see whether we need to fstrim. 8599 try { 8600 IStorageManager sm = PackageHelper.getStorageManager(); 8601 if (sm != null) { 8602 boolean doTrim = false; 8603 final long interval = android.provider.Settings.Global.getLong( 8604 mContext.getContentResolver(), 8605 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8606 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8607 if (interval > 0) { 8608 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8609 if (timeSinceLast > interval) { 8610 doTrim = true; 8611 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8612 + "; running immediately"); 8613 } 8614 } 8615 if (doTrim) { 8616 final boolean dexOptDialogShown; 8617 synchronized (mPackages) { 8618 dexOptDialogShown = mDexOptDialogShown; 8619 } 8620 if (!isFirstBoot() && dexOptDialogShown) { 8621 try { 8622 ActivityManager.getService().showBootMessage( 8623 mContext.getResources().getString( 8624 R.string.android_upgrading_fstrim), true); 8625 } catch (RemoteException e) { 8626 } 8627 } 8628 sm.runMaintenance(); 8629 } 8630 } else { 8631 Slog.e(TAG, "storageManager service unavailable!"); 8632 } 8633 } catch (RemoteException e) { 8634 // Can't happen; StorageManagerService is local 8635 } 8636 } 8637 8638 @Override 8639 public void updatePackagesIfNeeded() { 8640 enforceSystemOrRoot("Only the system can request package update"); 8641 8642 // We need to re-extract after an OTA. 8643 boolean causeUpgrade = isUpgrade(); 8644 8645 // First boot or factory reset. 8646 // Note: we also handle devices that are upgrading to N right now as if it is their 8647 // first boot, as they do not have profile data. 8648 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8649 8650 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8651 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8652 8653 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8654 return; 8655 } 8656 8657 List<PackageParser.Package> pkgs; 8658 synchronized (mPackages) { 8659 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8660 } 8661 8662 final long startTime = System.nanoTime(); 8663 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8664 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8665 8666 final int elapsedTimeSeconds = 8667 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8668 8669 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8670 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8671 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8672 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8673 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8674 } 8675 8676 /** 8677 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8678 * containing statistics about the invocation. The array consists of three elements, 8679 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8680 * and {@code numberOfPackagesFailed}. 8681 */ 8682 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8683 String compilerFilter) { 8684 8685 int numberOfPackagesVisited = 0; 8686 int numberOfPackagesOptimized = 0; 8687 int numberOfPackagesSkipped = 0; 8688 int numberOfPackagesFailed = 0; 8689 final int numberOfPackagesToDexopt = pkgs.size(); 8690 8691 for (PackageParser.Package pkg : pkgs) { 8692 numberOfPackagesVisited++; 8693 8694 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8695 if (DEBUG_DEXOPT) { 8696 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8697 } 8698 numberOfPackagesSkipped++; 8699 continue; 8700 } 8701 8702 if (DEBUG_DEXOPT) { 8703 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8704 numberOfPackagesToDexopt + ": " + pkg.packageName); 8705 } 8706 8707 if (showDialog) { 8708 try { 8709 ActivityManager.getService().showBootMessage( 8710 mContext.getResources().getString(R.string.android_upgrading_apk, 8711 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8712 } catch (RemoteException e) { 8713 } 8714 synchronized (mPackages) { 8715 mDexOptDialogShown = true; 8716 } 8717 } 8718 8719 // If the OTA updates a system app which was previously preopted to a non-preopted state 8720 // the app might end up being verified at runtime. That's because by default the apps 8721 // are verify-profile but for preopted apps there's no profile. 8722 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8723 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8724 // filter (by default 'quicken'). 8725 // Note that at this stage unused apps are already filtered. 8726 if (isSystemApp(pkg) && 8727 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8728 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8729 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8730 } 8731 8732 // checkProfiles is false to avoid merging profiles during boot which 8733 // might interfere with background compilation (b/28612421). 8734 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8735 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8736 // trade-off worth doing to save boot time work. 8737 int dexOptStatus = performDexOptTraced(pkg.packageName, 8738 false /* checkProfiles */, 8739 compilerFilter, 8740 false /* force */); 8741 switch (dexOptStatus) { 8742 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8743 numberOfPackagesOptimized++; 8744 break; 8745 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8746 numberOfPackagesSkipped++; 8747 break; 8748 case PackageDexOptimizer.DEX_OPT_FAILED: 8749 numberOfPackagesFailed++; 8750 break; 8751 default: 8752 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8753 break; 8754 } 8755 } 8756 8757 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8758 numberOfPackagesFailed }; 8759 } 8760 8761 @Override 8762 public void notifyPackageUse(String packageName, int reason) { 8763 synchronized (mPackages) { 8764 PackageParser.Package p = mPackages.get(packageName); 8765 if (p == null) { 8766 return; 8767 } 8768 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8769 } 8770 } 8771 8772 @Override 8773 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8774 int userId = UserHandle.getCallingUserId(); 8775 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8776 if (ai == null) { 8777 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8778 + loadingPackageName + ", user=" + userId); 8779 return; 8780 } 8781 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8782 } 8783 8784 @Override 8785 public boolean performDexOpt(String packageName, 8786 boolean checkProfiles, int compileReason, boolean force) { 8787 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8788 getCompilerFilterForReason(compileReason), force); 8789 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8790 } 8791 8792 @Override 8793 public boolean performDexOptMode(String packageName, 8794 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8795 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8796 targetCompilerFilter, force); 8797 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8798 } 8799 8800 private int performDexOptTraced(String packageName, 8801 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8802 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8803 try { 8804 return performDexOptInternal(packageName, checkProfiles, 8805 targetCompilerFilter, force); 8806 } finally { 8807 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8808 } 8809 } 8810 8811 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8812 // if the package can now be considered up to date for the given filter. 8813 private int performDexOptInternal(String packageName, 8814 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8815 PackageParser.Package p; 8816 synchronized (mPackages) { 8817 p = mPackages.get(packageName); 8818 if (p == null) { 8819 // Package could not be found. Report failure. 8820 return PackageDexOptimizer.DEX_OPT_FAILED; 8821 } 8822 mPackageUsage.maybeWriteAsync(mPackages); 8823 mCompilerStats.maybeWriteAsync(); 8824 } 8825 long callingId = Binder.clearCallingIdentity(); 8826 try { 8827 synchronized (mInstallLock) { 8828 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8829 targetCompilerFilter, force); 8830 } 8831 } finally { 8832 Binder.restoreCallingIdentity(callingId); 8833 } 8834 } 8835 8836 public ArraySet<String> getOptimizablePackages() { 8837 ArraySet<String> pkgs = new ArraySet<String>(); 8838 synchronized (mPackages) { 8839 for (PackageParser.Package p : mPackages.values()) { 8840 if (PackageDexOptimizer.canOptimizePackage(p)) { 8841 pkgs.add(p.packageName); 8842 } 8843 } 8844 } 8845 return pkgs; 8846 } 8847 8848 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8849 boolean checkProfiles, String targetCompilerFilter, 8850 boolean force) { 8851 // Select the dex optimizer based on the force parameter. 8852 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8853 // allocate an object here. 8854 PackageDexOptimizer pdo = force 8855 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8856 : mPackageDexOptimizer; 8857 8858 // Dexopt all dependencies first. Note: we ignore the return value and march on 8859 // on errors. 8860 // Note that we are going to call performDexOpt on those libraries as many times as 8861 // they are referenced in packages. When we do a batch of performDexOpt (for example 8862 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8863 // and the first package that uses the library will dexopt it. The 8864 // others will see that the compiled code for the library is up to date. 8865 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8866 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8867 if (!deps.isEmpty()) { 8868 for (PackageParser.Package depPackage : deps) { 8869 // TODO: Analyze and investigate if we (should) profile libraries. 8870 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8871 false /* checkProfiles */, 8872 targetCompilerFilter, 8873 getOrCreateCompilerPackageStats(depPackage), 8874 true /* isUsedByOtherApps */); 8875 } 8876 } 8877 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8878 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8879 mDexManager.isUsedByOtherApps(p.packageName)); 8880 } 8881 8882 // Performs dexopt on the used secondary dex files belonging to the given package. 8883 // Returns true if all dex files were process successfully (which could mean either dexopt or 8884 // skip). Returns false if any of the files caused errors. 8885 @Override 8886 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8887 boolean force) { 8888 mDexManager.reconcileSecondaryDexFiles(packageName); 8889 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8890 } 8891 8892 public boolean performDexOptSecondary(String packageName, int compileReason, 8893 boolean force) { 8894 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8895 } 8896 8897 /** 8898 * Reconcile the information we have about the secondary dex files belonging to 8899 * {@code packagName} and the actual dex files. For all dex files that were 8900 * deleted, update the internal records and delete the generated oat files. 8901 */ 8902 @Override 8903 public void reconcileSecondaryDexFiles(String packageName) { 8904 mDexManager.reconcileSecondaryDexFiles(packageName); 8905 } 8906 8907 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8908 // a reference there. 8909 /*package*/ DexManager getDexManager() { 8910 return mDexManager; 8911 } 8912 8913 /** 8914 * Execute the background dexopt job immediately. 8915 */ 8916 @Override 8917 public boolean runBackgroundDexoptJob() { 8918 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8919 } 8920 8921 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8922 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8923 || p.usesStaticLibraries != null) { 8924 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8925 Set<String> collectedNames = new HashSet<>(); 8926 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8927 8928 retValue.remove(p); 8929 8930 return retValue; 8931 } else { 8932 return Collections.emptyList(); 8933 } 8934 } 8935 8936 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8937 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8938 if (!collectedNames.contains(p.packageName)) { 8939 collectedNames.add(p.packageName); 8940 collected.add(p); 8941 8942 if (p.usesLibraries != null) { 8943 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8944 null, collected, collectedNames); 8945 } 8946 if (p.usesOptionalLibraries != null) { 8947 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8948 null, collected, collectedNames); 8949 } 8950 if (p.usesStaticLibraries != null) { 8951 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8952 p.usesStaticLibrariesVersions, collected, collectedNames); 8953 } 8954 } 8955 } 8956 8957 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8958 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8959 final int libNameCount = libs.size(); 8960 for (int i = 0; i < libNameCount; i++) { 8961 String libName = libs.get(i); 8962 int version = (versions != null && versions.length == libNameCount) 8963 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8964 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8965 if (libPkg != null) { 8966 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8967 } 8968 } 8969 } 8970 8971 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8972 synchronized (mPackages) { 8973 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8974 if (libEntry != null) { 8975 return mPackages.get(libEntry.apk); 8976 } 8977 return null; 8978 } 8979 } 8980 8981 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8982 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8983 if (versionedLib == null) { 8984 return null; 8985 } 8986 return versionedLib.get(version); 8987 } 8988 8989 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8990 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8991 pkg.staticSharedLibName); 8992 if (versionedLib == null) { 8993 return null; 8994 } 8995 int previousLibVersion = -1; 8996 final int versionCount = versionedLib.size(); 8997 for (int i = 0; i < versionCount; i++) { 8998 final int libVersion = versionedLib.keyAt(i); 8999 if (libVersion < pkg.staticSharedLibVersion) { 9000 previousLibVersion = Math.max(previousLibVersion, libVersion); 9001 } 9002 } 9003 if (previousLibVersion >= 0) { 9004 return versionedLib.get(previousLibVersion); 9005 } 9006 return null; 9007 } 9008 9009 public void shutdown() { 9010 mPackageUsage.writeNow(mPackages); 9011 mCompilerStats.writeNow(); 9012 } 9013 9014 @Override 9015 public void dumpProfiles(String packageName) { 9016 PackageParser.Package pkg; 9017 synchronized (mPackages) { 9018 pkg = mPackages.get(packageName); 9019 if (pkg == null) { 9020 throw new IllegalArgumentException("Unknown package: " + packageName); 9021 } 9022 } 9023 /* Only the shell, root, or the app user should be able to dump profiles. */ 9024 int callingUid = Binder.getCallingUid(); 9025 if (callingUid != Process.SHELL_UID && 9026 callingUid != Process.ROOT_UID && 9027 callingUid != pkg.applicationInfo.uid) { 9028 throw new SecurityException("dumpProfiles"); 9029 } 9030 9031 synchronized (mInstallLock) { 9032 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9033 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9034 try { 9035 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9036 String codePaths = TextUtils.join(";", allCodePaths); 9037 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9038 } catch (InstallerException e) { 9039 Slog.w(TAG, "Failed to dump profiles", e); 9040 } 9041 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9042 } 9043 } 9044 9045 @Override 9046 public void forceDexOpt(String packageName) { 9047 enforceSystemOrRoot("forceDexOpt"); 9048 9049 PackageParser.Package pkg; 9050 synchronized (mPackages) { 9051 pkg = mPackages.get(packageName); 9052 if (pkg == null) { 9053 throw new IllegalArgumentException("Unknown package: " + packageName); 9054 } 9055 } 9056 9057 synchronized (mInstallLock) { 9058 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9059 9060 // Whoever is calling forceDexOpt wants a compiled package. 9061 // Don't use profiles since that may cause compilation to be skipped. 9062 final int res = performDexOptInternalWithDependenciesLI(pkg, 9063 false /* checkProfiles */, getDefaultCompilerFilter(), 9064 true /* force */); 9065 9066 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9067 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9068 throw new IllegalStateException("Failed to dexopt: " + res); 9069 } 9070 } 9071 } 9072 9073 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9074 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9075 Slog.w(TAG, "Unable to update from " + oldPkg.name 9076 + " to " + newPkg.packageName 9077 + ": old package not in system partition"); 9078 return false; 9079 } else if (mPackages.get(oldPkg.name) != null) { 9080 Slog.w(TAG, "Unable to update from " + oldPkg.name 9081 + " to " + newPkg.packageName 9082 + ": old package still exists"); 9083 return false; 9084 } 9085 return true; 9086 } 9087 9088 void removeCodePathLI(File codePath) { 9089 if (codePath.isDirectory()) { 9090 try { 9091 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9092 } catch (InstallerException e) { 9093 Slog.w(TAG, "Failed to remove code path", e); 9094 } 9095 } else { 9096 codePath.delete(); 9097 } 9098 } 9099 9100 private int[] resolveUserIds(int userId) { 9101 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9102 } 9103 9104 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9105 if (pkg == null) { 9106 Slog.wtf(TAG, "Package was null!", new Throwable()); 9107 return; 9108 } 9109 clearAppDataLeafLIF(pkg, userId, flags); 9110 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9111 for (int i = 0; i < childCount; i++) { 9112 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9113 } 9114 } 9115 9116 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9117 final PackageSetting ps; 9118 synchronized (mPackages) { 9119 ps = mSettings.mPackages.get(pkg.packageName); 9120 } 9121 for (int realUserId : resolveUserIds(userId)) { 9122 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9123 try { 9124 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9125 ceDataInode); 9126 } catch (InstallerException e) { 9127 Slog.w(TAG, String.valueOf(e)); 9128 } 9129 } 9130 } 9131 9132 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9133 if (pkg == null) { 9134 Slog.wtf(TAG, "Package was null!", new Throwable()); 9135 return; 9136 } 9137 destroyAppDataLeafLIF(pkg, userId, flags); 9138 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9139 for (int i = 0; i < childCount; i++) { 9140 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9141 } 9142 } 9143 9144 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9145 final PackageSetting ps; 9146 synchronized (mPackages) { 9147 ps = mSettings.mPackages.get(pkg.packageName); 9148 } 9149 for (int realUserId : resolveUserIds(userId)) { 9150 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9151 try { 9152 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9153 ceDataInode); 9154 } catch (InstallerException e) { 9155 Slog.w(TAG, String.valueOf(e)); 9156 } 9157 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9158 } 9159 } 9160 9161 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9162 if (pkg == null) { 9163 Slog.wtf(TAG, "Package was null!", new Throwable()); 9164 return; 9165 } 9166 destroyAppProfilesLeafLIF(pkg); 9167 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9168 for (int i = 0; i < childCount; i++) { 9169 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9170 } 9171 } 9172 9173 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9174 try { 9175 mInstaller.destroyAppProfiles(pkg.packageName); 9176 } catch (InstallerException e) { 9177 Slog.w(TAG, String.valueOf(e)); 9178 } 9179 } 9180 9181 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9182 if (pkg == null) { 9183 Slog.wtf(TAG, "Package was null!", new Throwable()); 9184 return; 9185 } 9186 clearAppProfilesLeafLIF(pkg); 9187 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9188 for (int i = 0; i < childCount; i++) { 9189 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9190 } 9191 } 9192 9193 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9194 try { 9195 mInstaller.clearAppProfiles(pkg.packageName); 9196 } catch (InstallerException e) { 9197 Slog.w(TAG, String.valueOf(e)); 9198 } 9199 } 9200 9201 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9202 long lastUpdateTime) { 9203 // Set parent install/update time 9204 PackageSetting ps = (PackageSetting) pkg.mExtras; 9205 if (ps != null) { 9206 ps.firstInstallTime = firstInstallTime; 9207 ps.lastUpdateTime = lastUpdateTime; 9208 } 9209 // Set children install/update time 9210 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9211 for (int i = 0; i < childCount; i++) { 9212 PackageParser.Package childPkg = pkg.childPackages.get(i); 9213 ps = (PackageSetting) childPkg.mExtras; 9214 if (ps != null) { 9215 ps.firstInstallTime = firstInstallTime; 9216 ps.lastUpdateTime = lastUpdateTime; 9217 } 9218 } 9219 } 9220 9221 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 9222 PackageParser.Package changingLib) { 9223 if (file.path != null) { 9224 usesLibraryFiles.add(file.path); 9225 return; 9226 } 9227 PackageParser.Package p = mPackages.get(file.apk); 9228 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9229 // If we are doing this while in the middle of updating a library apk, 9230 // then we need to make sure to use that new apk for determining the 9231 // dependencies here. (We haven't yet finished committing the new apk 9232 // to the package manager state.) 9233 if (p == null || p.packageName.equals(changingLib.packageName)) { 9234 p = changingLib; 9235 } 9236 } 9237 if (p != null) { 9238 usesLibraryFiles.addAll(p.getAllCodePaths()); 9239 } 9240 } 9241 9242 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9243 PackageParser.Package changingLib) throws PackageManagerException { 9244 if (pkg == null) { 9245 return; 9246 } 9247 ArraySet<String> usesLibraryFiles = null; 9248 if (pkg.usesLibraries != null) { 9249 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9250 null, null, pkg.packageName, changingLib, true, null); 9251 } 9252 if (pkg.usesStaticLibraries != null) { 9253 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9254 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9255 pkg.packageName, changingLib, true, usesLibraryFiles); 9256 } 9257 if (pkg.usesOptionalLibraries != null) { 9258 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9259 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 9260 } 9261 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9262 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9263 } else { 9264 pkg.usesLibraryFiles = null; 9265 } 9266 } 9267 9268 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9269 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 9270 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9271 boolean required, @Nullable ArraySet<String> outUsedLibraries) 9272 throws PackageManagerException { 9273 final int libCount = requestedLibraries.size(); 9274 for (int i = 0; i < libCount; i++) { 9275 final String libName = requestedLibraries.get(i); 9276 final int libVersion = requiredVersions != null ? requiredVersions[i] 9277 : SharedLibraryInfo.VERSION_UNDEFINED; 9278 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9279 if (libEntry == null) { 9280 if (required) { 9281 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9282 "Package " + packageName + " requires unavailable shared library " 9283 + libName + "; failing!"); 9284 } else { 9285 Slog.w(TAG, "Package " + packageName 9286 + " desires unavailable shared library " 9287 + libName + "; ignoring!"); 9288 } 9289 } else { 9290 if (requiredVersions != null && requiredCertDigests != null) { 9291 if (libEntry.info.getVersion() != requiredVersions[i]) { 9292 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9293 "Package " + packageName + " requires unavailable static shared" 9294 + " library " + libName + " version " 9295 + libEntry.info.getVersion() + "; failing!"); 9296 } 9297 9298 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9299 if (libPkg == null) { 9300 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9301 "Package " + packageName + " requires unavailable static shared" 9302 + " library; failing!"); 9303 } 9304 9305 String expectedCertDigest = requiredCertDigests[i]; 9306 String libCertDigest = PackageUtils.computeCertSha256Digest( 9307 libPkg.mSignatures[0]); 9308 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9309 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9310 "Package " + packageName + " requires differently signed" + 9311 " static shared library; failing!"); 9312 } 9313 } 9314 9315 if (outUsedLibraries == null) { 9316 outUsedLibraries = new ArraySet<>(); 9317 } 9318 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9319 } 9320 } 9321 return outUsedLibraries; 9322 } 9323 9324 private static boolean hasString(List<String> list, List<String> which) { 9325 if (list == null) { 9326 return false; 9327 } 9328 for (int i=list.size()-1; i>=0; i--) { 9329 for (int j=which.size()-1; j>=0; j--) { 9330 if (which.get(j).equals(list.get(i))) { 9331 return true; 9332 } 9333 } 9334 } 9335 return false; 9336 } 9337 9338 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9339 PackageParser.Package changingPkg) { 9340 ArrayList<PackageParser.Package> res = null; 9341 for (PackageParser.Package pkg : mPackages.values()) { 9342 if (changingPkg != null 9343 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9344 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9345 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9346 changingPkg.staticSharedLibName)) { 9347 return null; 9348 } 9349 if (res == null) { 9350 res = new ArrayList<>(); 9351 } 9352 res.add(pkg); 9353 try { 9354 updateSharedLibrariesLPr(pkg, changingPkg); 9355 } catch (PackageManagerException e) { 9356 // If a system app update or an app and a required lib missing we 9357 // delete the package and for updated system apps keep the data as 9358 // it is better for the user to reinstall than to be in an limbo 9359 // state. Also libs disappearing under an app should never happen 9360 // - just in case. 9361 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9362 final int flags = pkg.isUpdatedSystemApp() 9363 ? PackageManager.DELETE_KEEP_DATA : 0; 9364 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9365 flags , null, true, null); 9366 } 9367 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9368 } 9369 } 9370 return res; 9371 } 9372 9373 /** 9374 * Derive the value of the {@code cpuAbiOverride} based on the provided 9375 * value and an optional stored value from the package settings. 9376 */ 9377 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9378 String cpuAbiOverride = null; 9379 9380 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9381 cpuAbiOverride = null; 9382 } else if (abiOverride != null) { 9383 cpuAbiOverride = abiOverride; 9384 } else if (settings != null) { 9385 cpuAbiOverride = settings.cpuAbiOverrideString; 9386 } 9387 9388 return cpuAbiOverride; 9389 } 9390 9391 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9392 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9393 throws PackageManagerException { 9394 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9395 // If the package has children and this is the first dive in the function 9396 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9397 // whether all packages (parent and children) would be successfully scanned 9398 // before the actual scan since scanning mutates internal state and we want 9399 // to atomically install the package and its children. 9400 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9401 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9402 scanFlags |= SCAN_CHECK_ONLY; 9403 } 9404 } else { 9405 scanFlags &= ~SCAN_CHECK_ONLY; 9406 } 9407 9408 final PackageParser.Package scannedPkg; 9409 try { 9410 // Scan the parent 9411 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9412 // Scan the children 9413 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9414 for (int i = 0; i < childCount; i++) { 9415 PackageParser.Package childPkg = pkg.childPackages.get(i); 9416 scanPackageLI(childPkg, policyFlags, 9417 scanFlags, currentTime, user); 9418 } 9419 } finally { 9420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9421 } 9422 9423 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9424 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9425 } 9426 9427 return scannedPkg; 9428 } 9429 9430 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9431 int scanFlags, long currentTime, @Nullable UserHandle user) 9432 throws PackageManagerException { 9433 boolean success = false; 9434 try { 9435 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9436 currentTime, user); 9437 success = true; 9438 return res; 9439 } finally { 9440 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9441 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9442 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9443 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9444 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9445 } 9446 } 9447 } 9448 9449 /** 9450 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9451 */ 9452 private static boolean apkHasCode(String fileName) { 9453 StrictJarFile jarFile = null; 9454 try { 9455 jarFile = new StrictJarFile(fileName, 9456 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9457 return jarFile.findEntry("classes.dex") != null; 9458 } catch (IOException ignore) { 9459 } finally { 9460 try { 9461 if (jarFile != null) { 9462 jarFile.close(); 9463 } 9464 } catch (IOException ignore) {} 9465 } 9466 return false; 9467 } 9468 9469 /** 9470 * Enforces code policy for the package. This ensures that if an APK has 9471 * declared hasCode="true" in its manifest that the APK actually contains 9472 * code. 9473 * 9474 * @throws PackageManagerException If bytecode could not be found when it should exist 9475 */ 9476 private static void assertCodePolicy(PackageParser.Package pkg) 9477 throws PackageManagerException { 9478 final boolean shouldHaveCode = 9479 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9480 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9481 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9482 "Package " + pkg.baseCodePath + " code is missing"); 9483 } 9484 9485 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9486 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9487 final boolean splitShouldHaveCode = 9488 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9489 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9490 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9491 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9492 } 9493 } 9494 } 9495 } 9496 9497 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9498 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9499 throws PackageManagerException { 9500 if (DEBUG_PACKAGE_SCANNING) { 9501 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9502 Log.d(TAG, "Scanning package " + pkg.packageName); 9503 } 9504 9505 applyPolicy(pkg, policyFlags); 9506 9507 assertPackageIsValid(pkg, policyFlags, scanFlags); 9508 9509 // Initialize package source and resource directories 9510 final File scanFile = new File(pkg.codePath); 9511 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9512 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9513 9514 SharedUserSetting suid = null; 9515 PackageSetting pkgSetting = null; 9516 9517 // Getting the package setting may have a side-effect, so if we 9518 // are only checking if scan would succeed, stash a copy of the 9519 // old setting to restore at the end. 9520 PackageSetting nonMutatedPs = null; 9521 9522 // We keep references to the derived CPU Abis from settings in oder to reuse 9523 // them in the case where we're not upgrading or booting for the first time. 9524 String primaryCpuAbiFromSettings = null; 9525 String secondaryCpuAbiFromSettings = null; 9526 9527 // writer 9528 synchronized (mPackages) { 9529 if (pkg.mSharedUserId != null) { 9530 // SIDE EFFECTS; may potentially allocate a new shared user 9531 suid = mSettings.getSharedUserLPw( 9532 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9533 if (DEBUG_PACKAGE_SCANNING) { 9534 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9535 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9536 + "): packages=" + suid.packages); 9537 } 9538 } 9539 9540 // Check if we are renaming from an original package name. 9541 PackageSetting origPackage = null; 9542 String realName = null; 9543 if (pkg.mOriginalPackages != null) { 9544 // This package may need to be renamed to a previously 9545 // installed name. Let's check on that... 9546 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9547 if (pkg.mOriginalPackages.contains(renamed)) { 9548 // This package had originally been installed as the 9549 // original name, and we have already taken care of 9550 // transitioning to the new one. Just update the new 9551 // one to continue using the old name. 9552 realName = pkg.mRealPackage; 9553 if (!pkg.packageName.equals(renamed)) { 9554 // Callers into this function may have already taken 9555 // care of renaming the package; only do it here if 9556 // it is not already done. 9557 pkg.setPackageName(renamed); 9558 } 9559 } else { 9560 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9561 if ((origPackage = mSettings.getPackageLPr( 9562 pkg.mOriginalPackages.get(i))) != null) { 9563 // We do have the package already installed under its 9564 // original name... should we use it? 9565 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9566 // New package is not compatible with original. 9567 origPackage = null; 9568 continue; 9569 } else if (origPackage.sharedUser != null) { 9570 // Make sure uid is compatible between packages. 9571 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9572 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9573 + " to " + pkg.packageName + ": old uid " 9574 + origPackage.sharedUser.name 9575 + " differs from " + pkg.mSharedUserId); 9576 origPackage = null; 9577 continue; 9578 } 9579 // TODO: Add case when shared user id is added [b/28144775] 9580 } else { 9581 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9582 + pkg.packageName + " to old name " + origPackage.name); 9583 } 9584 break; 9585 } 9586 } 9587 } 9588 } 9589 9590 if (mTransferedPackages.contains(pkg.packageName)) { 9591 Slog.w(TAG, "Package " + pkg.packageName 9592 + " was transferred to another, but its .apk remains"); 9593 } 9594 9595 // See comments in nonMutatedPs declaration 9596 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9597 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9598 if (foundPs != null) { 9599 nonMutatedPs = new PackageSetting(foundPs); 9600 } 9601 } 9602 9603 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9604 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9605 if (foundPs != null) { 9606 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9607 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9608 } 9609 } 9610 9611 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9612 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9613 PackageManagerService.reportSettingsProblem(Log.WARN, 9614 "Package " + pkg.packageName + " shared user changed from " 9615 + (pkgSetting.sharedUser != null 9616 ? pkgSetting.sharedUser.name : "<nothing>") 9617 + " to " 9618 + (suid != null ? suid.name : "<nothing>") 9619 + "; replacing with new"); 9620 pkgSetting = null; 9621 } 9622 final PackageSetting oldPkgSetting = 9623 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9624 final PackageSetting disabledPkgSetting = 9625 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9626 9627 String[] usesStaticLibraries = null; 9628 if (pkg.usesStaticLibraries != null) { 9629 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9630 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9631 } 9632 9633 if (pkgSetting == null) { 9634 final String parentPackageName = (pkg.parentPackage != null) 9635 ? pkg.parentPackage.packageName : null; 9636 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9637 // REMOVE SharedUserSetting from method; update in a separate call 9638 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9639 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9640 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9641 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9642 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9643 true /*allowInstall*/, instantApp, parentPackageName, 9644 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9645 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9646 // SIDE EFFECTS; updates system state; move elsewhere 9647 if (origPackage != null) { 9648 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9649 } 9650 mSettings.addUserToSettingLPw(pkgSetting); 9651 } else { 9652 // REMOVE SharedUserSetting from method; update in a separate call. 9653 // 9654 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9655 // secondaryCpuAbi are not known at this point so we always update them 9656 // to null here, only to reset them at a later point. 9657 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9658 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9659 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9660 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9661 UserManagerService.getInstance(), usesStaticLibraries, 9662 pkg.usesStaticLibrariesVersions); 9663 } 9664 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9665 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9666 9667 // SIDE EFFECTS; modifies system state; move elsewhere 9668 if (pkgSetting.origPackage != null) { 9669 // If we are first transitioning from an original package, 9670 // fix up the new package's name now. We need to do this after 9671 // looking up the package under its new name, so getPackageLP 9672 // can take care of fiddling things correctly. 9673 pkg.setPackageName(origPackage.name); 9674 9675 // File a report about this. 9676 String msg = "New package " + pkgSetting.realName 9677 + " renamed to replace old package " + pkgSetting.name; 9678 reportSettingsProblem(Log.WARN, msg); 9679 9680 // Make a note of it. 9681 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9682 mTransferedPackages.add(origPackage.name); 9683 } 9684 9685 // No longer need to retain this. 9686 pkgSetting.origPackage = null; 9687 } 9688 9689 // SIDE EFFECTS; modifies system state; move elsewhere 9690 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9691 // Make a note of it. 9692 mTransferedPackages.add(pkg.packageName); 9693 } 9694 9695 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9696 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9697 } 9698 9699 if ((scanFlags & SCAN_BOOTING) == 0 9700 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9701 // Check all shared libraries and map to their actual file path. 9702 // We only do this here for apps not on a system dir, because those 9703 // are the only ones that can fail an install due to this. We 9704 // will take care of the system apps by updating all of their 9705 // library paths after the scan is done. Also during the initial 9706 // scan don't update any libs as we do this wholesale after all 9707 // apps are scanned to avoid dependency based scanning. 9708 updateSharedLibrariesLPr(pkg, null); 9709 } 9710 9711 if (mFoundPolicyFile) { 9712 SELinuxMMAC.assignSeInfoValue(pkg); 9713 } 9714 pkg.applicationInfo.uid = pkgSetting.appId; 9715 pkg.mExtras = pkgSetting; 9716 9717 9718 // Static shared libs have same package with different versions where 9719 // we internally use a synthetic package name to allow multiple versions 9720 // of the same package, therefore we need to compare signatures against 9721 // the package setting for the latest library version. 9722 PackageSetting signatureCheckPs = pkgSetting; 9723 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9724 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9725 if (libraryEntry != null) { 9726 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9727 } 9728 } 9729 9730 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9731 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9732 // We just determined the app is signed correctly, so bring 9733 // over the latest parsed certs. 9734 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9735 } else { 9736 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9737 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9738 "Package " + pkg.packageName + " upgrade keys do not match the " 9739 + "previously installed version"); 9740 } else { 9741 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9742 String msg = "System package " + pkg.packageName 9743 + " signature changed; retaining data."; 9744 reportSettingsProblem(Log.WARN, msg); 9745 } 9746 } 9747 } else { 9748 try { 9749 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9750 verifySignaturesLP(signatureCheckPs, pkg); 9751 // We just determined the app is signed correctly, so bring 9752 // over the latest parsed certs. 9753 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9754 } catch (PackageManagerException e) { 9755 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9756 throw e; 9757 } 9758 // The signature has changed, but this package is in the system 9759 // image... let's recover! 9760 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9761 // However... if this package is part of a shared user, but it 9762 // doesn't match the signature of the shared user, let's fail. 9763 // What this means is that you can't change the signatures 9764 // associated with an overall shared user, which doesn't seem all 9765 // that unreasonable. 9766 if (signatureCheckPs.sharedUser != null) { 9767 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9768 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9769 throw new PackageManagerException( 9770 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9771 "Signature mismatch for shared user: " 9772 + pkgSetting.sharedUser); 9773 } 9774 } 9775 // File a report about this. 9776 String msg = "System package " + pkg.packageName 9777 + " signature changed; retaining data."; 9778 reportSettingsProblem(Log.WARN, msg); 9779 } 9780 } 9781 9782 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9783 // This package wants to adopt ownership of permissions from 9784 // another package. 9785 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9786 final String origName = pkg.mAdoptPermissions.get(i); 9787 final PackageSetting orig = mSettings.getPackageLPr(origName); 9788 if (orig != null) { 9789 if (verifyPackageUpdateLPr(orig, pkg)) { 9790 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9791 + pkg.packageName); 9792 // SIDE EFFECTS; updates permissions system state; move elsewhere 9793 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9794 } 9795 } 9796 } 9797 } 9798 } 9799 9800 pkg.applicationInfo.processName = fixProcessName( 9801 pkg.applicationInfo.packageName, 9802 pkg.applicationInfo.processName); 9803 9804 if (pkg != mPlatformPackage) { 9805 // Get all of our default paths setup 9806 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9807 } 9808 9809 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9810 9811 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9812 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9813 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9814 derivePackageAbi( 9815 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9816 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9817 9818 // Some system apps still use directory structure for native libraries 9819 // in which case we might end up not detecting abi solely based on apk 9820 // structure. Try to detect abi based on directory structure. 9821 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9822 pkg.applicationInfo.primaryCpuAbi == null) { 9823 setBundledAppAbisAndRoots(pkg, pkgSetting); 9824 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9825 } 9826 } else { 9827 // This is not a first boot or an upgrade, don't bother deriving the 9828 // ABI during the scan. Instead, trust the value that was stored in the 9829 // package setting. 9830 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9831 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9832 9833 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9834 9835 if (DEBUG_ABI_SELECTION) { 9836 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9837 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9838 pkg.applicationInfo.secondaryCpuAbi); 9839 } 9840 } 9841 } else { 9842 if ((scanFlags & SCAN_MOVE) != 0) { 9843 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9844 // but we already have this packages package info in the PackageSetting. We just 9845 // use that and derive the native library path based on the new codepath. 9846 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9847 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9848 } 9849 9850 // Set native library paths again. For moves, the path will be updated based on the 9851 // ABIs we've determined above. For non-moves, the path will be updated based on the 9852 // ABIs we determined during compilation, but the path will depend on the final 9853 // package path (after the rename away from the stage path). 9854 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9855 } 9856 9857 // This is a special case for the "system" package, where the ABI is 9858 // dictated by the zygote configuration (and init.rc). We should keep track 9859 // of this ABI so that we can deal with "normal" applications that run under 9860 // the same UID correctly. 9861 if (mPlatformPackage == pkg) { 9862 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9863 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9864 } 9865 9866 // If there's a mismatch between the abi-override in the package setting 9867 // and the abiOverride specified for the install. Warn about this because we 9868 // would've already compiled the app without taking the package setting into 9869 // account. 9870 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9871 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9872 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9873 " for package " + pkg.packageName); 9874 } 9875 } 9876 9877 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9878 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9879 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9880 9881 // Copy the derived override back to the parsed package, so that we can 9882 // update the package settings accordingly. 9883 pkg.cpuAbiOverride = cpuAbiOverride; 9884 9885 if (DEBUG_ABI_SELECTION) { 9886 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9887 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9888 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9889 } 9890 9891 // Push the derived path down into PackageSettings so we know what to 9892 // clean up at uninstall time. 9893 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9894 9895 if (DEBUG_ABI_SELECTION) { 9896 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9897 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9898 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9899 } 9900 9901 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9902 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9903 // We don't do this here during boot because we can do it all 9904 // at once after scanning all existing packages. 9905 // 9906 // We also do this *before* we perform dexopt on this package, so that 9907 // we can avoid redundant dexopts, and also to make sure we've got the 9908 // code and package path correct. 9909 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9910 } 9911 9912 if (mFactoryTest && pkg.requestedPermissions.contains( 9913 android.Manifest.permission.FACTORY_TEST)) { 9914 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9915 } 9916 9917 if (isSystemApp(pkg)) { 9918 pkgSetting.isOrphaned = true; 9919 } 9920 9921 // Take care of first install / last update times. 9922 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9923 if (currentTime != 0) { 9924 if (pkgSetting.firstInstallTime == 0) { 9925 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9926 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9927 pkgSetting.lastUpdateTime = currentTime; 9928 } 9929 } else if (pkgSetting.firstInstallTime == 0) { 9930 // We need *something*. Take time time stamp of the file. 9931 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9932 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9933 if (scanFileTime != pkgSetting.timeStamp) { 9934 // A package on the system image has changed; consider this 9935 // to be an update. 9936 pkgSetting.lastUpdateTime = scanFileTime; 9937 } 9938 } 9939 pkgSetting.setTimeStamp(scanFileTime); 9940 9941 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9942 if (nonMutatedPs != null) { 9943 synchronized (mPackages) { 9944 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9945 } 9946 } 9947 } else { 9948 final int userId = user == null ? 0 : user.getIdentifier(); 9949 // Modify state for the given package setting 9950 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9951 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9952 if (pkgSetting.getInstantApp(userId)) { 9953 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9954 } 9955 } 9956 return pkg; 9957 } 9958 9959 /** 9960 * Applies policy to the parsed package based upon the given policy flags. 9961 * Ensures the package is in a good state. 9962 * <p> 9963 * Implementation detail: This method must NOT have any side effect. It would 9964 * ideally be static, but, it requires locks to read system state. 9965 */ 9966 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9967 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9968 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9969 if (pkg.applicationInfo.isDirectBootAware()) { 9970 // we're direct boot aware; set for all components 9971 for (PackageParser.Service s : pkg.services) { 9972 s.info.encryptionAware = s.info.directBootAware = true; 9973 } 9974 for (PackageParser.Provider p : pkg.providers) { 9975 p.info.encryptionAware = p.info.directBootAware = true; 9976 } 9977 for (PackageParser.Activity a : pkg.activities) { 9978 a.info.encryptionAware = a.info.directBootAware = true; 9979 } 9980 for (PackageParser.Activity r : pkg.receivers) { 9981 r.info.encryptionAware = r.info.directBootAware = true; 9982 } 9983 } 9984 } else { 9985 // Only allow system apps to be flagged as core apps. 9986 pkg.coreApp = false; 9987 // clear flags not applicable to regular apps 9988 pkg.applicationInfo.privateFlags &= 9989 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9990 pkg.applicationInfo.privateFlags &= 9991 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9992 } 9993 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9994 9995 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9996 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9997 } 9998 9999 if (!isSystemApp(pkg)) { 10000 // Only system apps can use these features. 10001 pkg.mOriginalPackages = null; 10002 pkg.mRealPackage = null; 10003 pkg.mAdoptPermissions = null; 10004 } 10005 } 10006 10007 /** 10008 * Asserts the parsed package is valid according to the given policy. If the 10009 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10010 * <p> 10011 * Implementation detail: This method must NOT have any side effects. It would 10012 * ideally be static, but, it requires locks to read system state. 10013 * 10014 * @throws PackageManagerException If the package fails any of the validation checks 10015 */ 10016 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 10017 throws PackageManagerException { 10018 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10019 assertCodePolicy(pkg); 10020 } 10021 10022 if (pkg.applicationInfo.getCodePath() == null || 10023 pkg.applicationInfo.getResourcePath() == null) { 10024 // Bail out. The resource and code paths haven't been set. 10025 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10026 "Code and resource paths haven't been set correctly"); 10027 } 10028 10029 // Make sure we're not adding any bogus keyset info 10030 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10031 ksms.assertScannedPackageValid(pkg); 10032 10033 synchronized (mPackages) { 10034 // The special "android" package can only be defined once 10035 if (pkg.packageName.equals("android")) { 10036 if (mAndroidApplication != null) { 10037 Slog.w(TAG, "*************************************************"); 10038 Slog.w(TAG, "Core android package being redefined. Skipping."); 10039 Slog.w(TAG, " codePath=" + pkg.codePath); 10040 Slog.w(TAG, "*************************************************"); 10041 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10042 "Core android package being redefined. Skipping."); 10043 } 10044 } 10045 10046 // A package name must be unique; don't allow duplicates 10047 if (mPackages.containsKey(pkg.packageName)) { 10048 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10049 "Application package " + pkg.packageName 10050 + " already installed. Skipping duplicate."); 10051 } 10052 10053 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10054 // Static libs have a synthetic package name containing the version 10055 // but we still want the base name to be unique. 10056 if (mPackages.containsKey(pkg.manifestPackageName)) { 10057 throw new PackageManagerException( 10058 "Duplicate static shared lib provider package"); 10059 } 10060 10061 // Static shared libraries should have at least O target SDK 10062 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10063 throw new PackageManagerException( 10064 "Packages declaring static-shared libs must target O SDK or higher"); 10065 } 10066 10067 // Package declaring static a shared lib cannot be instant apps 10068 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10069 throw new PackageManagerException( 10070 "Packages declaring static-shared libs cannot be instant apps"); 10071 } 10072 10073 // Package declaring static a shared lib cannot be renamed since the package 10074 // name is synthetic and apps can't code around package manager internals. 10075 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10076 throw new PackageManagerException( 10077 "Packages declaring static-shared libs cannot be renamed"); 10078 } 10079 10080 // Package declaring static a shared lib cannot declare child packages 10081 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10082 throw new PackageManagerException( 10083 "Packages declaring static-shared libs cannot have child packages"); 10084 } 10085 10086 // Package declaring static a shared lib cannot declare dynamic libs 10087 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10088 throw new PackageManagerException( 10089 "Packages declaring static-shared libs cannot declare dynamic libs"); 10090 } 10091 10092 // Package declaring static a shared lib cannot declare shared users 10093 if (pkg.mSharedUserId != null) { 10094 throw new PackageManagerException( 10095 "Packages declaring static-shared libs cannot declare shared users"); 10096 } 10097 10098 // Static shared libs cannot declare activities 10099 if (!pkg.activities.isEmpty()) { 10100 throw new PackageManagerException( 10101 "Static shared libs cannot declare activities"); 10102 } 10103 10104 // Static shared libs cannot declare services 10105 if (!pkg.services.isEmpty()) { 10106 throw new PackageManagerException( 10107 "Static shared libs cannot declare services"); 10108 } 10109 10110 // Static shared libs cannot declare providers 10111 if (!pkg.providers.isEmpty()) { 10112 throw new PackageManagerException( 10113 "Static shared libs cannot declare content providers"); 10114 } 10115 10116 // Static shared libs cannot declare receivers 10117 if (!pkg.receivers.isEmpty()) { 10118 throw new PackageManagerException( 10119 "Static shared libs cannot declare broadcast receivers"); 10120 } 10121 10122 // Static shared libs cannot declare permission groups 10123 if (!pkg.permissionGroups.isEmpty()) { 10124 throw new PackageManagerException( 10125 "Static shared libs cannot declare permission groups"); 10126 } 10127 10128 // Static shared libs cannot declare permissions 10129 if (!pkg.permissions.isEmpty()) { 10130 throw new PackageManagerException( 10131 "Static shared libs cannot declare permissions"); 10132 } 10133 10134 // Static shared libs cannot declare protected broadcasts 10135 if (pkg.protectedBroadcasts != null) { 10136 throw new PackageManagerException( 10137 "Static shared libs cannot declare protected broadcasts"); 10138 } 10139 10140 // Static shared libs cannot be overlay targets 10141 if (pkg.mOverlayTarget != null) { 10142 throw new PackageManagerException( 10143 "Static shared libs cannot be overlay targets"); 10144 } 10145 10146 // The version codes must be ordered as lib versions 10147 int minVersionCode = Integer.MIN_VALUE; 10148 int maxVersionCode = Integer.MAX_VALUE; 10149 10150 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10151 pkg.staticSharedLibName); 10152 if (versionedLib != null) { 10153 final int versionCount = versionedLib.size(); 10154 for (int i = 0; i < versionCount; i++) { 10155 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10156 // TODO: We will change version code to long, so in the new API it is long 10157 final int libVersionCode = (int) libInfo.getDeclaringPackage() 10158 .getVersionCode(); 10159 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10160 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10161 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10162 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10163 } else { 10164 minVersionCode = maxVersionCode = libVersionCode; 10165 break; 10166 } 10167 } 10168 } 10169 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10170 throw new PackageManagerException("Static shared" 10171 + " lib version codes must be ordered as lib versions"); 10172 } 10173 } 10174 10175 // Only privileged apps and updated privileged apps can add child packages. 10176 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10177 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10178 throw new PackageManagerException("Only privileged apps can add child " 10179 + "packages. Ignoring package " + pkg.packageName); 10180 } 10181 final int childCount = pkg.childPackages.size(); 10182 for (int i = 0; i < childCount; i++) { 10183 PackageParser.Package childPkg = pkg.childPackages.get(i); 10184 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10185 childPkg.packageName)) { 10186 throw new PackageManagerException("Can't override child of " 10187 + "another disabled app. Ignoring package " + pkg.packageName); 10188 } 10189 } 10190 } 10191 10192 // If we're only installing presumed-existing packages, require that the 10193 // scanned APK is both already known and at the path previously established 10194 // for it. Previously unknown packages we pick up normally, but if we have an 10195 // a priori expectation about this package's install presence, enforce it. 10196 // With a singular exception for new system packages. When an OTA contains 10197 // a new system package, we allow the codepath to change from a system location 10198 // to the user-installed location. If we don't allow this change, any newer, 10199 // user-installed version of the application will be ignored. 10200 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10201 if (mExpectingBetter.containsKey(pkg.packageName)) { 10202 logCriticalInfo(Log.WARN, 10203 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10204 } else { 10205 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10206 if (known != null) { 10207 if (DEBUG_PACKAGE_SCANNING) { 10208 Log.d(TAG, "Examining " + pkg.codePath 10209 + " and requiring known paths " + known.codePathString 10210 + " & " + known.resourcePathString); 10211 } 10212 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10213 || !pkg.applicationInfo.getResourcePath().equals( 10214 known.resourcePathString)) { 10215 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10216 "Application package " + pkg.packageName 10217 + " found at " + pkg.applicationInfo.getCodePath() 10218 + " but expected at " + known.codePathString 10219 + "; ignoring."); 10220 } 10221 } 10222 } 10223 } 10224 10225 // Verify that this new package doesn't have any content providers 10226 // that conflict with existing packages. Only do this if the 10227 // package isn't already installed, since we don't want to break 10228 // things that are installed. 10229 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10230 final int N = pkg.providers.size(); 10231 int i; 10232 for (i=0; i<N; i++) { 10233 PackageParser.Provider p = pkg.providers.get(i); 10234 if (p.info.authority != null) { 10235 String names[] = p.info.authority.split(";"); 10236 for (int j = 0; j < names.length; j++) { 10237 if (mProvidersByAuthority.containsKey(names[j])) { 10238 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10239 final String otherPackageName = 10240 ((other != null && other.getComponentName() != null) ? 10241 other.getComponentName().getPackageName() : "?"); 10242 throw new PackageManagerException( 10243 INSTALL_FAILED_CONFLICTING_PROVIDER, 10244 "Can't install because provider name " + names[j] 10245 + " (in package " + pkg.applicationInfo.packageName 10246 + ") is already used by " + otherPackageName); 10247 } 10248 } 10249 } 10250 } 10251 } 10252 } 10253 } 10254 10255 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10256 int type, String declaringPackageName, int declaringVersionCode) { 10257 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10258 if (versionedLib == null) { 10259 versionedLib = new SparseArray<>(); 10260 mSharedLibraries.put(name, versionedLib); 10261 if (type == SharedLibraryInfo.TYPE_STATIC) { 10262 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10263 } 10264 } else if (versionedLib.indexOfKey(version) >= 0) { 10265 return false; 10266 } 10267 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10268 version, type, declaringPackageName, declaringVersionCode); 10269 versionedLib.put(version, libEntry); 10270 return true; 10271 } 10272 10273 private boolean removeSharedLibraryLPw(String name, int version) { 10274 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10275 if (versionedLib == null) { 10276 return false; 10277 } 10278 final int libIdx = versionedLib.indexOfKey(version); 10279 if (libIdx < 0) { 10280 return false; 10281 } 10282 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10283 versionedLib.remove(version); 10284 if (versionedLib.size() <= 0) { 10285 mSharedLibraries.remove(name); 10286 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10287 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10288 .getPackageName()); 10289 } 10290 } 10291 return true; 10292 } 10293 10294 /** 10295 * Adds a scanned package to the system. When this method is finished, the package will 10296 * be available for query, resolution, etc... 10297 */ 10298 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10299 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10300 final String pkgName = pkg.packageName; 10301 if (mCustomResolverComponentName != null && 10302 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10303 setUpCustomResolverActivity(pkg); 10304 } 10305 10306 if (pkg.packageName.equals("android")) { 10307 synchronized (mPackages) { 10308 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10309 // Set up information for our fall-back user intent resolution activity. 10310 mPlatformPackage = pkg; 10311 pkg.mVersionCode = mSdkVersion; 10312 mAndroidApplication = pkg.applicationInfo; 10313 if (!mResolverReplaced) { 10314 mResolveActivity.applicationInfo = mAndroidApplication; 10315 mResolveActivity.name = ResolverActivity.class.getName(); 10316 mResolveActivity.packageName = mAndroidApplication.packageName; 10317 mResolveActivity.processName = "system:ui"; 10318 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10319 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10320 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10321 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10322 mResolveActivity.exported = true; 10323 mResolveActivity.enabled = true; 10324 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10325 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10326 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10327 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10328 | ActivityInfo.CONFIG_ORIENTATION 10329 | ActivityInfo.CONFIG_KEYBOARD 10330 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10331 mResolveInfo.activityInfo = mResolveActivity; 10332 mResolveInfo.priority = 0; 10333 mResolveInfo.preferredOrder = 0; 10334 mResolveInfo.match = 0; 10335 mResolveComponentName = new ComponentName( 10336 mAndroidApplication.packageName, mResolveActivity.name); 10337 } 10338 } 10339 } 10340 } 10341 10342 ArrayList<PackageParser.Package> clientLibPkgs = null; 10343 // writer 10344 synchronized (mPackages) { 10345 boolean hasStaticSharedLibs = false; 10346 10347 // Any app can add new static shared libraries 10348 if (pkg.staticSharedLibName != null) { 10349 // Static shared libs don't allow renaming as they have synthetic package 10350 // names to allow install of multiple versions, so use name from manifest. 10351 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10352 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10353 pkg.manifestPackageName, pkg.mVersionCode)) { 10354 hasStaticSharedLibs = true; 10355 } else { 10356 Slog.w(TAG, "Package " + pkg.packageName + " library " 10357 + pkg.staticSharedLibName + " already exists; skipping"); 10358 } 10359 // Static shared libs cannot be updated once installed since they 10360 // use synthetic package name which includes the version code, so 10361 // not need to update other packages's shared lib dependencies. 10362 } 10363 10364 if (!hasStaticSharedLibs 10365 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10366 // Only system apps can add new dynamic shared libraries. 10367 if (pkg.libraryNames != null) { 10368 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10369 String name = pkg.libraryNames.get(i); 10370 boolean allowed = false; 10371 if (pkg.isUpdatedSystemApp()) { 10372 // New library entries can only be added through the 10373 // system image. This is important to get rid of a lot 10374 // of nasty edge cases: for example if we allowed a non- 10375 // system update of the app to add a library, then uninstalling 10376 // the update would make the library go away, and assumptions 10377 // we made such as through app install filtering would now 10378 // have allowed apps on the device which aren't compatible 10379 // with it. Better to just have the restriction here, be 10380 // conservative, and create many fewer cases that can negatively 10381 // impact the user experience. 10382 final PackageSetting sysPs = mSettings 10383 .getDisabledSystemPkgLPr(pkg.packageName); 10384 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10385 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10386 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10387 allowed = true; 10388 break; 10389 } 10390 } 10391 } 10392 } else { 10393 allowed = true; 10394 } 10395 if (allowed) { 10396 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10397 SharedLibraryInfo.VERSION_UNDEFINED, 10398 SharedLibraryInfo.TYPE_DYNAMIC, 10399 pkg.packageName, pkg.mVersionCode)) { 10400 Slog.w(TAG, "Package " + pkg.packageName + " library " 10401 + name + " already exists; skipping"); 10402 } 10403 } else { 10404 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10405 + name + " that is not declared on system image; skipping"); 10406 } 10407 } 10408 10409 if ((scanFlags & SCAN_BOOTING) == 0) { 10410 // If we are not booting, we need to update any applications 10411 // that are clients of our shared library. If we are booting, 10412 // this will all be done once the scan is complete. 10413 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10414 } 10415 } 10416 } 10417 } 10418 10419 if ((scanFlags & SCAN_BOOTING) != 0) { 10420 // No apps can run during boot scan, so they don't need to be frozen 10421 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10422 // Caller asked to not kill app, so it's probably not frozen 10423 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10424 // Caller asked us to ignore frozen check for some reason; they 10425 // probably didn't know the package name 10426 } else { 10427 // We're doing major surgery on this package, so it better be frozen 10428 // right now to keep it from launching 10429 checkPackageFrozen(pkgName); 10430 } 10431 10432 // Also need to kill any apps that are dependent on the library. 10433 if (clientLibPkgs != null) { 10434 for (int i=0; i<clientLibPkgs.size(); i++) { 10435 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10436 killApplication(clientPkg.applicationInfo.packageName, 10437 clientPkg.applicationInfo.uid, "update lib"); 10438 } 10439 } 10440 10441 // writer 10442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10443 10444 synchronized (mPackages) { 10445 // We don't expect installation to fail beyond this point 10446 10447 // Add the new setting to mSettings 10448 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10449 // Add the new setting to mPackages 10450 mPackages.put(pkg.applicationInfo.packageName, pkg); 10451 // Make sure we don't accidentally delete its data. 10452 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10453 while (iter.hasNext()) { 10454 PackageCleanItem item = iter.next(); 10455 if (pkgName.equals(item.packageName)) { 10456 iter.remove(); 10457 } 10458 } 10459 10460 // Add the package's KeySets to the global KeySetManagerService 10461 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10462 ksms.addScannedPackageLPw(pkg); 10463 10464 int N = pkg.providers.size(); 10465 StringBuilder r = null; 10466 int i; 10467 for (i=0; i<N; i++) { 10468 PackageParser.Provider p = pkg.providers.get(i); 10469 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10470 p.info.processName); 10471 mProviders.addProvider(p); 10472 p.syncable = p.info.isSyncable; 10473 if (p.info.authority != null) { 10474 String names[] = p.info.authority.split(";"); 10475 p.info.authority = null; 10476 for (int j = 0; j < names.length; j++) { 10477 if (j == 1 && p.syncable) { 10478 // We only want the first authority for a provider to possibly be 10479 // syncable, so if we already added this provider using a different 10480 // authority clear the syncable flag. We copy the provider before 10481 // changing it because the mProviders object contains a reference 10482 // to a provider that we don't want to change. 10483 // Only do this for the second authority since the resulting provider 10484 // object can be the same for all future authorities for this provider. 10485 p = new PackageParser.Provider(p); 10486 p.syncable = false; 10487 } 10488 if (!mProvidersByAuthority.containsKey(names[j])) { 10489 mProvidersByAuthority.put(names[j], p); 10490 if (p.info.authority == null) { 10491 p.info.authority = names[j]; 10492 } else { 10493 p.info.authority = p.info.authority + ";" + names[j]; 10494 } 10495 if (DEBUG_PACKAGE_SCANNING) { 10496 if (chatty) 10497 Log.d(TAG, "Registered content provider: " + names[j] 10498 + ", className = " + p.info.name + ", isSyncable = " 10499 + p.info.isSyncable); 10500 } 10501 } else { 10502 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10503 Slog.w(TAG, "Skipping provider name " + names[j] + 10504 " (in package " + pkg.applicationInfo.packageName + 10505 "): name already used by " 10506 + ((other != null && other.getComponentName() != null) 10507 ? other.getComponentName().getPackageName() : "?")); 10508 } 10509 } 10510 } 10511 if (chatty) { 10512 if (r == null) { 10513 r = new StringBuilder(256); 10514 } else { 10515 r.append(' '); 10516 } 10517 r.append(p.info.name); 10518 } 10519 } 10520 if (r != null) { 10521 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10522 } 10523 10524 N = pkg.services.size(); 10525 r = null; 10526 for (i=0; i<N; i++) { 10527 PackageParser.Service s = pkg.services.get(i); 10528 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10529 s.info.processName); 10530 mServices.addService(s); 10531 if (chatty) { 10532 if (r == null) { 10533 r = new StringBuilder(256); 10534 } else { 10535 r.append(' '); 10536 } 10537 r.append(s.info.name); 10538 } 10539 } 10540 if (r != null) { 10541 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10542 } 10543 10544 N = pkg.receivers.size(); 10545 r = null; 10546 for (i=0; i<N; i++) { 10547 PackageParser.Activity a = pkg.receivers.get(i); 10548 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10549 a.info.processName); 10550 mReceivers.addActivity(a, "receiver"); 10551 if (chatty) { 10552 if (r == null) { 10553 r = new StringBuilder(256); 10554 } else { 10555 r.append(' '); 10556 } 10557 r.append(a.info.name); 10558 } 10559 } 10560 if (r != null) { 10561 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10562 } 10563 10564 N = pkg.activities.size(); 10565 r = null; 10566 for (i=0; i<N; i++) { 10567 PackageParser.Activity a = pkg.activities.get(i); 10568 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10569 a.info.processName); 10570 mActivities.addActivity(a, "activity"); 10571 if (chatty) { 10572 if (r == null) { 10573 r = new StringBuilder(256); 10574 } else { 10575 r.append(' '); 10576 } 10577 r.append(a.info.name); 10578 } 10579 } 10580 if (r != null) { 10581 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10582 } 10583 10584 N = pkg.permissionGroups.size(); 10585 r = null; 10586 for (i=0; i<N; i++) { 10587 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10588 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10589 final String curPackageName = cur == null ? null : cur.info.packageName; 10590 // Dont allow ephemeral apps to define new permission groups. 10591 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10592 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10593 + pg.info.packageName 10594 + " ignored: instant apps cannot define new permission groups."); 10595 continue; 10596 } 10597 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10598 if (cur == null || isPackageUpdate) { 10599 mPermissionGroups.put(pg.info.name, pg); 10600 if (chatty) { 10601 if (r == null) { 10602 r = new StringBuilder(256); 10603 } else { 10604 r.append(' '); 10605 } 10606 if (isPackageUpdate) { 10607 r.append("UPD:"); 10608 } 10609 r.append(pg.info.name); 10610 } 10611 } else { 10612 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10613 + pg.info.packageName + " ignored: original from " 10614 + cur.info.packageName); 10615 if (chatty) { 10616 if (r == null) { 10617 r = new StringBuilder(256); 10618 } else { 10619 r.append(' '); 10620 } 10621 r.append("DUP:"); 10622 r.append(pg.info.name); 10623 } 10624 } 10625 } 10626 if (r != null) { 10627 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10628 } 10629 10630 N = pkg.permissions.size(); 10631 r = null; 10632 for (i=0; i<N; i++) { 10633 PackageParser.Permission p = pkg.permissions.get(i); 10634 10635 // Dont allow ephemeral apps to define new permissions. 10636 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10637 Slog.w(TAG, "Permission " + p.info.name + " from package " 10638 + p.info.packageName 10639 + " ignored: instant apps cannot define new permissions."); 10640 continue; 10641 } 10642 10643 // Assume by default that we did not install this permission into the system. 10644 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10645 10646 // Now that permission groups have a special meaning, we ignore permission 10647 // groups for legacy apps to prevent unexpected behavior. In particular, 10648 // permissions for one app being granted to someone just becase they happen 10649 // to be in a group defined by another app (before this had no implications). 10650 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10651 p.group = mPermissionGroups.get(p.info.group); 10652 // Warn for a permission in an unknown group. 10653 if (p.info.group != null && p.group == null) { 10654 Slog.w(TAG, "Permission " + p.info.name + " from package " 10655 + p.info.packageName + " in an unknown group " + p.info.group); 10656 } 10657 } 10658 10659 ArrayMap<String, BasePermission> permissionMap = 10660 p.tree ? mSettings.mPermissionTrees 10661 : mSettings.mPermissions; 10662 BasePermission bp = permissionMap.get(p.info.name); 10663 10664 // Allow system apps to redefine non-system permissions 10665 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10666 final boolean currentOwnerIsSystem = (bp.perm != null 10667 && isSystemApp(bp.perm.owner)); 10668 if (isSystemApp(p.owner)) { 10669 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10670 // It's a built-in permission and no owner, take ownership now 10671 bp.packageSetting = pkgSetting; 10672 bp.perm = p; 10673 bp.uid = pkg.applicationInfo.uid; 10674 bp.sourcePackage = p.info.packageName; 10675 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10676 } else if (!currentOwnerIsSystem) { 10677 String msg = "New decl " + p.owner + " of permission " 10678 + p.info.name + " is system; overriding " + bp.sourcePackage; 10679 reportSettingsProblem(Log.WARN, msg); 10680 bp = null; 10681 } 10682 } 10683 } 10684 10685 if (bp == null) { 10686 bp = new BasePermission(p.info.name, p.info.packageName, 10687 BasePermission.TYPE_NORMAL); 10688 permissionMap.put(p.info.name, bp); 10689 } 10690 10691 if (bp.perm == null) { 10692 if (bp.sourcePackage == null 10693 || bp.sourcePackage.equals(p.info.packageName)) { 10694 BasePermission tree = findPermissionTreeLP(p.info.name); 10695 if (tree == null 10696 || tree.sourcePackage.equals(p.info.packageName)) { 10697 bp.packageSetting = pkgSetting; 10698 bp.perm = p; 10699 bp.uid = pkg.applicationInfo.uid; 10700 bp.sourcePackage = p.info.packageName; 10701 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10702 if (chatty) { 10703 if (r == null) { 10704 r = new StringBuilder(256); 10705 } else { 10706 r.append(' '); 10707 } 10708 r.append(p.info.name); 10709 } 10710 } else { 10711 Slog.w(TAG, "Permission " + p.info.name + " from package " 10712 + p.info.packageName + " ignored: base tree " 10713 + tree.name + " is from package " 10714 + tree.sourcePackage); 10715 } 10716 } else { 10717 Slog.w(TAG, "Permission " + p.info.name + " from package " 10718 + p.info.packageName + " ignored: original from " 10719 + bp.sourcePackage); 10720 } 10721 } else if (chatty) { 10722 if (r == null) { 10723 r = new StringBuilder(256); 10724 } else { 10725 r.append(' '); 10726 } 10727 r.append("DUP:"); 10728 r.append(p.info.name); 10729 } 10730 if (bp.perm == p) { 10731 bp.protectionLevel = p.info.protectionLevel; 10732 } 10733 } 10734 10735 if (r != null) { 10736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10737 } 10738 10739 N = pkg.instrumentation.size(); 10740 r = null; 10741 for (i=0; i<N; i++) { 10742 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10743 a.info.packageName = pkg.applicationInfo.packageName; 10744 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10745 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10746 a.info.splitNames = pkg.splitNames; 10747 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10748 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10749 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10750 a.info.dataDir = pkg.applicationInfo.dataDir; 10751 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10752 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10753 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10754 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10755 mInstrumentation.put(a.getComponentName(), a); 10756 if (chatty) { 10757 if (r == null) { 10758 r = new StringBuilder(256); 10759 } else { 10760 r.append(' '); 10761 } 10762 r.append(a.info.name); 10763 } 10764 } 10765 if (r != null) { 10766 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10767 } 10768 10769 if (pkg.protectedBroadcasts != null) { 10770 N = pkg.protectedBroadcasts.size(); 10771 for (i=0; i<N; i++) { 10772 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10773 } 10774 } 10775 } 10776 10777 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10778 } 10779 10780 /** 10781 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10782 * is derived purely on the basis of the contents of {@code scanFile} and 10783 * {@code cpuAbiOverride}. 10784 * 10785 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10786 */ 10787 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10788 String cpuAbiOverride, boolean extractLibs, 10789 File appLib32InstallDir) 10790 throws PackageManagerException { 10791 // Give ourselves some initial paths; we'll come back for another 10792 // pass once we've determined ABI below. 10793 setNativeLibraryPaths(pkg, appLib32InstallDir); 10794 10795 // We would never need to extract libs for forward-locked and external packages, 10796 // since the container service will do it for us. We shouldn't attempt to 10797 // extract libs from system app when it was not updated. 10798 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10799 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10800 extractLibs = false; 10801 } 10802 10803 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10804 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10805 10806 NativeLibraryHelper.Handle handle = null; 10807 try { 10808 handle = NativeLibraryHelper.Handle.create(pkg); 10809 // TODO(multiArch): This can be null for apps that didn't go through the 10810 // usual installation process. We can calculate it again, like we 10811 // do during install time. 10812 // 10813 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10814 // unnecessary. 10815 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10816 10817 // Null out the abis so that they can be recalculated. 10818 pkg.applicationInfo.primaryCpuAbi = null; 10819 pkg.applicationInfo.secondaryCpuAbi = null; 10820 if (isMultiArch(pkg.applicationInfo)) { 10821 // Warn if we've set an abiOverride for multi-lib packages.. 10822 // By definition, we need to copy both 32 and 64 bit libraries for 10823 // such packages. 10824 if (pkg.cpuAbiOverride != null 10825 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10826 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10827 } 10828 10829 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10830 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10831 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10832 if (extractLibs) { 10833 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10834 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10835 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10836 useIsaSpecificSubdirs); 10837 } else { 10838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10839 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10840 } 10841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10842 } 10843 10844 maybeThrowExceptionForMultiArchCopy( 10845 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10846 10847 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10848 if (extractLibs) { 10849 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10850 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10851 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10852 useIsaSpecificSubdirs); 10853 } else { 10854 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10855 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10856 } 10857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10858 } 10859 10860 maybeThrowExceptionForMultiArchCopy( 10861 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10862 10863 if (abi64 >= 0) { 10864 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10865 } 10866 10867 if (abi32 >= 0) { 10868 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10869 if (abi64 >= 0) { 10870 if (pkg.use32bitAbi) { 10871 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10872 pkg.applicationInfo.primaryCpuAbi = abi; 10873 } else { 10874 pkg.applicationInfo.secondaryCpuAbi = abi; 10875 } 10876 } else { 10877 pkg.applicationInfo.primaryCpuAbi = abi; 10878 } 10879 } 10880 10881 } else { 10882 String[] abiList = (cpuAbiOverride != null) ? 10883 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10884 10885 // Enable gross and lame hacks for apps that are built with old 10886 // SDK tools. We must scan their APKs for renderscript bitcode and 10887 // not launch them if it's present. Don't bother checking on devices 10888 // that don't have 64 bit support. 10889 boolean needsRenderScriptOverride = false; 10890 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10891 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10892 abiList = Build.SUPPORTED_32_BIT_ABIS; 10893 needsRenderScriptOverride = true; 10894 } 10895 10896 final int copyRet; 10897 if (extractLibs) { 10898 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10899 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10900 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10901 } else { 10902 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10903 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10904 } 10905 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10906 10907 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10908 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10909 "Error unpackaging native libs for app, errorCode=" + copyRet); 10910 } 10911 10912 if (copyRet >= 0) { 10913 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10914 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10915 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10916 } else if (needsRenderScriptOverride) { 10917 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10918 } 10919 } 10920 } catch (IOException ioe) { 10921 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10922 } finally { 10923 IoUtils.closeQuietly(handle); 10924 } 10925 10926 // Now that we've calculated the ABIs and determined if it's an internal app, 10927 // we will go ahead and populate the nativeLibraryPath. 10928 setNativeLibraryPaths(pkg, appLib32InstallDir); 10929 } 10930 10931 /** 10932 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10933 * i.e, so that all packages can be run inside a single process if required. 10934 * 10935 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10936 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10937 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10938 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10939 * updating a package that belongs to a shared user. 10940 * 10941 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10942 * adds unnecessary complexity. 10943 */ 10944 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10945 PackageParser.Package scannedPackage) { 10946 String requiredInstructionSet = null; 10947 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10948 requiredInstructionSet = VMRuntime.getInstructionSet( 10949 scannedPackage.applicationInfo.primaryCpuAbi); 10950 } 10951 10952 PackageSetting requirer = null; 10953 for (PackageSetting ps : packagesForUser) { 10954 // If packagesForUser contains scannedPackage, we skip it. This will happen 10955 // when scannedPackage is an update of an existing package. Without this check, 10956 // we will never be able to change the ABI of any package belonging to a shared 10957 // user, even if it's compatible with other packages. 10958 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10959 if (ps.primaryCpuAbiString == null) { 10960 continue; 10961 } 10962 10963 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10964 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10965 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10966 // this but there's not much we can do. 10967 String errorMessage = "Instruction set mismatch, " 10968 + ((requirer == null) ? "[caller]" : requirer) 10969 + " requires " + requiredInstructionSet + " whereas " + ps 10970 + " requires " + instructionSet; 10971 Slog.w(TAG, errorMessage); 10972 } 10973 10974 if (requiredInstructionSet == null) { 10975 requiredInstructionSet = instructionSet; 10976 requirer = ps; 10977 } 10978 } 10979 } 10980 10981 if (requiredInstructionSet != null) { 10982 String adjustedAbi; 10983 if (requirer != null) { 10984 // requirer != null implies that either scannedPackage was null or that scannedPackage 10985 // did not require an ABI, in which case we have to adjust scannedPackage to match 10986 // the ABI of the set (which is the same as requirer's ABI) 10987 adjustedAbi = requirer.primaryCpuAbiString; 10988 if (scannedPackage != null) { 10989 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10990 } 10991 } else { 10992 // requirer == null implies that we're updating all ABIs in the set to 10993 // match scannedPackage. 10994 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10995 } 10996 10997 for (PackageSetting ps : packagesForUser) { 10998 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10999 if (ps.primaryCpuAbiString != null) { 11000 continue; 11001 } 11002 11003 ps.primaryCpuAbiString = adjustedAbi; 11004 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11005 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11006 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11007 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11008 + " (requirer=" 11009 + (requirer != null ? requirer.pkg : "null") 11010 + ", scannedPackage=" 11011 + (scannedPackage != null ? scannedPackage : "null") 11012 + ")"); 11013 try { 11014 mInstaller.rmdex(ps.codePathString, 11015 getDexCodeInstructionSet(getPreferredInstructionSet())); 11016 } catch (InstallerException ignored) { 11017 } 11018 } 11019 } 11020 } 11021 } 11022 } 11023 11024 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11025 synchronized (mPackages) { 11026 mResolverReplaced = true; 11027 // Set up information for custom user intent resolution activity. 11028 mResolveActivity.applicationInfo = pkg.applicationInfo; 11029 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11030 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11031 mResolveActivity.processName = pkg.applicationInfo.packageName; 11032 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11033 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11034 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11035 mResolveActivity.theme = 0; 11036 mResolveActivity.exported = true; 11037 mResolveActivity.enabled = true; 11038 mResolveInfo.activityInfo = mResolveActivity; 11039 mResolveInfo.priority = 0; 11040 mResolveInfo.preferredOrder = 0; 11041 mResolveInfo.match = 0; 11042 mResolveComponentName = mCustomResolverComponentName; 11043 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11044 mResolveComponentName); 11045 } 11046 } 11047 11048 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11049 if (installerActivity == null) { 11050 if (DEBUG_EPHEMERAL) { 11051 Slog.d(TAG, "Clear ephemeral installer activity"); 11052 } 11053 mInstantAppInstallerActivity = null; 11054 return; 11055 } 11056 11057 if (DEBUG_EPHEMERAL) { 11058 Slog.d(TAG, "Set ephemeral installer activity: " 11059 + installerActivity.getComponentName()); 11060 } 11061 // Set up information for ephemeral installer activity 11062 mInstantAppInstallerActivity = installerActivity; 11063 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11064 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11065 mInstantAppInstallerActivity.exported = true; 11066 mInstantAppInstallerActivity.enabled = true; 11067 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11068 mInstantAppInstallerInfo.priority = 0; 11069 mInstantAppInstallerInfo.preferredOrder = 1; 11070 mInstantAppInstallerInfo.isDefault = true; 11071 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11072 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11073 } 11074 11075 private static String calculateBundledApkRoot(final String codePathString) { 11076 final File codePath = new File(codePathString); 11077 final File codeRoot; 11078 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11079 codeRoot = Environment.getRootDirectory(); 11080 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11081 codeRoot = Environment.getOemDirectory(); 11082 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11083 codeRoot = Environment.getVendorDirectory(); 11084 } else { 11085 // Unrecognized code path; take its top real segment as the apk root: 11086 // e.g. /something/app/blah.apk => /something 11087 try { 11088 File f = codePath.getCanonicalFile(); 11089 File parent = f.getParentFile(); // non-null because codePath is a file 11090 File tmp; 11091 while ((tmp = parent.getParentFile()) != null) { 11092 f = parent; 11093 parent = tmp; 11094 } 11095 codeRoot = f; 11096 Slog.w(TAG, "Unrecognized code path " 11097 + codePath + " - using " + codeRoot); 11098 } catch (IOException e) { 11099 // Can't canonicalize the code path -- shenanigans? 11100 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11101 return Environment.getRootDirectory().getPath(); 11102 } 11103 } 11104 return codeRoot.getPath(); 11105 } 11106 11107 /** 11108 * Derive and set the location of native libraries for the given package, 11109 * which varies depending on where and how the package was installed. 11110 */ 11111 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11112 final ApplicationInfo info = pkg.applicationInfo; 11113 final String codePath = pkg.codePath; 11114 final File codeFile = new File(codePath); 11115 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11116 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11117 11118 info.nativeLibraryRootDir = null; 11119 info.nativeLibraryRootRequiresIsa = false; 11120 info.nativeLibraryDir = null; 11121 info.secondaryNativeLibraryDir = null; 11122 11123 if (isApkFile(codeFile)) { 11124 // Monolithic install 11125 if (bundledApp) { 11126 // If "/system/lib64/apkname" exists, assume that is the per-package 11127 // native library directory to use; otherwise use "/system/lib/apkname". 11128 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11129 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11130 getPrimaryInstructionSet(info)); 11131 11132 // This is a bundled system app so choose the path based on the ABI. 11133 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11134 // is just the default path. 11135 final String apkName = deriveCodePathName(codePath); 11136 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11137 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11138 apkName).getAbsolutePath(); 11139 11140 if (info.secondaryCpuAbi != null) { 11141 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11142 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11143 secondaryLibDir, apkName).getAbsolutePath(); 11144 } 11145 } else if (asecApp) { 11146 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11147 .getAbsolutePath(); 11148 } else { 11149 final String apkName = deriveCodePathName(codePath); 11150 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11151 .getAbsolutePath(); 11152 } 11153 11154 info.nativeLibraryRootRequiresIsa = false; 11155 info.nativeLibraryDir = info.nativeLibraryRootDir; 11156 } else { 11157 // Cluster install 11158 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11159 info.nativeLibraryRootRequiresIsa = true; 11160 11161 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11162 getPrimaryInstructionSet(info)).getAbsolutePath(); 11163 11164 if (info.secondaryCpuAbi != null) { 11165 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11166 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11167 } 11168 } 11169 } 11170 11171 /** 11172 * Calculate the abis and roots for a bundled app. These can uniquely 11173 * be determined from the contents of the system partition, i.e whether 11174 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11175 * of this information, and instead assume that the system was built 11176 * sensibly. 11177 */ 11178 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11179 PackageSetting pkgSetting) { 11180 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11181 11182 // If "/system/lib64/apkname" exists, assume that is the per-package 11183 // native library directory to use; otherwise use "/system/lib/apkname". 11184 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11185 setBundledAppAbi(pkg, apkRoot, apkName); 11186 // pkgSetting might be null during rescan following uninstall of updates 11187 // to a bundled app, so accommodate that possibility. The settings in 11188 // that case will be established later from the parsed package. 11189 // 11190 // If the settings aren't null, sync them up with what we've just derived. 11191 // note that apkRoot isn't stored in the package settings. 11192 if (pkgSetting != null) { 11193 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11194 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11195 } 11196 } 11197 11198 /** 11199 * Deduces the ABI of a bundled app and sets the relevant fields on the 11200 * parsed pkg object. 11201 * 11202 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11203 * under which system libraries are installed. 11204 * @param apkName the name of the installed package. 11205 */ 11206 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11207 final File codeFile = new File(pkg.codePath); 11208 11209 final boolean has64BitLibs; 11210 final boolean has32BitLibs; 11211 if (isApkFile(codeFile)) { 11212 // Monolithic install 11213 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11214 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11215 } else { 11216 // Cluster install 11217 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11218 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11219 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11220 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11221 has64BitLibs = (new File(rootDir, isa)).exists(); 11222 } else { 11223 has64BitLibs = false; 11224 } 11225 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11226 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11227 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11228 has32BitLibs = (new File(rootDir, isa)).exists(); 11229 } else { 11230 has32BitLibs = false; 11231 } 11232 } 11233 11234 if (has64BitLibs && !has32BitLibs) { 11235 // The package has 64 bit libs, but not 32 bit libs. Its primary 11236 // ABI should be 64 bit. We can safely assume here that the bundled 11237 // native libraries correspond to the most preferred ABI in the list. 11238 11239 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11240 pkg.applicationInfo.secondaryCpuAbi = null; 11241 } else if (has32BitLibs && !has64BitLibs) { 11242 // The package has 32 bit libs but not 64 bit libs. Its primary 11243 // ABI should be 32 bit. 11244 11245 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11246 pkg.applicationInfo.secondaryCpuAbi = null; 11247 } else if (has32BitLibs && has64BitLibs) { 11248 // The application has both 64 and 32 bit bundled libraries. We check 11249 // here that the app declares multiArch support, and warn if it doesn't. 11250 // 11251 // We will be lenient here and record both ABIs. The primary will be the 11252 // ABI that's higher on the list, i.e, a device that's configured to prefer 11253 // 64 bit apps will see a 64 bit primary ABI, 11254 11255 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11256 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11257 } 11258 11259 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11260 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11261 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11262 } else { 11263 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11264 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11265 } 11266 } else { 11267 pkg.applicationInfo.primaryCpuAbi = null; 11268 pkg.applicationInfo.secondaryCpuAbi = null; 11269 } 11270 } 11271 11272 private void killApplication(String pkgName, int appId, String reason) { 11273 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11274 } 11275 11276 private void killApplication(String pkgName, int appId, int userId, String reason) { 11277 // Request the ActivityManager to kill the process(only for existing packages) 11278 // so that we do not end up in a confused state while the user is still using the older 11279 // version of the application while the new one gets installed. 11280 final long token = Binder.clearCallingIdentity(); 11281 try { 11282 IActivityManager am = ActivityManager.getService(); 11283 if (am != null) { 11284 try { 11285 am.killApplication(pkgName, appId, userId, reason); 11286 } catch (RemoteException e) { 11287 } 11288 } 11289 } finally { 11290 Binder.restoreCallingIdentity(token); 11291 } 11292 } 11293 11294 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11295 // Remove the parent package setting 11296 PackageSetting ps = (PackageSetting) pkg.mExtras; 11297 if (ps != null) { 11298 removePackageLI(ps, chatty); 11299 } 11300 // Remove the child package setting 11301 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11302 for (int i = 0; i < childCount; i++) { 11303 PackageParser.Package childPkg = pkg.childPackages.get(i); 11304 ps = (PackageSetting) childPkg.mExtras; 11305 if (ps != null) { 11306 removePackageLI(ps, chatty); 11307 } 11308 } 11309 } 11310 11311 void removePackageLI(PackageSetting ps, boolean chatty) { 11312 if (DEBUG_INSTALL) { 11313 if (chatty) 11314 Log.d(TAG, "Removing package " + ps.name); 11315 } 11316 11317 // writer 11318 synchronized (mPackages) { 11319 mPackages.remove(ps.name); 11320 final PackageParser.Package pkg = ps.pkg; 11321 if (pkg != null) { 11322 cleanPackageDataStructuresLILPw(pkg, chatty); 11323 } 11324 } 11325 } 11326 11327 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11328 if (DEBUG_INSTALL) { 11329 if (chatty) 11330 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11331 } 11332 11333 // writer 11334 synchronized (mPackages) { 11335 // Remove the parent package 11336 mPackages.remove(pkg.applicationInfo.packageName); 11337 cleanPackageDataStructuresLILPw(pkg, chatty); 11338 11339 // Remove the child packages 11340 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11341 for (int i = 0; i < childCount; i++) { 11342 PackageParser.Package childPkg = pkg.childPackages.get(i); 11343 mPackages.remove(childPkg.applicationInfo.packageName); 11344 cleanPackageDataStructuresLILPw(childPkg, chatty); 11345 } 11346 } 11347 } 11348 11349 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11350 int N = pkg.providers.size(); 11351 StringBuilder r = null; 11352 int i; 11353 for (i=0; i<N; i++) { 11354 PackageParser.Provider p = pkg.providers.get(i); 11355 mProviders.removeProvider(p); 11356 if (p.info.authority == null) { 11357 11358 /* There was another ContentProvider with this authority when 11359 * this app was installed so this authority is null, 11360 * Ignore it as we don't have to unregister the provider. 11361 */ 11362 continue; 11363 } 11364 String names[] = p.info.authority.split(";"); 11365 for (int j = 0; j < names.length; j++) { 11366 if (mProvidersByAuthority.get(names[j]) == p) { 11367 mProvidersByAuthority.remove(names[j]); 11368 if (DEBUG_REMOVE) { 11369 if (chatty) 11370 Log.d(TAG, "Unregistered content provider: " + names[j] 11371 + ", className = " + p.info.name + ", isSyncable = " 11372 + p.info.isSyncable); 11373 } 11374 } 11375 } 11376 if (DEBUG_REMOVE && chatty) { 11377 if (r == null) { 11378 r = new StringBuilder(256); 11379 } else { 11380 r.append(' '); 11381 } 11382 r.append(p.info.name); 11383 } 11384 } 11385 if (r != null) { 11386 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11387 } 11388 11389 N = pkg.services.size(); 11390 r = null; 11391 for (i=0; i<N; i++) { 11392 PackageParser.Service s = pkg.services.get(i); 11393 mServices.removeService(s); 11394 if (chatty) { 11395 if (r == null) { 11396 r = new StringBuilder(256); 11397 } else { 11398 r.append(' '); 11399 } 11400 r.append(s.info.name); 11401 } 11402 } 11403 if (r != null) { 11404 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11405 } 11406 11407 N = pkg.receivers.size(); 11408 r = null; 11409 for (i=0; i<N; i++) { 11410 PackageParser.Activity a = pkg.receivers.get(i); 11411 mReceivers.removeActivity(a, "receiver"); 11412 if (DEBUG_REMOVE && chatty) { 11413 if (r == null) { 11414 r = new StringBuilder(256); 11415 } else { 11416 r.append(' '); 11417 } 11418 r.append(a.info.name); 11419 } 11420 } 11421 if (r != null) { 11422 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11423 } 11424 11425 N = pkg.activities.size(); 11426 r = null; 11427 for (i=0; i<N; i++) { 11428 PackageParser.Activity a = pkg.activities.get(i); 11429 mActivities.removeActivity(a, "activity"); 11430 if (DEBUG_REMOVE && chatty) { 11431 if (r == null) { 11432 r = new StringBuilder(256); 11433 } else { 11434 r.append(' '); 11435 } 11436 r.append(a.info.name); 11437 } 11438 } 11439 if (r != null) { 11440 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11441 } 11442 11443 N = pkg.permissions.size(); 11444 r = null; 11445 for (i=0; i<N; i++) { 11446 PackageParser.Permission p = pkg.permissions.get(i); 11447 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11448 if (bp == null) { 11449 bp = mSettings.mPermissionTrees.get(p.info.name); 11450 } 11451 if (bp != null && bp.perm == p) { 11452 bp.perm = null; 11453 if (DEBUG_REMOVE && chatty) { 11454 if (r == null) { 11455 r = new StringBuilder(256); 11456 } else { 11457 r.append(' '); 11458 } 11459 r.append(p.info.name); 11460 } 11461 } 11462 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11463 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11464 if (appOpPkgs != null) { 11465 appOpPkgs.remove(pkg.packageName); 11466 } 11467 } 11468 } 11469 if (r != null) { 11470 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11471 } 11472 11473 N = pkg.requestedPermissions.size(); 11474 r = null; 11475 for (i=0; i<N; i++) { 11476 String perm = pkg.requestedPermissions.get(i); 11477 BasePermission bp = mSettings.mPermissions.get(perm); 11478 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11479 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11480 if (appOpPkgs != null) { 11481 appOpPkgs.remove(pkg.packageName); 11482 if (appOpPkgs.isEmpty()) { 11483 mAppOpPermissionPackages.remove(perm); 11484 } 11485 } 11486 } 11487 } 11488 if (r != null) { 11489 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11490 } 11491 11492 N = pkg.instrumentation.size(); 11493 r = null; 11494 for (i=0; i<N; i++) { 11495 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11496 mInstrumentation.remove(a.getComponentName()); 11497 if (DEBUG_REMOVE && chatty) { 11498 if (r == null) { 11499 r = new StringBuilder(256); 11500 } else { 11501 r.append(' '); 11502 } 11503 r.append(a.info.name); 11504 } 11505 } 11506 if (r != null) { 11507 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11508 } 11509 11510 r = null; 11511 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11512 // Only system apps can hold shared libraries. 11513 if (pkg.libraryNames != null) { 11514 for (i = 0; i < pkg.libraryNames.size(); i++) { 11515 String name = pkg.libraryNames.get(i); 11516 if (removeSharedLibraryLPw(name, 0)) { 11517 if (DEBUG_REMOVE && chatty) { 11518 if (r == null) { 11519 r = new StringBuilder(256); 11520 } else { 11521 r.append(' '); 11522 } 11523 r.append(name); 11524 } 11525 } 11526 } 11527 } 11528 } 11529 11530 r = null; 11531 11532 // Any package can hold static shared libraries. 11533 if (pkg.staticSharedLibName != null) { 11534 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11535 if (DEBUG_REMOVE && chatty) { 11536 if (r == null) { 11537 r = new StringBuilder(256); 11538 } else { 11539 r.append(' '); 11540 } 11541 r.append(pkg.staticSharedLibName); 11542 } 11543 } 11544 } 11545 11546 if (r != null) { 11547 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11548 } 11549 } 11550 11551 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11552 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11553 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11554 return true; 11555 } 11556 } 11557 return false; 11558 } 11559 11560 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11561 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11562 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11563 11564 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11565 // Update the parent permissions 11566 updatePermissionsLPw(pkg.packageName, pkg, flags); 11567 // Update the child permissions 11568 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11569 for (int i = 0; i < childCount; i++) { 11570 PackageParser.Package childPkg = pkg.childPackages.get(i); 11571 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11572 } 11573 } 11574 11575 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11576 int flags) { 11577 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11578 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11579 } 11580 11581 private void updatePermissionsLPw(String changingPkg, 11582 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11583 // Make sure there are no dangling permission trees. 11584 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11585 while (it.hasNext()) { 11586 final BasePermission bp = it.next(); 11587 if (bp.packageSetting == null) { 11588 // We may not yet have parsed the package, so just see if 11589 // we still know about its settings. 11590 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11591 } 11592 if (bp.packageSetting == null) { 11593 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11594 + " from package " + bp.sourcePackage); 11595 it.remove(); 11596 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11597 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11598 Slog.i(TAG, "Removing old permission tree: " + bp.name 11599 + " from package " + bp.sourcePackage); 11600 flags |= UPDATE_PERMISSIONS_ALL; 11601 it.remove(); 11602 } 11603 } 11604 } 11605 11606 // Make sure all dynamic permissions have been assigned to a package, 11607 // and make sure there are no dangling permissions. 11608 it = mSettings.mPermissions.values().iterator(); 11609 while (it.hasNext()) { 11610 final BasePermission bp = it.next(); 11611 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11612 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11613 + bp.name + " pkg=" + bp.sourcePackage 11614 + " info=" + bp.pendingInfo); 11615 if (bp.packageSetting == null && bp.pendingInfo != null) { 11616 final BasePermission tree = findPermissionTreeLP(bp.name); 11617 if (tree != null && tree.perm != null) { 11618 bp.packageSetting = tree.packageSetting; 11619 bp.perm = new PackageParser.Permission(tree.perm.owner, 11620 new PermissionInfo(bp.pendingInfo)); 11621 bp.perm.info.packageName = tree.perm.info.packageName; 11622 bp.perm.info.name = bp.name; 11623 bp.uid = tree.uid; 11624 } 11625 } 11626 } 11627 if (bp.packageSetting == null) { 11628 // We may not yet have parsed the package, so just see if 11629 // we still know about its settings. 11630 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11631 } 11632 if (bp.packageSetting == null) { 11633 Slog.w(TAG, "Removing dangling permission: " + bp.name 11634 + " from package " + bp.sourcePackage); 11635 it.remove(); 11636 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11637 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11638 Slog.i(TAG, "Removing old permission: " + bp.name 11639 + " from package " + bp.sourcePackage); 11640 flags |= UPDATE_PERMISSIONS_ALL; 11641 it.remove(); 11642 } 11643 } 11644 } 11645 11646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11647 // Now update the permissions for all packages, in particular 11648 // replace the granted permissions of the system packages. 11649 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11650 for (PackageParser.Package pkg : mPackages.values()) { 11651 if (pkg != pkgInfo) { 11652 // Only replace for packages on requested volume 11653 final String volumeUuid = getVolumeUuidForPackage(pkg); 11654 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11655 && Objects.equals(replaceVolumeUuid, volumeUuid); 11656 grantPermissionsLPw(pkg, replace, changingPkg); 11657 } 11658 } 11659 } 11660 11661 if (pkgInfo != null) { 11662 // Only replace for packages on requested volume 11663 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11664 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11665 && Objects.equals(replaceVolumeUuid, volumeUuid); 11666 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11667 } 11668 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11669 } 11670 11671 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11672 String packageOfInterest) { 11673 // IMPORTANT: There are two types of permissions: install and runtime. 11674 // Install time permissions are granted when the app is installed to 11675 // all device users and users added in the future. Runtime permissions 11676 // are granted at runtime explicitly to specific users. Normal and signature 11677 // protected permissions are install time permissions. Dangerous permissions 11678 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11679 // otherwise they are runtime permissions. This function does not manage 11680 // runtime permissions except for the case an app targeting Lollipop MR1 11681 // being upgraded to target a newer SDK, in which case dangerous permissions 11682 // are transformed from install time to runtime ones. 11683 11684 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11685 if (ps == null) { 11686 return; 11687 } 11688 11689 PermissionsState permissionsState = ps.getPermissionsState(); 11690 PermissionsState origPermissions = permissionsState; 11691 11692 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11693 11694 boolean runtimePermissionsRevoked = false; 11695 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11696 11697 boolean changedInstallPermission = false; 11698 11699 if (replace) { 11700 ps.installPermissionsFixed = false; 11701 if (!ps.isSharedUser()) { 11702 origPermissions = new PermissionsState(permissionsState); 11703 permissionsState.reset(); 11704 } else { 11705 // We need to know only about runtime permission changes since the 11706 // calling code always writes the install permissions state but 11707 // the runtime ones are written only if changed. The only cases of 11708 // changed runtime permissions here are promotion of an install to 11709 // runtime and revocation of a runtime from a shared user. 11710 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11711 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11712 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11713 runtimePermissionsRevoked = true; 11714 } 11715 } 11716 } 11717 11718 permissionsState.setGlobalGids(mGlobalGids); 11719 11720 final int N = pkg.requestedPermissions.size(); 11721 for (int i=0; i<N; i++) { 11722 final String name = pkg.requestedPermissions.get(i); 11723 final BasePermission bp = mSettings.mPermissions.get(name); 11724 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11725 >= Build.VERSION_CODES.M; 11726 11727 if (DEBUG_INSTALL) { 11728 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11729 } 11730 11731 if (bp == null || bp.packageSetting == null) { 11732 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11733 Slog.w(TAG, "Unknown permission " + name 11734 + " in package " + pkg.packageName); 11735 } 11736 continue; 11737 } 11738 11739 11740 // Limit ephemeral apps to ephemeral allowed permissions. 11741 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11742 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11743 + pkg.packageName); 11744 continue; 11745 } 11746 11747 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 11748 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 11749 + pkg.packageName); 11750 continue; 11751 } 11752 11753 final String perm = bp.name; 11754 boolean allowedSig = false; 11755 int grant = GRANT_DENIED; 11756 11757 // Keep track of app op permissions. 11758 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11759 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11760 if (pkgs == null) { 11761 pkgs = new ArraySet<>(); 11762 mAppOpPermissionPackages.put(bp.name, pkgs); 11763 } 11764 pkgs.add(pkg.packageName); 11765 } 11766 11767 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11768 switch (level) { 11769 case PermissionInfo.PROTECTION_NORMAL: { 11770 // For all apps normal permissions are install time ones. 11771 grant = GRANT_INSTALL; 11772 } break; 11773 11774 case PermissionInfo.PROTECTION_DANGEROUS: { 11775 // If a permission review is required for legacy apps we represent 11776 // their permissions as always granted runtime ones since we need 11777 // to keep the review required permission flag per user while an 11778 // install permission's state is shared across all users. 11779 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11780 // For legacy apps dangerous permissions are install time ones. 11781 grant = GRANT_INSTALL; 11782 } else if (origPermissions.hasInstallPermission(bp.name)) { 11783 // For legacy apps that became modern, install becomes runtime. 11784 grant = GRANT_UPGRADE; 11785 } else if (mPromoteSystemApps 11786 && isSystemApp(ps) 11787 && mExistingSystemPackages.contains(ps.name)) { 11788 // For legacy system apps, install becomes runtime. 11789 // We cannot check hasInstallPermission() for system apps since those 11790 // permissions were granted implicitly and not persisted pre-M. 11791 grant = GRANT_UPGRADE; 11792 } else { 11793 // For modern apps keep runtime permissions unchanged. 11794 grant = GRANT_RUNTIME; 11795 } 11796 } break; 11797 11798 case PermissionInfo.PROTECTION_SIGNATURE: { 11799 // For all apps signature permissions are install time ones. 11800 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11801 if (allowedSig) { 11802 grant = GRANT_INSTALL; 11803 } 11804 } break; 11805 } 11806 11807 if (DEBUG_INSTALL) { 11808 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11809 } 11810 11811 if (grant != GRANT_DENIED) { 11812 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11813 // If this is an existing, non-system package, then 11814 // we can't add any new permissions to it. 11815 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11816 // Except... if this is a permission that was added 11817 // to the platform (note: need to only do this when 11818 // updating the platform). 11819 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11820 grant = GRANT_DENIED; 11821 } 11822 } 11823 } 11824 11825 switch (grant) { 11826 case GRANT_INSTALL: { 11827 // Revoke this as runtime permission to handle the case of 11828 // a runtime permission being downgraded to an install one. 11829 // Also in permission review mode we keep dangerous permissions 11830 // for legacy apps 11831 for (int userId : UserManagerService.getInstance().getUserIds()) { 11832 if (origPermissions.getRuntimePermissionState( 11833 bp.name, userId) != null) { 11834 // Revoke the runtime permission and clear the flags. 11835 origPermissions.revokeRuntimePermission(bp, userId); 11836 origPermissions.updatePermissionFlags(bp, userId, 11837 PackageManager.MASK_PERMISSION_FLAGS, 0); 11838 // If we revoked a permission permission, we have to write. 11839 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11840 changedRuntimePermissionUserIds, userId); 11841 } 11842 } 11843 // Grant an install permission. 11844 if (permissionsState.grantInstallPermission(bp) != 11845 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11846 changedInstallPermission = true; 11847 } 11848 } break; 11849 11850 case GRANT_RUNTIME: { 11851 // Grant previously granted runtime permissions. 11852 for (int userId : UserManagerService.getInstance().getUserIds()) { 11853 PermissionState permissionState = origPermissions 11854 .getRuntimePermissionState(bp.name, userId); 11855 int flags = permissionState != null 11856 ? permissionState.getFlags() : 0; 11857 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11858 // Don't propagate the permission in a permission review mode if 11859 // the former was revoked, i.e. marked to not propagate on upgrade. 11860 // Note that in a permission review mode install permissions are 11861 // represented as constantly granted runtime ones since we need to 11862 // keep a per user state associated with the permission. Also the 11863 // revoke on upgrade flag is no longer applicable and is reset. 11864 final boolean revokeOnUpgrade = (flags & PackageManager 11865 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11866 if (revokeOnUpgrade) { 11867 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11868 // Since we changed the flags, we have to write. 11869 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11870 changedRuntimePermissionUserIds, userId); 11871 } 11872 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11873 if (permissionsState.grantRuntimePermission(bp, userId) == 11874 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11875 // If we cannot put the permission as it was, 11876 // we have to write. 11877 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11878 changedRuntimePermissionUserIds, userId); 11879 } 11880 } 11881 11882 // If the app supports runtime permissions no need for a review. 11883 if (mPermissionReviewRequired 11884 && appSupportsRuntimePermissions 11885 && (flags & PackageManager 11886 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11887 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11888 // Since we changed the flags, we have to write. 11889 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11890 changedRuntimePermissionUserIds, userId); 11891 } 11892 } else if (mPermissionReviewRequired 11893 && !appSupportsRuntimePermissions) { 11894 // For legacy apps that need a permission review, every new 11895 // runtime permission is granted but it is pending a review. 11896 // We also need to review only platform defined runtime 11897 // permissions as these are the only ones the platform knows 11898 // how to disable the API to simulate revocation as legacy 11899 // apps don't expect to run with revoked permissions. 11900 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11901 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11902 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11903 // We changed the flags, hence have to write. 11904 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11905 changedRuntimePermissionUserIds, userId); 11906 } 11907 } 11908 if (permissionsState.grantRuntimePermission(bp, userId) 11909 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11910 // We changed the permission, hence have to write. 11911 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11912 changedRuntimePermissionUserIds, userId); 11913 } 11914 } 11915 // Propagate the permission flags. 11916 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11917 } 11918 } break; 11919 11920 case GRANT_UPGRADE: { 11921 // Grant runtime permissions for a previously held install permission. 11922 PermissionState permissionState = origPermissions 11923 .getInstallPermissionState(bp.name); 11924 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11925 11926 if (origPermissions.revokeInstallPermission(bp) 11927 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11928 // We will be transferring the permission flags, so clear them. 11929 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11930 PackageManager.MASK_PERMISSION_FLAGS, 0); 11931 changedInstallPermission = true; 11932 } 11933 11934 // If the permission is not to be promoted to runtime we ignore it and 11935 // also its other flags as they are not applicable to install permissions. 11936 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11937 for (int userId : currentUserIds) { 11938 if (permissionsState.grantRuntimePermission(bp, userId) != 11939 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11940 // Transfer the permission flags. 11941 permissionsState.updatePermissionFlags(bp, userId, 11942 flags, flags); 11943 // If we granted the permission, we have to write. 11944 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11945 changedRuntimePermissionUserIds, userId); 11946 } 11947 } 11948 } 11949 } break; 11950 11951 default: { 11952 if (packageOfInterest == null 11953 || packageOfInterest.equals(pkg.packageName)) { 11954 Slog.w(TAG, "Not granting permission " + perm 11955 + " to package " + pkg.packageName 11956 + " because it was previously installed without"); 11957 } 11958 } break; 11959 } 11960 } else { 11961 if (permissionsState.revokeInstallPermission(bp) != 11962 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11963 // Also drop the permission flags. 11964 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11965 PackageManager.MASK_PERMISSION_FLAGS, 0); 11966 changedInstallPermission = true; 11967 Slog.i(TAG, "Un-granting permission " + perm 11968 + " from package " + pkg.packageName 11969 + " (protectionLevel=" + bp.protectionLevel 11970 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11971 + ")"); 11972 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11973 // Don't print warning for app op permissions, since it is fine for them 11974 // not to be granted, there is a UI for the user to decide. 11975 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11976 Slog.w(TAG, "Not granting permission " + perm 11977 + " to package " + pkg.packageName 11978 + " (protectionLevel=" + bp.protectionLevel 11979 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11980 + ")"); 11981 } 11982 } 11983 } 11984 } 11985 11986 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11987 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11988 // This is the first that we have heard about this package, so the 11989 // permissions we have now selected are fixed until explicitly 11990 // changed. 11991 ps.installPermissionsFixed = true; 11992 } 11993 11994 // Persist the runtime permissions state for users with changes. If permissions 11995 // were revoked because no app in the shared user declares them we have to 11996 // write synchronously to avoid losing runtime permissions state. 11997 for (int userId : changedRuntimePermissionUserIds) { 11998 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11999 } 12000 } 12001 12002 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 12003 boolean allowed = false; 12004 final int NP = PackageParser.NEW_PERMISSIONS.length; 12005 for (int ip=0; ip<NP; ip++) { 12006 final PackageParser.NewPermissionInfo npi 12007 = PackageParser.NEW_PERMISSIONS[ip]; 12008 if (npi.name.equals(perm) 12009 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 12010 allowed = true; 12011 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 12012 + pkg.packageName); 12013 break; 12014 } 12015 } 12016 return allowed; 12017 } 12018 12019 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 12020 BasePermission bp, PermissionsState origPermissions) { 12021 boolean privilegedPermission = (bp.protectionLevel 12022 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 12023 boolean privappPermissionsDisable = 12024 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 12025 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 12026 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 12027 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 12028 && !platformPackage && platformPermission) { 12029 ArraySet<String> wlPermissions = SystemConfig.getInstance() 12030 .getPrivAppPermissions(pkg.packageName); 12031 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 12032 if (!whitelisted) { 12033 Slog.w(TAG, "Privileged permission " + perm + " for package " 12034 + pkg.packageName + " - not in privapp-permissions whitelist"); 12035 // Only report violations for apps on system image 12036 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 12037 if (mPrivappPermissionsViolations == null) { 12038 mPrivappPermissionsViolations = new ArraySet<>(); 12039 } 12040 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 12041 } 12042 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 12043 return false; 12044 } 12045 } 12046 } 12047 boolean allowed = (compareSignatures( 12048 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 12049 == PackageManager.SIGNATURE_MATCH) 12050 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 12051 == PackageManager.SIGNATURE_MATCH); 12052 if (!allowed && privilegedPermission) { 12053 if (isSystemApp(pkg)) { 12054 // For updated system applications, a system permission 12055 // is granted only if it had been defined by the original application. 12056 if (pkg.isUpdatedSystemApp()) { 12057 final PackageSetting sysPs = mSettings 12058 .getDisabledSystemPkgLPr(pkg.packageName); 12059 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 12060 // If the original was granted this permission, we take 12061 // that grant decision as read and propagate it to the 12062 // update. 12063 if (sysPs.isPrivileged()) { 12064 allowed = true; 12065 } 12066 } else { 12067 // The system apk may have been updated with an older 12068 // version of the one on the data partition, but which 12069 // granted a new system permission that it didn't have 12070 // before. In this case we do want to allow the app to 12071 // now get the new permission if the ancestral apk is 12072 // privileged to get it. 12073 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 12074 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 12075 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 12076 allowed = true; 12077 break; 12078 } 12079 } 12080 } 12081 // Also if a privileged parent package on the system image or any of 12082 // its children requested a privileged permission, the updated child 12083 // packages can also get the permission. 12084 if (pkg.parentPackage != null) { 12085 final PackageSetting disabledSysParentPs = mSettings 12086 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 12087 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 12088 && disabledSysParentPs.isPrivileged()) { 12089 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 12090 allowed = true; 12091 } else if (disabledSysParentPs.pkg.childPackages != null) { 12092 final int count = disabledSysParentPs.pkg.childPackages.size(); 12093 for (int i = 0; i < count; i++) { 12094 PackageParser.Package disabledSysChildPkg = 12095 disabledSysParentPs.pkg.childPackages.get(i); 12096 if (isPackageRequestingPermission(disabledSysChildPkg, 12097 perm)) { 12098 allowed = true; 12099 break; 12100 } 12101 } 12102 } 12103 } 12104 } 12105 } 12106 } else { 12107 allowed = isPrivilegedApp(pkg); 12108 } 12109 } 12110 } 12111 if (!allowed) { 12112 if (!allowed && (bp.protectionLevel 12113 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 12114 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 12115 // If this was a previously normal/dangerous permission that got moved 12116 // to a system permission as part of the runtime permission redesign, then 12117 // we still want to blindly grant it to old apps. 12118 allowed = true; 12119 } 12120 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 12121 && pkg.packageName.equals(mRequiredInstallerPackage)) { 12122 // If this permission is to be granted to the system installer and 12123 // this app is an installer, then it gets the permission. 12124 allowed = true; 12125 } 12126 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 12127 && pkg.packageName.equals(mRequiredVerifierPackage)) { 12128 // If this permission is to be granted to the system verifier and 12129 // this app is a verifier, then it gets the permission. 12130 allowed = true; 12131 } 12132 if (!allowed && (bp.protectionLevel 12133 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 12134 && isSystemApp(pkg)) { 12135 // Any pre-installed system app is allowed to get this permission. 12136 allowed = true; 12137 } 12138 if (!allowed && (bp.protectionLevel 12139 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 12140 // For development permissions, a development permission 12141 // is granted only if it was already granted. 12142 allowed = origPermissions.hasInstallPermission(perm); 12143 } 12144 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 12145 && pkg.packageName.equals(mSetupWizardPackage)) { 12146 // If this permission is to be granted to the system setup wizard and 12147 // this app is a setup wizard, then it gets the permission. 12148 allowed = true; 12149 } 12150 } 12151 return allowed; 12152 } 12153 12154 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 12155 final int permCount = pkg.requestedPermissions.size(); 12156 for (int j = 0; j < permCount; j++) { 12157 String requestedPermission = pkg.requestedPermissions.get(j); 12158 if (permission.equals(requestedPermission)) { 12159 return true; 12160 } 12161 } 12162 return false; 12163 } 12164 12165 final class ActivityIntentResolver 12166 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12167 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12168 boolean defaultOnly, int userId) { 12169 if (!sUserManager.exists(userId)) return null; 12170 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12171 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12172 } 12173 12174 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12175 int userId) { 12176 if (!sUserManager.exists(userId)) return null; 12177 mFlags = flags; 12178 return super.queryIntent(intent, resolvedType, 12179 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12180 userId); 12181 } 12182 12183 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12184 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12185 if (!sUserManager.exists(userId)) return null; 12186 if (packageActivities == null) { 12187 return null; 12188 } 12189 mFlags = flags; 12190 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12191 final int N = packageActivities.size(); 12192 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12193 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12194 12195 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12196 for (int i = 0; i < N; ++i) { 12197 intentFilters = packageActivities.get(i).intents; 12198 if (intentFilters != null && intentFilters.size() > 0) { 12199 PackageParser.ActivityIntentInfo[] array = 12200 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12201 intentFilters.toArray(array); 12202 listCut.add(array); 12203 } 12204 } 12205 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12206 } 12207 12208 /** 12209 * Finds a privileged activity that matches the specified activity names. 12210 */ 12211 private PackageParser.Activity findMatchingActivity( 12212 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12213 for (PackageParser.Activity sysActivity : activityList) { 12214 if (sysActivity.info.name.equals(activityInfo.name)) { 12215 return sysActivity; 12216 } 12217 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12218 return sysActivity; 12219 } 12220 if (sysActivity.info.targetActivity != null) { 12221 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12222 return sysActivity; 12223 } 12224 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12225 return sysActivity; 12226 } 12227 } 12228 } 12229 return null; 12230 } 12231 12232 public class IterGenerator<E> { 12233 public Iterator<E> generate(ActivityIntentInfo info) { 12234 return null; 12235 } 12236 } 12237 12238 public class ActionIterGenerator extends IterGenerator<String> { 12239 @Override 12240 public Iterator<String> generate(ActivityIntentInfo info) { 12241 return info.actionsIterator(); 12242 } 12243 } 12244 12245 public class CategoriesIterGenerator extends IterGenerator<String> { 12246 @Override 12247 public Iterator<String> generate(ActivityIntentInfo info) { 12248 return info.categoriesIterator(); 12249 } 12250 } 12251 12252 public class SchemesIterGenerator extends IterGenerator<String> { 12253 @Override 12254 public Iterator<String> generate(ActivityIntentInfo info) { 12255 return info.schemesIterator(); 12256 } 12257 } 12258 12259 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12260 @Override 12261 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12262 return info.authoritiesIterator(); 12263 } 12264 } 12265 12266 /** 12267 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12268 * MODIFIED. Do not pass in a list that should not be changed. 12269 */ 12270 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12271 IterGenerator<T> generator, Iterator<T> searchIterator) { 12272 // loop through the set of actions; every one must be found in the intent filter 12273 while (searchIterator.hasNext()) { 12274 // we must have at least one filter in the list to consider a match 12275 if (intentList.size() == 0) { 12276 break; 12277 } 12278 12279 final T searchAction = searchIterator.next(); 12280 12281 // loop through the set of intent filters 12282 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12283 while (intentIter.hasNext()) { 12284 final ActivityIntentInfo intentInfo = intentIter.next(); 12285 boolean selectionFound = false; 12286 12287 // loop through the intent filter's selection criteria; at least one 12288 // of them must match the searched criteria 12289 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12290 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12291 final T intentSelection = intentSelectionIter.next(); 12292 if (intentSelection != null && intentSelection.equals(searchAction)) { 12293 selectionFound = true; 12294 break; 12295 } 12296 } 12297 12298 // the selection criteria wasn't found in this filter's set; this filter 12299 // is not a potential match 12300 if (!selectionFound) { 12301 intentIter.remove(); 12302 } 12303 } 12304 } 12305 } 12306 12307 private boolean isProtectedAction(ActivityIntentInfo filter) { 12308 final Iterator<String> actionsIter = filter.actionsIterator(); 12309 while (actionsIter != null && actionsIter.hasNext()) { 12310 final String filterAction = actionsIter.next(); 12311 if (PROTECTED_ACTIONS.contains(filterAction)) { 12312 return true; 12313 } 12314 } 12315 return false; 12316 } 12317 12318 /** 12319 * Adjusts the priority of the given intent filter according to policy. 12320 * <p> 12321 * <ul> 12322 * <li>The priority for non privileged applications is capped to '0'</li> 12323 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12324 * <li>The priority for unbundled updates to privileged applications is capped to the 12325 * priority defined on the system partition</li> 12326 * </ul> 12327 * <p> 12328 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12329 * allowed to obtain any priority on any action. 12330 */ 12331 private void adjustPriority( 12332 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12333 // nothing to do; priority is fine as-is 12334 if (intent.getPriority() <= 0) { 12335 return; 12336 } 12337 12338 final ActivityInfo activityInfo = intent.activity.info; 12339 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12340 12341 final boolean privilegedApp = 12342 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12343 if (!privilegedApp) { 12344 // non-privileged applications can never define a priority >0 12345 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12346 + " package: " + applicationInfo.packageName 12347 + " activity: " + intent.activity.className 12348 + " origPrio: " + intent.getPriority()); 12349 intent.setPriority(0); 12350 return; 12351 } 12352 12353 if (systemActivities == null) { 12354 // the system package is not disabled; we're parsing the system partition 12355 if (isProtectedAction(intent)) { 12356 if (mDeferProtectedFilters) { 12357 // We can't deal with these just yet. No component should ever obtain a 12358 // >0 priority for a protected actions, with ONE exception -- the setup 12359 // wizard. The setup wizard, however, cannot be known until we're able to 12360 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12361 // until all intent filters have been processed. Chicken, meet egg. 12362 // Let the filter temporarily have a high priority and rectify the 12363 // priorities after all system packages have been scanned. 12364 mProtectedFilters.add(intent); 12365 if (DEBUG_FILTERS) { 12366 Slog.i(TAG, "Protected action; save for later;" 12367 + " package: " + applicationInfo.packageName 12368 + " activity: " + intent.activity.className 12369 + " origPrio: " + intent.getPriority()); 12370 } 12371 return; 12372 } else { 12373 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12374 Slog.i(TAG, "No setup wizard;" 12375 + " All protected intents capped to priority 0"); 12376 } 12377 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12378 if (DEBUG_FILTERS) { 12379 Slog.i(TAG, "Found setup wizard;" 12380 + " allow priority " + intent.getPriority() + ";" 12381 + " package: " + intent.activity.info.packageName 12382 + " activity: " + intent.activity.className 12383 + " priority: " + intent.getPriority()); 12384 } 12385 // setup wizard gets whatever it wants 12386 return; 12387 } 12388 Slog.w(TAG, "Protected action; cap priority to 0;" 12389 + " package: " + intent.activity.info.packageName 12390 + " activity: " + intent.activity.className 12391 + " origPrio: " + intent.getPriority()); 12392 intent.setPriority(0); 12393 return; 12394 } 12395 } 12396 // privileged apps on the system image get whatever priority they request 12397 return; 12398 } 12399 12400 // privileged app unbundled update ... try to find the same activity 12401 final PackageParser.Activity foundActivity = 12402 findMatchingActivity(systemActivities, activityInfo); 12403 if (foundActivity == null) { 12404 // this is a new activity; it cannot obtain >0 priority 12405 if (DEBUG_FILTERS) { 12406 Slog.i(TAG, "New activity; cap priority to 0;" 12407 + " package: " + applicationInfo.packageName 12408 + " activity: " + intent.activity.className 12409 + " origPrio: " + intent.getPriority()); 12410 } 12411 intent.setPriority(0); 12412 return; 12413 } 12414 12415 // found activity, now check for filter equivalence 12416 12417 // a shallow copy is enough; we modify the list, not its contents 12418 final List<ActivityIntentInfo> intentListCopy = 12419 new ArrayList<>(foundActivity.intents); 12420 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12421 12422 // find matching action subsets 12423 final Iterator<String> actionsIterator = intent.actionsIterator(); 12424 if (actionsIterator != null) { 12425 getIntentListSubset( 12426 intentListCopy, new ActionIterGenerator(), actionsIterator); 12427 if (intentListCopy.size() == 0) { 12428 // no more intents to match; we're not equivalent 12429 if (DEBUG_FILTERS) { 12430 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12431 + " package: " + applicationInfo.packageName 12432 + " activity: " + intent.activity.className 12433 + " origPrio: " + intent.getPriority()); 12434 } 12435 intent.setPriority(0); 12436 return; 12437 } 12438 } 12439 12440 // find matching category subsets 12441 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12442 if (categoriesIterator != null) { 12443 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12444 categoriesIterator); 12445 if (intentListCopy.size() == 0) { 12446 // no more intents to match; we're not equivalent 12447 if (DEBUG_FILTERS) { 12448 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12449 + " package: " + applicationInfo.packageName 12450 + " activity: " + intent.activity.className 12451 + " origPrio: " + intent.getPriority()); 12452 } 12453 intent.setPriority(0); 12454 return; 12455 } 12456 } 12457 12458 // find matching schemes subsets 12459 final Iterator<String> schemesIterator = intent.schemesIterator(); 12460 if (schemesIterator != null) { 12461 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12462 schemesIterator); 12463 if (intentListCopy.size() == 0) { 12464 // no more intents to match; we're not equivalent 12465 if (DEBUG_FILTERS) { 12466 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12467 + " package: " + applicationInfo.packageName 12468 + " activity: " + intent.activity.className 12469 + " origPrio: " + intent.getPriority()); 12470 } 12471 intent.setPriority(0); 12472 return; 12473 } 12474 } 12475 12476 // find matching authorities subsets 12477 final Iterator<IntentFilter.AuthorityEntry> 12478 authoritiesIterator = intent.authoritiesIterator(); 12479 if (authoritiesIterator != null) { 12480 getIntentListSubset(intentListCopy, 12481 new AuthoritiesIterGenerator(), 12482 authoritiesIterator); 12483 if (intentListCopy.size() == 0) { 12484 // no more intents to match; we're not equivalent 12485 if (DEBUG_FILTERS) { 12486 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12487 + " package: " + applicationInfo.packageName 12488 + " activity: " + intent.activity.className 12489 + " origPrio: " + intent.getPriority()); 12490 } 12491 intent.setPriority(0); 12492 return; 12493 } 12494 } 12495 12496 // we found matching filter(s); app gets the max priority of all intents 12497 int cappedPriority = 0; 12498 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12499 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12500 } 12501 if (intent.getPriority() > cappedPriority) { 12502 if (DEBUG_FILTERS) { 12503 Slog.i(TAG, "Found matching filter(s);" 12504 + " cap priority to " + cappedPriority + ";" 12505 + " package: " + applicationInfo.packageName 12506 + " activity: " + intent.activity.className 12507 + " origPrio: " + intent.getPriority()); 12508 } 12509 intent.setPriority(cappedPriority); 12510 return; 12511 } 12512 // all this for nothing; the requested priority was <= what was on the system 12513 } 12514 12515 public final void addActivity(PackageParser.Activity a, String type) { 12516 mActivities.put(a.getComponentName(), a); 12517 if (DEBUG_SHOW_INFO) 12518 Log.v( 12519 TAG, " " + type + " " + 12520 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12521 if (DEBUG_SHOW_INFO) 12522 Log.v(TAG, " Class=" + a.info.name); 12523 final int NI = a.intents.size(); 12524 for (int j=0; j<NI; j++) { 12525 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12526 if ("activity".equals(type)) { 12527 final PackageSetting ps = 12528 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12529 final List<PackageParser.Activity> systemActivities = 12530 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12531 adjustPriority(systemActivities, intent); 12532 } 12533 if (DEBUG_SHOW_INFO) { 12534 Log.v(TAG, " IntentFilter:"); 12535 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12536 } 12537 if (!intent.debugCheck()) { 12538 Log.w(TAG, "==> For Activity " + a.info.name); 12539 } 12540 addFilter(intent); 12541 } 12542 } 12543 12544 public final void removeActivity(PackageParser.Activity a, String type) { 12545 mActivities.remove(a.getComponentName()); 12546 if (DEBUG_SHOW_INFO) { 12547 Log.v(TAG, " " + type + " " 12548 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12549 : a.info.name) + ":"); 12550 Log.v(TAG, " Class=" + a.info.name); 12551 } 12552 final int NI = a.intents.size(); 12553 for (int j=0; j<NI; j++) { 12554 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12555 if (DEBUG_SHOW_INFO) { 12556 Log.v(TAG, " IntentFilter:"); 12557 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12558 } 12559 removeFilter(intent); 12560 } 12561 } 12562 12563 @Override 12564 protected boolean allowFilterResult( 12565 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12566 ActivityInfo filterAi = filter.activity.info; 12567 for (int i=dest.size()-1; i>=0; i--) { 12568 ActivityInfo destAi = dest.get(i).activityInfo; 12569 if (destAi.name == filterAi.name 12570 && destAi.packageName == filterAi.packageName) { 12571 return false; 12572 } 12573 } 12574 return true; 12575 } 12576 12577 @Override 12578 protected ActivityIntentInfo[] newArray(int size) { 12579 return new ActivityIntentInfo[size]; 12580 } 12581 12582 @Override 12583 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12584 if (!sUserManager.exists(userId)) return true; 12585 PackageParser.Package p = filter.activity.owner; 12586 if (p != null) { 12587 PackageSetting ps = (PackageSetting)p.mExtras; 12588 if (ps != null) { 12589 // System apps are never considered stopped for purposes of 12590 // filtering, because there may be no way for the user to 12591 // actually re-launch them. 12592 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12593 && ps.getStopped(userId); 12594 } 12595 } 12596 return false; 12597 } 12598 12599 @Override 12600 protected boolean isPackageForFilter(String packageName, 12601 PackageParser.ActivityIntentInfo info) { 12602 return packageName.equals(info.activity.owner.packageName); 12603 } 12604 12605 @Override 12606 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12607 int match, int userId) { 12608 if (!sUserManager.exists(userId)) return null; 12609 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12610 return null; 12611 } 12612 final PackageParser.Activity activity = info.activity; 12613 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12614 if (ps == null) { 12615 return null; 12616 } 12617 final PackageUserState userState = ps.readUserState(userId); 12618 ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId); 12619 if (ai == null) { 12620 return null; 12621 } 12622 final boolean matchExplicitlyVisibleOnly = 12623 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12624 final boolean matchVisibleToInstantApp = 12625 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12626 final boolean componentVisible = 12627 matchVisibleToInstantApp 12628 && info.isVisibleToInstantApp() 12629 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12630 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12631 // throw out filters that aren't visible to ephemeral apps 12632 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12633 return null; 12634 } 12635 // throw out instant app filters if we're not explicitly requesting them 12636 if (!matchInstantApp && userState.instantApp) { 12637 return null; 12638 } 12639 // throw out instant app filters if updates are available; will trigger 12640 // instant app resolution 12641 if (userState.instantApp && ps.isUpdateAvailable()) { 12642 return null; 12643 } 12644 final ResolveInfo res = new ResolveInfo(); 12645 res.activityInfo = ai; 12646 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12647 res.filter = info; 12648 } 12649 if (info != null) { 12650 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12651 } 12652 res.priority = info.getPriority(); 12653 res.preferredOrder = activity.owner.mPreferredOrder; 12654 //System.out.println("Result: " + res.activityInfo.className + 12655 // " = " + res.priority); 12656 res.match = match; 12657 res.isDefault = info.hasDefault; 12658 res.labelRes = info.labelRes; 12659 res.nonLocalizedLabel = info.nonLocalizedLabel; 12660 if (userNeedsBadging(userId)) { 12661 res.noResourceId = true; 12662 } else { 12663 res.icon = info.icon; 12664 } 12665 res.iconResourceId = info.icon; 12666 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12667 res.isInstantAppAvailable = userState.instantApp; 12668 return res; 12669 } 12670 12671 @Override 12672 protected void sortResults(List<ResolveInfo> results) { 12673 Collections.sort(results, mResolvePrioritySorter); 12674 } 12675 12676 @Override 12677 protected void dumpFilter(PrintWriter out, String prefix, 12678 PackageParser.ActivityIntentInfo filter) { 12679 out.print(prefix); out.print( 12680 Integer.toHexString(System.identityHashCode(filter.activity))); 12681 out.print(' '); 12682 filter.activity.printComponentShortName(out); 12683 out.print(" filter "); 12684 out.println(Integer.toHexString(System.identityHashCode(filter))); 12685 } 12686 12687 @Override 12688 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12689 return filter.activity; 12690 } 12691 12692 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12693 PackageParser.Activity activity = (PackageParser.Activity)label; 12694 out.print(prefix); out.print( 12695 Integer.toHexString(System.identityHashCode(activity))); 12696 out.print(' '); 12697 activity.printComponentShortName(out); 12698 if (count > 1) { 12699 out.print(" ("); out.print(count); out.print(" filters)"); 12700 } 12701 out.println(); 12702 } 12703 12704 // Keys are String (activity class name), values are Activity. 12705 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12706 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12707 private int mFlags; 12708 } 12709 12710 private final class ServiceIntentResolver 12711 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12712 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12713 boolean defaultOnly, int userId) { 12714 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12715 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12716 } 12717 12718 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12719 int userId) { 12720 if (!sUserManager.exists(userId)) return null; 12721 mFlags = flags; 12722 return super.queryIntent(intent, resolvedType, 12723 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12724 userId); 12725 } 12726 12727 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12728 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12729 if (!sUserManager.exists(userId)) return null; 12730 if (packageServices == null) { 12731 return null; 12732 } 12733 mFlags = flags; 12734 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12735 final int N = packageServices.size(); 12736 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12737 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12738 12739 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12740 for (int i = 0; i < N; ++i) { 12741 intentFilters = packageServices.get(i).intents; 12742 if (intentFilters != null && intentFilters.size() > 0) { 12743 PackageParser.ServiceIntentInfo[] array = 12744 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12745 intentFilters.toArray(array); 12746 listCut.add(array); 12747 } 12748 } 12749 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12750 } 12751 12752 public final void addService(PackageParser.Service s) { 12753 mServices.put(s.getComponentName(), s); 12754 if (DEBUG_SHOW_INFO) { 12755 Log.v(TAG, " " 12756 + (s.info.nonLocalizedLabel != null 12757 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12758 Log.v(TAG, " Class=" + s.info.name); 12759 } 12760 final int NI = s.intents.size(); 12761 int j; 12762 for (j=0; j<NI; j++) { 12763 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12764 if (DEBUG_SHOW_INFO) { 12765 Log.v(TAG, " IntentFilter:"); 12766 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12767 } 12768 if (!intent.debugCheck()) { 12769 Log.w(TAG, "==> For Service " + s.info.name); 12770 } 12771 addFilter(intent); 12772 } 12773 } 12774 12775 public final void removeService(PackageParser.Service s) { 12776 mServices.remove(s.getComponentName()); 12777 if (DEBUG_SHOW_INFO) { 12778 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12779 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12780 Log.v(TAG, " Class=" + s.info.name); 12781 } 12782 final int NI = s.intents.size(); 12783 int j; 12784 for (j=0; j<NI; j++) { 12785 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12786 if (DEBUG_SHOW_INFO) { 12787 Log.v(TAG, " IntentFilter:"); 12788 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12789 } 12790 removeFilter(intent); 12791 } 12792 } 12793 12794 @Override 12795 protected boolean allowFilterResult( 12796 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12797 ServiceInfo filterSi = filter.service.info; 12798 for (int i=dest.size()-1; i>=0; i--) { 12799 ServiceInfo destAi = dest.get(i).serviceInfo; 12800 if (destAi.name == filterSi.name 12801 && destAi.packageName == filterSi.packageName) { 12802 return false; 12803 } 12804 } 12805 return true; 12806 } 12807 12808 @Override 12809 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12810 return new PackageParser.ServiceIntentInfo[size]; 12811 } 12812 12813 @Override 12814 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12815 if (!sUserManager.exists(userId)) return true; 12816 PackageParser.Package p = filter.service.owner; 12817 if (p != null) { 12818 PackageSetting ps = (PackageSetting)p.mExtras; 12819 if (ps != null) { 12820 // System apps are never considered stopped for purposes of 12821 // filtering, because there may be no way for the user to 12822 // actually re-launch them. 12823 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12824 && ps.getStopped(userId); 12825 } 12826 } 12827 return false; 12828 } 12829 12830 @Override 12831 protected boolean isPackageForFilter(String packageName, 12832 PackageParser.ServiceIntentInfo info) { 12833 return packageName.equals(info.service.owner.packageName); 12834 } 12835 12836 @Override 12837 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12838 int match, int userId) { 12839 if (!sUserManager.exists(userId)) return null; 12840 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12841 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12842 return null; 12843 } 12844 final PackageParser.Service service = info.service; 12845 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12846 if (ps == null) { 12847 return null; 12848 } 12849 final PackageUserState userState = ps.readUserState(userId); 12850 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12851 userState, userId); 12852 if (si == null) { 12853 return null; 12854 } 12855 final boolean matchVisibleToInstantApp = 12856 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12857 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12858 // throw out filters that aren't visible to ephemeral apps 12859 if (matchVisibleToInstantApp 12860 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12861 return null; 12862 } 12863 // throw out ephemeral filters if we're not explicitly requesting them 12864 if (!isInstantApp && userState.instantApp) { 12865 return null; 12866 } 12867 // throw out instant app filters if updates are available; will trigger 12868 // instant app resolution 12869 if (userState.instantApp && ps.isUpdateAvailable()) { 12870 return null; 12871 } 12872 final ResolveInfo res = new ResolveInfo(); 12873 res.serviceInfo = si; 12874 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12875 res.filter = filter; 12876 } 12877 res.priority = info.getPriority(); 12878 res.preferredOrder = service.owner.mPreferredOrder; 12879 res.match = match; 12880 res.isDefault = info.hasDefault; 12881 res.labelRes = info.labelRes; 12882 res.nonLocalizedLabel = info.nonLocalizedLabel; 12883 res.icon = info.icon; 12884 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12885 return res; 12886 } 12887 12888 @Override 12889 protected void sortResults(List<ResolveInfo> results) { 12890 Collections.sort(results, mResolvePrioritySorter); 12891 } 12892 12893 @Override 12894 protected void dumpFilter(PrintWriter out, String prefix, 12895 PackageParser.ServiceIntentInfo filter) { 12896 out.print(prefix); out.print( 12897 Integer.toHexString(System.identityHashCode(filter.service))); 12898 out.print(' '); 12899 filter.service.printComponentShortName(out); 12900 out.print(" filter "); 12901 out.println(Integer.toHexString(System.identityHashCode(filter))); 12902 } 12903 12904 @Override 12905 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12906 return filter.service; 12907 } 12908 12909 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12910 PackageParser.Service service = (PackageParser.Service)label; 12911 out.print(prefix); out.print( 12912 Integer.toHexString(System.identityHashCode(service))); 12913 out.print(' '); 12914 service.printComponentShortName(out); 12915 if (count > 1) { 12916 out.print(" ("); out.print(count); out.print(" filters)"); 12917 } 12918 out.println(); 12919 } 12920 12921// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12922// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12923// final List<ResolveInfo> retList = Lists.newArrayList(); 12924// while (i.hasNext()) { 12925// final ResolveInfo resolveInfo = (ResolveInfo) i; 12926// if (isEnabledLP(resolveInfo.serviceInfo)) { 12927// retList.add(resolveInfo); 12928// } 12929// } 12930// return retList; 12931// } 12932 12933 // Keys are String (activity class name), values are Activity. 12934 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12935 = new ArrayMap<ComponentName, PackageParser.Service>(); 12936 private int mFlags; 12937 } 12938 12939 private final class ProviderIntentResolver 12940 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12941 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12942 boolean defaultOnly, int userId) { 12943 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12944 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12945 } 12946 12947 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12948 int userId) { 12949 if (!sUserManager.exists(userId)) 12950 return null; 12951 mFlags = flags; 12952 return super.queryIntent(intent, resolvedType, 12953 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12954 userId); 12955 } 12956 12957 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12958 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12959 if (!sUserManager.exists(userId)) 12960 return null; 12961 if (packageProviders == null) { 12962 return null; 12963 } 12964 mFlags = flags; 12965 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12966 final int N = packageProviders.size(); 12967 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12968 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12969 12970 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12971 for (int i = 0; i < N; ++i) { 12972 intentFilters = packageProviders.get(i).intents; 12973 if (intentFilters != null && intentFilters.size() > 0) { 12974 PackageParser.ProviderIntentInfo[] array = 12975 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12976 intentFilters.toArray(array); 12977 listCut.add(array); 12978 } 12979 } 12980 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12981 } 12982 12983 public final void addProvider(PackageParser.Provider p) { 12984 if (mProviders.containsKey(p.getComponentName())) { 12985 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12986 return; 12987 } 12988 12989 mProviders.put(p.getComponentName(), p); 12990 if (DEBUG_SHOW_INFO) { 12991 Log.v(TAG, " " 12992 + (p.info.nonLocalizedLabel != null 12993 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12994 Log.v(TAG, " Class=" + p.info.name); 12995 } 12996 final int NI = p.intents.size(); 12997 int j; 12998 for (j = 0; j < NI; j++) { 12999 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13000 if (DEBUG_SHOW_INFO) { 13001 Log.v(TAG, " IntentFilter:"); 13002 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13003 } 13004 if (!intent.debugCheck()) { 13005 Log.w(TAG, "==> For Provider " + p.info.name); 13006 } 13007 addFilter(intent); 13008 } 13009 } 13010 13011 public final void removeProvider(PackageParser.Provider p) { 13012 mProviders.remove(p.getComponentName()); 13013 if (DEBUG_SHOW_INFO) { 13014 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13015 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13016 Log.v(TAG, " Class=" + p.info.name); 13017 } 13018 final int NI = p.intents.size(); 13019 int j; 13020 for (j = 0; j < NI; j++) { 13021 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13022 if (DEBUG_SHOW_INFO) { 13023 Log.v(TAG, " IntentFilter:"); 13024 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13025 } 13026 removeFilter(intent); 13027 } 13028 } 13029 13030 @Override 13031 protected boolean allowFilterResult( 13032 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13033 ProviderInfo filterPi = filter.provider.info; 13034 for (int i = dest.size() - 1; i >= 0; i--) { 13035 ProviderInfo destPi = dest.get(i).providerInfo; 13036 if (destPi.name == filterPi.name 13037 && destPi.packageName == filterPi.packageName) { 13038 return false; 13039 } 13040 } 13041 return true; 13042 } 13043 13044 @Override 13045 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13046 return new PackageParser.ProviderIntentInfo[size]; 13047 } 13048 13049 @Override 13050 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13051 if (!sUserManager.exists(userId)) 13052 return true; 13053 PackageParser.Package p = filter.provider.owner; 13054 if (p != null) { 13055 PackageSetting ps = (PackageSetting) p.mExtras; 13056 if (ps != null) { 13057 // System apps are never considered stopped for purposes of 13058 // filtering, because there may be no way for the user to 13059 // actually re-launch them. 13060 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13061 && ps.getStopped(userId); 13062 } 13063 } 13064 return false; 13065 } 13066 13067 @Override 13068 protected boolean isPackageForFilter(String packageName, 13069 PackageParser.ProviderIntentInfo info) { 13070 return packageName.equals(info.provider.owner.packageName); 13071 } 13072 13073 @Override 13074 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13075 int match, int userId) { 13076 if (!sUserManager.exists(userId)) 13077 return null; 13078 final PackageParser.ProviderIntentInfo info = filter; 13079 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13080 return null; 13081 } 13082 final PackageParser.Provider provider = info.provider; 13083 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13084 if (ps == null) { 13085 return null; 13086 } 13087 final PackageUserState userState = ps.readUserState(userId); 13088 final boolean matchVisibleToInstantApp = 13089 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13090 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13091 // throw out filters that aren't visible to instant applications 13092 if (matchVisibleToInstantApp 13093 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13094 return null; 13095 } 13096 // throw out instant application filters if we're not explicitly requesting them 13097 if (!isInstantApp && userState.instantApp) { 13098 return null; 13099 } 13100 // throw out instant application filters if updates are available; will trigger 13101 // instant application resolution 13102 if (userState.instantApp && ps.isUpdateAvailable()) { 13103 return null; 13104 } 13105 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13106 userState, userId); 13107 if (pi == null) { 13108 return null; 13109 } 13110 final ResolveInfo res = new ResolveInfo(); 13111 res.providerInfo = pi; 13112 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13113 res.filter = filter; 13114 } 13115 res.priority = info.getPriority(); 13116 res.preferredOrder = provider.owner.mPreferredOrder; 13117 res.match = match; 13118 res.isDefault = info.hasDefault; 13119 res.labelRes = info.labelRes; 13120 res.nonLocalizedLabel = info.nonLocalizedLabel; 13121 res.icon = info.icon; 13122 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13123 return res; 13124 } 13125 13126 @Override 13127 protected void sortResults(List<ResolveInfo> results) { 13128 Collections.sort(results, mResolvePrioritySorter); 13129 } 13130 13131 @Override 13132 protected void dumpFilter(PrintWriter out, String prefix, 13133 PackageParser.ProviderIntentInfo filter) { 13134 out.print(prefix); 13135 out.print( 13136 Integer.toHexString(System.identityHashCode(filter.provider))); 13137 out.print(' '); 13138 filter.provider.printComponentShortName(out); 13139 out.print(" filter "); 13140 out.println(Integer.toHexString(System.identityHashCode(filter))); 13141 } 13142 13143 @Override 13144 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13145 return filter.provider; 13146 } 13147 13148 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13149 PackageParser.Provider provider = (PackageParser.Provider)label; 13150 out.print(prefix); out.print( 13151 Integer.toHexString(System.identityHashCode(provider))); 13152 out.print(' '); 13153 provider.printComponentShortName(out); 13154 if (count > 1) { 13155 out.print(" ("); out.print(count); out.print(" filters)"); 13156 } 13157 out.println(); 13158 } 13159 13160 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13161 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13162 private int mFlags; 13163 } 13164 13165 static final class EphemeralIntentResolver 13166 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13167 /** 13168 * The result that has the highest defined order. Ordering applies on a 13169 * per-package basis. Mapping is from package name to Pair of order and 13170 * EphemeralResolveInfo. 13171 * <p> 13172 * NOTE: This is implemented as a field variable for convenience and efficiency. 13173 * By having a field variable, we're able to track filter ordering as soon as 13174 * a non-zero order is defined. Otherwise, multiple loops across the result set 13175 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13176 * this needs to be contained entirely within {@link #filterResults}. 13177 */ 13178 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13179 13180 @Override 13181 protected AuxiliaryResolveInfo[] newArray(int size) { 13182 return new AuxiliaryResolveInfo[size]; 13183 } 13184 13185 @Override 13186 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13187 return true; 13188 } 13189 13190 @Override 13191 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13192 int userId) { 13193 if (!sUserManager.exists(userId)) { 13194 return null; 13195 } 13196 final String packageName = responseObj.resolveInfo.getPackageName(); 13197 final Integer order = responseObj.getOrder(); 13198 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13199 mOrderResult.get(packageName); 13200 // ordering is enabled and this item's order isn't high enough 13201 if (lastOrderResult != null && lastOrderResult.first >= order) { 13202 return null; 13203 } 13204 final InstantAppResolveInfo res = responseObj.resolveInfo; 13205 if (order > 0) { 13206 // non-zero order, enable ordering 13207 mOrderResult.put(packageName, new Pair<>(order, res)); 13208 } 13209 return responseObj; 13210 } 13211 13212 @Override 13213 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13214 // only do work if ordering is enabled [most of the time it won't be] 13215 if (mOrderResult.size() == 0) { 13216 return; 13217 } 13218 int resultSize = results.size(); 13219 for (int i = 0; i < resultSize; i++) { 13220 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13221 final String packageName = info.getPackageName(); 13222 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13223 if (savedInfo == null) { 13224 // package doesn't having ordering 13225 continue; 13226 } 13227 if (savedInfo.second == info) { 13228 // circled back to the highest ordered item; remove from order list 13229 mOrderResult.remove(savedInfo); 13230 if (mOrderResult.size() == 0) { 13231 // no more ordered items 13232 break; 13233 } 13234 continue; 13235 } 13236 // item has a worse order, remove it from the result list 13237 results.remove(i); 13238 resultSize--; 13239 i--; 13240 } 13241 } 13242 } 13243 13244 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13245 new Comparator<ResolveInfo>() { 13246 public int compare(ResolveInfo r1, ResolveInfo r2) { 13247 int v1 = r1.priority; 13248 int v2 = r2.priority; 13249 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13250 if (v1 != v2) { 13251 return (v1 > v2) ? -1 : 1; 13252 } 13253 v1 = r1.preferredOrder; 13254 v2 = r2.preferredOrder; 13255 if (v1 != v2) { 13256 return (v1 > v2) ? -1 : 1; 13257 } 13258 if (r1.isDefault != r2.isDefault) { 13259 return r1.isDefault ? -1 : 1; 13260 } 13261 v1 = r1.match; 13262 v2 = r2.match; 13263 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13264 if (v1 != v2) { 13265 return (v1 > v2) ? -1 : 1; 13266 } 13267 if (r1.system != r2.system) { 13268 return r1.system ? -1 : 1; 13269 } 13270 if (r1.activityInfo != null) { 13271 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13272 } 13273 if (r1.serviceInfo != null) { 13274 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13275 } 13276 if (r1.providerInfo != null) { 13277 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13278 } 13279 return 0; 13280 } 13281 }; 13282 13283 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13284 new Comparator<ProviderInfo>() { 13285 public int compare(ProviderInfo p1, ProviderInfo p2) { 13286 final int v1 = p1.initOrder; 13287 final int v2 = p2.initOrder; 13288 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13289 } 13290 }; 13291 13292 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13293 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13294 final int[] userIds) { 13295 mHandler.post(new Runnable() { 13296 @Override 13297 public void run() { 13298 try { 13299 final IActivityManager am = ActivityManager.getService(); 13300 if (am == null) return; 13301 final int[] resolvedUserIds; 13302 if (userIds == null) { 13303 resolvedUserIds = am.getRunningUserIds(); 13304 } else { 13305 resolvedUserIds = userIds; 13306 } 13307 for (int id : resolvedUserIds) { 13308 final Intent intent = new Intent(action, 13309 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13310 if (extras != null) { 13311 intent.putExtras(extras); 13312 } 13313 if (targetPkg != null) { 13314 intent.setPackage(targetPkg); 13315 } 13316 // Modify the UID when posting to other users 13317 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13318 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13319 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13320 intent.putExtra(Intent.EXTRA_UID, uid); 13321 } 13322 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13323 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13324 if (DEBUG_BROADCASTS) { 13325 RuntimeException here = new RuntimeException("here"); 13326 here.fillInStackTrace(); 13327 Slog.d(TAG, "Sending to user " + id + ": " 13328 + intent.toShortString(false, true, false, false) 13329 + " " + intent.getExtras(), here); 13330 } 13331 am.broadcastIntent(null, intent, null, finishedReceiver, 13332 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13333 null, finishedReceiver != null, false, id); 13334 } 13335 } catch (RemoteException ex) { 13336 } 13337 } 13338 }); 13339 } 13340 13341 /** 13342 * Check if the external storage media is available. This is true if there 13343 * is a mounted external storage medium or if the external storage is 13344 * emulated. 13345 */ 13346 private boolean isExternalMediaAvailable() { 13347 return mMediaMounted || Environment.isExternalStorageEmulated(); 13348 } 13349 13350 @Override 13351 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13352 // writer 13353 synchronized (mPackages) { 13354 if (!isExternalMediaAvailable()) { 13355 // If the external storage is no longer mounted at this point, 13356 // the caller may not have been able to delete all of this 13357 // packages files and can not delete any more. Bail. 13358 return null; 13359 } 13360 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13361 if (lastPackage != null) { 13362 pkgs.remove(lastPackage); 13363 } 13364 if (pkgs.size() > 0) { 13365 return pkgs.get(0); 13366 } 13367 } 13368 return null; 13369 } 13370 13371 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13372 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13373 userId, andCode ? 1 : 0, packageName); 13374 if (mSystemReady) { 13375 msg.sendToTarget(); 13376 } else { 13377 if (mPostSystemReadyMessages == null) { 13378 mPostSystemReadyMessages = new ArrayList<>(); 13379 } 13380 mPostSystemReadyMessages.add(msg); 13381 } 13382 } 13383 13384 void startCleaningPackages() { 13385 // reader 13386 if (!isExternalMediaAvailable()) { 13387 return; 13388 } 13389 synchronized (mPackages) { 13390 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13391 return; 13392 } 13393 } 13394 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13395 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13396 IActivityManager am = ActivityManager.getService(); 13397 if (am != null) { 13398 int dcsUid = -1; 13399 synchronized (mPackages) { 13400 if (!mDefaultContainerWhitelisted) { 13401 mDefaultContainerWhitelisted = true; 13402 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13403 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13404 } 13405 } 13406 try { 13407 if (dcsUid > 0) { 13408 am.backgroundWhitelistUid(dcsUid); 13409 } 13410 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13411 UserHandle.USER_SYSTEM); 13412 } catch (RemoteException e) { 13413 } 13414 } 13415 } 13416 13417 @Override 13418 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13419 int installFlags, String installerPackageName, int userId) { 13420 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13421 13422 final int callingUid = Binder.getCallingUid(); 13423 enforceCrossUserPermission(callingUid, userId, 13424 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13425 13426 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13427 try { 13428 if (observer != null) { 13429 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13430 } 13431 } catch (RemoteException re) { 13432 } 13433 return; 13434 } 13435 13436 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13437 installFlags |= PackageManager.INSTALL_FROM_ADB; 13438 13439 } else { 13440 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13441 // about installerPackageName. 13442 13443 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13444 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13445 } 13446 13447 UserHandle user; 13448 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13449 user = UserHandle.ALL; 13450 } else { 13451 user = new UserHandle(userId); 13452 } 13453 13454 // Only system components can circumvent runtime permissions when installing. 13455 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13456 && mContext.checkCallingOrSelfPermission(Manifest.permission 13457 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13458 throw new SecurityException("You need the " 13459 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13460 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13461 } 13462 13463 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13464 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13465 throw new IllegalArgumentException( 13466 "New installs into ASEC containers no longer supported"); 13467 } 13468 13469 final File originFile = new File(originPath); 13470 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13471 13472 final Message msg = mHandler.obtainMessage(INIT_COPY); 13473 final VerificationInfo verificationInfo = new VerificationInfo( 13474 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13475 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13476 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13477 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13478 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13479 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13480 msg.obj = params; 13481 13482 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13483 System.identityHashCode(msg.obj)); 13484 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13485 System.identityHashCode(msg.obj)); 13486 13487 mHandler.sendMessage(msg); 13488 } 13489 13490 13491 /** 13492 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13493 * it is acting on behalf on an enterprise or the user). 13494 * 13495 * Note that the ordering of the conditionals in this method is important. The checks we perform 13496 * are as follows, in this order: 13497 * 13498 * 1) If the install is being performed by a system app, we can trust the app to have set the 13499 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13500 * what it is. 13501 * 2) If the install is being performed by a device or profile owner app, the install reason 13502 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13503 * set the install reason correctly. If the app targets an older SDK version where install 13504 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13505 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13506 * 3) In all other cases, the install is being performed by a regular app that is neither part 13507 * of the system nor a device or profile owner. We have no reason to believe that this app is 13508 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13509 * set to enterprise policy and if so, change it to unknown instead. 13510 */ 13511 private int fixUpInstallReason(String installerPackageName, int installerUid, 13512 int installReason) { 13513 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13514 == PERMISSION_GRANTED) { 13515 // If the install is being performed by a system app, we trust that app to have set the 13516 // install reason correctly. 13517 return installReason; 13518 } 13519 13520 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13521 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13522 if (dpm != null) { 13523 ComponentName owner = null; 13524 try { 13525 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13526 if (owner == null) { 13527 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13528 } 13529 } catch (RemoteException e) { 13530 } 13531 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13532 // If the install is being performed by a device or profile owner, the install 13533 // reason should be enterprise policy. 13534 return PackageManager.INSTALL_REASON_POLICY; 13535 } 13536 } 13537 13538 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13539 // If the install is being performed by a regular app (i.e. neither system app nor 13540 // device or profile owner), we have no reason to believe that the app is acting on 13541 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13542 // change it to unknown instead. 13543 return PackageManager.INSTALL_REASON_UNKNOWN; 13544 } 13545 13546 // If the install is being performed by a regular app and the install reason was set to any 13547 // value but enterprise policy, leave the install reason unchanged. 13548 return installReason; 13549 } 13550 13551 void installStage(String packageName, File stagedDir, String stagedCid, 13552 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13553 String installerPackageName, int installerUid, UserHandle user, 13554 Certificate[][] certificates) { 13555 if (DEBUG_EPHEMERAL) { 13556 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13557 Slog.d(TAG, "Ephemeral install of " + packageName); 13558 } 13559 } 13560 final VerificationInfo verificationInfo = new VerificationInfo( 13561 sessionParams.originatingUri, sessionParams.referrerUri, 13562 sessionParams.originatingUid, installerUid); 13563 13564 final OriginInfo origin; 13565 if (stagedDir != null) { 13566 origin = OriginInfo.fromStagedFile(stagedDir); 13567 } else { 13568 origin = OriginInfo.fromStagedContainer(stagedCid); 13569 } 13570 13571 final Message msg = mHandler.obtainMessage(INIT_COPY); 13572 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13573 sessionParams.installReason); 13574 final InstallParams params = new InstallParams(origin, null, observer, 13575 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13576 verificationInfo, user, sessionParams.abiOverride, 13577 sessionParams.grantedRuntimePermissions, certificates, installReason); 13578 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13579 msg.obj = params; 13580 13581 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13582 System.identityHashCode(msg.obj)); 13583 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13584 System.identityHashCode(msg.obj)); 13585 13586 mHandler.sendMessage(msg); 13587 } 13588 13589 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13590 int userId) { 13591 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13592 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13593 } 13594 13595 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) { 13596 if (ArrayUtils.isEmpty(userIds)) { 13597 return; 13598 } 13599 Bundle extras = new Bundle(1); 13600 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13601 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13602 13603 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13604 packageName, extras, 0, null, null, userIds); 13605 if (isSystem) { 13606 mHandler.post(() -> { 13607 for (int userId : userIds) { 13608 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13609 } 13610 } 13611 ); 13612 } 13613 } 13614 13615 /** 13616 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13617 * automatically without needing an explicit launch. 13618 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13619 */ 13620 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13621 // If user is not running, the app didn't miss any broadcast 13622 if (!mUserManagerInternal.isUserRunning(userId)) { 13623 return; 13624 } 13625 final IActivityManager am = ActivityManager.getService(); 13626 try { 13627 // Deliver LOCKED_BOOT_COMPLETED first 13628 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13629 .setPackage(packageName); 13630 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13631 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13632 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13633 13634 // Deliver BOOT_COMPLETED only if user is unlocked 13635 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13636 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13637 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13638 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13639 } 13640 } catch (RemoteException e) { 13641 throw e.rethrowFromSystemServer(); 13642 } 13643 } 13644 13645 @Override 13646 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13647 int userId) { 13648 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13649 PackageSetting pkgSetting; 13650 final int uid = Binder.getCallingUid(); 13651 enforceCrossUserPermission(uid, userId, 13652 true /* requireFullPermission */, true /* checkShell */, 13653 "setApplicationHiddenSetting for user " + userId); 13654 13655 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13656 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13657 return false; 13658 } 13659 13660 long callingId = Binder.clearCallingIdentity(); 13661 try { 13662 boolean sendAdded = false; 13663 boolean sendRemoved = false; 13664 // writer 13665 synchronized (mPackages) { 13666 pkgSetting = mSettings.mPackages.get(packageName); 13667 if (pkgSetting == null) { 13668 return false; 13669 } 13670 // Do not allow "android" is being disabled 13671 if ("android".equals(packageName)) { 13672 Slog.w(TAG, "Cannot hide package: android"); 13673 return false; 13674 } 13675 // Cannot hide static shared libs as they are considered 13676 // a part of the using app (emulating static linking). Also 13677 // static libs are installed always on internal storage. 13678 PackageParser.Package pkg = mPackages.get(packageName); 13679 if (pkg != null && pkg.staticSharedLibName != null) { 13680 Slog.w(TAG, "Cannot hide package: " + packageName 13681 + " providing static shared library: " 13682 + pkg.staticSharedLibName); 13683 return false; 13684 } 13685 // Only allow protected packages to hide themselves. 13686 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13687 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13688 Slog.w(TAG, "Not hiding protected package: " + packageName); 13689 return false; 13690 } 13691 13692 if (pkgSetting.getHidden(userId) != hidden) { 13693 pkgSetting.setHidden(hidden, userId); 13694 mSettings.writePackageRestrictionsLPr(userId); 13695 if (hidden) { 13696 sendRemoved = true; 13697 } else { 13698 sendAdded = true; 13699 } 13700 } 13701 } 13702 if (sendAdded) { 13703 sendPackageAddedForUser(packageName, pkgSetting, userId); 13704 return true; 13705 } 13706 if (sendRemoved) { 13707 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13708 "hiding pkg"); 13709 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13710 return true; 13711 } 13712 } finally { 13713 Binder.restoreCallingIdentity(callingId); 13714 } 13715 return false; 13716 } 13717 13718 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13719 int userId) { 13720 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13721 info.removedPackage = packageName; 13722 info.installerPackageName = pkgSetting.installerPackageName; 13723 info.removedUsers = new int[] {userId}; 13724 info.broadcastUsers = new int[] {userId}; 13725 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13726 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13727 } 13728 13729 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13730 if (pkgList.length > 0) { 13731 Bundle extras = new Bundle(1); 13732 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13733 13734 sendPackageBroadcast( 13735 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13736 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13737 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13738 new int[] {userId}); 13739 } 13740 } 13741 13742 /** 13743 * Returns true if application is not found or there was an error. Otherwise it returns 13744 * the hidden state of the package for the given user. 13745 */ 13746 @Override 13747 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13749 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13750 true /* requireFullPermission */, false /* checkShell */, 13751 "getApplicationHidden for user " + userId); 13752 PackageSetting pkgSetting; 13753 long callingId = Binder.clearCallingIdentity(); 13754 try { 13755 // writer 13756 synchronized (mPackages) { 13757 pkgSetting = mSettings.mPackages.get(packageName); 13758 if (pkgSetting == null) { 13759 return true; 13760 } 13761 return pkgSetting.getHidden(userId); 13762 } 13763 } finally { 13764 Binder.restoreCallingIdentity(callingId); 13765 } 13766 } 13767 13768 /** 13769 * @hide 13770 */ 13771 @Override 13772 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13773 int installReason) { 13774 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13775 null); 13776 PackageSetting pkgSetting; 13777 final int uid = Binder.getCallingUid(); 13778 enforceCrossUserPermission(uid, userId, 13779 true /* requireFullPermission */, true /* checkShell */, 13780 "installExistingPackage for user " + userId); 13781 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13782 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13783 } 13784 13785 long callingId = Binder.clearCallingIdentity(); 13786 try { 13787 boolean installed = false; 13788 final boolean instantApp = 13789 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13790 final boolean fullApp = 13791 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13792 13793 // writer 13794 synchronized (mPackages) { 13795 pkgSetting = mSettings.mPackages.get(packageName); 13796 if (pkgSetting == null) { 13797 return PackageManager.INSTALL_FAILED_INVALID_URI; 13798 } 13799 if (!pkgSetting.getInstalled(userId)) { 13800 pkgSetting.setInstalled(true, userId); 13801 pkgSetting.setHidden(false, userId); 13802 pkgSetting.setInstallReason(installReason, userId); 13803 mSettings.writePackageRestrictionsLPr(userId); 13804 mSettings.writeKernelMappingLPr(pkgSetting); 13805 installed = true; 13806 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13807 // upgrade app from instant to full; we don't allow app downgrade 13808 installed = true; 13809 } 13810 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13811 } 13812 13813 if (installed) { 13814 if (pkgSetting.pkg != null) { 13815 synchronized (mInstallLock) { 13816 // We don't need to freeze for a brand new install 13817 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13818 } 13819 } 13820 sendPackageAddedForUser(packageName, pkgSetting, userId); 13821 synchronized (mPackages) { 13822 updateSequenceNumberLP(packageName, new int[]{ userId }); 13823 } 13824 } 13825 } finally { 13826 Binder.restoreCallingIdentity(callingId); 13827 } 13828 13829 return PackageManager.INSTALL_SUCCEEDED; 13830 } 13831 13832 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13833 boolean instantApp, boolean fullApp) { 13834 // no state specified; do nothing 13835 if (!instantApp && !fullApp) { 13836 return; 13837 } 13838 if (userId != UserHandle.USER_ALL) { 13839 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13840 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13841 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13842 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13843 } 13844 } else { 13845 for (int currentUserId : sUserManager.getUserIds()) { 13846 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13847 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13848 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13849 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13850 } 13851 } 13852 } 13853 } 13854 13855 boolean isUserRestricted(int userId, String restrictionKey) { 13856 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13857 if (restrictions.getBoolean(restrictionKey, false)) { 13858 Log.w(TAG, "User is restricted: " + restrictionKey); 13859 return true; 13860 } 13861 return false; 13862 } 13863 13864 @Override 13865 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13866 int userId) { 13867 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13868 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13869 true /* requireFullPermission */, true /* checkShell */, 13870 "setPackagesSuspended for user " + userId); 13871 13872 if (ArrayUtils.isEmpty(packageNames)) { 13873 return packageNames; 13874 } 13875 13876 // List of package names for whom the suspended state has changed. 13877 List<String> changedPackages = new ArrayList<>(packageNames.length); 13878 // List of package names for whom the suspended state is not set as requested in this 13879 // method. 13880 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13881 long callingId = Binder.clearCallingIdentity(); 13882 try { 13883 for (int i = 0; i < packageNames.length; i++) { 13884 String packageName = packageNames[i]; 13885 boolean changed = false; 13886 final int appId; 13887 synchronized (mPackages) { 13888 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13889 if (pkgSetting == null) { 13890 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13891 + "\". Skipping suspending/un-suspending."); 13892 unactionedPackages.add(packageName); 13893 continue; 13894 } 13895 appId = pkgSetting.appId; 13896 if (pkgSetting.getSuspended(userId) != suspended) { 13897 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13898 unactionedPackages.add(packageName); 13899 continue; 13900 } 13901 pkgSetting.setSuspended(suspended, userId); 13902 mSettings.writePackageRestrictionsLPr(userId); 13903 changed = true; 13904 changedPackages.add(packageName); 13905 } 13906 } 13907 13908 if (changed && suspended) { 13909 killApplication(packageName, UserHandle.getUid(userId, appId), 13910 "suspending package"); 13911 } 13912 } 13913 } finally { 13914 Binder.restoreCallingIdentity(callingId); 13915 } 13916 13917 if (!changedPackages.isEmpty()) { 13918 sendPackagesSuspendedForUser(changedPackages.toArray( 13919 new String[changedPackages.size()]), userId, suspended); 13920 } 13921 13922 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13923 } 13924 13925 @Override 13926 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13927 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13928 true /* requireFullPermission */, false /* checkShell */, 13929 "isPackageSuspendedForUser for user " + userId); 13930 synchronized (mPackages) { 13931 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13932 if (pkgSetting == null) { 13933 throw new IllegalArgumentException("Unknown target package: " + packageName); 13934 } 13935 return pkgSetting.getSuspended(userId); 13936 } 13937 } 13938 13939 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13940 if (isPackageDeviceAdmin(packageName, userId)) { 13941 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13942 + "\": has an active device admin"); 13943 return false; 13944 } 13945 13946 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13947 if (packageName.equals(activeLauncherPackageName)) { 13948 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13949 + "\": contains the active launcher"); 13950 return false; 13951 } 13952 13953 if (packageName.equals(mRequiredInstallerPackage)) { 13954 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13955 + "\": required for package installation"); 13956 return false; 13957 } 13958 13959 if (packageName.equals(mRequiredUninstallerPackage)) { 13960 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13961 + "\": required for package uninstallation"); 13962 return false; 13963 } 13964 13965 if (packageName.equals(mRequiredVerifierPackage)) { 13966 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13967 + "\": required for package verification"); 13968 return false; 13969 } 13970 13971 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13972 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13973 + "\": is the default dialer"); 13974 return false; 13975 } 13976 13977 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13978 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13979 + "\": protected package"); 13980 return false; 13981 } 13982 13983 // Cannot suspend static shared libs as they are considered 13984 // a part of the using app (emulating static linking). Also 13985 // static libs are installed always on internal storage. 13986 PackageParser.Package pkg = mPackages.get(packageName); 13987 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13988 Slog.w(TAG, "Cannot suspend package: " + packageName 13989 + " providing static shared library: " 13990 + pkg.staticSharedLibName); 13991 return false; 13992 } 13993 13994 return true; 13995 } 13996 13997 private String getActiveLauncherPackageName(int userId) { 13998 Intent intent = new Intent(Intent.ACTION_MAIN); 13999 intent.addCategory(Intent.CATEGORY_HOME); 14000 ResolveInfo resolveInfo = resolveIntent( 14001 intent, 14002 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14003 PackageManager.MATCH_DEFAULT_ONLY, 14004 userId); 14005 14006 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14007 } 14008 14009 private String getDefaultDialerPackageName(int userId) { 14010 synchronized (mPackages) { 14011 return mSettings.getDefaultDialerPackageNameLPw(userId); 14012 } 14013 } 14014 14015 @Override 14016 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14017 mContext.enforceCallingOrSelfPermission( 14018 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14019 "Only package verification agents can verify applications"); 14020 14021 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14022 final PackageVerificationResponse response = new PackageVerificationResponse( 14023 verificationCode, Binder.getCallingUid()); 14024 msg.arg1 = id; 14025 msg.obj = response; 14026 mHandler.sendMessage(msg); 14027 } 14028 14029 @Override 14030 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14031 long millisecondsToDelay) { 14032 mContext.enforceCallingOrSelfPermission( 14033 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14034 "Only package verification agents can extend verification timeouts"); 14035 14036 final PackageVerificationState state = mPendingVerification.get(id); 14037 final PackageVerificationResponse response = new PackageVerificationResponse( 14038 verificationCodeAtTimeout, Binder.getCallingUid()); 14039 14040 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14041 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14042 } 14043 if (millisecondsToDelay < 0) { 14044 millisecondsToDelay = 0; 14045 } 14046 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14047 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14048 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14049 } 14050 14051 if ((state != null) && !state.timeoutExtended()) { 14052 state.extendTimeout(); 14053 14054 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14055 msg.arg1 = id; 14056 msg.obj = response; 14057 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14058 } 14059 } 14060 14061 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14062 int verificationCode, UserHandle user) { 14063 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14064 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14065 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14066 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14067 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14068 14069 mContext.sendBroadcastAsUser(intent, user, 14070 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14071 } 14072 14073 private ComponentName matchComponentForVerifier(String packageName, 14074 List<ResolveInfo> receivers) { 14075 ActivityInfo targetReceiver = null; 14076 14077 final int NR = receivers.size(); 14078 for (int i = 0; i < NR; i++) { 14079 final ResolveInfo info = receivers.get(i); 14080 if (info.activityInfo == null) { 14081 continue; 14082 } 14083 14084 if (packageName.equals(info.activityInfo.packageName)) { 14085 targetReceiver = info.activityInfo; 14086 break; 14087 } 14088 } 14089 14090 if (targetReceiver == null) { 14091 return null; 14092 } 14093 14094 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14095 } 14096 14097 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14098 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14099 if (pkgInfo.verifiers.length == 0) { 14100 return null; 14101 } 14102 14103 final int N = pkgInfo.verifiers.length; 14104 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14105 for (int i = 0; i < N; i++) { 14106 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14107 14108 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14109 receivers); 14110 if (comp == null) { 14111 continue; 14112 } 14113 14114 final int verifierUid = getUidForVerifier(verifierInfo); 14115 if (verifierUid == -1) { 14116 continue; 14117 } 14118 14119 if (DEBUG_VERIFY) { 14120 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14121 + " with the correct signature"); 14122 } 14123 sufficientVerifiers.add(comp); 14124 verificationState.addSufficientVerifier(verifierUid); 14125 } 14126 14127 return sufficientVerifiers; 14128 } 14129 14130 private int getUidForVerifier(VerifierInfo verifierInfo) { 14131 synchronized (mPackages) { 14132 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14133 if (pkg == null) { 14134 return -1; 14135 } else if (pkg.mSignatures.length != 1) { 14136 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14137 + " has more than one signature; ignoring"); 14138 return -1; 14139 } 14140 14141 /* 14142 * If the public key of the package's signature does not match 14143 * our expected public key, then this is a different package and 14144 * we should skip. 14145 */ 14146 14147 final byte[] expectedPublicKey; 14148 try { 14149 final Signature verifierSig = pkg.mSignatures[0]; 14150 final PublicKey publicKey = verifierSig.getPublicKey(); 14151 expectedPublicKey = publicKey.getEncoded(); 14152 } catch (CertificateException e) { 14153 return -1; 14154 } 14155 14156 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14157 14158 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14159 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14160 + " does not have the expected public key; ignoring"); 14161 return -1; 14162 } 14163 14164 return pkg.applicationInfo.uid; 14165 } 14166 } 14167 14168 @Override 14169 public void finishPackageInstall(int token, boolean didLaunch) { 14170 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14171 14172 if (DEBUG_INSTALL) { 14173 Slog.v(TAG, "BM finishing package install for " + token); 14174 } 14175 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14176 14177 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14178 mHandler.sendMessage(msg); 14179 } 14180 14181 /** 14182 * Get the verification agent timeout. Used for both the APK verifier and the 14183 * intent filter verifier. 14184 * 14185 * @return verification timeout in milliseconds 14186 */ 14187 private long getVerificationTimeout() { 14188 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14189 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14190 DEFAULT_VERIFICATION_TIMEOUT); 14191 } 14192 14193 /** 14194 * Get the default verification agent response code. 14195 * 14196 * @return default verification response code 14197 */ 14198 private int getDefaultVerificationResponse() { 14199 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14200 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14201 DEFAULT_VERIFICATION_RESPONSE); 14202 } 14203 14204 /** 14205 * Check whether or not package verification has been enabled. 14206 * 14207 * @return true if verification should be performed 14208 */ 14209 private boolean isVerificationEnabled(int userId, int installFlags) { 14210 if (!DEFAULT_VERIFY_ENABLE) { 14211 return false; 14212 } 14213 14214 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14215 14216 // Check if installing from ADB 14217 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14218 // Do not run verification in a test harness environment 14219 if (ActivityManager.isRunningInTestHarness()) { 14220 return false; 14221 } 14222 if (ensureVerifyAppsEnabled) { 14223 return true; 14224 } 14225 // Check if the developer does not want package verification for ADB installs 14226 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14227 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14228 return false; 14229 } 14230 } 14231 14232 if (ensureVerifyAppsEnabled) { 14233 return true; 14234 } 14235 14236 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14237 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14238 } 14239 14240 @Override 14241 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14242 throws RemoteException { 14243 mContext.enforceCallingOrSelfPermission( 14244 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14245 "Only intentfilter verification agents can verify applications"); 14246 14247 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14248 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14249 Binder.getCallingUid(), verificationCode, failedDomains); 14250 msg.arg1 = id; 14251 msg.obj = response; 14252 mHandler.sendMessage(msg); 14253 } 14254 14255 @Override 14256 public int getIntentVerificationStatus(String packageName, int userId) { 14257 synchronized (mPackages) { 14258 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14259 } 14260 } 14261 14262 @Override 14263 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14264 mContext.enforceCallingOrSelfPermission( 14265 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14266 14267 boolean result = false; 14268 synchronized (mPackages) { 14269 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14270 } 14271 if (result) { 14272 scheduleWritePackageRestrictionsLocked(userId); 14273 } 14274 return result; 14275 } 14276 14277 @Override 14278 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14279 String packageName) { 14280 synchronized (mPackages) { 14281 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14282 } 14283 } 14284 14285 @Override 14286 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14287 if (TextUtils.isEmpty(packageName)) { 14288 return ParceledListSlice.emptyList(); 14289 } 14290 synchronized (mPackages) { 14291 PackageParser.Package pkg = mPackages.get(packageName); 14292 if (pkg == null || pkg.activities == null) { 14293 return ParceledListSlice.emptyList(); 14294 } 14295 final int count = pkg.activities.size(); 14296 ArrayList<IntentFilter> result = new ArrayList<>(); 14297 for (int n=0; n<count; n++) { 14298 PackageParser.Activity activity = pkg.activities.get(n); 14299 if (activity.intents != null && activity.intents.size() > 0) { 14300 result.addAll(activity.intents); 14301 } 14302 } 14303 return new ParceledListSlice<>(result); 14304 } 14305 } 14306 14307 @Override 14308 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14309 mContext.enforceCallingOrSelfPermission( 14310 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14311 14312 synchronized (mPackages) { 14313 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14314 if (packageName != null) { 14315 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 14316 packageName, userId); 14317 } 14318 return result; 14319 } 14320 } 14321 14322 @Override 14323 public String getDefaultBrowserPackageName(int userId) { 14324 synchronized (mPackages) { 14325 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14326 } 14327 } 14328 14329 /** 14330 * Get the "allow unknown sources" setting. 14331 * 14332 * @return the current "allow unknown sources" setting 14333 */ 14334 private int getUnknownSourcesSettings() { 14335 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14336 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14337 -1); 14338 } 14339 14340 @Override 14341 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14342 final int uid = Binder.getCallingUid(); 14343 // writer 14344 synchronized (mPackages) { 14345 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14346 if (targetPackageSetting == null) { 14347 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14348 } 14349 14350 PackageSetting installerPackageSetting; 14351 if (installerPackageName != null) { 14352 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14353 if (installerPackageSetting == null) { 14354 throw new IllegalArgumentException("Unknown installer package: " 14355 + installerPackageName); 14356 } 14357 } else { 14358 installerPackageSetting = null; 14359 } 14360 14361 Signature[] callerSignature; 14362 Object obj = mSettings.getUserIdLPr(uid); 14363 if (obj != null) { 14364 if (obj instanceof SharedUserSetting) { 14365 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14366 } else if (obj instanceof PackageSetting) { 14367 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14368 } else { 14369 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14370 } 14371 } else { 14372 throw new SecurityException("Unknown calling UID: " + uid); 14373 } 14374 14375 // Verify: can't set installerPackageName to a package that is 14376 // not signed with the same cert as the caller. 14377 if (installerPackageSetting != null) { 14378 if (compareSignatures(callerSignature, 14379 installerPackageSetting.signatures.mSignatures) 14380 != PackageManager.SIGNATURE_MATCH) { 14381 throw new SecurityException( 14382 "Caller does not have same cert as new installer package " 14383 + installerPackageName); 14384 } 14385 } 14386 14387 // Verify: if target already has an installer package, it must 14388 // be signed with the same cert as the caller. 14389 if (targetPackageSetting.installerPackageName != null) { 14390 PackageSetting setting = mSettings.mPackages.get( 14391 targetPackageSetting.installerPackageName); 14392 // If the currently set package isn't valid, then it's always 14393 // okay to change it. 14394 if (setting != null) { 14395 if (compareSignatures(callerSignature, 14396 setting.signatures.mSignatures) 14397 != PackageManager.SIGNATURE_MATCH) { 14398 throw new SecurityException( 14399 "Caller does not have same cert as old installer package " 14400 + targetPackageSetting.installerPackageName); 14401 } 14402 } 14403 } 14404 14405 // Okay! 14406 targetPackageSetting.installerPackageName = installerPackageName; 14407 if (installerPackageName != null) { 14408 mSettings.mInstallerPackages.add(installerPackageName); 14409 } 14410 scheduleWriteSettingsLocked(); 14411 } 14412 } 14413 14414 @Override 14415 public void setApplicationCategoryHint(String packageName, int categoryHint, 14416 String callerPackageName) { 14417 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14418 callerPackageName); 14419 synchronized (mPackages) { 14420 PackageSetting ps = mSettings.mPackages.get(packageName); 14421 if (ps == null) { 14422 throw new IllegalArgumentException("Unknown target package " + packageName); 14423 } 14424 14425 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14426 throw new IllegalArgumentException("Calling package " + callerPackageName 14427 + " is not installer for " + packageName); 14428 } 14429 14430 if (ps.categoryHint != categoryHint) { 14431 ps.categoryHint = categoryHint; 14432 scheduleWriteSettingsLocked(); 14433 } 14434 } 14435 } 14436 14437 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14438 // Queue up an async operation since the package installation may take a little while. 14439 mHandler.post(new Runnable() { 14440 public void run() { 14441 mHandler.removeCallbacks(this); 14442 // Result object to be returned 14443 PackageInstalledInfo res = new PackageInstalledInfo(); 14444 res.setReturnCode(currentStatus); 14445 res.uid = -1; 14446 res.pkg = null; 14447 res.removedInfo = null; 14448 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14449 args.doPreInstall(res.returnCode); 14450 synchronized (mInstallLock) { 14451 installPackageTracedLI(args, res); 14452 } 14453 args.doPostInstall(res.returnCode, res.uid); 14454 } 14455 14456 // A restore should be performed at this point if (a) the install 14457 // succeeded, (b) the operation is not an update, and (c) the new 14458 // package has not opted out of backup participation. 14459 final boolean update = res.removedInfo != null 14460 && res.removedInfo.removedPackage != null; 14461 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14462 boolean doRestore = !update 14463 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14464 14465 // Set up the post-install work request bookkeeping. This will be used 14466 // and cleaned up by the post-install event handling regardless of whether 14467 // there's a restore pass performed. Token values are >= 1. 14468 int token; 14469 if (mNextInstallToken < 0) mNextInstallToken = 1; 14470 token = mNextInstallToken++; 14471 14472 PostInstallData data = new PostInstallData(args, res); 14473 mRunningInstalls.put(token, data); 14474 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14475 14476 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14477 // Pass responsibility to the Backup Manager. It will perform a 14478 // restore if appropriate, then pass responsibility back to the 14479 // Package Manager to run the post-install observer callbacks 14480 // and broadcasts. 14481 IBackupManager bm = IBackupManager.Stub.asInterface( 14482 ServiceManager.getService(Context.BACKUP_SERVICE)); 14483 if (bm != null) { 14484 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14485 + " to BM for possible restore"); 14486 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14487 try { 14488 // TODO: http://b/22388012 14489 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14490 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14491 } else { 14492 doRestore = false; 14493 } 14494 } catch (RemoteException e) { 14495 // can't happen; the backup manager is local 14496 } catch (Exception e) { 14497 Slog.e(TAG, "Exception trying to enqueue restore", e); 14498 doRestore = false; 14499 } 14500 } else { 14501 Slog.e(TAG, "Backup Manager not found!"); 14502 doRestore = false; 14503 } 14504 } 14505 14506 if (!doRestore) { 14507 // No restore possible, or the Backup Manager was mysteriously not 14508 // available -- just fire the post-install work request directly. 14509 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14510 14511 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14512 14513 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14514 mHandler.sendMessage(msg); 14515 } 14516 } 14517 }); 14518 } 14519 14520 /** 14521 * Callback from PackageSettings whenever an app is first transitioned out of the 14522 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14523 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14524 * here whether the app is the target of an ongoing install, and only send the 14525 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14526 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14527 * handling. 14528 */ 14529 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14530 // Serialize this with the rest of the install-process message chain. In the 14531 // restore-at-install case, this Runnable will necessarily run before the 14532 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14533 // are coherent. In the non-restore case, the app has already completed install 14534 // and been launched through some other means, so it is not in a problematic 14535 // state for observers to see the FIRST_LAUNCH signal. 14536 mHandler.post(new Runnable() { 14537 @Override 14538 public void run() { 14539 for (int i = 0; i < mRunningInstalls.size(); i++) { 14540 final PostInstallData data = mRunningInstalls.valueAt(i); 14541 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14542 continue; 14543 } 14544 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14545 // right package; but is it for the right user? 14546 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14547 if (userId == data.res.newUsers[uIndex]) { 14548 if (DEBUG_BACKUP) { 14549 Slog.i(TAG, "Package " + pkgName 14550 + " being restored so deferring FIRST_LAUNCH"); 14551 } 14552 return; 14553 } 14554 } 14555 } 14556 } 14557 // didn't find it, so not being restored 14558 if (DEBUG_BACKUP) { 14559 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14560 } 14561 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14562 } 14563 }); 14564 } 14565 14566 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14567 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14568 installerPkg, null, userIds); 14569 } 14570 14571 private abstract class HandlerParams { 14572 private static final int MAX_RETRIES = 4; 14573 14574 /** 14575 * Number of times startCopy() has been attempted and had a non-fatal 14576 * error. 14577 */ 14578 private int mRetries = 0; 14579 14580 /** User handle for the user requesting the information or installation. */ 14581 private final UserHandle mUser; 14582 String traceMethod; 14583 int traceCookie; 14584 14585 HandlerParams(UserHandle user) { 14586 mUser = user; 14587 } 14588 14589 UserHandle getUser() { 14590 return mUser; 14591 } 14592 14593 HandlerParams setTraceMethod(String traceMethod) { 14594 this.traceMethod = traceMethod; 14595 return this; 14596 } 14597 14598 HandlerParams setTraceCookie(int traceCookie) { 14599 this.traceCookie = traceCookie; 14600 return this; 14601 } 14602 14603 final boolean startCopy() { 14604 boolean res; 14605 try { 14606 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14607 14608 if (++mRetries > MAX_RETRIES) { 14609 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14610 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14611 handleServiceError(); 14612 return false; 14613 } else { 14614 handleStartCopy(); 14615 res = true; 14616 } 14617 } catch (RemoteException e) { 14618 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14619 mHandler.sendEmptyMessage(MCS_RECONNECT); 14620 res = false; 14621 } 14622 handleReturnCode(); 14623 return res; 14624 } 14625 14626 final void serviceError() { 14627 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14628 handleServiceError(); 14629 handleReturnCode(); 14630 } 14631 14632 abstract void handleStartCopy() throws RemoteException; 14633 abstract void handleServiceError(); 14634 abstract void handleReturnCode(); 14635 } 14636 14637 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14638 for (File path : paths) { 14639 try { 14640 mcs.clearDirectory(path.getAbsolutePath()); 14641 } catch (RemoteException e) { 14642 } 14643 } 14644 } 14645 14646 static class OriginInfo { 14647 /** 14648 * Location where install is coming from, before it has been 14649 * copied/renamed into place. This could be a single monolithic APK 14650 * file, or a cluster directory. This location may be untrusted. 14651 */ 14652 final File file; 14653 final String cid; 14654 14655 /** 14656 * Flag indicating that {@link #file} or {@link #cid} has already been 14657 * staged, meaning downstream users don't need to defensively copy the 14658 * contents. 14659 */ 14660 final boolean staged; 14661 14662 /** 14663 * Flag indicating that {@link #file} or {@link #cid} is an already 14664 * installed app that is being moved. 14665 */ 14666 final boolean existing; 14667 14668 final String resolvedPath; 14669 final File resolvedFile; 14670 14671 static OriginInfo fromNothing() { 14672 return new OriginInfo(null, null, false, false); 14673 } 14674 14675 static OriginInfo fromUntrustedFile(File file) { 14676 return new OriginInfo(file, null, false, false); 14677 } 14678 14679 static OriginInfo fromExistingFile(File file) { 14680 return new OriginInfo(file, null, false, true); 14681 } 14682 14683 static OriginInfo fromStagedFile(File file) { 14684 return new OriginInfo(file, null, true, false); 14685 } 14686 14687 static OriginInfo fromStagedContainer(String cid) { 14688 return new OriginInfo(null, cid, true, false); 14689 } 14690 14691 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14692 this.file = file; 14693 this.cid = cid; 14694 this.staged = staged; 14695 this.existing = existing; 14696 14697 if (cid != null) { 14698 resolvedPath = PackageHelper.getSdDir(cid); 14699 resolvedFile = new File(resolvedPath); 14700 } else if (file != null) { 14701 resolvedPath = file.getAbsolutePath(); 14702 resolvedFile = file; 14703 } else { 14704 resolvedPath = null; 14705 resolvedFile = null; 14706 } 14707 } 14708 } 14709 14710 static class MoveInfo { 14711 final int moveId; 14712 final String fromUuid; 14713 final String toUuid; 14714 final String packageName; 14715 final String dataAppName; 14716 final int appId; 14717 final String seinfo; 14718 final int targetSdkVersion; 14719 14720 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14721 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14722 this.moveId = moveId; 14723 this.fromUuid = fromUuid; 14724 this.toUuid = toUuid; 14725 this.packageName = packageName; 14726 this.dataAppName = dataAppName; 14727 this.appId = appId; 14728 this.seinfo = seinfo; 14729 this.targetSdkVersion = targetSdkVersion; 14730 } 14731 } 14732 14733 static class VerificationInfo { 14734 /** A constant used to indicate that a uid value is not present. */ 14735 public static final int NO_UID = -1; 14736 14737 /** URI referencing where the package was downloaded from. */ 14738 final Uri originatingUri; 14739 14740 /** HTTP referrer URI associated with the originatingURI. */ 14741 final Uri referrer; 14742 14743 /** UID of the application that the install request originated from. */ 14744 final int originatingUid; 14745 14746 /** UID of application requesting the install */ 14747 final int installerUid; 14748 14749 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14750 this.originatingUri = originatingUri; 14751 this.referrer = referrer; 14752 this.originatingUid = originatingUid; 14753 this.installerUid = installerUid; 14754 } 14755 } 14756 14757 class InstallParams extends HandlerParams { 14758 final OriginInfo origin; 14759 final MoveInfo move; 14760 final IPackageInstallObserver2 observer; 14761 int installFlags; 14762 final String installerPackageName; 14763 final String volumeUuid; 14764 private InstallArgs mArgs; 14765 private int mRet; 14766 final String packageAbiOverride; 14767 final String[] grantedRuntimePermissions; 14768 final VerificationInfo verificationInfo; 14769 final Certificate[][] certificates; 14770 final int installReason; 14771 14772 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14773 int installFlags, String installerPackageName, String volumeUuid, 14774 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14775 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14776 super(user); 14777 this.origin = origin; 14778 this.move = move; 14779 this.observer = observer; 14780 this.installFlags = installFlags; 14781 this.installerPackageName = installerPackageName; 14782 this.volumeUuid = volumeUuid; 14783 this.verificationInfo = verificationInfo; 14784 this.packageAbiOverride = packageAbiOverride; 14785 this.grantedRuntimePermissions = grantedPermissions; 14786 this.certificates = certificates; 14787 this.installReason = installReason; 14788 } 14789 14790 @Override 14791 public String toString() { 14792 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14793 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14794 } 14795 14796 private int installLocationPolicy(PackageInfoLite pkgLite) { 14797 String packageName = pkgLite.packageName; 14798 int installLocation = pkgLite.installLocation; 14799 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14800 // reader 14801 synchronized (mPackages) { 14802 // Currently installed package which the new package is attempting to replace or 14803 // null if no such package is installed. 14804 PackageParser.Package installedPkg = mPackages.get(packageName); 14805 // Package which currently owns the data which the new package will own if installed. 14806 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14807 // will be null whereas dataOwnerPkg will contain information about the package 14808 // which was uninstalled while keeping its data. 14809 PackageParser.Package dataOwnerPkg = installedPkg; 14810 if (dataOwnerPkg == null) { 14811 PackageSetting ps = mSettings.mPackages.get(packageName); 14812 if (ps != null) { 14813 dataOwnerPkg = ps.pkg; 14814 } 14815 } 14816 14817 if (dataOwnerPkg != null) { 14818 // If installed, the package will get access to data left on the device by its 14819 // predecessor. As a security measure, this is permited only if this is not a 14820 // version downgrade or if the predecessor package is marked as debuggable and 14821 // a downgrade is explicitly requested. 14822 // 14823 // On debuggable platform builds, downgrades are permitted even for 14824 // non-debuggable packages to make testing easier. Debuggable platform builds do 14825 // not offer security guarantees and thus it's OK to disable some security 14826 // mechanisms to make debugging/testing easier on those builds. However, even on 14827 // debuggable builds downgrades of packages are permitted only if requested via 14828 // installFlags. This is because we aim to keep the behavior of debuggable 14829 // platform builds as close as possible to the behavior of non-debuggable 14830 // platform builds. 14831 final boolean downgradeRequested = 14832 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14833 final boolean packageDebuggable = 14834 (dataOwnerPkg.applicationInfo.flags 14835 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14836 final boolean downgradePermitted = 14837 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14838 if (!downgradePermitted) { 14839 try { 14840 checkDowngrade(dataOwnerPkg, pkgLite); 14841 } catch (PackageManagerException e) { 14842 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14843 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14844 } 14845 } 14846 } 14847 14848 if (installedPkg != null) { 14849 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14850 // Check for updated system application. 14851 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14852 if (onSd) { 14853 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14854 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14855 } 14856 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14857 } else { 14858 if (onSd) { 14859 // Install flag overrides everything. 14860 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14861 } 14862 // If current upgrade specifies particular preference 14863 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14864 // Application explicitly specified internal. 14865 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14866 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14867 // App explictly prefers external. Let policy decide 14868 } else { 14869 // Prefer previous location 14870 if (isExternal(installedPkg)) { 14871 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14872 } 14873 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14874 } 14875 } 14876 } else { 14877 // Invalid install. Return error code 14878 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14879 } 14880 } 14881 } 14882 // All the special cases have been taken care of. 14883 // Return result based on recommended install location. 14884 if (onSd) { 14885 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14886 } 14887 return pkgLite.recommendedInstallLocation; 14888 } 14889 14890 /* 14891 * Invoke remote method to get package information and install 14892 * location values. Override install location based on default 14893 * policy if needed and then create install arguments based 14894 * on the install location. 14895 */ 14896 public void handleStartCopy() throws RemoteException { 14897 int ret = PackageManager.INSTALL_SUCCEEDED; 14898 14899 // If we're already staged, we've firmly committed to an install location 14900 if (origin.staged) { 14901 if (origin.file != null) { 14902 installFlags |= PackageManager.INSTALL_INTERNAL; 14903 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14904 } else if (origin.cid != null) { 14905 installFlags |= PackageManager.INSTALL_EXTERNAL; 14906 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14907 } else { 14908 throw new IllegalStateException("Invalid stage location"); 14909 } 14910 } 14911 14912 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14913 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14914 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14915 PackageInfoLite pkgLite = null; 14916 14917 if (onInt && onSd) { 14918 // Check if both bits are set. 14919 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14920 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14921 } else if (onSd && ephemeral) { 14922 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14923 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14924 } else { 14925 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14926 packageAbiOverride); 14927 14928 if (DEBUG_EPHEMERAL && ephemeral) { 14929 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14930 } 14931 14932 /* 14933 * If we have too little free space, try to free cache 14934 * before giving up. 14935 */ 14936 if (!origin.staged && pkgLite.recommendedInstallLocation 14937 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14938 // TODO: focus freeing disk space on the target device 14939 final StorageManager storage = StorageManager.from(mContext); 14940 final long lowThreshold = storage.getStorageLowBytes( 14941 Environment.getDataDirectory()); 14942 14943 final long sizeBytes = mContainerService.calculateInstalledSize( 14944 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14945 14946 try { 14947 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14948 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14949 installFlags, packageAbiOverride); 14950 } catch (InstallerException e) { 14951 Slog.w(TAG, "Failed to free cache", e); 14952 } 14953 14954 /* 14955 * The cache free must have deleted the file we 14956 * downloaded to install. 14957 * 14958 * TODO: fix the "freeCache" call to not delete 14959 * the file we care about. 14960 */ 14961 if (pkgLite.recommendedInstallLocation 14962 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14963 pkgLite.recommendedInstallLocation 14964 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14965 } 14966 } 14967 } 14968 14969 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14970 int loc = pkgLite.recommendedInstallLocation; 14971 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14972 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14973 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14974 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14975 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14976 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14977 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14978 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14979 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14980 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14981 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14982 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14983 } else { 14984 // Override with defaults if needed. 14985 loc = installLocationPolicy(pkgLite); 14986 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14987 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14988 } else if (!onSd && !onInt) { 14989 // Override install location with flags 14990 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14991 // Set the flag to install on external media. 14992 installFlags |= PackageManager.INSTALL_EXTERNAL; 14993 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14994 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14995 if (DEBUG_EPHEMERAL) { 14996 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14997 } 14998 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14999 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15000 |PackageManager.INSTALL_INTERNAL); 15001 } else { 15002 // Make sure the flag for installing on external 15003 // media is unset 15004 installFlags |= PackageManager.INSTALL_INTERNAL; 15005 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15006 } 15007 } 15008 } 15009 } 15010 15011 final InstallArgs args = createInstallArgs(this); 15012 mArgs = args; 15013 15014 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15015 // TODO: http://b/22976637 15016 // Apps installed for "all" users use the device owner to verify the app 15017 UserHandle verifierUser = getUser(); 15018 if (verifierUser == UserHandle.ALL) { 15019 verifierUser = UserHandle.SYSTEM; 15020 } 15021 15022 /* 15023 * Determine if we have any installed package verifiers. If we 15024 * do, then we'll defer to them to verify the packages. 15025 */ 15026 final int requiredUid = mRequiredVerifierPackage == null ? -1 15027 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15028 verifierUser.getIdentifier()); 15029 if (!origin.existing && requiredUid != -1 15030 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 15031 final Intent verification = new Intent( 15032 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15033 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15034 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15035 PACKAGE_MIME_TYPE); 15036 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15037 15038 // Query all live verifiers based on current user state 15039 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15040 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 15041 15042 if (DEBUG_VERIFY) { 15043 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15044 + verification.toString() + " with " + pkgLite.verifiers.length 15045 + " optional verifiers"); 15046 } 15047 15048 final int verificationId = mPendingVerificationToken++; 15049 15050 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15051 15052 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15053 installerPackageName); 15054 15055 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15056 installFlags); 15057 15058 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15059 pkgLite.packageName); 15060 15061 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15062 pkgLite.versionCode); 15063 15064 if (verificationInfo != null) { 15065 if (verificationInfo.originatingUri != null) { 15066 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15067 verificationInfo.originatingUri); 15068 } 15069 if (verificationInfo.referrer != null) { 15070 verification.putExtra(Intent.EXTRA_REFERRER, 15071 verificationInfo.referrer); 15072 } 15073 if (verificationInfo.originatingUid >= 0) { 15074 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15075 verificationInfo.originatingUid); 15076 } 15077 if (verificationInfo.installerUid >= 0) { 15078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15079 verificationInfo.installerUid); 15080 } 15081 } 15082 15083 final PackageVerificationState verificationState = new PackageVerificationState( 15084 requiredUid, args); 15085 15086 mPendingVerification.append(verificationId, verificationState); 15087 15088 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15089 receivers, verificationState); 15090 15091 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15092 final long idleDuration = getVerificationTimeout(); 15093 15094 /* 15095 * If any sufficient verifiers were listed in the package 15096 * manifest, attempt to ask them. 15097 */ 15098 if (sufficientVerifiers != null) { 15099 final int N = sufficientVerifiers.size(); 15100 if (N == 0) { 15101 Slog.i(TAG, "Additional verifiers required, but none installed."); 15102 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15103 } else { 15104 for (int i = 0; i < N; i++) { 15105 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15106 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15107 verifierComponent.getPackageName(), idleDuration, 15108 verifierUser.getIdentifier(), false, "package verifier"); 15109 15110 final Intent sufficientIntent = new Intent(verification); 15111 sufficientIntent.setComponent(verifierComponent); 15112 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15113 } 15114 } 15115 } 15116 15117 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15118 mRequiredVerifierPackage, receivers); 15119 if (ret == PackageManager.INSTALL_SUCCEEDED 15120 && mRequiredVerifierPackage != null) { 15121 Trace.asyncTraceBegin( 15122 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15123 /* 15124 * Send the intent to the required verification agent, 15125 * but only start the verification timeout after the 15126 * target BroadcastReceivers have run. 15127 */ 15128 verification.setComponent(requiredVerifierComponent); 15129 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15130 mRequiredVerifierPackage, idleDuration, 15131 verifierUser.getIdentifier(), false, "package verifier"); 15132 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15133 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15134 new BroadcastReceiver() { 15135 @Override 15136 public void onReceive(Context context, Intent intent) { 15137 final Message msg = mHandler 15138 .obtainMessage(CHECK_PENDING_VERIFICATION); 15139 msg.arg1 = verificationId; 15140 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15141 } 15142 }, null, 0, null, null); 15143 15144 /* 15145 * We don't want the copy to proceed until verification 15146 * succeeds, so null out this field. 15147 */ 15148 mArgs = null; 15149 } 15150 } else { 15151 /* 15152 * No package verification is enabled, so immediately start 15153 * the remote call to initiate copy using temporary file. 15154 */ 15155 ret = args.copyApk(mContainerService, true); 15156 } 15157 } 15158 15159 mRet = ret; 15160 } 15161 15162 @Override 15163 void handleReturnCode() { 15164 // If mArgs is null, then MCS couldn't be reached. When it 15165 // reconnects, it will try again to install. At that point, this 15166 // will succeed. 15167 if (mArgs != null) { 15168 processPendingInstall(mArgs, mRet); 15169 } 15170 } 15171 15172 @Override 15173 void handleServiceError() { 15174 mArgs = createInstallArgs(this); 15175 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15176 } 15177 15178 public boolean isForwardLocked() { 15179 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15180 } 15181 } 15182 15183 /** 15184 * Used during creation of InstallArgs 15185 * 15186 * @param installFlags package installation flags 15187 * @return true if should be installed on external storage 15188 */ 15189 private static boolean installOnExternalAsec(int installFlags) { 15190 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 15191 return false; 15192 } 15193 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 15194 return true; 15195 } 15196 return false; 15197 } 15198 15199 /** 15200 * Used during creation of InstallArgs 15201 * 15202 * @param installFlags package installation flags 15203 * @return true if should be installed as forward locked 15204 */ 15205 private static boolean installForwardLocked(int installFlags) { 15206 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15207 } 15208 15209 private InstallArgs createInstallArgs(InstallParams params) { 15210 if (params.move != null) { 15211 return new MoveInstallArgs(params); 15212 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 15213 return new AsecInstallArgs(params); 15214 } else { 15215 return new FileInstallArgs(params); 15216 } 15217 } 15218 15219 /** 15220 * Create args that describe an existing installed package. Typically used 15221 * when cleaning up old installs, or used as a move source. 15222 */ 15223 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15224 String resourcePath, String[] instructionSets) { 15225 final boolean isInAsec; 15226 if (installOnExternalAsec(installFlags)) { 15227 /* Apps on SD card are always in ASEC containers. */ 15228 isInAsec = true; 15229 } else if (installForwardLocked(installFlags) 15230 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 15231 /* 15232 * Forward-locked apps are only in ASEC containers if they're the 15233 * new style 15234 */ 15235 isInAsec = true; 15236 } else { 15237 isInAsec = false; 15238 } 15239 15240 if (isInAsec) { 15241 return new AsecInstallArgs(codePath, instructionSets, 15242 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 15243 } else { 15244 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15245 } 15246 } 15247 15248 static abstract class InstallArgs { 15249 /** @see InstallParams#origin */ 15250 final OriginInfo origin; 15251 /** @see InstallParams#move */ 15252 final MoveInfo move; 15253 15254 final IPackageInstallObserver2 observer; 15255 // Always refers to PackageManager flags only 15256 final int installFlags; 15257 final String installerPackageName; 15258 final String volumeUuid; 15259 final UserHandle user; 15260 final String abiOverride; 15261 final String[] installGrantPermissions; 15262 /** If non-null, drop an async trace when the install completes */ 15263 final String traceMethod; 15264 final int traceCookie; 15265 final Certificate[][] certificates; 15266 final int installReason; 15267 15268 // The list of instruction sets supported by this app. This is currently 15269 // only used during the rmdex() phase to clean up resources. We can get rid of this 15270 // if we move dex files under the common app path. 15271 /* nullable */ String[] instructionSets; 15272 15273 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15274 int installFlags, String installerPackageName, String volumeUuid, 15275 UserHandle user, String[] instructionSets, 15276 String abiOverride, String[] installGrantPermissions, 15277 String traceMethod, int traceCookie, Certificate[][] certificates, 15278 int installReason) { 15279 this.origin = origin; 15280 this.move = move; 15281 this.installFlags = installFlags; 15282 this.observer = observer; 15283 this.installerPackageName = installerPackageName; 15284 this.volumeUuid = volumeUuid; 15285 this.user = user; 15286 this.instructionSets = instructionSets; 15287 this.abiOverride = abiOverride; 15288 this.installGrantPermissions = installGrantPermissions; 15289 this.traceMethod = traceMethod; 15290 this.traceCookie = traceCookie; 15291 this.certificates = certificates; 15292 this.installReason = installReason; 15293 } 15294 15295 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15296 abstract int doPreInstall(int status); 15297 15298 /** 15299 * Rename package into final resting place. All paths on the given 15300 * scanned package should be updated to reflect the rename. 15301 */ 15302 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15303 abstract int doPostInstall(int status, int uid); 15304 15305 /** @see PackageSettingBase#codePathString */ 15306 abstract String getCodePath(); 15307 /** @see PackageSettingBase#resourcePathString */ 15308 abstract String getResourcePath(); 15309 15310 // Need installer lock especially for dex file removal. 15311 abstract void cleanUpResourcesLI(); 15312 abstract boolean doPostDeleteLI(boolean delete); 15313 15314 /** 15315 * Called before the source arguments are copied. This is used mostly 15316 * for MoveParams when it needs to read the source file to put it in the 15317 * destination. 15318 */ 15319 int doPreCopy() { 15320 return PackageManager.INSTALL_SUCCEEDED; 15321 } 15322 15323 /** 15324 * Called after the source arguments are copied. This is used mostly for 15325 * MoveParams when it needs to read the source file to put it in the 15326 * destination. 15327 */ 15328 int doPostCopy(int uid) { 15329 return PackageManager.INSTALL_SUCCEEDED; 15330 } 15331 15332 protected boolean isFwdLocked() { 15333 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15334 } 15335 15336 protected boolean isExternalAsec() { 15337 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15338 } 15339 15340 protected boolean isEphemeral() { 15341 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15342 } 15343 15344 UserHandle getUser() { 15345 return user; 15346 } 15347 } 15348 15349 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15350 if (!allCodePaths.isEmpty()) { 15351 if (instructionSets == null) { 15352 throw new IllegalStateException("instructionSet == null"); 15353 } 15354 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15355 for (String codePath : allCodePaths) { 15356 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15357 try { 15358 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15359 } catch (InstallerException ignored) { 15360 } 15361 } 15362 } 15363 } 15364 } 15365 15366 /** 15367 * Logic to handle installation of non-ASEC applications, including copying 15368 * and renaming logic. 15369 */ 15370 class FileInstallArgs extends InstallArgs { 15371 private File codeFile; 15372 private File resourceFile; 15373 15374 // Example topology: 15375 // /data/app/com.example/base.apk 15376 // /data/app/com.example/split_foo.apk 15377 // /data/app/com.example/lib/arm/libfoo.so 15378 // /data/app/com.example/lib/arm64/libfoo.so 15379 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15380 15381 /** New install */ 15382 FileInstallArgs(InstallParams params) { 15383 super(params.origin, params.move, params.observer, params.installFlags, 15384 params.installerPackageName, params.volumeUuid, 15385 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15386 params.grantedRuntimePermissions, 15387 params.traceMethod, params.traceCookie, params.certificates, 15388 params.installReason); 15389 if (isFwdLocked()) { 15390 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15391 } 15392 } 15393 15394 /** Existing install */ 15395 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15396 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15397 null, null, null, 0, null /*certificates*/, 15398 PackageManager.INSTALL_REASON_UNKNOWN); 15399 this.codeFile = (codePath != null) ? new File(codePath) : null; 15400 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15401 } 15402 15403 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15404 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15405 try { 15406 return doCopyApk(imcs, temp); 15407 } finally { 15408 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15409 } 15410 } 15411 15412 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15413 if (origin.staged) { 15414 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15415 codeFile = origin.file; 15416 resourceFile = origin.file; 15417 return PackageManager.INSTALL_SUCCEEDED; 15418 } 15419 15420 try { 15421 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15422 final File tempDir = 15423 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15424 codeFile = tempDir; 15425 resourceFile = tempDir; 15426 } catch (IOException e) { 15427 Slog.w(TAG, "Failed to create copy file: " + e); 15428 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15429 } 15430 15431 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15432 @Override 15433 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15434 if (!FileUtils.isValidExtFilename(name)) { 15435 throw new IllegalArgumentException("Invalid filename: " + name); 15436 } 15437 try { 15438 final File file = new File(codeFile, name); 15439 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15440 O_RDWR | O_CREAT, 0644); 15441 Os.chmod(file.getAbsolutePath(), 0644); 15442 return new ParcelFileDescriptor(fd); 15443 } catch (ErrnoException e) { 15444 throw new RemoteException("Failed to open: " + e.getMessage()); 15445 } 15446 } 15447 }; 15448 15449 int ret = PackageManager.INSTALL_SUCCEEDED; 15450 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15451 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15452 Slog.e(TAG, "Failed to copy package"); 15453 return ret; 15454 } 15455 15456 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15457 NativeLibraryHelper.Handle handle = null; 15458 try { 15459 handle = NativeLibraryHelper.Handle.create(codeFile); 15460 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15461 abiOverride); 15462 } catch (IOException e) { 15463 Slog.e(TAG, "Copying native libraries failed", e); 15464 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15465 } finally { 15466 IoUtils.closeQuietly(handle); 15467 } 15468 15469 return ret; 15470 } 15471 15472 int doPreInstall(int status) { 15473 if (status != PackageManager.INSTALL_SUCCEEDED) { 15474 cleanUp(); 15475 } 15476 return status; 15477 } 15478 15479 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15480 if (status != PackageManager.INSTALL_SUCCEEDED) { 15481 cleanUp(); 15482 return false; 15483 } 15484 15485 final File targetDir = codeFile.getParentFile(); 15486 final File beforeCodeFile = codeFile; 15487 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15488 15489 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15490 try { 15491 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15492 } catch (ErrnoException e) { 15493 Slog.w(TAG, "Failed to rename", e); 15494 return false; 15495 } 15496 15497 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15498 Slog.w(TAG, "Failed to restorecon"); 15499 return false; 15500 } 15501 15502 // Reflect the rename internally 15503 codeFile = afterCodeFile; 15504 resourceFile = afterCodeFile; 15505 15506 // Reflect the rename in scanned details 15507 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15508 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15509 afterCodeFile, pkg.baseCodePath)); 15510 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15511 afterCodeFile, pkg.splitCodePaths)); 15512 15513 // Reflect the rename in app info 15514 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15515 pkg.setApplicationInfoCodePath(pkg.codePath); 15516 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15517 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15518 pkg.setApplicationInfoResourcePath(pkg.codePath); 15519 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15520 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15521 15522 return true; 15523 } 15524 15525 int doPostInstall(int status, int uid) { 15526 if (status != PackageManager.INSTALL_SUCCEEDED) { 15527 cleanUp(); 15528 } 15529 return status; 15530 } 15531 15532 @Override 15533 String getCodePath() { 15534 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15535 } 15536 15537 @Override 15538 String getResourcePath() { 15539 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15540 } 15541 15542 private boolean cleanUp() { 15543 if (codeFile == null || !codeFile.exists()) { 15544 return false; 15545 } 15546 15547 removeCodePathLI(codeFile); 15548 15549 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15550 resourceFile.delete(); 15551 } 15552 15553 return true; 15554 } 15555 15556 void cleanUpResourcesLI() { 15557 // Try enumerating all code paths before deleting 15558 List<String> allCodePaths = Collections.EMPTY_LIST; 15559 if (codeFile != null && codeFile.exists()) { 15560 try { 15561 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15562 allCodePaths = pkg.getAllCodePaths(); 15563 } catch (PackageParserException e) { 15564 // Ignored; we tried our best 15565 } 15566 } 15567 15568 cleanUp(); 15569 removeDexFiles(allCodePaths, instructionSets); 15570 } 15571 15572 boolean doPostDeleteLI(boolean delete) { 15573 // XXX err, shouldn't we respect the delete flag? 15574 cleanUpResourcesLI(); 15575 return true; 15576 } 15577 } 15578 15579 private boolean isAsecExternal(String cid) { 15580 final String asecPath = PackageHelper.getSdFilesystem(cid); 15581 return !asecPath.startsWith(mAsecInternalPath); 15582 } 15583 15584 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15585 PackageManagerException { 15586 if (copyRet < 0) { 15587 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15588 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15589 throw new PackageManagerException(copyRet, message); 15590 } 15591 } 15592 } 15593 15594 /** 15595 * Extract the StorageManagerService "container ID" from the full code path of an 15596 * .apk. 15597 */ 15598 static String cidFromCodePath(String fullCodePath) { 15599 int eidx = fullCodePath.lastIndexOf("/"); 15600 String subStr1 = fullCodePath.substring(0, eidx); 15601 int sidx = subStr1.lastIndexOf("/"); 15602 return subStr1.substring(sidx+1, eidx); 15603 } 15604 15605 /** 15606 * Logic to handle installation of ASEC applications, including copying and 15607 * renaming logic. 15608 */ 15609 class AsecInstallArgs extends InstallArgs { 15610 static final String RES_FILE_NAME = "pkg.apk"; 15611 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15612 15613 String cid; 15614 String packagePath; 15615 String resourcePath; 15616 15617 /** New install */ 15618 AsecInstallArgs(InstallParams params) { 15619 super(params.origin, params.move, params.observer, params.installFlags, 15620 params.installerPackageName, params.volumeUuid, 15621 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15622 params.grantedRuntimePermissions, 15623 params.traceMethod, params.traceCookie, params.certificates, 15624 params.installReason); 15625 } 15626 15627 /** Existing install */ 15628 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15629 boolean isExternal, boolean isForwardLocked) { 15630 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15631 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15632 instructionSets, null, null, null, 0, null /*certificates*/, 15633 PackageManager.INSTALL_REASON_UNKNOWN); 15634 // Hackily pretend we're still looking at a full code path 15635 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15636 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15637 } 15638 15639 // Extract cid from fullCodePath 15640 int eidx = fullCodePath.lastIndexOf("/"); 15641 String subStr1 = fullCodePath.substring(0, eidx); 15642 int sidx = subStr1.lastIndexOf("/"); 15643 cid = subStr1.substring(sidx+1, eidx); 15644 setMountPath(subStr1); 15645 } 15646 15647 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15648 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15649 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15650 instructionSets, null, null, null, 0, null /*certificates*/, 15651 PackageManager.INSTALL_REASON_UNKNOWN); 15652 this.cid = cid; 15653 setMountPath(PackageHelper.getSdDir(cid)); 15654 } 15655 15656 void createCopyFile() { 15657 cid = mInstallerService.allocateExternalStageCidLegacy(); 15658 } 15659 15660 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15661 if (origin.staged && origin.cid != null) { 15662 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15663 cid = origin.cid; 15664 setMountPath(PackageHelper.getSdDir(cid)); 15665 return PackageManager.INSTALL_SUCCEEDED; 15666 } 15667 15668 if (temp) { 15669 createCopyFile(); 15670 } else { 15671 /* 15672 * Pre-emptively destroy the container since it's destroyed if 15673 * copying fails due to it existing anyway. 15674 */ 15675 PackageHelper.destroySdDir(cid); 15676 } 15677 15678 final String newMountPath = imcs.copyPackageToContainer( 15679 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15680 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15681 15682 if (newMountPath != null) { 15683 setMountPath(newMountPath); 15684 return PackageManager.INSTALL_SUCCEEDED; 15685 } else { 15686 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15687 } 15688 } 15689 15690 @Override 15691 String getCodePath() { 15692 return packagePath; 15693 } 15694 15695 @Override 15696 String getResourcePath() { 15697 return resourcePath; 15698 } 15699 15700 int doPreInstall(int status) { 15701 if (status != PackageManager.INSTALL_SUCCEEDED) { 15702 // Destroy container 15703 PackageHelper.destroySdDir(cid); 15704 } else { 15705 boolean mounted = PackageHelper.isContainerMounted(cid); 15706 if (!mounted) { 15707 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15708 Process.SYSTEM_UID); 15709 if (newMountPath != null) { 15710 setMountPath(newMountPath); 15711 } else { 15712 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15713 } 15714 } 15715 } 15716 return status; 15717 } 15718 15719 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15720 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15721 String newMountPath = null; 15722 if (PackageHelper.isContainerMounted(cid)) { 15723 // Unmount the container 15724 if (!PackageHelper.unMountSdDir(cid)) { 15725 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15726 return false; 15727 } 15728 } 15729 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15730 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15731 " which might be stale. Will try to clean up."); 15732 // Clean up the stale container and proceed to recreate. 15733 if (!PackageHelper.destroySdDir(newCacheId)) { 15734 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15735 return false; 15736 } 15737 // Successfully cleaned up stale container. Try to rename again. 15738 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15739 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15740 + " inspite of cleaning it up."); 15741 return false; 15742 } 15743 } 15744 if (!PackageHelper.isContainerMounted(newCacheId)) { 15745 Slog.w(TAG, "Mounting container " + newCacheId); 15746 newMountPath = PackageHelper.mountSdDir(newCacheId, 15747 getEncryptKey(), Process.SYSTEM_UID); 15748 } else { 15749 newMountPath = PackageHelper.getSdDir(newCacheId); 15750 } 15751 if (newMountPath == null) { 15752 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15753 return false; 15754 } 15755 Log.i(TAG, "Succesfully renamed " + cid + 15756 " to " + newCacheId + 15757 " at new path: " + newMountPath); 15758 cid = newCacheId; 15759 15760 final File beforeCodeFile = new File(packagePath); 15761 setMountPath(newMountPath); 15762 final File afterCodeFile = new File(packagePath); 15763 15764 // Reflect the rename in scanned details 15765 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15766 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15767 afterCodeFile, pkg.baseCodePath)); 15768 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15769 afterCodeFile, pkg.splitCodePaths)); 15770 15771 // Reflect the rename in app info 15772 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15773 pkg.setApplicationInfoCodePath(pkg.codePath); 15774 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15775 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15776 pkg.setApplicationInfoResourcePath(pkg.codePath); 15777 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15778 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15779 15780 return true; 15781 } 15782 15783 private void setMountPath(String mountPath) { 15784 final File mountFile = new File(mountPath); 15785 15786 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15787 if (monolithicFile.exists()) { 15788 packagePath = monolithicFile.getAbsolutePath(); 15789 if (isFwdLocked()) { 15790 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15791 } else { 15792 resourcePath = packagePath; 15793 } 15794 } else { 15795 packagePath = mountFile.getAbsolutePath(); 15796 resourcePath = packagePath; 15797 } 15798 } 15799 15800 int doPostInstall(int status, int uid) { 15801 if (status != PackageManager.INSTALL_SUCCEEDED) { 15802 cleanUp(); 15803 } else { 15804 final int groupOwner; 15805 final String protectedFile; 15806 if (isFwdLocked()) { 15807 groupOwner = UserHandle.getSharedAppGid(uid); 15808 protectedFile = RES_FILE_NAME; 15809 } else { 15810 groupOwner = -1; 15811 protectedFile = null; 15812 } 15813 15814 if (uid < Process.FIRST_APPLICATION_UID 15815 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15816 Slog.e(TAG, "Failed to finalize " + cid); 15817 PackageHelper.destroySdDir(cid); 15818 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15819 } 15820 15821 boolean mounted = PackageHelper.isContainerMounted(cid); 15822 if (!mounted) { 15823 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15824 } 15825 } 15826 return status; 15827 } 15828 15829 private void cleanUp() { 15830 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15831 15832 // Destroy secure container 15833 PackageHelper.destroySdDir(cid); 15834 } 15835 15836 private List<String> getAllCodePaths() { 15837 final File codeFile = new File(getCodePath()); 15838 if (codeFile != null && codeFile.exists()) { 15839 try { 15840 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15841 return pkg.getAllCodePaths(); 15842 } catch (PackageParserException e) { 15843 // Ignored; we tried our best 15844 } 15845 } 15846 return Collections.EMPTY_LIST; 15847 } 15848 15849 void cleanUpResourcesLI() { 15850 // Enumerate all code paths before deleting 15851 cleanUpResourcesLI(getAllCodePaths()); 15852 } 15853 15854 private void cleanUpResourcesLI(List<String> allCodePaths) { 15855 cleanUp(); 15856 removeDexFiles(allCodePaths, instructionSets); 15857 } 15858 15859 String getPackageName() { 15860 return getAsecPackageName(cid); 15861 } 15862 15863 boolean doPostDeleteLI(boolean delete) { 15864 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15865 final List<String> allCodePaths = getAllCodePaths(); 15866 boolean mounted = PackageHelper.isContainerMounted(cid); 15867 if (mounted) { 15868 // Unmount first 15869 if (PackageHelper.unMountSdDir(cid)) { 15870 mounted = false; 15871 } 15872 } 15873 if (!mounted && delete) { 15874 cleanUpResourcesLI(allCodePaths); 15875 } 15876 return !mounted; 15877 } 15878 15879 @Override 15880 int doPreCopy() { 15881 if (isFwdLocked()) { 15882 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15883 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15884 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15885 } 15886 } 15887 15888 return PackageManager.INSTALL_SUCCEEDED; 15889 } 15890 15891 @Override 15892 int doPostCopy(int uid) { 15893 if (isFwdLocked()) { 15894 if (uid < Process.FIRST_APPLICATION_UID 15895 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15896 RES_FILE_NAME)) { 15897 Slog.e(TAG, "Failed to finalize " + cid); 15898 PackageHelper.destroySdDir(cid); 15899 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15900 } 15901 } 15902 15903 return PackageManager.INSTALL_SUCCEEDED; 15904 } 15905 } 15906 15907 /** 15908 * Logic to handle movement of existing installed applications. 15909 */ 15910 class MoveInstallArgs extends InstallArgs { 15911 private File codeFile; 15912 private File resourceFile; 15913 15914 /** New install */ 15915 MoveInstallArgs(InstallParams params) { 15916 super(params.origin, params.move, params.observer, params.installFlags, 15917 params.installerPackageName, params.volumeUuid, 15918 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15919 params.grantedRuntimePermissions, 15920 params.traceMethod, params.traceCookie, params.certificates, 15921 params.installReason); 15922 } 15923 15924 int copyApk(IMediaContainerService imcs, boolean temp) { 15925 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15926 + move.fromUuid + " to " + move.toUuid); 15927 synchronized (mInstaller) { 15928 try { 15929 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15930 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15931 } catch (InstallerException e) { 15932 Slog.w(TAG, "Failed to move app", e); 15933 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15934 } 15935 } 15936 15937 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15938 resourceFile = codeFile; 15939 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15940 15941 return PackageManager.INSTALL_SUCCEEDED; 15942 } 15943 15944 int doPreInstall(int status) { 15945 if (status != PackageManager.INSTALL_SUCCEEDED) { 15946 cleanUp(move.toUuid); 15947 } 15948 return status; 15949 } 15950 15951 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15952 if (status != PackageManager.INSTALL_SUCCEEDED) { 15953 cleanUp(move.toUuid); 15954 return false; 15955 } 15956 15957 // Reflect the move in app info 15958 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15959 pkg.setApplicationInfoCodePath(pkg.codePath); 15960 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15961 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15962 pkg.setApplicationInfoResourcePath(pkg.codePath); 15963 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15964 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15965 15966 return true; 15967 } 15968 15969 int doPostInstall(int status, int uid) { 15970 if (status == PackageManager.INSTALL_SUCCEEDED) { 15971 cleanUp(move.fromUuid); 15972 } else { 15973 cleanUp(move.toUuid); 15974 } 15975 return status; 15976 } 15977 15978 @Override 15979 String getCodePath() { 15980 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15981 } 15982 15983 @Override 15984 String getResourcePath() { 15985 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15986 } 15987 15988 private boolean cleanUp(String volumeUuid) { 15989 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15990 move.dataAppName); 15991 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15992 final int[] userIds = sUserManager.getUserIds(); 15993 synchronized (mInstallLock) { 15994 // Clean up both app data and code 15995 // All package moves are frozen until finished 15996 for (int userId : userIds) { 15997 try { 15998 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15999 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 16000 } catch (InstallerException e) { 16001 Slog.w(TAG, String.valueOf(e)); 16002 } 16003 } 16004 removeCodePathLI(codeFile); 16005 } 16006 return true; 16007 } 16008 16009 void cleanUpResourcesLI() { 16010 throw new UnsupportedOperationException(); 16011 } 16012 16013 boolean doPostDeleteLI(boolean delete) { 16014 throw new UnsupportedOperationException(); 16015 } 16016 } 16017 16018 static String getAsecPackageName(String packageCid) { 16019 int idx = packageCid.lastIndexOf("-"); 16020 if (idx == -1) { 16021 return packageCid; 16022 } 16023 return packageCid.substring(0, idx); 16024 } 16025 16026 // Utility method used to create code paths based on package name and available index. 16027 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 16028 String idxStr = ""; 16029 int idx = 1; 16030 // Fall back to default value of idx=1 if prefix is not 16031 // part of oldCodePath 16032 if (oldCodePath != null) { 16033 String subStr = oldCodePath; 16034 // Drop the suffix right away 16035 if (suffix != null && subStr.endsWith(suffix)) { 16036 subStr = subStr.substring(0, subStr.length() - suffix.length()); 16037 } 16038 // If oldCodePath already contains prefix find out the 16039 // ending index to either increment or decrement. 16040 int sidx = subStr.lastIndexOf(prefix); 16041 if (sidx != -1) { 16042 subStr = subStr.substring(sidx + prefix.length()); 16043 if (subStr != null) { 16044 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 16045 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 16046 } 16047 try { 16048 idx = Integer.parseInt(subStr); 16049 if (idx <= 1) { 16050 idx++; 16051 } else { 16052 idx--; 16053 } 16054 } catch(NumberFormatException e) { 16055 } 16056 } 16057 } 16058 } 16059 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16060 return prefix + idxStr; 16061 } 16062 16063 private File getNextCodePath(File targetDir, String packageName) { 16064 File result; 16065 SecureRandom random = new SecureRandom(); 16066 byte[] bytes = new byte[16]; 16067 do { 16068 random.nextBytes(bytes); 16069 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16070 result = new File(targetDir, packageName + "-" + suffix); 16071 } while (result.exists()); 16072 return result; 16073 } 16074 16075 // Utility method that returns the relative package path with respect 16076 // to the installation directory. Like say for /data/data/com.test-1.apk 16077 // string com.test-1 is returned. 16078 static String deriveCodePathName(String codePath) { 16079 if (codePath == null) { 16080 return null; 16081 } 16082 final File codeFile = new File(codePath); 16083 final String name = codeFile.getName(); 16084 if (codeFile.isDirectory()) { 16085 return name; 16086 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16087 final int lastDot = name.lastIndexOf('.'); 16088 return name.substring(0, lastDot); 16089 } else { 16090 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16091 return null; 16092 } 16093 } 16094 16095 static class PackageInstalledInfo { 16096 String name; 16097 int uid; 16098 // The set of users that originally had this package installed. 16099 int[] origUsers; 16100 // The set of users that now have this package installed. 16101 int[] newUsers; 16102 PackageParser.Package pkg; 16103 int returnCode; 16104 String returnMsg; 16105 PackageRemovedInfo removedInfo; 16106 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16107 16108 public void setError(int code, String msg) { 16109 setReturnCode(code); 16110 setReturnMessage(msg); 16111 Slog.w(TAG, msg); 16112 } 16113 16114 public void setError(String msg, PackageParserException e) { 16115 setReturnCode(e.error); 16116 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16117 Slog.w(TAG, msg, e); 16118 } 16119 16120 public void setError(String msg, PackageManagerException e) { 16121 returnCode = e.error; 16122 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16123 Slog.w(TAG, msg, e); 16124 } 16125 16126 public void setReturnCode(int returnCode) { 16127 this.returnCode = returnCode; 16128 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16129 for (int i = 0; i < childCount; i++) { 16130 addedChildPackages.valueAt(i).returnCode = returnCode; 16131 } 16132 } 16133 16134 private void setReturnMessage(String returnMsg) { 16135 this.returnMsg = returnMsg; 16136 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16137 for (int i = 0; i < childCount; i++) { 16138 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16139 } 16140 } 16141 16142 // In some error cases we want to convey more info back to the observer 16143 String origPackage; 16144 String origPermission; 16145 } 16146 16147 /* 16148 * Install a non-existing package. 16149 */ 16150 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 16151 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 16152 PackageInstalledInfo res, int installReason) { 16153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16154 16155 // Remember this for later, in case we need to rollback this install 16156 String pkgName = pkg.packageName; 16157 16158 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16159 16160 synchronized(mPackages) { 16161 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16162 if (renamedPackage != null) { 16163 // A package with the same name is already installed, though 16164 // it has been renamed to an older name. The package we 16165 // are trying to install should be installed as an update to 16166 // the existing one, but that has not been requested, so bail. 16167 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16168 + " without first uninstalling package running as " 16169 + renamedPackage); 16170 return; 16171 } 16172 if (mPackages.containsKey(pkgName)) { 16173 // Don't allow installation over an existing package with the same name. 16174 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16175 + " without first uninstalling."); 16176 return; 16177 } 16178 } 16179 16180 try { 16181 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 16182 System.currentTimeMillis(), user); 16183 16184 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16185 16186 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16187 prepareAppDataAfterInstallLIF(newPackage); 16188 16189 } else { 16190 // Remove package from internal structures, but keep around any 16191 // data that might have already existed 16192 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16193 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16194 } 16195 } catch (PackageManagerException e) { 16196 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16197 } 16198 16199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16200 } 16201 16202 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 16203 // Can't rotate keys during boot or if sharedUser. 16204 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 16205 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 16206 return false; 16207 } 16208 // app is using upgradeKeySets; make sure all are valid 16209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16210 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 16211 for (int i = 0; i < upgradeKeySets.length; i++) { 16212 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 16213 Slog.wtf(TAG, "Package " 16214 + (oldPs.name != null ? oldPs.name : "<null>") 16215 + " contains upgrade-key-set reference to unknown key-set: " 16216 + upgradeKeySets[i] 16217 + " reverting to signatures check."); 16218 return false; 16219 } 16220 } 16221 return true; 16222 } 16223 16224 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 16225 // Upgrade keysets are being used. Determine if new package has a superset of the 16226 // required keys. 16227 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 16228 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16229 for (int i = 0; i < upgradeKeySets.length; i++) { 16230 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 16231 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 16232 return true; 16233 } 16234 } 16235 return false; 16236 } 16237 16238 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16239 try (DigestInputStream digestStream = 16240 new DigestInputStream(new FileInputStream(file), digest)) { 16241 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16242 } 16243 } 16244 16245 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 16246 UserHandle user, String installerPackageName, PackageInstalledInfo res, 16247 int installReason) { 16248 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16249 16250 final PackageParser.Package oldPackage; 16251 final PackageSetting ps; 16252 final String pkgName = pkg.packageName; 16253 final int[] allUsers; 16254 final int[] installedUsers; 16255 16256 synchronized(mPackages) { 16257 oldPackage = mPackages.get(pkgName); 16258 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16259 16260 // don't allow upgrade to target a release SDK from a pre-release SDK 16261 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16262 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16263 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16264 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16265 if (oldTargetsPreRelease 16266 && !newTargetsPreRelease 16267 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16268 Slog.w(TAG, "Can't install package targeting released sdk"); 16269 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16270 return; 16271 } 16272 16273 ps = mSettings.mPackages.get(pkgName); 16274 16275 // verify signatures are valid 16276 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 16277 if (!checkUpgradeKeySetLP(ps, pkg)) { 16278 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16279 "New package not signed by keys specified by upgrade-keysets: " 16280 + pkgName); 16281 return; 16282 } 16283 } else { 16284 // default to original signature matching 16285 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 16286 != PackageManager.SIGNATURE_MATCH) { 16287 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16288 "New package has a different signature: " + pkgName); 16289 return; 16290 } 16291 } 16292 16293 // don't allow a system upgrade unless the upgrade hash matches 16294 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 16295 byte[] digestBytes = null; 16296 try { 16297 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16298 updateDigest(digest, new File(pkg.baseCodePath)); 16299 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16300 for (String path : pkg.splitCodePaths) { 16301 updateDigest(digest, new File(path)); 16302 } 16303 } 16304 digestBytes = digest.digest(); 16305 } catch (NoSuchAlgorithmException | IOException e) { 16306 res.setError(INSTALL_FAILED_INVALID_APK, 16307 "Could not compute hash: " + pkgName); 16308 return; 16309 } 16310 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16311 res.setError(INSTALL_FAILED_INVALID_APK, 16312 "New package fails restrict-update check: " + pkgName); 16313 return; 16314 } 16315 // retain upgrade restriction 16316 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16317 } 16318 16319 // Check for shared user id changes 16320 String invalidPackageName = 16321 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16322 if (invalidPackageName != null) { 16323 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16324 "Package " + invalidPackageName + " tried to change user " 16325 + oldPackage.mSharedUserId); 16326 return; 16327 } 16328 16329 // In case of rollback, remember per-user/profile install state 16330 allUsers = sUserManager.getUserIds(); 16331 installedUsers = ps.queryInstalledUsers(allUsers, true); 16332 16333 // don't allow an upgrade from full to ephemeral 16334 if (isInstantApp) { 16335 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16336 for (int currentUser : allUsers) { 16337 if (!ps.getInstantApp(currentUser)) { 16338 // can't downgrade from full to instant 16339 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16340 + " for user: " + currentUser); 16341 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16342 return; 16343 } 16344 } 16345 } else if (!ps.getInstantApp(user.getIdentifier())) { 16346 // can't downgrade from full to instant 16347 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16348 + " for user: " + user.getIdentifier()); 16349 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16350 return; 16351 } 16352 } 16353 } 16354 16355 // Update what is removed 16356 res.removedInfo = new PackageRemovedInfo(this); 16357 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16358 res.removedInfo.removedPackage = oldPackage.packageName; 16359 res.removedInfo.installerPackageName = ps.installerPackageName; 16360 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16361 res.removedInfo.isUpdate = true; 16362 res.removedInfo.origUsers = installedUsers; 16363 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16364 for (int i = 0; i < installedUsers.length; i++) { 16365 final int userId = installedUsers[i]; 16366 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16367 } 16368 16369 final int childCount = (oldPackage.childPackages != null) 16370 ? oldPackage.childPackages.size() : 0; 16371 for (int i = 0; i < childCount; i++) { 16372 boolean childPackageUpdated = false; 16373 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16374 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16375 if (res.addedChildPackages != null) { 16376 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16377 if (childRes != null) { 16378 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16379 childRes.removedInfo.removedPackage = childPkg.packageName; 16380 if (childPs != null) { 16381 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16382 } 16383 childRes.removedInfo.isUpdate = true; 16384 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16385 childPackageUpdated = true; 16386 } 16387 } 16388 if (!childPackageUpdated) { 16389 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16390 childRemovedRes.removedPackage = childPkg.packageName; 16391 if (childPs != null) { 16392 childRemovedRes.installerPackageName = childPs.installerPackageName; 16393 } 16394 childRemovedRes.isUpdate = false; 16395 childRemovedRes.dataRemoved = true; 16396 synchronized (mPackages) { 16397 if (childPs != null) { 16398 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16399 } 16400 } 16401 if (res.removedInfo.removedChildPackages == null) { 16402 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16403 } 16404 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16405 } 16406 } 16407 16408 boolean sysPkg = (isSystemApp(oldPackage)); 16409 if (sysPkg) { 16410 // Set the system/privileged flags as needed 16411 final boolean privileged = 16412 (oldPackage.applicationInfo.privateFlags 16413 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16414 final int systemPolicyFlags = policyFlags 16415 | PackageParser.PARSE_IS_SYSTEM 16416 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16417 16418 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16419 user, allUsers, installerPackageName, res, installReason); 16420 } else { 16421 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16422 user, allUsers, installerPackageName, res, installReason); 16423 } 16424 } 16425 16426 public List<String> getPreviousCodePaths(String packageName) { 16427 final PackageSetting ps = mSettings.mPackages.get(packageName); 16428 final List<String> result = new ArrayList<String>(); 16429 if (ps != null && ps.oldCodePaths != null) { 16430 result.addAll(ps.oldCodePaths); 16431 } 16432 return result; 16433 } 16434 16435 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16436 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16437 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16438 int installReason) { 16439 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16440 + deletedPackage); 16441 16442 String pkgName = deletedPackage.packageName; 16443 boolean deletedPkg = true; 16444 boolean addedPkg = false; 16445 boolean updatedSettings = false; 16446 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16447 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16448 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16449 16450 final long origUpdateTime = (pkg.mExtras != null) 16451 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16452 16453 // First delete the existing package while retaining the data directory 16454 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16455 res.removedInfo, true, pkg)) { 16456 // If the existing package wasn't successfully deleted 16457 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16458 deletedPkg = false; 16459 } else { 16460 // Successfully deleted the old package; proceed with replace. 16461 16462 // If deleted package lived in a container, give users a chance to 16463 // relinquish resources before killing. 16464 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16465 if (DEBUG_INSTALL) { 16466 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16467 } 16468 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16469 final ArrayList<String> pkgList = new ArrayList<String>(1); 16470 pkgList.add(deletedPackage.applicationInfo.packageName); 16471 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16472 } 16473 16474 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16475 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16476 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16477 16478 try { 16479 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16480 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16481 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16482 installReason); 16483 16484 // Update the in-memory copy of the previous code paths. 16485 PackageSetting ps = mSettings.mPackages.get(pkgName); 16486 if (!killApp) { 16487 if (ps.oldCodePaths == null) { 16488 ps.oldCodePaths = new ArraySet<>(); 16489 } 16490 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16491 if (deletedPackage.splitCodePaths != null) { 16492 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16493 } 16494 } else { 16495 ps.oldCodePaths = null; 16496 } 16497 if (ps.childPackageNames != null) { 16498 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16499 final String childPkgName = ps.childPackageNames.get(i); 16500 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16501 childPs.oldCodePaths = ps.oldCodePaths; 16502 } 16503 } 16504 // set instant app status, but, only if it's explicitly specified 16505 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16506 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16507 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16508 prepareAppDataAfterInstallLIF(newPackage); 16509 addedPkg = true; 16510 mDexManager.notifyPackageUpdated(newPackage.packageName, 16511 newPackage.baseCodePath, newPackage.splitCodePaths); 16512 } catch (PackageManagerException e) { 16513 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16514 } 16515 } 16516 16517 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16518 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16519 16520 // Revert all internal state mutations and added folders for the failed install 16521 if (addedPkg) { 16522 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16523 res.removedInfo, true, null); 16524 } 16525 16526 // Restore the old package 16527 if (deletedPkg) { 16528 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16529 File restoreFile = new File(deletedPackage.codePath); 16530 // Parse old package 16531 boolean oldExternal = isExternal(deletedPackage); 16532 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16533 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16534 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16535 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16536 try { 16537 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16538 null); 16539 } catch (PackageManagerException e) { 16540 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16541 + e.getMessage()); 16542 return; 16543 } 16544 16545 synchronized (mPackages) { 16546 // Ensure the installer package name up to date 16547 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16548 16549 // Update permissions for restored package 16550 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16551 16552 mSettings.writeLPr(); 16553 } 16554 16555 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16556 } 16557 } else { 16558 synchronized (mPackages) { 16559 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16560 if (ps != null) { 16561 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16562 if (res.removedInfo.removedChildPackages != null) { 16563 final int childCount = res.removedInfo.removedChildPackages.size(); 16564 // Iterate in reverse as we may modify the collection 16565 for (int i = childCount - 1; i >= 0; i--) { 16566 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16567 if (res.addedChildPackages.containsKey(childPackageName)) { 16568 res.removedInfo.removedChildPackages.removeAt(i); 16569 } else { 16570 PackageRemovedInfo childInfo = res.removedInfo 16571 .removedChildPackages.valueAt(i); 16572 childInfo.removedForAllUsers = mPackages.get( 16573 childInfo.removedPackage) == null; 16574 } 16575 } 16576 } 16577 } 16578 } 16579 } 16580 } 16581 16582 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16583 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16584 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16585 int installReason) { 16586 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16587 + ", old=" + deletedPackage); 16588 16589 final boolean disabledSystem; 16590 16591 // Remove existing system package 16592 removePackageLI(deletedPackage, true); 16593 16594 synchronized (mPackages) { 16595 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16596 } 16597 if (!disabledSystem) { 16598 // We didn't need to disable the .apk as a current system package, 16599 // which means we are replacing another update that is already 16600 // installed. We need to make sure to delete the older one's .apk. 16601 res.removedInfo.args = createInstallArgsForExisting(0, 16602 deletedPackage.applicationInfo.getCodePath(), 16603 deletedPackage.applicationInfo.getResourcePath(), 16604 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16605 } else { 16606 res.removedInfo.args = null; 16607 } 16608 16609 // Successfully disabled the old package. Now proceed with re-installation 16610 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16611 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16612 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16613 16614 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16615 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16616 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16617 16618 PackageParser.Package newPackage = null; 16619 try { 16620 // Add the package to the internal data structures 16621 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16622 16623 // Set the update and install times 16624 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16625 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16626 System.currentTimeMillis()); 16627 16628 // Update the package dynamic state if succeeded 16629 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16630 // Now that the install succeeded make sure we remove data 16631 // directories for any child package the update removed. 16632 final int deletedChildCount = (deletedPackage.childPackages != null) 16633 ? deletedPackage.childPackages.size() : 0; 16634 final int newChildCount = (newPackage.childPackages != null) 16635 ? newPackage.childPackages.size() : 0; 16636 for (int i = 0; i < deletedChildCount; i++) { 16637 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16638 boolean childPackageDeleted = true; 16639 for (int j = 0; j < newChildCount; j++) { 16640 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16641 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16642 childPackageDeleted = false; 16643 break; 16644 } 16645 } 16646 if (childPackageDeleted) { 16647 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16648 deletedChildPkg.packageName); 16649 if (ps != null && res.removedInfo.removedChildPackages != null) { 16650 PackageRemovedInfo removedChildRes = res.removedInfo 16651 .removedChildPackages.get(deletedChildPkg.packageName); 16652 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16653 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16654 } 16655 } 16656 } 16657 16658 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16659 installReason); 16660 prepareAppDataAfterInstallLIF(newPackage); 16661 16662 mDexManager.notifyPackageUpdated(newPackage.packageName, 16663 newPackage.baseCodePath, newPackage.splitCodePaths); 16664 } 16665 } catch (PackageManagerException e) { 16666 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16667 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16668 } 16669 16670 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16671 // Re installation failed. Restore old information 16672 // Remove new pkg information 16673 if (newPackage != null) { 16674 removeInstalledPackageLI(newPackage, true); 16675 } 16676 // Add back the old system package 16677 try { 16678 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16679 } catch (PackageManagerException e) { 16680 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16681 } 16682 16683 synchronized (mPackages) { 16684 if (disabledSystem) { 16685 enableSystemPackageLPw(deletedPackage); 16686 } 16687 16688 // Ensure the installer package name up to date 16689 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16690 16691 // Update permissions for restored package 16692 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16693 16694 mSettings.writeLPr(); 16695 } 16696 16697 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16698 + " after failed upgrade"); 16699 } 16700 } 16701 16702 /** 16703 * Checks whether the parent or any of the child packages have a change shared 16704 * user. For a package to be a valid update the shred users of the parent and 16705 * the children should match. We may later support changing child shared users. 16706 * @param oldPkg The updated package. 16707 * @param newPkg The update package. 16708 * @return The shared user that change between the versions. 16709 */ 16710 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16711 PackageParser.Package newPkg) { 16712 // Check parent shared user 16713 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16714 return newPkg.packageName; 16715 } 16716 // Check child shared users 16717 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16718 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16719 for (int i = 0; i < newChildCount; i++) { 16720 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16721 // If this child was present, did it have the same shared user? 16722 for (int j = 0; j < oldChildCount; j++) { 16723 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16724 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16725 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16726 return newChildPkg.packageName; 16727 } 16728 } 16729 } 16730 return null; 16731 } 16732 16733 private void removeNativeBinariesLI(PackageSetting ps) { 16734 // Remove the lib path for the parent package 16735 if (ps != null) { 16736 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16737 // Remove the lib path for the child packages 16738 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16739 for (int i = 0; i < childCount; i++) { 16740 PackageSetting childPs = null; 16741 synchronized (mPackages) { 16742 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16743 } 16744 if (childPs != null) { 16745 NativeLibraryHelper.removeNativeBinariesLI(childPs 16746 .legacyNativeLibraryPathString); 16747 } 16748 } 16749 } 16750 } 16751 16752 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16753 // Enable the parent package 16754 mSettings.enableSystemPackageLPw(pkg.packageName); 16755 // Enable the child packages 16756 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16757 for (int i = 0; i < childCount; i++) { 16758 PackageParser.Package childPkg = pkg.childPackages.get(i); 16759 mSettings.enableSystemPackageLPw(childPkg.packageName); 16760 } 16761 } 16762 16763 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16764 PackageParser.Package newPkg) { 16765 // Disable the parent package (parent always replaced) 16766 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16767 // Disable the child packages 16768 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16769 for (int i = 0; i < childCount; i++) { 16770 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16771 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16772 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16773 } 16774 return disabled; 16775 } 16776 16777 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16778 String installerPackageName) { 16779 // Enable the parent package 16780 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16781 // Enable the child packages 16782 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16783 for (int i = 0; i < childCount; i++) { 16784 PackageParser.Package childPkg = pkg.childPackages.get(i); 16785 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16786 } 16787 } 16788 16789 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16790 // Collect all used permissions in the UID 16791 ArraySet<String> usedPermissions = new ArraySet<>(); 16792 final int packageCount = su.packages.size(); 16793 for (int i = 0; i < packageCount; i++) { 16794 PackageSetting ps = su.packages.valueAt(i); 16795 if (ps.pkg == null) { 16796 continue; 16797 } 16798 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16799 for (int j = 0; j < requestedPermCount; j++) { 16800 String permission = ps.pkg.requestedPermissions.get(j); 16801 BasePermission bp = mSettings.mPermissions.get(permission); 16802 if (bp != null) { 16803 usedPermissions.add(permission); 16804 } 16805 } 16806 } 16807 16808 PermissionsState permissionsState = su.getPermissionsState(); 16809 // Prune install permissions 16810 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16811 final int installPermCount = installPermStates.size(); 16812 for (int i = installPermCount - 1; i >= 0; i--) { 16813 PermissionState permissionState = installPermStates.get(i); 16814 if (!usedPermissions.contains(permissionState.getName())) { 16815 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16816 if (bp != null) { 16817 permissionsState.revokeInstallPermission(bp); 16818 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16819 PackageManager.MASK_PERMISSION_FLAGS, 0); 16820 } 16821 } 16822 } 16823 16824 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16825 16826 // Prune runtime permissions 16827 for (int userId : allUserIds) { 16828 List<PermissionState> runtimePermStates = permissionsState 16829 .getRuntimePermissionStates(userId); 16830 final int runtimePermCount = runtimePermStates.size(); 16831 for (int i = runtimePermCount - 1; i >= 0; i--) { 16832 PermissionState permissionState = runtimePermStates.get(i); 16833 if (!usedPermissions.contains(permissionState.getName())) { 16834 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16835 if (bp != null) { 16836 permissionsState.revokeRuntimePermission(bp, userId); 16837 permissionsState.updatePermissionFlags(bp, userId, 16838 PackageManager.MASK_PERMISSION_FLAGS, 0); 16839 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16840 runtimePermissionChangedUserIds, userId); 16841 } 16842 } 16843 } 16844 } 16845 16846 return runtimePermissionChangedUserIds; 16847 } 16848 16849 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16850 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16851 // Update the parent package setting 16852 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16853 res, user, installReason); 16854 // Update the child packages setting 16855 final int childCount = (newPackage.childPackages != null) 16856 ? newPackage.childPackages.size() : 0; 16857 for (int i = 0; i < childCount; i++) { 16858 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16859 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16860 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16861 childRes.origUsers, childRes, user, installReason); 16862 } 16863 } 16864 16865 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16866 String installerPackageName, int[] allUsers, int[] installedForUsers, 16867 PackageInstalledInfo res, UserHandle user, int installReason) { 16868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16869 16870 String pkgName = newPackage.packageName; 16871 synchronized (mPackages) { 16872 //write settings. the installStatus will be incomplete at this stage. 16873 //note that the new package setting would have already been 16874 //added to mPackages. It hasn't been persisted yet. 16875 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16876 // TODO: Remove this write? It's also written at the end of this method 16877 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16878 mSettings.writeLPr(); 16879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16880 } 16881 16882 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16883 synchronized (mPackages) { 16884 updatePermissionsLPw(newPackage.packageName, newPackage, 16885 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16886 ? UPDATE_PERMISSIONS_ALL : 0)); 16887 // For system-bundled packages, we assume that installing an upgraded version 16888 // of the package implies that the user actually wants to run that new code, 16889 // so we enable the package. 16890 PackageSetting ps = mSettings.mPackages.get(pkgName); 16891 final int userId = user.getIdentifier(); 16892 if (ps != null) { 16893 if (isSystemApp(newPackage)) { 16894 if (DEBUG_INSTALL) { 16895 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16896 } 16897 // Enable system package for requested users 16898 if (res.origUsers != null) { 16899 for (int origUserId : res.origUsers) { 16900 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16901 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16902 origUserId, installerPackageName); 16903 } 16904 } 16905 } 16906 // Also convey the prior install/uninstall state 16907 if (allUsers != null && installedForUsers != null) { 16908 for (int currentUserId : allUsers) { 16909 final boolean installed = ArrayUtils.contains( 16910 installedForUsers, currentUserId); 16911 if (DEBUG_INSTALL) { 16912 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16913 } 16914 ps.setInstalled(installed, currentUserId); 16915 } 16916 // these install state changes will be persisted in the 16917 // upcoming call to mSettings.writeLPr(). 16918 } 16919 } 16920 // It's implied that when a user requests installation, they want the app to be 16921 // installed and enabled. 16922 if (userId != UserHandle.USER_ALL) { 16923 ps.setInstalled(true, userId); 16924 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16925 } 16926 16927 // When replacing an existing package, preserve the original install reason for all 16928 // users that had the package installed before. 16929 final Set<Integer> previousUserIds = new ArraySet<>(); 16930 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16931 final int installReasonCount = res.removedInfo.installReasons.size(); 16932 for (int i = 0; i < installReasonCount; i++) { 16933 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16934 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16935 ps.setInstallReason(previousInstallReason, previousUserId); 16936 previousUserIds.add(previousUserId); 16937 } 16938 } 16939 16940 // Set install reason for users that are having the package newly installed. 16941 if (userId == UserHandle.USER_ALL) { 16942 for (int currentUserId : sUserManager.getUserIds()) { 16943 if (!previousUserIds.contains(currentUserId)) { 16944 ps.setInstallReason(installReason, currentUserId); 16945 } 16946 } 16947 } else if (!previousUserIds.contains(userId)) { 16948 ps.setInstallReason(installReason, userId); 16949 } 16950 mSettings.writeKernelMappingLPr(ps); 16951 } 16952 res.name = pkgName; 16953 res.uid = newPackage.applicationInfo.uid; 16954 res.pkg = newPackage; 16955 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16956 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16957 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16958 //to update install status 16959 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16960 mSettings.writeLPr(); 16961 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16962 } 16963 16964 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16965 } 16966 16967 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16968 try { 16969 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16970 installPackageLI(args, res); 16971 } finally { 16972 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16973 } 16974 } 16975 16976 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16977 final int installFlags = args.installFlags; 16978 final String installerPackageName = args.installerPackageName; 16979 final String volumeUuid = args.volumeUuid; 16980 final File tmpPackageFile = new File(args.getCodePath()); 16981 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16982 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16983 || (args.volumeUuid != null)); 16984 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16985 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16986 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16987 boolean replace = false; 16988 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16989 if (args.move != null) { 16990 // moving a complete application; perform an initial scan on the new install location 16991 scanFlags |= SCAN_INITIAL; 16992 } 16993 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16994 scanFlags |= SCAN_DONT_KILL_APP; 16995 } 16996 if (instantApp) { 16997 scanFlags |= SCAN_AS_INSTANT_APP; 16998 } 16999 if (fullApp) { 17000 scanFlags |= SCAN_AS_FULL_APP; 17001 } 17002 17003 // Result object to be returned 17004 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17005 17006 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 17007 17008 // Sanity check 17009 if (instantApp && (forwardLocked || onExternal)) { 17010 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 17011 + " external=" + onExternal); 17012 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17013 return; 17014 } 17015 17016 // Retrieve PackageSettings and parse package 17017 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 17018 | PackageParser.PARSE_ENFORCE_CODE 17019 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 17020 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 17021 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 17022 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 17023 PackageParser pp = new PackageParser(); 17024 pp.setSeparateProcesses(mSeparateProcesses); 17025 pp.setDisplayMetrics(mMetrics); 17026 pp.setCallback(mPackageParserCallback); 17027 17028 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 17029 final PackageParser.Package pkg; 17030 try { 17031 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 17032 } catch (PackageParserException e) { 17033 res.setError("Failed parse during installPackageLI", e); 17034 return; 17035 } finally { 17036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17037 } 17038 17039 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 17040 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 17041 Slog.w(TAG, "Instant app package " + pkg.packageName 17042 + " does not target O, this will be a fatal error."); 17043 // STOPSHIP: Make this a fatal error 17044 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 17045 } 17046 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 17047 Slog.w(TAG, "Instant app package " + pkg.packageName 17048 + " does not target targetSandboxVersion 2, this will be a fatal error."); 17049 // STOPSHIP: Make this a fatal error 17050 pkg.applicationInfo.targetSandboxVersion = 2; 17051 } 17052 17053 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17054 // Static shared libraries have synthetic package names 17055 renameStaticSharedLibraryPackage(pkg); 17056 17057 // No static shared libs on external storage 17058 if (onExternal) { 17059 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17060 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17061 "Packages declaring static-shared libs cannot be updated"); 17062 return; 17063 } 17064 } 17065 17066 // If we are installing a clustered package add results for the children 17067 if (pkg.childPackages != null) { 17068 synchronized (mPackages) { 17069 final int childCount = pkg.childPackages.size(); 17070 for (int i = 0; i < childCount; i++) { 17071 PackageParser.Package childPkg = pkg.childPackages.get(i); 17072 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17073 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17074 childRes.pkg = childPkg; 17075 childRes.name = childPkg.packageName; 17076 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17077 if (childPs != null) { 17078 childRes.origUsers = childPs.queryInstalledUsers( 17079 sUserManager.getUserIds(), true); 17080 } 17081 if ((mPackages.containsKey(childPkg.packageName))) { 17082 childRes.removedInfo = new PackageRemovedInfo(this); 17083 childRes.removedInfo.removedPackage = childPkg.packageName; 17084 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17085 } 17086 if (res.addedChildPackages == null) { 17087 res.addedChildPackages = new ArrayMap<>(); 17088 } 17089 res.addedChildPackages.put(childPkg.packageName, childRes); 17090 } 17091 } 17092 } 17093 17094 // If package doesn't declare API override, mark that we have an install 17095 // time CPU ABI override. 17096 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17097 pkg.cpuAbiOverride = args.abiOverride; 17098 } 17099 17100 String pkgName = res.name = pkg.packageName; 17101 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17102 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17103 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17104 return; 17105 } 17106 } 17107 17108 try { 17109 // either use what we've been given or parse directly from the APK 17110 if (args.certificates != null) { 17111 try { 17112 PackageParser.populateCertificates(pkg, args.certificates); 17113 } catch (PackageParserException e) { 17114 // there was something wrong with the certificates we were given; 17115 // try to pull them from the APK 17116 PackageParser.collectCertificates(pkg, parseFlags); 17117 } 17118 } else { 17119 PackageParser.collectCertificates(pkg, parseFlags); 17120 } 17121 } catch (PackageParserException e) { 17122 res.setError("Failed collect during installPackageLI", e); 17123 return; 17124 } 17125 17126 // Get rid of all references to package scan path via parser. 17127 pp = null; 17128 String oldCodePath = null; 17129 boolean systemApp = false; 17130 synchronized (mPackages) { 17131 // Check if installing already existing package 17132 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17133 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17134 if (pkg.mOriginalPackages != null 17135 && pkg.mOriginalPackages.contains(oldName) 17136 && mPackages.containsKey(oldName)) { 17137 // This package is derived from an original package, 17138 // and this device has been updating from that original 17139 // name. We must continue using the original name, so 17140 // rename the new package here. 17141 pkg.setPackageName(oldName); 17142 pkgName = pkg.packageName; 17143 replace = true; 17144 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17145 + oldName + " pkgName=" + pkgName); 17146 } else if (mPackages.containsKey(pkgName)) { 17147 // This package, under its official name, already exists 17148 // on the device; we should replace it. 17149 replace = true; 17150 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17151 } 17152 17153 // Child packages are installed through the parent package 17154 if (pkg.parentPackage != null) { 17155 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17156 "Package " + pkg.packageName + " is child of package " 17157 + pkg.parentPackage.parentPackage + ". Child packages " 17158 + "can be updated only through the parent package."); 17159 return; 17160 } 17161 17162 if (replace) { 17163 // Prevent apps opting out from runtime permissions 17164 PackageParser.Package oldPackage = mPackages.get(pkgName); 17165 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17166 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17167 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17168 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17169 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17170 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17171 + " doesn't support runtime permissions but the old" 17172 + " target SDK " + oldTargetSdk + " does."); 17173 return; 17174 } 17175 // Prevent apps from downgrading their targetSandbox. 17176 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17177 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17178 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17179 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17180 "Package " + pkg.packageName + " new target sandbox " 17181 + newTargetSandbox + " is incompatible with the previous value of" 17182 + oldTargetSandbox + "."); 17183 return; 17184 } 17185 17186 // Prevent installing of child packages 17187 if (oldPackage.parentPackage != null) { 17188 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17189 "Package " + pkg.packageName + " is child of package " 17190 + oldPackage.parentPackage + ". Child packages " 17191 + "can be updated only through the parent package."); 17192 return; 17193 } 17194 } 17195 } 17196 17197 PackageSetting ps = mSettings.mPackages.get(pkgName); 17198 if (ps != null) { 17199 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17200 17201 // Static shared libs have same package with different versions where 17202 // we internally use a synthetic package name to allow multiple versions 17203 // of the same package, therefore we need to compare signatures against 17204 // the package setting for the latest library version. 17205 PackageSetting signatureCheckPs = ps; 17206 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17207 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17208 if (libraryEntry != null) { 17209 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17210 } 17211 } 17212 17213 // Quick sanity check that we're signed correctly if updating; 17214 // we'll check this again later when scanning, but we want to 17215 // bail early here before tripping over redefined permissions. 17216 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 17217 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 17218 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17219 + pkg.packageName + " upgrade keys do not match the " 17220 + "previously installed version"); 17221 return; 17222 } 17223 } else { 17224 try { 17225 verifySignaturesLP(signatureCheckPs, pkg); 17226 } catch (PackageManagerException e) { 17227 res.setError(e.error, e.getMessage()); 17228 return; 17229 } 17230 } 17231 17232 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17233 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17234 systemApp = (ps.pkg.applicationInfo.flags & 17235 ApplicationInfo.FLAG_SYSTEM) != 0; 17236 } 17237 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17238 } 17239 17240 int N = pkg.permissions.size(); 17241 for (int i = N-1; i >= 0; i--) { 17242 PackageParser.Permission perm = pkg.permissions.get(i); 17243 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 17244 17245 // Don't allow anyone but the system to define ephemeral permissions. 17246 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 17247 && !systemApp) { 17248 Slog.w(TAG, "Non-System package " + pkg.packageName 17249 + " attempting to delcare ephemeral permission " 17250 + perm.info.name + "; Removing ephemeral."); 17251 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 17252 } 17253 // Check whether the newly-scanned package wants to define an already-defined perm 17254 if (bp != null) { 17255 // If the defining package is signed with our cert, it's okay. This 17256 // also includes the "updating the same package" case, of course. 17257 // "updating same package" could also involve key-rotation. 17258 final boolean sigsOk; 17259 if (bp.sourcePackage.equals(pkg.packageName) 17260 && (bp.packageSetting instanceof PackageSetting) 17261 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 17262 scanFlags))) { 17263 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 17264 } else { 17265 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 17266 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 17267 } 17268 if (!sigsOk) { 17269 // If the owning package is the system itself, we log but allow 17270 // install to proceed; we fail the install on all other permission 17271 // redefinitions. 17272 if (!bp.sourcePackage.equals("android")) { 17273 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17274 + pkg.packageName + " attempting to redeclare permission " 17275 + perm.info.name + " already owned by " + bp.sourcePackage); 17276 res.origPermission = perm.info.name; 17277 res.origPackage = bp.sourcePackage; 17278 return; 17279 } else { 17280 Slog.w(TAG, "Package " + pkg.packageName 17281 + " attempting to redeclare system permission " 17282 + perm.info.name + "; ignoring new declaration"); 17283 pkg.permissions.remove(i); 17284 } 17285 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17286 // Prevent apps to change protection level to dangerous from any other 17287 // type as this would allow a privilege escalation where an app adds a 17288 // normal/signature permission in other app's group and later redefines 17289 // it as dangerous leading to the group auto-grant. 17290 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17291 == PermissionInfo.PROTECTION_DANGEROUS) { 17292 if (bp != null && !bp.isRuntime()) { 17293 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17294 + "non-runtime permission " + perm.info.name 17295 + " to runtime; keeping old protection level"); 17296 perm.info.protectionLevel = bp.protectionLevel; 17297 } 17298 } 17299 } 17300 } 17301 } 17302 } 17303 17304 if (systemApp) { 17305 if (onExternal) { 17306 // Abort update; system app can't be replaced with app on sdcard 17307 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17308 "Cannot install updates to system apps on sdcard"); 17309 return; 17310 } else if (instantApp) { 17311 // Abort update; system app can't be replaced with an instant app 17312 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17313 "Cannot update a system app with an instant app"); 17314 return; 17315 } 17316 } 17317 17318 if (args.move != null) { 17319 // We did an in-place move, so dex is ready to roll 17320 scanFlags |= SCAN_NO_DEX; 17321 scanFlags |= SCAN_MOVE; 17322 17323 synchronized (mPackages) { 17324 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17325 if (ps == null) { 17326 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17327 "Missing settings for moved package " + pkgName); 17328 } 17329 17330 // We moved the entire application as-is, so bring over the 17331 // previously derived ABI information. 17332 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17333 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17334 } 17335 17336 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17337 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17338 scanFlags |= SCAN_NO_DEX; 17339 17340 try { 17341 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17342 args.abiOverride : pkg.cpuAbiOverride); 17343 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17344 true /*extractLibs*/, mAppLib32InstallDir); 17345 } catch (PackageManagerException pme) { 17346 Slog.e(TAG, "Error deriving application ABI", pme); 17347 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17348 return; 17349 } 17350 17351 // Shared libraries for the package need to be updated. 17352 synchronized (mPackages) { 17353 try { 17354 updateSharedLibrariesLPr(pkg, null); 17355 } catch (PackageManagerException e) { 17356 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17357 } 17358 } 17359 17360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17361 // Do not run PackageDexOptimizer through the local performDexOpt 17362 // method because `pkg` may not be in `mPackages` yet. 17363 // 17364 // Also, don't fail application installs if the dexopt step fails. 17365 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17366 null /* instructionSets */, false /* checkProfiles */, 17367 getCompilerFilterForReason(REASON_INSTALL), 17368 getOrCreateCompilerPackageStats(pkg), 17369 mDexManager.isUsedByOtherApps(pkg.packageName)); 17370 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17371 17372 // Notify BackgroundDexOptService that the package has been changed. 17373 // If this is an update of a package which used to fail to compile, 17374 // BDOS will remove it from its blacklist. 17375 // TODO: Layering violation 17376 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17377 } 17378 17379 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17380 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17381 return; 17382 } 17383 17384 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17385 17386 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17387 "installPackageLI")) { 17388 if (replace) { 17389 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17390 // Static libs have a synthetic package name containing the version 17391 // and cannot be updated as an update would get a new package name, 17392 // unless this is the exact same version code which is useful for 17393 // development. 17394 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17395 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17396 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17397 + "static-shared libs cannot be updated"); 17398 return; 17399 } 17400 } 17401 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17402 installerPackageName, res, args.installReason); 17403 } else { 17404 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17405 args.user, installerPackageName, volumeUuid, res, args.installReason); 17406 } 17407 } 17408 17409 synchronized (mPackages) { 17410 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17411 if (ps != null) { 17412 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17413 ps.setUpdateAvailable(false /*updateAvailable*/); 17414 } 17415 17416 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17417 for (int i = 0; i < childCount; i++) { 17418 PackageParser.Package childPkg = pkg.childPackages.get(i); 17419 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17420 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17421 if (childPs != null) { 17422 childRes.newUsers = childPs.queryInstalledUsers( 17423 sUserManager.getUserIds(), true); 17424 } 17425 } 17426 17427 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17428 updateSequenceNumberLP(pkgName, res.newUsers); 17429 updateInstantAppInstallerLocked(pkgName); 17430 } 17431 } 17432 } 17433 17434 private void startIntentFilterVerifications(int userId, boolean replacing, 17435 PackageParser.Package pkg) { 17436 if (mIntentFilterVerifierComponent == null) { 17437 Slog.w(TAG, "No IntentFilter verification will not be done as " 17438 + "there is no IntentFilterVerifier available!"); 17439 return; 17440 } 17441 17442 final int verifierUid = getPackageUid( 17443 mIntentFilterVerifierComponent.getPackageName(), 17444 MATCH_DEBUG_TRIAGED_MISSING, 17445 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17446 17447 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17448 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17449 mHandler.sendMessage(msg); 17450 17451 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17452 for (int i = 0; i < childCount; i++) { 17453 PackageParser.Package childPkg = pkg.childPackages.get(i); 17454 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17455 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17456 mHandler.sendMessage(msg); 17457 } 17458 } 17459 17460 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17461 PackageParser.Package pkg) { 17462 int size = pkg.activities.size(); 17463 if (size == 0) { 17464 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17465 "No activity, so no need to verify any IntentFilter!"); 17466 return; 17467 } 17468 17469 final boolean hasDomainURLs = hasDomainURLs(pkg); 17470 if (!hasDomainURLs) { 17471 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17472 "No domain URLs, so no need to verify any IntentFilter!"); 17473 return; 17474 } 17475 17476 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17477 + " if any IntentFilter from the " + size 17478 + " Activities needs verification ..."); 17479 17480 int count = 0; 17481 final String packageName = pkg.packageName; 17482 17483 synchronized (mPackages) { 17484 // If this is a new install and we see that we've already run verification for this 17485 // package, we have nothing to do: it means the state was restored from backup. 17486 if (!replacing) { 17487 IntentFilterVerificationInfo ivi = 17488 mSettings.getIntentFilterVerificationLPr(packageName); 17489 if (ivi != null) { 17490 if (DEBUG_DOMAIN_VERIFICATION) { 17491 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17492 + ivi.getStatusString()); 17493 } 17494 return; 17495 } 17496 } 17497 17498 // If any filters need to be verified, then all need to be. 17499 boolean needToVerify = false; 17500 for (PackageParser.Activity a : pkg.activities) { 17501 for (ActivityIntentInfo filter : a.intents) { 17502 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17503 if (DEBUG_DOMAIN_VERIFICATION) { 17504 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17505 } 17506 needToVerify = true; 17507 break; 17508 } 17509 } 17510 } 17511 17512 if (needToVerify) { 17513 final int verificationId = mIntentFilterVerificationToken++; 17514 for (PackageParser.Activity a : pkg.activities) { 17515 for (ActivityIntentInfo filter : a.intents) { 17516 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17517 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17518 "Verification needed for IntentFilter:" + filter.toString()); 17519 mIntentFilterVerifier.addOneIntentFilterVerification( 17520 verifierUid, userId, verificationId, filter, packageName); 17521 count++; 17522 } 17523 } 17524 } 17525 } 17526 } 17527 17528 if (count > 0) { 17529 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17530 + " IntentFilter verification" + (count > 1 ? "s" : "") 17531 + " for userId:" + userId); 17532 mIntentFilterVerifier.startVerifications(userId); 17533 } else { 17534 if (DEBUG_DOMAIN_VERIFICATION) { 17535 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17536 } 17537 } 17538 } 17539 17540 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17541 final ComponentName cn = filter.activity.getComponentName(); 17542 final String packageName = cn.getPackageName(); 17543 17544 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17545 packageName); 17546 if (ivi == null) { 17547 return true; 17548 } 17549 int status = ivi.getStatus(); 17550 switch (status) { 17551 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17552 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17553 return true; 17554 17555 default: 17556 // Nothing to do 17557 return false; 17558 } 17559 } 17560 17561 private static boolean isMultiArch(ApplicationInfo info) { 17562 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17563 } 17564 17565 private static boolean isExternal(PackageParser.Package pkg) { 17566 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17567 } 17568 17569 private static boolean isExternal(PackageSetting ps) { 17570 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17571 } 17572 17573 private static boolean isSystemApp(PackageParser.Package pkg) { 17574 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17575 } 17576 17577 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17578 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17579 } 17580 17581 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17582 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17583 } 17584 17585 private static boolean isSystemApp(PackageSetting ps) { 17586 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17587 } 17588 17589 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17590 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17591 } 17592 17593 private int packageFlagsToInstallFlags(PackageSetting ps) { 17594 int installFlags = 0; 17595 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17596 // This existing package was an external ASEC install when we have 17597 // the external flag without a UUID 17598 installFlags |= PackageManager.INSTALL_EXTERNAL; 17599 } 17600 if (ps.isForwardLocked()) { 17601 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17602 } 17603 return installFlags; 17604 } 17605 17606 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17607 if (isExternal(pkg)) { 17608 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17609 return StorageManager.UUID_PRIMARY_PHYSICAL; 17610 } else { 17611 return pkg.volumeUuid; 17612 } 17613 } else { 17614 return StorageManager.UUID_PRIVATE_INTERNAL; 17615 } 17616 } 17617 17618 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17619 if (isExternal(pkg)) { 17620 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17621 return mSettings.getExternalVersion(); 17622 } else { 17623 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17624 } 17625 } else { 17626 return mSettings.getInternalVersion(); 17627 } 17628 } 17629 17630 private void deleteTempPackageFiles() { 17631 final FilenameFilter filter = new FilenameFilter() { 17632 public boolean accept(File dir, String name) { 17633 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17634 } 17635 }; 17636 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17637 file.delete(); 17638 } 17639 } 17640 17641 @Override 17642 public void deletePackageAsUser(String packageName, int versionCode, 17643 IPackageDeleteObserver observer, int userId, int flags) { 17644 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17645 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17646 } 17647 17648 @Override 17649 public void deletePackageVersioned(VersionedPackage versionedPackage, 17650 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17651 mContext.enforceCallingOrSelfPermission( 17652 android.Manifest.permission.DELETE_PACKAGES, null); 17653 Preconditions.checkNotNull(versionedPackage); 17654 Preconditions.checkNotNull(observer); 17655 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17656 PackageManager.VERSION_CODE_HIGHEST, 17657 Integer.MAX_VALUE, "versionCode must be >= -1"); 17658 17659 final String packageName = versionedPackage.getPackageName(); 17660 // TODO: We will change version code to long, so in the new API it is long 17661 final int versionCode = (int) versionedPackage.getVersionCode(); 17662 final String internalPackageName; 17663 synchronized (mPackages) { 17664 // Normalize package name to handle renamed packages and static libs 17665 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17666 // TODO: We will change version code to long, so in the new API it is long 17667 (int) versionedPackage.getVersionCode()); 17668 } 17669 17670 final int uid = Binder.getCallingUid(); 17671 if (!isOrphaned(internalPackageName) 17672 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17673 try { 17674 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17675 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17676 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17677 observer.onUserActionRequired(intent); 17678 } catch (RemoteException re) { 17679 } 17680 return; 17681 } 17682 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17683 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17684 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17685 mContext.enforceCallingOrSelfPermission( 17686 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17687 "deletePackage for user " + userId); 17688 } 17689 17690 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17691 try { 17692 observer.onPackageDeleted(packageName, 17693 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17694 } catch (RemoteException re) { 17695 } 17696 return; 17697 } 17698 17699 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17700 try { 17701 observer.onPackageDeleted(packageName, 17702 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17703 } catch (RemoteException re) { 17704 } 17705 return; 17706 } 17707 17708 if (DEBUG_REMOVE) { 17709 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17710 + " deleteAllUsers: " + deleteAllUsers + " version=" 17711 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17712 ? "VERSION_CODE_HIGHEST" : versionCode)); 17713 } 17714 // Queue up an async operation since the package deletion may take a little while. 17715 mHandler.post(new Runnable() { 17716 public void run() { 17717 mHandler.removeCallbacks(this); 17718 int returnCode; 17719 if (!deleteAllUsers) { 17720 returnCode = deletePackageX(internalPackageName, versionCode, 17721 userId, deleteFlags); 17722 } else { 17723 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17724 internalPackageName, users); 17725 // If nobody is blocking uninstall, proceed with delete for all users 17726 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17727 returnCode = deletePackageX(internalPackageName, versionCode, 17728 userId, deleteFlags); 17729 } else { 17730 // Otherwise uninstall individually for users with blockUninstalls=false 17731 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17732 for (int userId : users) { 17733 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17734 returnCode = deletePackageX(internalPackageName, versionCode, 17735 userId, userFlags); 17736 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17737 Slog.w(TAG, "Package delete failed for user " + userId 17738 + ", returnCode " + returnCode); 17739 } 17740 } 17741 } 17742 // The app has only been marked uninstalled for certain users. 17743 // We still need to report that delete was blocked 17744 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17745 } 17746 } 17747 try { 17748 observer.onPackageDeleted(packageName, returnCode, null); 17749 } catch (RemoteException e) { 17750 Log.i(TAG, "Observer no longer exists."); 17751 } //end catch 17752 } //end run 17753 }); 17754 } 17755 17756 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17757 if (pkg.staticSharedLibName != null) { 17758 return pkg.manifestPackageName; 17759 } 17760 return pkg.packageName; 17761 } 17762 17763 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17764 // Handle renamed packages 17765 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17766 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17767 17768 // Is this a static library? 17769 SparseArray<SharedLibraryEntry> versionedLib = 17770 mStaticLibsByDeclaringPackage.get(packageName); 17771 if (versionedLib == null || versionedLib.size() <= 0) { 17772 return packageName; 17773 } 17774 17775 // Figure out which lib versions the caller can see 17776 SparseIntArray versionsCallerCanSee = null; 17777 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17778 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17779 && callingAppId != Process.ROOT_UID) { 17780 versionsCallerCanSee = new SparseIntArray(); 17781 String libName = versionedLib.valueAt(0).info.getName(); 17782 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17783 if (uidPackages != null) { 17784 for (String uidPackage : uidPackages) { 17785 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17786 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17787 if (libIdx >= 0) { 17788 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17789 versionsCallerCanSee.append(libVersion, libVersion); 17790 } 17791 } 17792 } 17793 } 17794 17795 // Caller can see nothing - done 17796 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17797 return packageName; 17798 } 17799 17800 // Find the version the caller can see and the app version code 17801 SharedLibraryEntry highestVersion = null; 17802 final int versionCount = versionedLib.size(); 17803 for (int i = 0; i < versionCount; i++) { 17804 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17805 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17806 libEntry.info.getVersion()) < 0) { 17807 continue; 17808 } 17809 // TODO: We will change version code to long, so in the new API it is long 17810 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17811 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17812 if (libVersionCode == versionCode) { 17813 return libEntry.apk; 17814 } 17815 } else if (highestVersion == null) { 17816 highestVersion = libEntry; 17817 } else if (libVersionCode > highestVersion.info 17818 .getDeclaringPackage().getVersionCode()) { 17819 highestVersion = libEntry; 17820 } 17821 } 17822 17823 if (highestVersion != null) { 17824 return highestVersion.apk; 17825 } 17826 17827 return packageName; 17828 } 17829 17830 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17831 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17832 || callingUid == Process.SYSTEM_UID) { 17833 return true; 17834 } 17835 final int callingUserId = UserHandle.getUserId(callingUid); 17836 // If the caller installed the pkgName, then allow it to silently uninstall. 17837 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17838 return true; 17839 } 17840 17841 // Allow package verifier to silently uninstall. 17842 if (mRequiredVerifierPackage != null && 17843 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17844 return true; 17845 } 17846 17847 // Allow package uninstaller to silently uninstall. 17848 if (mRequiredUninstallerPackage != null && 17849 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17850 return true; 17851 } 17852 17853 // Allow storage manager to silently uninstall. 17854 if (mStorageManagerPackage != null && 17855 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17856 return true; 17857 } 17858 return false; 17859 } 17860 17861 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17862 int[] result = EMPTY_INT_ARRAY; 17863 for (int userId : userIds) { 17864 if (getBlockUninstallForUser(packageName, userId)) { 17865 result = ArrayUtils.appendInt(result, userId); 17866 } 17867 } 17868 return result; 17869 } 17870 17871 @Override 17872 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17873 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17874 } 17875 17876 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17877 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17878 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17879 try { 17880 if (dpm != null) { 17881 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17882 /* callingUserOnly =*/ false); 17883 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17884 : deviceOwnerComponentName.getPackageName(); 17885 // Does the package contains the device owner? 17886 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17887 // this check is probably not needed, since DO should be registered as a device 17888 // admin on some user too. (Original bug for this: b/17657954) 17889 if (packageName.equals(deviceOwnerPackageName)) { 17890 return true; 17891 } 17892 // Does it contain a device admin for any user? 17893 int[] users; 17894 if (userId == UserHandle.USER_ALL) { 17895 users = sUserManager.getUserIds(); 17896 } else { 17897 users = new int[]{userId}; 17898 } 17899 for (int i = 0; i < users.length; ++i) { 17900 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17901 return true; 17902 } 17903 } 17904 } 17905 } catch (RemoteException e) { 17906 } 17907 return false; 17908 } 17909 17910 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17911 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17912 } 17913 17914 /** 17915 * This method is an internal method that could be get invoked either 17916 * to delete an installed package or to clean up a failed installation. 17917 * After deleting an installed package, a broadcast is sent to notify any 17918 * listeners that the package has been removed. For cleaning up a failed 17919 * installation, the broadcast is not necessary since the package's 17920 * installation wouldn't have sent the initial broadcast either 17921 * The key steps in deleting a package are 17922 * deleting the package information in internal structures like mPackages, 17923 * deleting the packages base directories through installd 17924 * updating mSettings to reflect current status 17925 * persisting settings for later use 17926 * sending a broadcast if necessary 17927 */ 17928 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17929 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17930 final boolean res; 17931 17932 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17933 ? UserHandle.USER_ALL : userId; 17934 17935 if (isPackageDeviceAdmin(packageName, removeUser)) { 17936 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17937 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17938 } 17939 17940 PackageSetting uninstalledPs = null; 17941 PackageParser.Package pkg = null; 17942 17943 // for the uninstall-updates case and restricted profiles, remember the per- 17944 // user handle installed state 17945 int[] allUsers; 17946 synchronized (mPackages) { 17947 uninstalledPs = mSettings.mPackages.get(packageName); 17948 if (uninstalledPs == null) { 17949 Slog.w(TAG, "Not removing non-existent package " + packageName); 17950 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17951 } 17952 17953 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17954 && uninstalledPs.versionCode != versionCode) { 17955 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17956 + uninstalledPs.versionCode + " != " + versionCode); 17957 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17958 } 17959 17960 // Static shared libs can be declared by any package, so let us not 17961 // allow removing a package if it provides a lib others depend on. 17962 pkg = mPackages.get(packageName); 17963 if (pkg != null && pkg.staticSharedLibName != null) { 17964 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17965 pkg.staticSharedLibVersion); 17966 if (libEntry != null) { 17967 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17968 libEntry.info, 0, userId); 17969 if (!ArrayUtils.isEmpty(libClientPackages)) { 17970 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17971 + " hosting lib " + libEntry.info.getName() + " version " 17972 + libEntry.info.getVersion() + " used by " + libClientPackages); 17973 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17974 } 17975 } 17976 } 17977 17978 allUsers = sUserManager.getUserIds(); 17979 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17980 } 17981 17982 final int freezeUser; 17983 if (isUpdatedSystemApp(uninstalledPs) 17984 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17985 // We're downgrading a system app, which will apply to all users, so 17986 // freeze them all during the downgrade 17987 freezeUser = UserHandle.USER_ALL; 17988 } else { 17989 freezeUser = removeUser; 17990 } 17991 17992 synchronized (mInstallLock) { 17993 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17994 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17995 deleteFlags, "deletePackageX")) { 17996 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17997 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17998 } 17999 synchronized (mPackages) { 18000 if (res) { 18001 if (pkg != null) { 18002 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18003 } 18004 updateSequenceNumberLP(packageName, info.removedUsers); 18005 updateInstantAppInstallerLocked(packageName); 18006 } 18007 } 18008 } 18009 18010 if (res) { 18011 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18012 info.sendPackageRemovedBroadcasts(killApp); 18013 info.sendSystemPackageUpdatedBroadcasts(); 18014 info.sendSystemPackageAppearedBroadcasts(); 18015 } 18016 // Force a gc here. 18017 Runtime.getRuntime().gc(); 18018 // Delete the resources here after sending the broadcast to let 18019 // other processes clean up before deleting resources. 18020 if (info.args != null) { 18021 synchronized (mInstallLock) { 18022 info.args.doPostDeleteLI(true); 18023 } 18024 } 18025 18026 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18027 } 18028 18029 static class PackageRemovedInfo { 18030 final PackageSender packageSender; 18031 String removedPackage; 18032 String installerPackageName; 18033 int uid = -1; 18034 int removedAppId = -1; 18035 int[] origUsers; 18036 int[] removedUsers = null; 18037 int[] broadcastUsers = null; 18038 SparseArray<Integer> installReasons; 18039 boolean isRemovedPackageSystemUpdate = false; 18040 boolean isUpdate; 18041 boolean dataRemoved; 18042 boolean removedForAllUsers; 18043 boolean isStaticSharedLib; 18044 // Clean up resources deleted packages. 18045 InstallArgs args = null; 18046 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18047 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18048 18049 PackageRemovedInfo(PackageSender packageSender) { 18050 this.packageSender = packageSender; 18051 } 18052 18053 void sendPackageRemovedBroadcasts(boolean killApp) { 18054 sendPackageRemovedBroadcastInternal(killApp); 18055 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18056 for (int i = 0; i < childCount; i++) { 18057 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18058 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18059 } 18060 } 18061 18062 void sendSystemPackageUpdatedBroadcasts() { 18063 if (isRemovedPackageSystemUpdate) { 18064 sendSystemPackageUpdatedBroadcastsInternal(); 18065 final int childCount = (removedChildPackages != null) 18066 ? removedChildPackages.size() : 0; 18067 for (int i = 0; i < childCount; i++) { 18068 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18069 if (childInfo.isRemovedPackageSystemUpdate) { 18070 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18071 } 18072 } 18073 } 18074 } 18075 18076 void sendSystemPackageAppearedBroadcasts() { 18077 final int packageCount = (appearedChildPackages != null) 18078 ? appearedChildPackages.size() : 0; 18079 for (int i = 0; i < packageCount; i++) { 18080 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18081 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18082 true, UserHandle.getAppId(installedInfo.uid), 18083 installedInfo.newUsers); 18084 } 18085 } 18086 18087 private void sendSystemPackageUpdatedBroadcastsInternal() { 18088 Bundle extras = new Bundle(2); 18089 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18090 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18091 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18092 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18093 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18094 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18095 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18096 null, null, 0, removedPackage, null, null); 18097 if (installerPackageName != null) { 18098 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18099 removedPackage, extras, 0 /*flags*/, 18100 installerPackageName, null, null); 18101 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18102 removedPackage, extras, 0 /*flags*/, 18103 installerPackageName, null, null); 18104 } 18105 } 18106 18107 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18108 // Don't send static shared library removal broadcasts as these 18109 // libs are visible only the the apps that depend on them an one 18110 // cannot remove the library if it has a dependency. 18111 if (isStaticSharedLib) { 18112 return; 18113 } 18114 Bundle extras = new Bundle(2); 18115 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18116 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18117 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18118 if (isUpdate || isRemovedPackageSystemUpdate) { 18119 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18120 } 18121 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18122 if (removedPackage != null) { 18123 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18124 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 18125 if (installerPackageName != null) { 18126 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18127 removedPackage, extras, 0 /*flags*/, 18128 installerPackageName, null, broadcastUsers); 18129 } 18130 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18131 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18132 removedPackage, extras, 18133 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18134 null, null, broadcastUsers); 18135 } 18136 } 18137 if (removedAppId >= 0) { 18138 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 18139 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers); 18140 } 18141 } 18142 18143 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18144 removedUsers = userIds; 18145 if (removedUsers == null) { 18146 broadcastUsers = null; 18147 return; 18148 } 18149 18150 broadcastUsers = EMPTY_INT_ARRAY; 18151 for (int i = userIds.length - 1; i >= 0; --i) { 18152 final int userId = userIds[i]; 18153 if (deletedPackageSetting.getInstantApp(userId)) { 18154 continue; 18155 } 18156 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18157 } 18158 } 18159 } 18160 18161 /* 18162 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18163 * flag is not set, the data directory is removed as well. 18164 * make sure this flag is set for partially installed apps. If not its meaningless to 18165 * delete a partially installed application. 18166 */ 18167 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18168 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18169 String packageName = ps.name; 18170 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18171 // Retrieve object to delete permissions for shared user later on 18172 final PackageParser.Package deletedPkg; 18173 final PackageSetting deletedPs; 18174 // reader 18175 synchronized (mPackages) { 18176 deletedPkg = mPackages.get(packageName); 18177 deletedPs = mSettings.mPackages.get(packageName); 18178 if (outInfo != null) { 18179 outInfo.removedPackage = packageName; 18180 outInfo.installerPackageName = ps.installerPackageName; 18181 outInfo.isStaticSharedLib = deletedPkg != null 18182 && deletedPkg.staticSharedLibName != null; 18183 outInfo.populateUsers(deletedPs == null ? null 18184 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18185 } 18186 } 18187 18188 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 18189 18190 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18191 final PackageParser.Package resolvedPkg; 18192 if (deletedPkg != null) { 18193 resolvedPkg = deletedPkg; 18194 } else { 18195 // We don't have a parsed package when it lives on an ejected 18196 // adopted storage device, so fake something together 18197 resolvedPkg = new PackageParser.Package(ps.name); 18198 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18199 } 18200 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18201 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18202 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18203 if (outInfo != null) { 18204 outInfo.dataRemoved = true; 18205 } 18206 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18207 } 18208 18209 int removedAppId = -1; 18210 18211 // writer 18212 synchronized (mPackages) { 18213 boolean installedStateChanged = false; 18214 if (deletedPs != null) { 18215 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18216 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18217 clearDefaultBrowserIfNeeded(packageName); 18218 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18219 removedAppId = mSettings.removePackageLPw(packageName); 18220 if (outInfo != null) { 18221 outInfo.removedAppId = removedAppId; 18222 } 18223 updatePermissionsLPw(deletedPs.name, null, 0); 18224 if (deletedPs.sharedUser != null) { 18225 // Remove permissions associated with package. Since runtime 18226 // permissions are per user we have to kill the removed package 18227 // or packages running under the shared user of the removed 18228 // package if revoking the permissions requested only by the removed 18229 // package is successful and this causes a change in gids. 18230 for (int userId : UserManagerService.getInstance().getUserIds()) { 18231 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18232 userId); 18233 if (userIdToKill == UserHandle.USER_ALL 18234 || userIdToKill >= UserHandle.USER_SYSTEM) { 18235 // If gids changed for this user, kill all affected packages. 18236 mHandler.post(new Runnable() { 18237 @Override 18238 public void run() { 18239 // This has to happen with no lock held. 18240 killApplication(deletedPs.name, deletedPs.appId, 18241 KILL_APP_REASON_GIDS_CHANGED); 18242 } 18243 }); 18244 break; 18245 } 18246 } 18247 } 18248 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18249 } 18250 // make sure to preserve per-user disabled state if this removal was just 18251 // a downgrade of a system app to the factory package 18252 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18253 if (DEBUG_REMOVE) { 18254 Slog.d(TAG, "Propagating install state across downgrade"); 18255 } 18256 for (int userId : allUserHandles) { 18257 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18258 if (DEBUG_REMOVE) { 18259 Slog.d(TAG, " user " + userId + " => " + installed); 18260 } 18261 if (installed != ps.getInstalled(userId)) { 18262 installedStateChanged = true; 18263 } 18264 ps.setInstalled(installed, userId); 18265 } 18266 } 18267 } 18268 // can downgrade to reader 18269 if (writeSettings) { 18270 // Save settings now 18271 mSettings.writeLPr(); 18272 } 18273 if (installedStateChanged) { 18274 mSettings.writeKernelMappingLPr(ps); 18275 } 18276 } 18277 if (removedAppId != -1) { 18278 // A user ID was deleted here. Go through all users and remove it 18279 // from KeyStore. 18280 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18281 } 18282 } 18283 18284 static boolean locationIsPrivileged(File path) { 18285 try { 18286 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 18287 .getCanonicalPath(); 18288 return path.getCanonicalPath().startsWith(privilegedAppDir); 18289 } catch (IOException e) { 18290 Slog.e(TAG, "Unable to access code path " + path); 18291 } 18292 return false; 18293 } 18294 18295 /* 18296 * Tries to delete system package. 18297 */ 18298 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18299 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18300 boolean writeSettings) { 18301 if (deletedPs.parentPackageName != null) { 18302 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18303 return false; 18304 } 18305 18306 final boolean applyUserRestrictions 18307 = (allUserHandles != null) && (outInfo.origUsers != null); 18308 final PackageSetting disabledPs; 18309 // Confirm if the system package has been updated 18310 // An updated system app can be deleted. This will also have to restore 18311 // the system pkg from system partition 18312 // reader 18313 synchronized (mPackages) { 18314 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18315 } 18316 18317 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18318 + " disabledPs=" + disabledPs); 18319 18320 if (disabledPs == null) { 18321 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18322 return false; 18323 } else if (DEBUG_REMOVE) { 18324 Slog.d(TAG, "Deleting system pkg from data partition"); 18325 } 18326 18327 if (DEBUG_REMOVE) { 18328 if (applyUserRestrictions) { 18329 Slog.d(TAG, "Remembering install states:"); 18330 for (int userId : allUserHandles) { 18331 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18332 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18333 } 18334 } 18335 } 18336 18337 // Delete the updated package 18338 outInfo.isRemovedPackageSystemUpdate = true; 18339 if (outInfo.removedChildPackages != null) { 18340 final int childCount = (deletedPs.childPackageNames != null) 18341 ? deletedPs.childPackageNames.size() : 0; 18342 for (int i = 0; i < childCount; i++) { 18343 String childPackageName = deletedPs.childPackageNames.get(i); 18344 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18345 .contains(childPackageName)) { 18346 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18347 childPackageName); 18348 if (childInfo != null) { 18349 childInfo.isRemovedPackageSystemUpdate = true; 18350 } 18351 } 18352 } 18353 } 18354 18355 if (disabledPs.versionCode < deletedPs.versionCode) { 18356 // Delete data for downgrades 18357 flags &= ~PackageManager.DELETE_KEEP_DATA; 18358 } else { 18359 // Preserve data by setting flag 18360 flags |= PackageManager.DELETE_KEEP_DATA; 18361 } 18362 18363 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18364 outInfo, writeSettings, disabledPs.pkg); 18365 if (!ret) { 18366 return false; 18367 } 18368 18369 // writer 18370 synchronized (mPackages) { 18371 // Reinstate the old system package 18372 enableSystemPackageLPw(disabledPs.pkg); 18373 // Remove any native libraries from the upgraded package. 18374 removeNativeBinariesLI(deletedPs); 18375 } 18376 18377 // Install the system package 18378 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18379 int parseFlags = mDefParseFlags 18380 | PackageParser.PARSE_MUST_BE_APK 18381 | PackageParser.PARSE_IS_SYSTEM 18382 | PackageParser.PARSE_IS_SYSTEM_DIR; 18383 if (locationIsPrivileged(disabledPs.codePath)) { 18384 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18385 } 18386 18387 final PackageParser.Package newPkg; 18388 try { 18389 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18390 0 /* currentTime */, null); 18391 } catch (PackageManagerException e) { 18392 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18393 + e.getMessage()); 18394 return false; 18395 } 18396 18397 try { 18398 // update shared libraries for the newly re-installed system package 18399 updateSharedLibrariesLPr(newPkg, null); 18400 } catch (PackageManagerException e) { 18401 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18402 } 18403 18404 prepareAppDataAfterInstallLIF(newPkg); 18405 18406 // writer 18407 synchronized (mPackages) { 18408 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18409 18410 // Propagate the permissions state as we do not want to drop on the floor 18411 // runtime permissions. The update permissions method below will take 18412 // care of removing obsolete permissions and grant install permissions. 18413 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18414 updatePermissionsLPw(newPkg.packageName, newPkg, 18415 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18416 18417 if (applyUserRestrictions) { 18418 boolean installedStateChanged = false; 18419 if (DEBUG_REMOVE) { 18420 Slog.d(TAG, "Propagating install state across reinstall"); 18421 } 18422 for (int userId : allUserHandles) { 18423 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18424 if (DEBUG_REMOVE) { 18425 Slog.d(TAG, " user " + userId + " => " + installed); 18426 } 18427 if (installed != ps.getInstalled(userId)) { 18428 installedStateChanged = true; 18429 } 18430 ps.setInstalled(installed, userId); 18431 18432 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18433 } 18434 // Regardless of writeSettings we need to ensure that this restriction 18435 // state propagation is persisted 18436 mSettings.writeAllUsersPackageRestrictionsLPr(); 18437 if (installedStateChanged) { 18438 mSettings.writeKernelMappingLPr(ps); 18439 } 18440 } 18441 // can downgrade to reader here 18442 if (writeSettings) { 18443 mSettings.writeLPr(); 18444 } 18445 } 18446 return true; 18447 } 18448 18449 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18450 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18451 PackageRemovedInfo outInfo, boolean writeSettings, 18452 PackageParser.Package replacingPackage) { 18453 synchronized (mPackages) { 18454 if (outInfo != null) { 18455 outInfo.uid = ps.appId; 18456 } 18457 18458 if (outInfo != null && outInfo.removedChildPackages != null) { 18459 final int childCount = (ps.childPackageNames != null) 18460 ? ps.childPackageNames.size() : 0; 18461 for (int i = 0; i < childCount; i++) { 18462 String childPackageName = ps.childPackageNames.get(i); 18463 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18464 if (childPs == null) { 18465 return false; 18466 } 18467 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18468 childPackageName); 18469 if (childInfo != null) { 18470 childInfo.uid = childPs.appId; 18471 } 18472 } 18473 } 18474 } 18475 18476 // Delete package data from internal structures and also remove data if flag is set 18477 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18478 18479 // Delete the child packages data 18480 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18481 for (int i = 0; i < childCount; i++) { 18482 PackageSetting childPs; 18483 synchronized (mPackages) { 18484 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18485 } 18486 if (childPs != null) { 18487 PackageRemovedInfo childOutInfo = (outInfo != null 18488 && outInfo.removedChildPackages != null) 18489 ? outInfo.removedChildPackages.get(childPs.name) : null; 18490 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18491 && (replacingPackage != null 18492 && !replacingPackage.hasChildPackage(childPs.name)) 18493 ? flags & ~DELETE_KEEP_DATA : flags; 18494 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18495 deleteFlags, writeSettings); 18496 } 18497 } 18498 18499 // Delete application code and resources only for parent packages 18500 if (ps.parentPackageName == null) { 18501 if (deleteCodeAndResources && (outInfo != null)) { 18502 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18503 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18504 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18505 } 18506 } 18507 18508 return true; 18509 } 18510 18511 @Override 18512 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18513 int userId) { 18514 mContext.enforceCallingOrSelfPermission( 18515 android.Manifest.permission.DELETE_PACKAGES, null); 18516 synchronized (mPackages) { 18517 // Cannot block uninstall of static shared libs as they are 18518 // considered a part of the using app (emulating static linking). 18519 // Also static libs are installed always on internal storage. 18520 PackageParser.Package pkg = mPackages.get(packageName); 18521 if (pkg != null && pkg.staticSharedLibName != null) { 18522 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18523 + " providing static shared library: " + pkg.staticSharedLibName); 18524 return false; 18525 } 18526 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18527 mSettings.writePackageRestrictionsLPr(userId); 18528 } 18529 return true; 18530 } 18531 18532 @Override 18533 public boolean getBlockUninstallForUser(String packageName, int userId) { 18534 synchronized (mPackages) { 18535 return mSettings.getBlockUninstallLPr(userId, packageName); 18536 } 18537 } 18538 18539 @Override 18540 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18541 int callingUid = Binder.getCallingUid(); 18542 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18543 throw new SecurityException( 18544 "setRequiredForSystemUser can only be run by the system or root"); 18545 } 18546 synchronized (mPackages) { 18547 PackageSetting ps = mSettings.mPackages.get(packageName); 18548 if (ps == null) { 18549 Log.w(TAG, "Package doesn't exist: " + packageName); 18550 return false; 18551 } 18552 if (systemUserApp) { 18553 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18554 } else { 18555 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18556 } 18557 mSettings.writeLPr(); 18558 } 18559 return true; 18560 } 18561 18562 /* 18563 * This method handles package deletion in general 18564 */ 18565 private boolean deletePackageLIF(String packageName, UserHandle user, 18566 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18567 PackageRemovedInfo outInfo, boolean writeSettings, 18568 PackageParser.Package replacingPackage) { 18569 if (packageName == null) { 18570 Slog.w(TAG, "Attempt to delete null packageName."); 18571 return false; 18572 } 18573 18574 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18575 18576 PackageSetting ps; 18577 synchronized (mPackages) { 18578 ps = mSettings.mPackages.get(packageName); 18579 if (ps == null) { 18580 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18581 return false; 18582 } 18583 18584 if (ps.parentPackageName != null && (!isSystemApp(ps) 18585 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18586 if (DEBUG_REMOVE) { 18587 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18588 + ((user == null) ? UserHandle.USER_ALL : user)); 18589 } 18590 final int removedUserId = (user != null) ? user.getIdentifier() 18591 : UserHandle.USER_ALL; 18592 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18593 return false; 18594 } 18595 markPackageUninstalledForUserLPw(ps, user); 18596 scheduleWritePackageRestrictionsLocked(user); 18597 return true; 18598 } 18599 } 18600 18601 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18602 && user.getIdentifier() != UserHandle.USER_ALL)) { 18603 // The caller is asking that the package only be deleted for a single 18604 // user. To do this, we just mark its uninstalled state and delete 18605 // its data. If this is a system app, we only allow this to happen if 18606 // they have set the special DELETE_SYSTEM_APP which requests different 18607 // semantics than normal for uninstalling system apps. 18608 markPackageUninstalledForUserLPw(ps, user); 18609 18610 if (!isSystemApp(ps)) { 18611 // Do not uninstall the APK if an app should be cached 18612 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18613 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18614 // Other user still have this package installed, so all 18615 // we need to do is clear this user's data and save that 18616 // it is uninstalled. 18617 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18618 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18619 return false; 18620 } 18621 scheduleWritePackageRestrictionsLocked(user); 18622 return true; 18623 } else { 18624 // We need to set it back to 'installed' so the uninstall 18625 // broadcasts will be sent correctly. 18626 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18627 ps.setInstalled(true, user.getIdentifier()); 18628 mSettings.writeKernelMappingLPr(ps); 18629 } 18630 } else { 18631 // This is a system app, so we assume that the 18632 // other users still have this package installed, so all 18633 // we need to do is clear this user's data and save that 18634 // it is uninstalled. 18635 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18636 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18637 return false; 18638 } 18639 scheduleWritePackageRestrictionsLocked(user); 18640 return true; 18641 } 18642 } 18643 18644 // If we are deleting a composite package for all users, keep track 18645 // of result for each child. 18646 if (ps.childPackageNames != null && outInfo != null) { 18647 synchronized (mPackages) { 18648 final int childCount = ps.childPackageNames.size(); 18649 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18650 for (int i = 0; i < childCount; i++) { 18651 String childPackageName = ps.childPackageNames.get(i); 18652 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18653 childInfo.removedPackage = childPackageName; 18654 childInfo.installerPackageName = ps.installerPackageName; 18655 outInfo.removedChildPackages.put(childPackageName, childInfo); 18656 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18657 if (childPs != null) { 18658 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18659 } 18660 } 18661 } 18662 } 18663 18664 boolean ret = false; 18665 if (isSystemApp(ps)) { 18666 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18667 // When an updated system application is deleted we delete the existing resources 18668 // as well and fall back to existing code in system partition 18669 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18670 } else { 18671 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18672 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18673 outInfo, writeSettings, replacingPackage); 18674 } 18675 18676 // Take a note whether we deleted the package for all users 18677 if (outInfo != null) { 18678 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18679 if (outInfo.removedChildPackages != null) { 18680 synchronized (mPackages) { 18681 final int childCount = outInfo.removedChildPackages.size(); 18682 for (int i = 0; i < childCount; i++) { 18683 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18684 if (childInfo != null) { 18685 childInfo.removedForAllUsers = mPackages.get( 18686 childInfo.removedPackage) == null; 18687 } 18688 } 18689 } 18690 } 18691 // If we uninstalled an update to a system app there may be some 18692 // child packages that appeared as they are declared in the system 18693 // app but were not declared in the update. 18694 if (isSystemApp(ps)) { 18695 synchronized (mPackages) { 18696 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18697 final int childCount = (updatedPs.childPackageNames != null) 18698 ? updatedPs.childPackageNames.size() : 0; 18699 for (int i = 0; i < childCount; i++) { 18700 String childPackageName = updatedPs.childPackageNames.get(i); 18701 if (outInfo.removedChildPackages == null 18702 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18703 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18704 if (childPs == null) { 18705 continue; 18706 } 18707 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18708 installRes.name = childPackageName; 18709 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18710 installRes.pkg = mPackages.get(childPackageName); 18711 installRes.uid = childPs.pkg.applicationInfo.uid; 18712 if (outInfo.appearedChildPackages == null) { 18713 outInfo.appearedChildPackages = new ArrayMap<>(); 18714 } 18715 outInfo.appearedChildPackages.put(childPackageName, installRes); 18716 } 18717 } 18718 } 18719 } 18720 } 18721 18722 return ret; 18723 } 18724 18725 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18726 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18727 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18728 for (int nextUserId : userIds) { 18729 if (DEBUG_REMOVE) { 18730 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18731 } 18732 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18733 false /*installed*/, 18734 true /*stopped*/, 18735 true /*notLaunched*/, 18736 false /*hidden*/, 18737 false /*suspended*/, 18738 false /*instantApp*/, 18739 null /*lastDisableAppCaller*/, 18740 null /*enabledComponents*/, 18741 null /*disabledComponents*/, 18742 ps.readUserState(nextUserId).domainVerificationStatus, 18743 0, PackageManager.INSTALL_REASON_UNKNOWN); 18744 } 18745 mSettings.writeKernelMappingLPr(ps); 18746 } 18747 18748 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18749 PackageRemovedInfo outInfo) { 18750 final PackageParser.Package pkg; 18751 synchronized (mPackages) { 18752 pkg = mPackages.get(ps.name); 18753 } 18754 18755 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18756 : new int[] {userId}; 18757 for (int nextUserId : userIds) { 18758 if (DEBUG_REMOVE) { 18759 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18760 + nextUserId); 18761 } 18762 18763 destroyAppDataLIF(pkg, userId, 18764 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18765 destroyAppProfilesLIF(pkg, userId); 18766 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18767 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18768 schedulePackageCleaning(ps.name, nextUserId, false); 18769 synchronized (mPackages) { 18770 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18771 scheduleWritePackageRestrictionsLocked(nextUserId); 18772 } 18773 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18774 } 18775 } 18776 18777 if (outInfo != null) { 18778 outInfo.removedPackage = ps.name; 18779 outInfo.installerPackageName = ps.installerPackageName; 18780 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18781 outInfo.removedAppId = ps.appId; 18782 outInfo.removedUsers = userIds; 18783 outInfo.broadcastUsers = userIds; 18784 } 18785 18786 return true; 18787 } 18788 18789 private final class ClearStorageConnection implements ServiceConnection { 18790 IMediaContainerService mContainerService; 18791 18792 @Override 18793 public void onServiceConnected(ComponentName name, IBinder service) { 18794 synchronized (this) { 18795 mContainerService = IMediaContainerService.Stub 18796 .asInterface(Binder.allowBlocking(service)); 18797 notifyAll(); 18798 } 18799 } 18800 18801 @Override 18802 public void onServiceDisconnected(ComponentName name) { 18803 } 18804 } 18805 18806 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18807 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18808 18809 final boolean mounted; 18810 if (Environment.isExternalStorageEmulated()) { 18811 mounted = true; 18812 } else { 18813 final String status = Environment.getExternalStorageState(); 18814 18815 mounted = status.equals(Environment.MEDIA_MOUNTED) 18816 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18817 } 18818 18819 if (!mounted) { 18820 return; 18821 } 18822 18823 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18824 int[] users; 18825 if (userId == UserHandle.USER_ALL) { 18826 users = sUserManager.getUserIds(); 18827 } else { 18828 users = new int[] { userId }; 18829 } 18830 final ClearStorageConnection conn = new ClearStorageConnection(); 18831 if (mContext.bindServiceAsUser( 18832 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18833 try { 18834 for (int curUser : users) { 18835 long timeout = SystemClock.uptimeMillis() + 5000; 18836 synchronized (conn) { 18837 long now; 18838 while (conn.mContainerService == null && 18839 (now = SystemClock.uptimeMillis()) < timeout) { 18840 try { 18841 conn.wait(timeout - now); 18842 } catch (InterruptedException e) { 18843 } 18844 } 18845 } 18846 if (conn.mContainerService == null) { 18847 return; 18848 } 18849 18850 final UserEnvironment userEnv = new UserEnvironment(curUser); 18851 clearDirectory(conn.mContainerService, 18852 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18853 if (allData) { 18854 clearDirectory(conn.mContainerService, 18855 userEnv.buildExternalStorageAppDataDirs(packageName)); 18856 clearDirectory(conn.mContainerService, 18857 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18858 } 18859 } 18860 } finally { 18861 mContext.unbindService(conn); 18862 } 18863 } 18864 } 18865 18866 @Override 18867 public void clearApplicationProfileData(String packageName) { 18868 enforceSystemOrRoot("Only the system can clear all profile data"); 18869 18870 final PackageParser.Package pkg; 18871 synchronized (mPackages) { 18872 pkg = mPackages.get(packageName); 18873 } 18874 18875 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18876 synchronized (mInstallLock) { 18877 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18878 } 18879 } 18880 } 18881 18882 @Override 18883 public void clearApplicationUserData(final String packageName, 18884 final IPackageDataObserver observer, final int userId) { 18885 mContext.enforceCallingOrSelfPermission( 18886 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18887 18888 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18889 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18890 18891 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18892 throw new SecurityException("Cannot clear data for a protected package: " 18893 + packageName); 18894 } 18895 // Queue up an async operation since the package deletion may take a little while. 18896 mHandler.post(new Runnable() { 18897 public void run() { 18898 mHandler.removeCallbacks(this); 18899 final boolean succeeded; 18900 try (PackageFreezer freezer = freezePackage(packageName, 18901 "clearApplicationUserData")) { 18902 synchronized (mInstallLock) { 18903 succeeded = clearApplicationUserDataLIF(packageName, userId); 18904 } 18905 clearExternalStorageDataSync(packageName, userId, true); 18906 synchronized (mPackages) { 18907 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18908 packageName, userId); 18909 } 18910 } 18911 if (succeeded) { 18912 // invoke DeviceStorageMonitor's update method to clear any notifications 18913 DeviceStorageMonitorInternal dsm = LocalServices 18914 .getService(DeviceStorageMonitorInternal.class); 18915 if (dsm != null) { 18916 dsm.checkMemory(); 18917 } 18918 } 18919 if(observer != null) { 18920 try { 18921 observer.onRemoveCompleted(packageName, succeeded); 18922 } catch (RemoteException e) { 18923 Log.i(TAG, "Observer no longer exists."); 18924 } 18925 } //end if observer 18926 } //end run 18927 }); 18928 } 18929 18930 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18931 if (packageName == null) { 18932 Slog.w(TAG, "Attempt to delete null packageName."); 18933 return false; 18934 } 18935 18936 // Try finding details about the requested package 18937 PackageParser.Package pkg; 18938 synchronized (mPackages) { 18939 pkg = mPackages.get(packageName); 18940 if (pkg == null) { 18941 final PackageSetting ps = mSettings.mPackages.get(packageName); 18942 if (ps != null) { 18943 pkg = ps.pkg; 18944 } 18945 } 18946 18947 if (pkg == null) { 18948 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18949 return false; 18950 } 18951 18952 PackageSetting ps = (PackageSetting) pkg.mExtras; 18953 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18954 } 18955 18956 clearAppDataLIF(pkg, userId, 18957 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18958 18959 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18960 removeKeystoreDataIfNeeded(userId, appId); 18961 18962 UserManagerInternal umInternal = getUserManagerInternal(); 18963 final int flags; 18964 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18965 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18966 } else if (umInternal.isUserRunning(userId)) { 18967 flags = StorageManager.FLAG_STORAGE_DE; 18968 } else { 18969 flags = 0; 18970 } 18971 prepareAppDataContentsLIF(pkg, userId, flags); 18972 18973 return true; 18974 } 18975 18976 /** 18977 * Reverts user permission state changes (permissions and flags) in 18978 * all packages for a given user. 18979 * 18980 * @param userId The device user for which to do a reset. 18981 */ 18982 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18983 final int packageCount = mPackages.size(); 18984 for (int i = 0; i < packageCount; i++) { 18985 PackageParser.Package pkg = mPackages.valueAt(i); 18986 PackageSetting ps = (PackageSetting) pkg.mExtras; 18987 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18988 } 18989 } 18990 18991 private void resetNetworkPolicies(int userId) { 18992 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18993 } 18994 18995 /** 18996 * Reverts user permission state changes (permissions and flags). 18997 * 18998 * @param ps The package for which to reset. 18999 * @param userId The device user for which to do a reset. 19000 */ 19001 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19002 final PackageSetting ps, final int userId) { 19003 if (ps.pkg == null) { 19004 return; 19005 } 19006 19007 // These are flags that can change base on user actions. 19008 final int userSettableMask = FLAG_PERMISSION_USER_SET 19009 | FLAG_PERMISSION_USER_FIXED 19010 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19011 | FLAG_PERMISSION_REVIEW_REQUIRED; 19012 19013 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19014 | FLAG_PERMISSION_POLICY_FIXED; 19015 19016 boolean writeInstallPermissions = false; 19017 boolean writeRuntimePermissions = false; 19018 19019 final int permissionCount = ps.pkg.requestedPermissions.size(); 19020 for (int i = 0; i < permissionCount; i++) { 19021 String permission = ps.pkg.requestedPermissions.get(i); 19022 19023 BasePermission bp = mSettings.mPermissions.get(permission); 19024 if (bp == null) { 19025 continue; 19026 } 19027 19028 // If shared user we just reset the state to which only this app contributed. 19029 if (ps.sharedUser != null) { 19030 boolean used = false; 19031 final int packageCount = ps.sharedUser.packages.size(); 19032 for (int j = 0; j < packageCount; j++) { 19033 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19034 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19035 && pkg.pkg.requestedPermissions.contains(permission)) { 19036 used = true; 19037 break; 19038 } 19039 } 19040 if (used) { 19041 continue; 19042 } 19043 } 19044 19045 PermissionsState permissionsState = ps.getPermissionsState(); 19046 19047 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 19048 19049 // Always clear the user settable flags. 19050 final boolean hasInstallState = permissionsState.getInstallPermissionState( 19051 bp.name) != null; 19052 // If permission review is enabled and this is a legacy app, mark the 19053 // permission as requiring a review as this is the initial state. 19054 int flags = 0; 19055 if (mPermissionReviewRequired 19056 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19057 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19058 } 19059 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19060 if (hasInstallState) { 19061 writeInstallPermissions = true; 19062 } else { 19063 writeRuntimePermissions = true; 19064 } 19065 } 19066 19067 // Below is only runtime permission handling. 19068 if (!bp.isRuntime()) { 19069 continue; 19070 } 19071 19072 // Never clobber system or policy. 19073 if ((oldFlags & policyOrSystemFlags) != 0) { 19074 continue; 19075 } 19076 19077 // If this permission was granted by default, make sure it is. 19078 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19079 if (permissionsState.grantRuntimePermission(bp, userId) 19080 != PERMISSION_OPERATION_FAILURE) { 19081 writeRuntimePermissions = true; 19082 } 19083 // If permission review is enabled the permissions for a legacy apps 19084 // are represented as constantly granted runtime ones, so don't revoke. 19085 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19086 // Otherwise, reset the permission. 19087 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19088 switch (revokeResult) { 19089 case PERMISSION_OPERATION_SUCCESS: 19090 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19091 writeRuntimePermissions = true; 19092 final int appId = ps.appId; 19093 mHandler.post(new Runnable() { 19094 @Override 19095 public void run() { 19096 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19097 } 19098 }); 19099 } break; 19100 } 19101 } 19102 } 19103 19104 // Synchronously write as we are taking permissions away. 19105 if (writeRuntimePermissions) { 19106 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19107 } 19108 19109 // Synchronously write as we are taking permissions away. 19110 if (writeInstallPermissions) { 19111 mSettings.writeLPr(); 19112 } 19113 } 19114 19115 /** 19116 * Remove entries from the keystore daemon. Will only remove it if the 19117 * {@code appId} is valid. 19118 */ 19119 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19120 if (appId < 0) { 19121 return; 19122 } 19123 19124 final KeyStore keyStore = KeyStore.getInstance(); 19125 if (keyStore != null) { 19126 if (userId == UserHandle.USER_ALL) { 19127 for (final int individual : sUserManager.getUserIds()) { 19128 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19129 } 19130 } else { 19131 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19132 } 19133 } else { 19134 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19135 } 19136 } 19137 19138 @Override 19139 public void deleteApplicationCacheFiles(final String packageName, 19140 final IPackageDataObserver observer) { 19141 final int userId = UserHandle.getCallingUserId(); 19142 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19143 } 19144 19145 @Override 19146 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19147 final IPackageDataObserver observer) { 19148 mContext.enforceCallingOrSelfPermission( 19149 android.Manifest.permission.DELETE_CACHE_FILES, null); 19150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 19151 /* requireFullPermission= */ true, /* checkShell= */ false, 19152 "delete application cache files"); 19153 19154 final PackageParser.Package pkg; 19155 synchronized (mPackages) { 19156 pkg = mPackages.get(packageName); 19157 } 19158 19159 // Queue up an async operation since the package deletion may take a little while. 19160 mHandler.post(new Runnable() { 19161 public void run() { 19162 synchronized (mInstallLock) { 19163 final int flags = StorageManager.FLAG_STORAGE_DE 19164 | StorageManager.FLAG_STORAGE_CE; 19165 // We're only clearing cache files, so we don't care if the 19166 // app is unfrozen and still able to run 19167 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19168 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19169 } 19170 clearExternalStorageDataSync(packageName, userId, false); 19171 if (observer != null) { 19172 try { 19173 observer.onRemoveCompleted(packageName, true); 19174 } catch (RemoteException e) { 19175 Log.i(TAG, "Observer no longer exists."); 19176 } 19177 } 19178 } 19179 }); 19180 } 19181 19182 @Override 19183 public void getPackageSizeInfo(final String packageName, int userHandle, 19184 final IPackageStatsObserver observer) { 19185 throw new UnsupportedOperationException( 19186 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19187 } 19188 19189 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19190 final PackageSetting ps; 19191 synchronized (mPackages) { 19192 ps = mSettings.mPackages.get(packageName); 19193 if (ps == null) { 19194 Slog.w(TAG, "Failed to find settings for " + packageName); 19195 return false; 19196 } 19197 } 19198 19199 final String[] packageNames = { packageName }; 19200 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19201 final String[] codePaths = { ps.codePathString }; 19202 19203 try { 19204 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19205 ps.appId, ceDataInodes, codePaths, stats); 19206 19207 // For now, ignore code size of packages on system partition 19208 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19209 stats.codeSize = 0; 19210 } 19211 19212 // External clients expect these to be tracked separately 19213 stats.dataSize -= stats.cacheSize; 19214 19215 } catch (InstallerException e) { 19216 Slog.w(TAG, String.valueOf(e)); 19217 return false; 19218 } 19219 19220 return true; 19221 } 19222 19223 private int getUidTargetSdkVersionLockedLPr(int uid) { 19224 Object obj = mSettings.getUserIdLPr(uid); 19225 if (obj instanceof SharedUserSetting) { 19226 final SharedUserSetting sus = (SharedUserSetting) obj; 19227 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19228 final Iterator<PackageSetting> it = sus.packages.iterator(); 19229 while (it.hasNext()) { 19230 final PackageSetting ps = it.next(); 19231 if (ps.pkg != null) { 19232 int v = ps.pkg.applicationInfo.targetSdkVersion; 19233 if (v < vers) vers = v; 19234 } 19235 } 19236 return vers; 19237 } else if (obj instanceof PackageSetting) { 19238 final PackageSetting ps = (PackageSetting) obj; 19239 if (ps.pkg != null) { 19240 return ps.pkg.applicationInfo.targetSdkVersion; 19241 } 19242 } 19243 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19244 } 19245 19246 @Override 19247 public void addPreferredActivity(IntentFilter filter, int match, 19248 ComponentName[] set, ComponentName activity, int userId) { 19249 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19250 "Adding preferred"); 19251 } 19252 19253 private void addPreferredActivityInternal(IntentFilter filter, int match, 19254 ComponentName[] set, ComponentName activity, boolean always, int userId, 19255 String opname) { 19256 // writer 19257 int callingUid = Binder.getCallingUid(); 19258 enforceCrossUserPermission(callingUid, userId, 19259 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19260 if (filter.countActions() == 0) { 19261 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19262 return; 19263 } 19264 synchronized (mPackages) { 19265 if (mContext.checkCallingOrSelfPermission( 19266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19267 != PackageManager.PERMISSION_GRANTED) { 19268 if (getUidTargetSdkVersionLockedLPr(callingUid) 19269 < Build.VERSION_CODES.FROYO) { 19270 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19271 + callingUid); 19272 return; 19273 } 19274 mContext.enforceCallingOrSelfPermission( 19275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19276 } 19277 19278 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19279 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19280 + userId + ":"); 19281 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19282 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19283 scheduleWritePackageRestrictionsLocked(userId); 19284 postPreferredActivityChangedBroadcast(userId); 19285 } 19286 } 19287 19288 private void postPreferredActivityChangedBroadcast(int userId) { 19289 mHandler.post(() -> { 19290 final IActivityManager am = ActivityManager.getService(); 19291 if (am == null) { 19292 return; 19293 } 19294 19295 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19296 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19297 try { 19298 am.broadcastIntent(null, intent, null, null, 19299 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19300 null, false, false, userId); 19301 } catch (RemoteException e) { 19302 } 19303 }); 19304 } 19305 19306 @Override 19307 public void replacePreferredActivity(IntentFilter filter, int match, 19308 ComponentName[] set, ComponentName activity, int userId) { 19309 if (filter.countActions() != 1) { 19310 throw new IllegalArgumentException( 19311 "replacePreferredActivity expects filter to have only 1 action."); 19312 } 19313 if (filter.countDataAuthorities() != 0 19314 || filter.countDataPaths() != 0 19315 || filter.countDataSchemes() > 1 19316 || filter.countDataTypes() != 0) { 19317 throw new IllegalArgumentException( 19318 "replacePreferredActivity expects filter to have no data authorities, " + 19319 "paths, or types; and at most one scheme."); 19320 } 19321 19322 final int callingUid = Binder.getCallingUid(); 19323 enforceCrossUserPermission(callingUid, userId, 19324 true /* requireFullPermission */, false /* checkShell */, 19325 "replace preferred activity"); 19326 synchronized (mPackages) { 19327 if (mContext.checkCallingOrSelfPermission( 19328 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19329 != PackageManager.PERMISSION_GRANTED) { 19330 if (getUidTargetSdkVersionLockedLPr(callingUid) 19331 < Build.VERSION_CODES.FROYO) { 19332 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19333 + Binder.getCallingUid()); 19334 return; 19335 } 19336 mContext.enforceCallingOrSelfPermission( 19337 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19338 } 19339 19340 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19341 if (pir != null) { 19342 // Get all of the existing entries that exactly match this filter. 19343 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19344 if (existing != null && existing.size() == 1) { 19345 PreferredActivity cur = existing.get(0); 19346 if (DEBUG_PREFERRED) { 19347 Slog.i(TAG, "Checking replace of preferred:"); 19348 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19349 if (!cur.mPref.mAlways) { 19350 Slog.i(TAG, " -- CUR; not mAlways!"); 19351 } else { 19352 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19353 Slog.i(TAG, " -- CUR: mSet=" 19354 + Arrays.toString(cur.mPref.mSetComponents)); 19355 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19356 Slog.i(TAG, " -- NEW: mMatch=" 19357 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19358 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19359 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19360 } 19361 } 19362 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19363 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19364 && cur.mPref.sameSet(set)) { 19365 // Setting the preferred activity to what it happens to be already 19366 if (DEBUG_PREFERRED) { 19367 Slog.i(TAG, "Replacing with same preferred activity " 19368 + cur.mPref.mShortComponent + " for user " 19369 + userId + ":"); 19370 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19371 } 19372 return; 19373 } 19374 } 19375 19376 if (existing != null) { 19377 if (DEBUG_PREFERRED) { 19378 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19379 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19380 } 19381 for (int i = 0; i < existing.size(); i++) { 19382 PreferredActivity pa = existing.get(i); 19383 if (DEBUG_PREFERRED) { 19384 Slog.i(TAG, "Removing existing preferred activity " 19385 + pa.mPref.mComponent + ":"); 19386 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19387 } 19388 pir.removeFilter(pa); 19389 } 19390 } 19391 } 19392 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19393 "Replacing preferred"); 19394 } 19395 } 19396 19397 @Override 19398 public void clearPackagePreferredActivities(String packageName) { 19399 final int uid = Binder.getCallingUid(); 19400 // writer 19401 synchronized (mPackages) { 19402 PackageParser.Package pkg = mPackages.get(packageName); 19403 if (pkg == null || pkg.applicationInfo.uid != uid) { 19404 if (mContext.checkCallingOrSelfPermission( 19405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19406 != PackageManager.PERMISSION_GRANTED) { 19407 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19408 < Build.VERSION_CODES.FROYO) { 19409 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19410 + Binder.getCallingUid()); 19411 return; 19412 } 19413 mContext.enforceCallingOrSelfPermission( 19414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19415 } 19416 } 19417 19418 int user = UserHandle.getCallingUserId(); 19419 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19420 scheduleWritePackageRestrictionsLocked(user); 19421 } 19422 } 19423 } 19424 19425 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19426 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19427 ArrayList<PreferredActivity> removed = null; 19428 boolean changed = false; 19429 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19430 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19431 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19432 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19433 continue; 19434 } 19435 Iterator<PreferredActivity> it = pir.filterIterator(); 19436 while (it.hasNext()) { 19437 PreferredActivity pa = it.next(); 19438 // Mark entry for removal only if it matches the package name 19439 // and the entry is of type "always". 19440 if (packageName == null || 19441 (pa.mPref.mComponent.getPackageName().equals(packageName) 19442 && pa.mPref.mAlways)) { 19443 if (removed == null) { 19444 removed = new ArrayList<PreferredActivity>(); 19445 } 19446 removed.add(pa); 19447 } 19448 } 19449 if (removed != null) { 19450 for (int j=0; j<removed.size(); j++) { 19451 PreferredActivity pa = removed.get(j); 19452 pir.removeFilter(pa); 19453 } 19454 changed = true; 19455 } 19456 } 19457 if (changed) { 19458 postPreferredActivityChangedBroadcast(userId); 19459 } 19460 return changed; 19461 } 19462 19463 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19464 private void clearIntentFilterVerificationsLPw(int userId) { 19465 final int packageCount = mPackages.size(); 19466 for (int i = 0; i < packageCount; i++) { 19467 PackageParser.Package pkg = mPackages.valueAt(i); 19468 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19469 } 19470 } 19471 19472 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19473 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19474 if (userId == UserHandle.USER_ALL) { 19475 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19476 sUserManager.getUserIds())) { 19477 for (int oneUserId : sUserManager.getUserIds()) { 19478 scheduleWritePackageRestrictionsLocked(oneUserId); 19479 } 19480 } 19481 } else { 19482 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19483 scheduleWritePackageRestrictionsLocked(userId); 19484 } 19485 } 19486 } 19487 19488 /** Clears state for all users, and touches intent filter verification policy */ 19489 void clearDefaultBrowserIfNeeded(String packageName) { 19490 for (int oneUserId : sUserManager.getUserIds()) { 19491 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19492 } 19493 } 19494 19495 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19496 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19497 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19498 if (packageName.equals(defaultBrowserPackageName)) { 19499 setDefaultBrowserPackageName(null, userId); 19500 } 19501 } 19502 } 19503 19504 @Override 19505 public void resetApplicationPreferences(int userId) { 19506 mContext.enforceCallingOrSelfPermission( 19507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19508 final long identity = Binder.clearCallingIdentity(); 19509 // writer 19510 try { 19511 synchronized (mPackages) { 19512 clearPackagePreferredActivitiesLPw(null, userId); 19513 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19514 // TODO: We have to reset the default SMS and Phone. This requires 19515 // significant refactoring to keep all default apps in the package 19516 // manager (cleaner but more work) or have the services provide 19517 // callbacks to the package manager to request a default app reset. 19518 applyFactoryDefaultBrowserLPw(userId); 19519 clearIntentFilterVerificationsLPw(userId); 19520 primeDomainVerificationsLPw(userId); 19521 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19522 scheduleWritePackageRestrictionsLocked(userId); 19523 } 19524 resetNetworkPolicies(userId); 19525 } finally { 19526 Binder.restoreCallingIdentity(identity); 19527 } 19528 } 19529 19530 @Override 19531 public int getPreferredActivities(List<IntentFilter> outFilters, 19532 List<ComponentName> outActivities, String packageName) { 19533 19534 int num = 0; 19535 final int userId = UserHandle.getCallingUserId(); 19536 // reader 19537 synchronized (mPackages) { 19538 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19539 if (pir != null) { 19540 final Iterator<PreferredActivity> it = pir.filterIterator(); 19541 while (it.hasNext()) { 19542 final PreferredActivity pa = it.next(); 19543 if (packageName == null 19544 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19545 && pa.mPref.mAlways)) { 19546 if (outFilters != null) { 19547 outFilters.add(new IntentFilter(pa)); 19548 } 19549 if (outActivities != null) { 19550 outActivities.add(pa.mPref.mComponent); 19551 } 19552 } 19553 } 19554 } 19555 } 19556 19557 return num; 19558 } 19559 19560 @Override 19561 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19562 int userId) { 19563 int callingUid = Binder.getCallingUid(); 19564 if (callingUid != Process.SYSTEM_UID) { 19565 throw new SecurityException( 19566 "addPersistentPreferredActivity can only be run by the system"); 19567 } 19568 if (filter.countActions() == 0) { 19569 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19570 return; 19571 } 19572 synchronized (mPackages) { 19573 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19574 ":"); 19575 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19576 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19577 new PersistentPreferredActivity(filter, activity)); 19578 scheduleWritePackageRestrictionsLocked(userId); 19579 postPreferredActivityChangedBroadcast(userId); 19580 } 19581 } 19582 19583 @Override 19584 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19585 int callingUid = Binder.getCallingUid(); 19586 if (callingUid != Process.SYSTEM_UID) { 19587 throw new SecurityException( 19588 "clearPackagePersistentPreferredActivities can only be run by the system"); 19589 } 19590 ArrayList<PersistentPreferredActivity> removed = null; 19591 boolean changed = false; 19592 synchronized (mPackages) { 19593 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19594 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19595 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19596 .valueAt(i); 19597 if (userId != thisUserId) { 19598 continue; 19599 } 19600 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19601 while (it.hasNext()) { 19602 PersistentPreferredActivity ppa = it.next(); 19603 // Mark entry for removal only if it matches the package name. 19604 if (ppa.mComponent.getPackageName().equals(packageName)) { 19605 if (removed == null) { 19606 removed = new ArrayList<PersistentPreferredActivity>(); 19607 } 19608 removed.add(ppa); 19609 } 19610 } 19611 if (removed != null) { 19612 for (int j=0; j<removed.size(); j++) { 19613 PersistentPreferredActivity ppa = removed.get(j); 19614 ppir.removeFilter(ppa); 19615 } 19616 changed = true; 19617 } 19618 } 19619 19620 if (changed) { 19621 scheduleWritePackageRestrictionsLocked(userId); 19622 postPreferredActivityChangedBroadcast(userId); 19623 } 19624 } 19625 } 19626 19627 /** 19628 * Common machinery for picking apart a restored XML blob and passing 19629 * it to a caller-supplied functor to be applied to the running system. 19630 */ 19631 private void restoreFromXml(XmlPullParser parser, int userId, 19632 String expectedStartTag, BlobXmlRestorer functor) 19633 throws IOException, XmlPullParserException { 19634 int type; 19635 while ((type = parser.next()) != XmlPullParser.START_TAG 19636 && type != XmlPullParser.END_DOCUMENT) { 19637 } 19638 if (type != XmlPullParser.START_TAG) { 19639 // oops didn't find a start tag?! 19640 if (DEBUG_BACKUP) { 19641 Slog.e(TAG, "Didn't find start tag during restore"); 19642 } 19643 return; 19644 } 19645Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19646 // this is supposed to be TAG_PREFERRED_BACKUP 19647 if (!expectedStartTag.equals(parser.getName())) { 19648 if (DEBUG_BACKUP) { 19649 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19650 } 19651 return; 19652 } 19653 19654 // skip interfering stuff, then we're aligned with the backing implementation 19655 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19656Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19657 functor.apply(parser, userId); 19658 } 19659 19660 private interface BlobXmlRestorer { 19661 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19662 } 19663 19664 /** 19665 * Non-Binder method, support for the backup/restore mechanism: write the 19666 * full set of preferred activities in its canonical XML format. Returns the 19667 * XML output as a byte array, or null if there is none. 19668 */ 19669 @Override 19670 public byte[] getPreferredActivityBackup(int userId) { 19671 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19672 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19673 } 19674 19675 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19676 try { 19677 final XmlSerializer serializer = new FastXmlSerializer(); 19678 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19679 serializer.startDocument(null, true); 19680 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19681 19682 synchronized (mPackages) { 19683 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19684 } 19685 19686 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19687 serializer.endDocument(); 19688 serializer.flush(); 19689 } catch (Exception e) { 19690 if (DEBUG_BACKUP) { 19691 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19692 } 19693 return null; 19694 } 19695 19696 return dataStream.toByteArray(); 19697 } 19698 19699 @Override 19700 public void restorePreferredActivities(byte[] backup, int userId) { 19701 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19702 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19703 } 19704 19705 try { 19706 final XmlPullParser parser = Xml.newPullParser(); 19707 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19708 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19709 new BlobXmlRestorer() { 19710 @Override 19711 public void apply(XmlPullParser parser, int userId) 19712 throws XmlPullParserException, IOException { 19713 synchronized (mPackages) { 19714 mSettings.readPreferredActivitiesLPw(parser, userId); 19715 } 19716 } 19717 } ); 19718 } catch (Exception e) { 19719 if (DEBUG_BACKUP) { 19720 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19721 } 19722 } 19723 } 19724 19725 /** 19726 * Non-Binder method, support for the backup/restore mechanism: write the 19727 * default browser (etc) settings in its canonical XML format. Returns the default 19728 * browser XML representation as a byte array, or null if there is none. 19729 */ 19730 @Override 19731 public byte[] getDefaultAppsBackup(int userId) { 19732 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19733 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19734 } 19735 19736 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19737 try { 19738 final XmlSerializer serializer = new FastXmlSerializer(); 19739 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19740 serializer.startDocument(null, true); 19741 serializer.startTag(null, TAG_DEFAULT_APPS); 19742 19743 synchronized (mPackages) { 19744 mSettings.writeDefaultAppsLPr(serializer, userId); 19745 } 19746 19747 serializer.endTag(null, TAG_DEFAULT_APPS); 19748 serializer.endDocument(); 19749 serializer.flush(); 19750 } catch (Exception e) { 19751 if (DEBUG_BACKUP) { 19752 Slog.e(TAG, "Unable to write default apps for backup", e); 19753 } 19754 return null; 19755 } 19756 19757 return dataStream.toByteArray(); 19758 } 19759 19760 @Override 19761 public void restoreDefaultApps(byte[] backup, int userId) { 19762 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19763 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19764 } 19765 19766 try { 19767 final XmlPullParser parser = Xml.newPullParser(); 19768 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19769 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19770 new BlobXmlRestorer() { 19771 @Override 19772 public void apply(XmlPullParser parser, int userId) 19773 throws XmlPullParserException, IOException { 19774 synchronized (mPackages) { 19775 mSettings.readDefaultAppsLPw(parser, userId); 19776 } 19777 } 19778 } ); 19779 } catch (Exception e) { 19780 if (DEBUG_BACKUP) { 19781 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19782 } 19783 } 19784 } 19785 19786 @Override 19787 public byte[] getIntentFilterVerificationBackup(int userId) { 19788 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19789 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19790 } 19791 19792 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19793 try { 19794 final XmlSerializer serializer = new FastXmlSerializer(); 19795 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19796 serializer.startDocument(null, true); 19797 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19798 19799 synchronized (mPackages) { 19800 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19801 } 19802 19803 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19804 serializer.endDocument(); 19805 serializer.flush(); 19806 } catch (Exception e) { 19807 if (DEBUG_BACKUP) { 19808 Slog.e(TAG, "Unable to write default apps for backup", e); 19809 } 19810 return null; 19811 } 19812 19813 return dataStream.toByteArray(); 19814 } 19815 19816 @Override 19817 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19818 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19819 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19820 } 19821 19822 try { 19823 final XmlPullParser parser = Xml.newPullParser(); 19824 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19825 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19826 new BlobXmlRestorer() { 19827 @Override 19828 public void apply(XmlPullParser parser, int userId) 19829 throws XmlPullParserException, IOException { 19830 synchronized (mPackages) { 19831 mSettings.readAllDomainVerificationsLPr(parser, userId); 19832 mSettings.writeLPr(); 19833 } 19834 } 19835 } ); 19836 } catch (Exception e) { 19837 if (DEBUG_BACKUP) { 19838 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19839 } 19840 } 19841 } 19842 19843 @Override 19844 public byte[] getPermissionGrantBackup(int userId) { 19845 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19846 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19847 } 19848 19849 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19850 try { 19851 final XmlSerializer serializer = new FastXmlSerializer(); 19852 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19853 serializer.startDocument(null, true); 19854 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19855 19856 synchronized (mPackages) { 19857 serializeRuntimePermissionGrantsLPr(serializer, userId); 19858 } 19859 19860 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19861 serializer.endDocument(); 19862 serializer.flush(); 19863 } catch (Exception e) { 19864 if (DEBUG_BACKUP) { 19865 Slog.e(TAG, "Unable to write default apps for backup", e); 19866 } 19867 return null; 19868 } 19869 19870 return dataStream.toByteArray(); 19871 } 19872 19873 @Override 19874 public void restorePermissionGrants(byte[] backup, int userId) { 19875 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19876 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19877 } 19878 19879 try { 19880 final XmlPullParser parser = Xml.newPullParser(); 19881 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19882 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19883 new BlobXmlRestorer() { 19884 @Override 19885 public void apply(XmlPullParser parser, int userId) 19886 throws XmlPullParserException, IOException { 19887 synchronized (mPackages) { 19888 processRestoredPermissionGrantsLPr(parser, userId); 19889 } 19890 } 19891 } ); 19892 } catch (Exception e) { 19893 if (DEBUG_BACKUP) { 19894 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19895 } 19896 } 19897 } 19898 19899 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19900 throws IOException { 19901 serializer.startTag(null, TAG_ALL_GRANTS); 19902 19903 final int N = mSettings.mPackages.size(); 19904 for (int i = 0; i < N; i++) { 19905 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19906 boolean pkgGrantsKnown = false; 19907 19908 PermissionsState packagePerms = ps.getPermissionsState(); 19909 19910 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19911 final int grantFlags = state.getFlags(); 19912 // only look at grants that are not system/policy fixed 19913 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19914 final boolean isGranted = state.isGranted(); 19915 // And only back up the user-twiddled state bits 19916 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19917 final String packageName = mSettings.mPackages.keyAt(i); 19918 if (!pkgGrantsKnown) { 19919 serializer.startTag(null, TAG_GRANT); 19920 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19921 pkgGrantsKnown = true; 19922 } 19923 19924 final boolean userSet = 19925 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19926 final boolean userFixed = 19927 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19928 final boolean revoke = 19929 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19930 19931 serializer.startTag(null, TAG_PERMISSION); 19932 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19933 if (isGranted) { 19934 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19935 } 19936 if (userSet) { 19937 serializer.attribute(null, ATTR_USER_SET, "true"); 19938 } 19939 if (userFixed) { 19940 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19941 } 19942 if (revoke) { 19943 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19944 } 19945 serializer.endTag(null, TAG_PERMISSION); 19946 } 19947 } 19948 } 19949 19950 if (pkgGrantsKnown) { 19951 serializer.endTag(null, TAG_GRANT); 19952 } 19953 } 19954 19955 serializer.endTag(null, TAG_ALL_GRANTS); 19956 } 19957 19958 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19959 throws XmlPullParserException, IOException { 19960 String pkgName = null; 19961 int outerDepth = parser.getDepth(); 19962 int type; 19963 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19964 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19965 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19966 continue; 19967 } 19968 19969 final String tagName = parser.getName(); 19970 if (tagName.equals(TAG_GRANT)) { 19971 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19972 if (DEBUG_BACKUP) { 19973 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19974 } 19975 } else if (tagName.equals(TAG_PERMISSION)) { 19976 19977 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19978 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19979 19980 int newFlagSet = 0; 19981 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19982 newFlagSet |= FLAG_PERMISSION_USER_SET; 19983 } 19984 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19985 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19986 } 19987 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19988 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19989 } 19990 if (DEBUG_BACKUP) { 19991 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19992 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19993 } 19994 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19995 if (ps != null) { 19996 // Already installed so we apply the grant immediately 19997 if (DEBUG_BACKUP) { 19998 Slog.v(TAG, " + already installed; applying"); 19999 } 20000 PermissionsState perms = ps.getPermissionsState(); 20001 BasePermission bp = mSettings.mPermissions.get(permName); 20002 if (bp != null) { 20003 if (isGranted) { 20004 perms.grantRuntimePermission(bp, userId); 20005 } 20006 if (newFlagSet != 0) { 20007 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20008 } 20009 } 20010 } else { 20011 // Need to wait for post-restore install to apply the grant 20012 if (DEBUG_BACKUP) { 20013 Slog.v(TAG, " - not yet installed; saving for later"); 20014 } 20015 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20016 isGranted, newFlagSet, userId); 20017 } 20018 } else { 20019 PackageManagerService.reportSettingsProblem(Log.WARN, 20020 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20021 XmlUtils.skipCurrentTag(parser); 20022 } 20023 } 20024 20025 scheduleWriteSettingsLocked(); 20026 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20027 } 20028 20029 @Override 20030 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20031 int sourceUserId, int targetUserId, int flags) { 20032 mContext.enforceCallingOrSelfPermission( 20033 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20034 int callingUid = Binder.getCallingUid(); 20035 enforceOwnerRights(ownerPackage, callingUid); 20036 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20037 if (intentFilter.countActions() == 0) { 20038 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20039 return; 20040 } 20041 synchronized (mPackages) { 20042 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20043 ownerPackage, targetUserId, flags); 20044 CrossProfileIntentResolver resolver = 20045 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20046 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20047 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20048 if (existing != null) { 20049 int size = existing.size(); 20050 for (int i = 0; i < size; i++) { 20051 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20052 return; 20053 } 20054 } 20055 } 20056 resolver.addFilter(newFilter); 20057 scheduleWritePackageRestrictionsLocked(sourceUserId); 20058 } 20059 } 20060 20061 @Override 20062 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20063 mContext.enforceCallingOrSelfPermission( 20064 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20065 int callingUid = Binder.getCallingUid(); 20066 enforceOwnerRights(ownerPackage, callingUid); 20067 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20068 synchronized (mPackages) { 20069 CrossProfileIntentResolver resolver = 20070 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20071 ArraySet<CrossProfileIntentFilter> set = 20072 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20073 for (CrossProfileIntentFilter filter : set) { 20074 if (filter.getOwnerPackage().equals(ownerPackage)) { 20075 resolver.removeFilter(filter); 20076 } 20077 } 20078 scheduleWritePackageRestrictionsLocked(sourceUserId); 20079 } 20080 } 20081 20082 // Enforcing that callingUid is owning pkg on userId 20083 private void enforceOwnerRights(String pkg, int callingUid) { 20084 // The system owns everything. 20085 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20086 return; 20087 } 20088 int callingUserId = UserHandle.getUserId(callingUid); 20089 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20090 if (pi == null) { 20091 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20092 + callingUserId); 20093 } 20094 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20095 throw new SecurityException("Calling uid " + callingUid 20096 + " does not own package " + pkg); 20097 } 20098 } 20099 20100 @Override 20101 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20102 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20103 } 20104 20105 /** 20106 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20107 * then reports the most likely home activity or null if there are more than one. 20108 */ 20109 public ComponentName getDefaultHomeActivity(int userId) { 20110 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20111 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20112 if (cn != null) { 20113 return cn; 20114 } 20115 20116 // Find the launcher with the highest priority and return that component if there are no 20117 // other home activity with the same priority. 20118 int lastPriority = Integer.MIN_VALUE; 20119 ComponentName lastComponent = null; 20120 final int size = allHomeCandidates.size(); 20121 for (int i = 0; i < size; i++) { 20122 final ResolveInfo ri = allHomeCandidates.get(i); 20123 if (ri.priority > lastPriority) { 20124 lastComponent = ri.activityInfo.getComponentName(); 20125 lastPriority = ri.priority; 20126 } else if (ri.priority == lastPriority) { 20127 // Two components found with same priority. 20128 lastComponent = null; 20129 } 20130 } 20131 return lastComponent; 20132 } 20133 20134 private Intent getHomeIntent() { 20135 Intent intent = new Intent(Intent.ACTION_MAIN); 20136 intent.addCategory(Intent.CATEGORY_HOME); 20137 intent.addCategory(Intent.CATEGORY_DEFAULT); 20138 return intent; 20139 } 20140 20141 private IntentFilter getHomeFilter() { 20142 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20143 filter.addCategory(Intent.CATEGORY_HOME); 20144 filter.addCategory(Intent.CATEGORY_DEFAULT); 20145 return filter; 20146 } 20147 20148 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20149 int userId) { 20150 Intent intent = getHomeIntent(); 20151 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20152 PackageManager.GET_META_DATA, userId); 20153 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20154 true, false, false, userId); 20155 20156 allHomeCandidates.clear(); 20157 if (list != null) { 20158 for (ResolveInfo ri : list) { 20159 allHomeCandidates.add(ri); 20160 } 20161 } 20162 return (preferred == null || preferred.activityInfo == null) 20163 ? null 20164 : new ComponentName(preferred.activityInfo.packageName, 20165 preferred.activityInfo.name); 20166 } 20167 20168 @Override 20169 public void setHomeActivity(ComponentName comp, int userId) { 20170 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20171 getHomeActivitiesAsUser(homeActivities, userId); 20172 20173 boolean found = false; 20174 20175 final int size = homeActivities.size(); 20176 final ComponentName[] set = new ComponentName[size]; 20177 for (int i = 0; i < size; i++) { 20178 final ResolveInfo candidate = homeActivities.get(i); 20179 final ActivityInfo info = candidate.activityInfo; 20180 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20181 set[i] = activityName; 20182 if (!found && activityName.equals(comp)) { 20183 found = true; 20184 } 20185 } 20186 if (!found) { 20187 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20188 + userId); 20189 } 20190 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20191 set, comp, userId); 20192 } 20193 20194 private @Nullable String getSetupWizardPackageName() { 20195 final Intent intent = new Intent(Intent.ACTION_MAIN); 20196 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20197 20198 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20199 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20200 | MATCH_DISABLED_COMPONENTS, 20201 UserHandle.myUserId()); 20202 if (matches.size() == 1) { 20203 return matches.get(0).getComponentInfo().packageName; 20204 } else { 20205 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20206 + ": matches=" + matches); 20207 return null; 20208 } 20209 } 20210 20211 private @Nullable String getStorageManagerPackageName() { 20212 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20213 20214 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20215 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20216 | MATCH_DISABLED_COMPONENTS, 20217 UserHandle.myUserId()); 20218 if (matches.size() == 1) { 20219 return matches.get(0).getComponentInfo().packageName; 20220 } else { 20221 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20222 + matches.size() + ": matches=" + matches); 20223 return null; 20224 } 20225 } 20226 20227 @Override 20228 public void setApplicationEnabledSetting(String appPackageName, 20229 int newState, int flags, int userId, String callingPackage) { 20230 if (!sUserManager.exists(userId)) return; 20231 if (callingPackage == null) { 20232 callingPackage = Integer.toString(Binder.getCallingUid()); 20233 } 20234 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20235 } 20236 20237 @Override 20238 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20239 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20240 synchronized (mPackages) { 20241 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20242 if (pkgSetting != null) { 20243 pkgSetting.setUpdateAvailable(updateAvailable); 20244 } 20245 } 20246 } 20247 20248 @Override 20249 public void setComponentEnabledSetting(ComponentName componentName, 20250 int newState, int flags, int userId) { 20251 if (!sUserManager.exists(userId)) return; 20252 setEnabledSetting(componentName.getPackageName(), 20253 componentName.getClassName(), newState, flags, userId, null); 20254 } 20255 20256 private void setEnabledSetting(final String packageName, String className, int newState, 20257 final int flags, int userId, String callingPackage) { 20258 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20259 || newState == COMPONENT_ENABLED_STATE_ENABLED 20260 || newState == COMPONENT_ENABLED_STATE_DISABLED 20261 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20262 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20263 throw new IllegalArgumentException("Invalid new component state: " 20264 + newState); 20265 } 20266 PackageSetting pkgSetting; 20267 final int uid = Binder.getCallingUid(); 20268 final int permission; 20269 if (uid == Process.SYSTEM_UID) { 20270 permission = PackageManager.PERMISSION_GRANTED; 20271 } else { 20272 permission = mContext.checkCallingOrSelfPermission( 20273 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20274 } 20275 enforceCrossUserPermission(uid, userId, 20276 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20277 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20278 boolean sendNow = false; 20279 boolean isApp = (className == null); 20280 String componentName = isApp ? packageName : className; 20281 int packageUid = -1; 20282 ArrayList<String> components; 20283 20284 // writer 20285 synchronized (mPackages) { 20286 pkgSetting = mSettings.mPackages.get(packageName); 20287 if (pkgSetting == null) { 20288 if (className == null) { 20289 throw new IllegalArgumentException("Unknown package: " + packageName); 20290 } 20291 throw new IllegalArgumentException( 20292 "Unknown component: " + packageName + "/" + className); 20293 } 20294 } 20295 20296 // Limit who can change which apps 20297 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 20298 // Don't allow apps that don't have permission to modify other apps 20299 if (!allowedByPermission) { 20300 throw new SecurityException( 20301 "Permission Denial: attempt to change component state from pid=" 20302 + Binder.getCallingPid() 20303 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 20304 } 20305 // Don't allow changing protected packages. 20306 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20307 throw new SecurityException("Cannot disable a protected package: " + packageName); 20308 } 20309 } 20310 20311 synchronized (mPackages) { 20312 if (uid == Process.SHELL_UID 20313 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20314 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20315 // unless it is a test package. 20316 int oldState = pkgSetting.getEnabled(userId); 20317 if (className == null 20318 && 20319 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20320 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20321 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20322 && 20323 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20324 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20325 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20326 // ok 20327 } else { 20328 throw new SecurityException( 20329 "Shell cannot change component state for " + packageName + "/" 20330 + className + " to " + newState); 20331 } 20332 } 20333 if (className == null) { 20334 // We're dealing with an application/package level state change 20335 if (pkgSetting.getEnabled(userId) == newState) { 20336 // Nothing to do 20337 return; 20338 } 20339 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20340 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20341 // Don't care about who enables an app. 20342 callingPackage = null; 20343 } 20344 pkgSetting.setEnabled(newState, userId, callingPackage); 20345 // pkgSetting.pkg.mSetEnabled = newState; 20346 } else { 20347 // We're dealing with a component level state change 20348 // First, verify that this is a valid class name. 20349 PackageParser.Package pkg = pkgSetting.pkg; 20350 if (pkg == null || !pkg.hasComponentClassName(className)) { 20351 if (pkg != null && 20352 pkg.applicationInfo.targetSdkVersion >= 20353 Build.VERSION_CODES.JELLY_BEAN) { 20354 throw new IllegalArgumentException("Component class " + className 20355 + " does not exist in " + packageName); 20356 } else { 20357 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20358 + className + " does not exist in " + packageName); 20359 } 20360 } 20361 switch (newState) { 20362 case COMPONENT_ENABLED_STATE_ENABLED: 20363 if (!pkgSetting.enableComponentLPw(className, userId)) { 20364 return; 20365 } 20366 break; 20367 case COMPONENT_ENABLED_STATE_DISABLED: 20368 if (!pkgSetting.disableComponentLPw(className, userId)) { 20369 return; 20370 } 20371 break; 20372 case COMPONENT_ENABLED_STATE_DEFAULT: 20373 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20374 return; 20375 } 20376 break; 20377 default: 20378 Slog.e(TAG, "Invalid new component state: " + newState); 20379 return; 20380 } 20381 } 20382 scheduleWritePackageRestrictionsLocked(userId); 20383 updateSequenceNumberLP(packageName, new int[] { userId }); 20384 final long callingId = Binder.clearCallingIdentity(); 20385 try { 20386 updateInstantAppInstallerLocked(packageName); 20387 } finally { 20388 Binder.restoreCallingIdentity(callingId); 20389 } 20390 components = mPendingBroadcasts.get(userId, packageName); 20391 final boolean newPackage = components == null; 20392 if (newPackage) { 20393 components = new ArrayList<String>(); 20394 } 20395 if (!components.contains(componentName)) { 20396 components.add(componentName); 20397 } 20398 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20399 sendNow = true; 20400 // Purge entry from pending broadcast list if another one exists already 20401 // since we are sending one right away. 20402 mPendingBroadcasts.remove(userId, packageName); 20403 } else { 20404 if (newPackage) { 20405 mPendingBroadcasts.put(userId, packageName, components); 20406 } 20407 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20408 // Schedule a message 20409 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20410 } 20411 } 20412 } 20413 20414 long callingId = Binder.clearCallingIdentity(); 20415 try { 20416 if (sendNow) { 20417 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20418 sendPackageChangedBroadcast(packageName, 20419 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20420 } 20421 } finally { 20422 Binder.restoreCallingIdentity(callingId); 20423 } 20424 } 20425 20426 @Override 20427 public void flushPackageRestrictionsAsUser(int userId) { 20428 if (!sUserManager.exists(userId)) { 20429 return; 20430 } 20431 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20432 false /* checkShell */, "flushPackageRestrictions"); 20433 synchronized (mPackages) { 20434 mSettings.writePackageRestrictionsLPr(userId); 20435 mDirtyUsers.remove(userId); 20436 if (mDirtyUsers.isEmpty()) { 20437 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20438 } 20439 } 20440 } 20441 20442 private void sendPackageChangedBroadcast(String packageName, 20443 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20444 if (DEBUG_INSTALL) 20445 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20446 + componentNames); 20447 Bundle extras = new Bundle(4); 20448 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20449 String nameList[] = new String[componentNames.size()]; 20450 componentNames.toArray(nameList); 20451 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20452 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20453 extras.putInt(Intent.EXTRA_UID, packageUid); 20454 // If this is not reporting a change of the overall package, then only send it 20455 // to registered receivers. We don't want to launch a swath of apps for every 20456 // little component state change. 20457 final int flags = !componentNames.contains(packageName) 20458 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20459 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20460 new int[] {UserHandle.getUserId(packageUid)}); 20461 } 20462 20463 @Override 20464 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20465 if (!sUserManager.exists(userId)) return; 20466 final int uid = Binder.getCallingUid(); 20467 final int permission = mContext.checkCallingOrSelfPermission( 20468 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20469 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20470 enforceCrossUserPermission(uid, userId, 20471 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20472 // writer 20473 synchronized (mPackages) { 20474 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20475 allowedByPermission, uid, userId)) { 20476 scheduleWritePackageRestrictionsLocked(userId); 20477 } 20478 } 20479 } 20480 20481 @Override 20482 public String getInstallerPackageName(String packageName) { 20483 // reader 20484 synchronized (mPackages) { 20485 return mSettings.getInstallerPackageNameLPr(packageName); 20486 } 20487 } 20488 20489 public boolean isOrphaned(String packageName) { 20490 // reader 20491 synchronized (mPackages) { 20492 return mSettings.isOrphaned(packageName); 20493 } 20494 } 20495 20496 @Override 20497 public int getApplicationEnabledSetting(String packageName, int userId) { 20498 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20499 int uid = Binder.getCallingUid(); 20500 enforceCrossUserPermission(uid, userId, 20501 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20502 // reader 20503 synchronized (mPackages) { 20504 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20505 } 20506 } 20507 20508 @Override 20509 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20510 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20511 int uid = Binder.getCallingUid(); 20512 enforceCrossUserPermission(uid, userId, 20513 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20514 // reader 20515 synchronized (mPackages) { 20516 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20517 } 20518 } 20519 20520 @Override 20521 public void enterSafeMode() { 20522 enforceSystemOrRoot("Only the system can request entering safe mode"); 20523 20524 if (!mSystemReady) { 20525 mSafeMode = true; 20526 } 20527 } 20528 20529 @Override 20530 public void systemReady() { 20531 mSystemReady = true; 20532 final ContentResolver resolver = mContext.getContentResolver(); 20533 ContentObserver co = new ContentObserver(mHandler) { 20534 @Override 20535 public void onChange(boolean selfChange) { 20536 mEphemeralAppsDisabled = 20537 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20538 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20539 } 20540 }; 20541 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20542 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20543 false, co, UserHandle.USER_SYSTEM); 20544 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20545 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20546 co.onChange(true); 20547 20548 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20549 // disabled after already being started. 20550 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20551 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20552 20553 // Read the compatibilty setting when the system is ready. 20554 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20555 mContext.getContentResolver(), 20556 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20557 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20558 if (DEBUG_SETTINGS) { 20559 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20560 } 20561 20562 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20563 20564 synchronized (mPackages) { 20565 // Verify that all of the preferred activity components actually 20566 // exist. It is possible for applications to be updated and at 20567 // that point remove a previously declared activity component that 20568 // had been set as a preferred activity. We try to clean this up 20569 // the next time we encounter that preferred activity, but it is 20570 // possible for the user flow to never be able to return to that 20571 // situation so here we do a sanity check to make sure we haven't 20572 // left any junk around. 20573 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20574 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20575 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20576 removed.clear(); 20577 for (PreferredActivity pa : pir.filterSet()) { 20578 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20579 removed.add(pa); 20580 } 20581 } 20582 if (removed.size() > 0) { 20583 for (int r=0; r<removed.size(); r++) { 20584 PreferredActivity pa = removed.get(r); 20585 Slog.w(TAG, "Removing dangling preferred activity: " 20586 + pa.mPref.mComponent); 20587 pir.removeFilter(pa); 20588 } 20589 mSettings.writePackageRestrictionsLPr( 20590 mSettings.mPreferredActivities.keyAt(i)); 20591 } 20592 } 20593 20594 for (int userId : UserManagerService.getInstance().getUserIds()) { 20595 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20596 grantPermissionsUserIds = ArrayUtils.appendInt( 20597 grantPermissionsUserIds, userId); 20598 } 20599 } 20600 } 20601 sUserManager.systemReady(); 20602 20603 // If we upgraded grant all default permissions before kicking off. 20604 for (int userId : grantPermissionsUserIds) { 20605 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20606 } 20607 20608 // If we did not grant default permissions, we preload from this the 20609 // default permission exceptions lazily to ensure we don't hit the 20610 // disk on a new user creation. 20611 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20612 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20613 } 20614 20615 // Kick off any messages waiting for system ready 20616 if (mPostSystemReadyMessages != null) { 20617 for (Message msg : mPostSystemReadyMessages) { 20618 msg.sendToTarget(); 20619 } 20620 mPostSystemReadyMessages = null; 20621 } 20622 20623 // Watch for external volumes that come and go over time 20624 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20625 storage.registerListener(mStorageListener); 20626 20627 mInstallerService.systemReady(); 20628 mPackageDexOptimizer.systemReady(); 20629 20630 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20631 StorageManagerInternal.class); 20632 StorageManagerInternal.addExternalStoragePolicy( 20633 new StorageManagerInternal.ExternalStorageMountPolicy() { 20634 @Override 20635 public int getMountMode(int uid, String packageName) { 20636 if (Process.isIsolated(uid)) { 20637 return Zygote.MOUNT_EXTERNAL_NONE; 20638 } 20639 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20640 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20641 } 20642 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20643 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20644 } 20645 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20646 return Zygote.MOUNT_EXTERNAL_READ; 20647 } 20648 return Zygote.MOUNT_EXTERNAL_WRITE; 20649 } 20650 20651 @Override 20652 public boolean hasExternalStorage(int uid, String packageName) { 20653 return true; 20654 } 20655 }); 20656 20657 // Now that we're mostly running, clean up stale users and apps 20658 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20659 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20660 20661 if (mPrivappPermissionsViolations != null) { 20662 Slog.wtf(TAG,"Signature|privileged permissions not in " 20663 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20664 mPrivappPermissionsViolations = null; 20665 } 20666 } 20667 20668 public void waitForAppDataPrepared() { 20669 if (mPrepareAppDataFuture == null) { 20670 return; 20671 } 20672 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20673 mPrepareAppDataFuture = null; 20674 } 20675 20676 @Override 20677 public boolean isSafeMode() { 20678 return mSafeMode; 20679 } 20680 20681 @Override 20682 public boolean hasSystemUidErrors() { 20683 return mHasSystemUidErrors; 20684 } 20685 20686 static String arrayToString(int[] array) { 20687 StringBuffer buf = new StringBuffer(128); 20688 buf.append('['); 20689 if (array != null) { 20690 for (int i=0; i<array.length; i++) { 20691 if (i > 0) buf.append(", "); 20692 buf.append(array[i]); 20693 } 20694 } 20695 buf.append(']'); 20696 return buf.toString(); 20697 } 20698 20699 static class DumpState { 20700 public static final int DUMP_LIBS = 1 << 0; 20701 public static final int DUMP_FEATURES = 1 << 1; 20702 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20703 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20704 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20705 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20706 public static final int DUMP_PERMISSIONS = 1 << 6; 20707 public static final int DUMP_PACKAGES = 1 << 7; 20708 public static final int DUMP_SHARED_USERS = 1 << 8; 20709 public static final int DUMP_MESSAGES = 1 << 9; 20710 public static final int DUMP_PROVIDERS = 1 << 10; 20711 public static final int DUMP_VERIFIERS = 1 << 11; 20712 public static final int DUMP_PREFERRED = 1 << 12; 20713 public static final int DUMP_PREFERRED_XML = 1 << 13; 20714 public static final int DUMP_KEYSETS = 1 << 14; 20715 public static final int DUMP_VERSION = 1 << 15; 20716 public static final int DUMP_INSTALLS = 1 << 16; 20717 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20718 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20719 public static final int DUMP_FROZEN = 1 << 19; 20720 public static final int DUMP_DEXOPT = 1 << 20; 20721 public static final int DUMP_COMPILER_STATS = 1 << 21; 20722 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20723 public static final int DUMP_CHANGES = 1 << 23; 20724 20725 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20726 20727 private int mTypes; 20728 20729 private int mOptions; 20730 20731 private boolean mTitlePrinted; 20732 20733 private SharedUserSetting mSharedUser; 20734 20735 public boolean isDumping(int type) { 20736 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20737 return true; 20738 } 20739 20740 return (mTypes & type) != 0; 20741 } 20742 20743 public void setDump(int type) { 20744 mTypes |= type; 20745 } 20746 20747 public boolean isOptionEnabled(int option) { 20748 return (mOptions & option) != 0; 20749 } 20750 20751 public void setOptionEnabled(int option) { 20752 mOptions |= option; 20753 } 20754 20755 public boolean onTitlePrinted() { 20756 final boolean printed = mTitlePrinted; 20757 mTitlePrinted = true; 20758 return printed; 20759 } 20760 20761 public boolean getTitlePrinted() { 20762 return mTitlePrinted; 20763 } 20764 20765 public void setTitlePrinted(boolean enabled) { 20766 mTitlePrinted = enabled; 20767 } 20768 20769 public SharedUserSetting getSharedUser() { 20770 return mSharedUser; 20771 } 20772 20773 public void setSharedUser(SharedUserSetting user) { 20774 mSharedUser = user; 20775 } 20776 } 20777 20778 @Override 20779 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20780 FileDescriptor err, String[] args, ShellCallback callback, 20781 ResultReceiver resultReceiver) { 20782 (new PackageManagerShellCommand(this)).exec( 20783 this, in, out, err, args, callback, resultReceiver); 20784 } 20785 20786 @Override 20787 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20788 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20789 20790 DumpState dumpState = new DumpState(); 20791 boolean fullPreferred = false; 20792 boolean checkin = false; 20793 20794 String packageName = null; 20795 ArraySet<String> permissionNames = null; 20796 20797 int opti = 0; 20798 while (opti < args.length) { 20799 String opt = args[opti]; 20800 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20801 break; 20802 } 20803 opti++; 20804 20805 if ("-a".equals(opt)) { 20806 // Right now we only know how to print all. 20807 } else if ("-h".equals(opt)) { 20808 pw.println("Package manager dump options:"); 20809 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20810 pw.println(" --checkin: dump for a checkin"); 20811 pw.println(" -f: print details of intent filters"); 20812 pw.println(" -h: print this help"); 20813 pw.println(" cmd may be one of:"); 20814 pw.println(" l[ibraries]: list known shared libraries"); 20815 pw.println(" f[eatures]: list device features"); 20816 pw.println(" k[eysets]: print known keysets"); 20817 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20818 pw.println(" perm[issions]: dump permissions"); 20819 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20820 pw.println(" pref[erred]: print preferred package settings"); 20821 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20822 pw.println(" prov[iders]: dump content providers"); 20823 pw.println(" p[ackages]: dump installed packages"); 20824 pw.println(" s[hared-users]: dump shared user IDs"); 20825 pw.println(" m[essages]: print collected runtime messages"); 20826 pw.println(" v[erifiers]: print package verifier info"); 20827 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20828 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20829 pw.println(" version: print database version info"); 20830 pw.println(" write: write current settings now"); 20831 pw.println(" installs: details about install sessions"); 20832 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20833 pw.println(" dexopt: dump dexopt state"); 20834 pw.println(" compiler-stats: dump compiler statistics"); 20835 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20836 pw.println(" <package.name>: info about given package"); 20837 return; 20838 } else if ("--checkin".equals(opt)) { 20839 checkin = true; 20840 } else if ("-f".equals(opt)) { 20841 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20842 } else if ("--proto".equals(opt)) { 20843 dumpProto(fd); 20844 return; 20845 } else { 20846 pw.println("Unknown argument: " + opt + "; use -h for help"); 20847 } 20848 } 20849 20850 // Is the caller requesting to dump a particular piece of data? 20851 if (opti < args.length) { 20852 String cmd = args[opti]; 20853 opti++; 20854 // Is this a package name? 20855 if ("android".equals(cmd) || cmd.contains(".")) { 20856 packageName = cmd; 20857 // When dumping a single package, we always dump all of its 20858 // filter information since the amount of data will be reasonable. 20859 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20860 } else if ("check-permission".equals(cmd)) { 20861 if (opti >= args.length) { 20862 pw.println("Error: check-permission missing permission argument"); 20863 return; 20864 } 20865 String perm = args[opti]; 20866 opti++; 20867 if (opti >= args.length) { 20868 pw.println("Error: check-permission missing package argument"); 20869 return; 20870 } 20871 20872 String pkg = args[opti]; 20873 opti++; 20874 int user = UserHandle.getUserId(Binder.getCallingUid()); 20875 if (opti < args.length) { 20876 try { 20877 user = Integer.parseInt(args[opti]); 20878 } catch (NumberFormatException e) { 20879 pw.println("Error: check-permission user argument is not a number: " 20880 + args[opti]); 20881 return; 20882 } 20883 } 20884 20885 // Normalize package name to handle renamed packages and static libs 20886 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20887 20888 pw.println(checkPermission(perm, pkg, user)); 20889 return; 20890 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20891 dumpState.setDump(DumpState.DUMP_LIBS); 20892 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20893 dumpState.setDump(DumpState.DUMP_FEATURES); 20894 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20895 if (opti >= args.length) { 20896 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20897 | DumpState.DUMP_SERVICE_RESOLVERS 20898 | DumpState.DUMP_RECEIVER_RESOLVERS 20899 | DumpState.DUMP_CONTENT_RESOLVERS); 20900 } else { 20901 while (opti < args.length) { 20902 String name = args[opti]; 20903 if ("a".equals(name) || "activity".equals(name)) { 20904 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20905 } else if ("s".equals(name) || "service".equals(name)) { 20906 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20907 } else if ("r".equals(name) || "receiver".equals(name)) { 20908 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20909 } else if ("c".equals(name) || "content".equals(name)) { 20910 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20911 } else { 20912 pw.println("Error: unknown resolver table type: " + name); 20913 return; 20914 } 20915 opti++; 20916 } 20917 } 20918 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20919 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20920 } else if ("permission".equals(cmd)) { 20921 if (opti >= args.length) { 20922 pw.println("Error: permission requires permission name"); 20923 return; 20924 } 20925 permissionNames = new ArraySet<>(); 20926 while (opti < args.length) { 20927 permissionNames.add(args[opti]); 20928 opti++; 20929 } 20930 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20931 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20932 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20933 dumpState.setDump(DumpState.DUMP_PREFERRED); 20934 } else if ("preferred-xml".equals(cmd)) { 20935 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20936 if (opti < args.length && "--full".equals(args[opti])) { 20937 fullPreferred = true; 20938 opti++; 20939 } 20940 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20941 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20942 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20943 dumpState.setDump(DumpState.DUMP_PACKAGES); 20944 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20945 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20946 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20947 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20948 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20949 dumpState.setDump(DumpState.DUMP_MESSAGES); 20950 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20951 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20952 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20953 || "intent-filter-verifiers".equals(cmd)) { 20954 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20955 } else if ("version".equals(cmd)) { 20956 dumpState.setDump(DumpState.DUMP_VERSION); 20957 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20958 dumpState.setDump(DumpState.DUMP_KEYSETS); 20959 } else if ("installs".equals(cmd)) { 20960 dumpState.setDump(DumpState.DUMP_INSTALLS); 20961 } else if ("frozen".equals(cmd)) { 20962 dumpState.setDump(DumpState.DUMP_FROZEN); 20963 } else if ("dexopt".equals(cmd)) { 20964 dumpState.setDump(DumpState.DUMP_DEXOPT); 20965 } else if ("compiler-stats".equals(cmd)) { 20966 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20967 } else if ("enabled-overlays".equals(cmd)) { 20968 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20969 } else if ("changes".equals(cmd)) { 20970 dumpState.setDump(DumpState.DUMP_CHANGES); 20971 } else if ("write".equals(cmd)) { 20972 synchronized (mPackages) { 20973 mSettings.writeLPr(); 20974 pw.println("Settings written."); 20975 return; 20976 } 20977 } 20978 } 20979 20980 if (checkin) { 20981 pw.println("vers,1"); 20982 } 20983 20984 // reader 20985 synchronized (mPackages) { 20986 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20987 if (!checkin) { 20988 if (dumpState.onTitlePrinted()) 20989 pw.println(); 20990 pw.println("Database versions:"); 20991 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20992 } 20993 } 20994 20995 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20996 if (!checkin) { 20997 if (dumpState.onTitlePrinted()) 20998 pw.println(); 20999 pw.println("Verifiers:"); 21000 pw.print(" Required: "); 21001 pw.print(mRequiredVerifierPackage); 21002 pw.print(" (uid="); 21003 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21004 UserHandle.USER_SYSTEM)); 21005 pw.println(")"); 21006 } else if (mRequiredVerifierPackage != null) { 21007 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21008 pw.print(","); 21009 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21010 UserHandle.USER_SYSTEM)); 21011 } 21012 } 21013 21014 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21015 packageName == null) { 21016 if (mIntentFilterVerifierComponent != null) { 21017 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21018 if (!checkin) { 21019 if (dumpState.onTitlePrinted()) 21020 pw.println(); 21021 pw.println("Intent Filter Verifier:"); 21022 pw.print(" Using: "); 21023 pw.print(verifierPackageName); 21024 pw.print(" (uid="); 21025 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21026 UserHandle.USER_SYSTEM)); 21027 pw.println(")"); 21028 } else if (verifierPackageName != null) { 21029 pw.print("ifv,"); pw.print(verifierPackageName); 21030 pw.print(","); 21031 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21032 UserHandle.USER_SYSTEM)); 21033 } 21034 } else { 21035 pw.println(); 21036 pw.println("No Intent Filter Verifier available!"); 21037 } 21038 } 21039 21040 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21041 boolean printedHeader = false; 21042 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21043 while (it.hasNext()) { 21044 String libName = it.next(); 21045 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21046 if (versionedLib == null) { 21047 continue; 21048 } 21049 final int versionCount = versionedLib.size(); 21050 for (int i = 0; i < versionCount; i++) { 21051 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21052 if (!checkin) { 21053 if (!printedHeader) { 21054 if (dumpState.onTitlePrinted()) 21055 pw.println(); 21056 pw.println("Libraries:"); 21057 printedHeader = true; 21058 } 21059 pw.print(" "); 21060 } else { 21061 pw.print("lib,"); 21062 } 21063 pw.print(libEntry.info.getName()); 21064 if (libEntry.info.isStatic()) { 21065 pw.print(" version=" + libEntry.info.getVersion()); 21066 } 21067 if (!checkin) { 21068 pw.print(" -> "); 21069 } 21070 if (libEntry.path != null) { 21071 pw.print(" (jar) "); 21072 pw.print(libEntry.path); 21073 } else { 21074 pw.print(" (apk) "); 21075 pw.print(libEntry.apk); 21076 } 21077 pw.println(); 21078 } 21079 } 21080 } 21081 21082 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21083 if (dumpState.onTitlePrinted()) 21084 pw.println(); 21085 if (!checkin) { 21086 pw.println("Features:"); 21087 } 21088 21089 synchronized (mAvailableFeatures) { 21090 for (FeatureInfo feat : mAvailableFeatures.values()) { 21091 if (checkin) { 21092 pw.print("feat,"); 21093 pw.print(feat.name); 21094 pw.print(","); 21095 pw.println(feat.version); 21096 } else { 21097 pw.print(" "); 21098 pw.print(feat.name); 21099 if (feat.version > 0) { 21100 pw.print(" version="); 21101 pw.print(feat.version); 21102 } 21103 pw.println(); 21104 } 21105 } 21106 } 21107 } 21108 21109 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21110 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21111 : "Activity Resolver Table:", " ", packageName, 21112 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21113 dumpState.setTitlePrinted(true); 21114 } 21115 } 21116 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21117 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21118 : "Receiver Resolver Table:", " ", packageName, 21119 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21120 dumpState.setTitlePrinted(true); 21121 } 21122 } 21123 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21124 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21125 : "Service Resolver Table:", " ", packageName, 21126 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21127 dumpState.setTitlePrinted(true); 21128 } 21129 } 21130 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21131 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21132 : "Provider Resolver Table:", " ", packageName, 21133 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21134 dumpState.setTitlePrinted(true); 21135 } 21136 } 21137 21138 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21139 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21140 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21141 int user = mSettings.mPreferredActivities.keyAt(i); 21142 if (pir.dump(pw, 21143 dumpState.getTitlePrinted() 21144 ? "\nPreferred Activities User " + user + ":" 21145 : "Preferred Activities User " + user + ":", " ", 21146 packageName, true, false)) { 21147 dumpState.setTitlePrinted(true); 21148 } 21149 } 21150 } 21151 21152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21153 pw.flush(); 21154 FileOutputStream fout = new FileOutputStream(fd); 21155 BufferedOutputStream str = new BufferedOutputStream(fout); 21156 XmlSerializer serializer = new FastXmlSerializer(); 21157 try { 21158 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21159 serializer.startDocument(null, true); 21160 serializer.setFeature( 21161 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21162 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21163 serializer.endDocument(); 21164 serializer.flush(); 21165 } catch (IllegalArgumentException e) { 21166 pw.println("Failed writing: " + e); 21167 } catch (IllegalStateException e) { 21168 pw.println("Failed writing: " + e); 21169 } catch (IOException e) { 21170 pw.println("Failed writing: " + e); 21171 } 21172 } 21173 21174 if (!checkin 21175 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21176 && packageName == null) { 21177 pw.println(); 21178 int count = mSettings.mPackages.size(); 21179 if (count == 0) { 21180 pw.println("No applications!"); 21181 pw.println(); 21182 } else { 21183 final String prefix = " "; 21184 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21185 if (allPackageSettings.size() == 0) { 21186 pw.println("No domain preferred apps!"); 21187 pw.println(); 21188 } else { 21189 pw.println("App verification status:"); 21190 pw.println(); 21191 count = 0; 21192 for (PackageSetting ps : allPackageSettings) { 21193 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21194 if (ivi == null || ivi.getPackageName() == null) continue; 21195 pw.println(prefix + "Package: " + ivi.getPackageName()); 21196 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21197 pw.println(prefix + "Status: " + ivi.getStatusString()); 21198 pw.println(); 21199 count++; 21200 } 21201 if (count == 0) { 21202 pw.println(prefix + "No app verification established."); 21203 pw.println(); 21204 } 21205 for (int userId : sUserManager.getUserIds()) { 21206 pw.println("App linkages for user " + userId + ":"); 21207 pw.println(); 21208 count = 0; 21209 for (PackageSetting ps : allPackageSettings) { 21210 final long status = ps.getDomainVerificationStatusForUser(userId); 21211 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21212 && !DEBUG_DOMAIN_VERIFICATION) { 21213 continue; 21214 } 21215 pw.println(prefix + "Package: " + ps.name); 21216 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21217 String statusStr = IntentFilterVerificationInfo. 21218 getStatusStringFromValue(status); 21219 pw.println(prefix + "Status: " + statusStr); 21220 pw.println(); 21221 count++; 21222 } 21223 if (count == 0) { 21224 pw.println(prefix + "No configured app linkages."); 21225 pw.println(); 21226 } 21227 } 21228 } 21229 } 21230 } 21231 21232 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21233 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21234 if (packageName == null && permissionNames == null) { 21235 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 21236 if (iperm == 0) { 21237 if (dumpState.onTitlePrinted()) 21238 pw.println(); 21239 pw.println("AppOp Permissions:"); 21240 } 21241 pw.print(" AppOp Permission "); 21242 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 21243 pw.println(":"); 21244 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 21245 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 21246 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 21247 } 21248 } 21249 } 21250 } 21251 21252 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21253 boolean printedSomething = false; 21254 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21255 if (packageName != null && !packageName.equals(p.info.packageName)) { 21256 continue; 21257 } 21258 if (!printedSomething) { 21259 if (dumpState.onTitlePrinted()) 21260 pw.println(); 21261 pw.println("Registered ContentProviders:"); 21262 printedSomething = true; 21263 } 21264 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21265 pw.print(" "); pw.println(p.toString()); 21266 } 21267 printedSomething = false; 21268 for (Map.Entry<String, PackageParser.Provider> entry : 21269 mProvidersByAuthority.entrySet()) { 21270 PackageParser.Provider p = entry.getValue(); 21271 if (packageName != null && !packageName.equals(p.info.packageName)) { 21272 continue; 21273 } 21274 if (!printedSomething) { 21275 if (dumpState.onTitlePrinted()) 21276 pw.println(); 21277 pw.println("ContentProvider Authorities:"); 21278 printedSomething = true; 21279 } 21280 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21281 pw.print(" "); pw.println(p.toString()); 21282 if (p.info != null && p.info.applicationInfo != null) { 21283 final String appInfo = p.info.applicationInfo.toString(); 21284 pw.print(" applicationInfo="); pw.println(appInfo); 21285 } 21286 } 21287 } 21288 21289 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21290 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21291 } 21292 21293 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21294 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21295 } 21296 21297 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21298 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21299 } 21300 21301 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21302 if (dumpState.onTitlePrinted()) pw.println(); 21303 pw.println("Package Changes:"); 21304 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21305 final int K = mChangedPackages.size(); 21306 for (int i = 0; i < K; i++) { 21307 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21308 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21309 final int N = changes.size(); 21310 if (N == 0) { 21311 pw.print(" "); pw.println("No packages changed"); 21312 } else { 21313 for (int j = 0; j < N; j++) { 21314 final String pkgName = changes.valueAt(j); 21315 final int sequenceNumber = changes.keyAt(j); 21316 pw.print(" "); 21317 pw.print("seq="); 21318 pw.print(sequenceNumber); 21319 pw.print(", package="); 21320 pw.println(pkgName); 21321 } 21322 } 21323 } 21324 } 21325 21326 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21327 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21328 } 21329 21330 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21331 // XXX should handle packageName != null by dumping only install data that 21332 // the given package is involved with. 21333 if (dumpState.onTitlePrinted()) pw.println(); 21334 21335 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21336 ipw.println(); 21337 ipw.println("Frozen packages:"); 21338 ipw.increaseIndent(); 21339 if (mFrozenPackages.size() == 0) { 21340 ipw.println("(none)"); 21341 } else { 21342 for (int i = 0; i < mFrozenPackages.size(); i++) { 21343 ipw.println(mFrozenPackages.valueAt(i)); 21344 } 21345 } 21346 ipw.decreaseIndent(); 21347 } 21348 21349 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21350 if (dumpState.onTitlePrinted()) pw.println(); 21351 dumpDexoptStateLPr(pw, packageName); 21352 } 21353 21354 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21355 if (dumpState.onTitlePrinted()) pw.println(); 21356 dumpCompilerStatsLPr(pw, packageName); 21357 } 21358 21359 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 21360 if (dumpState.onTitlePrinted()) pw.println(); 21361 dumpEnabledOverlaysLPr(pw); 21362 } 21363 21364 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21365 if (dumpState.onTitlePrinted()) pw.println(); 21366 mSettings.dumpReadMessagesLPr(pw, dumpState); 21367 21368 pw.println(); 21369 pw.println("Package warning messages:"); 21370 BufferedReader in = null; 21371 String line = null; 21372 try { 21373 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21374 while ((line = in.readLine()) != null) { 21375 if (line.contains("ignored: updated version")) continue; 21376 pw.println(line); 21377 } 21378 } catch (IOException ignored) { 21379 } finally { 21380 IoUtils.closeQuietly(in); 21381 } 21382 } 21383 21384 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21385 BufferedReader in = null; 21386 String line = null; 21387 try { 21388 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21389 while ((line = in.readLine()) != null) { 21390 if (line.contains("ignored: updated version")) continue; 21391 pw.print("msg,"); 21392 pw.println(line); 21393 } 21394 } catch (IOException ignored) { 21395 } finally { 21396 IoUtils.closeQuietly(in); 21397 } 21398 } 21399 } 21400 21401 // PackageInstaller should be called outside of mPackages lock 21402 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21403 // XXX should handle packageName != null by dumping only install data that 21404 // the given package is involved with. 21405 if (dumpState.onTitlePrinted()) pw.println(); 21406 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21407 } 21408 } 21409 21410 private void dumpProto(FileDescriptor fd) { 21411 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21412 21413 synchronized (mPackages) { 21414 final long requiredVerifierPackageToken = 21415 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21416 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21417 proto.write( 21418 PackageServiceDumpProto.PackageShortProto.UID, 21419 getPackageUid( 21420 mRequiredVerifierPackage, 21421 MATCH_DEBUG_TRIAGED_MISSING, 21422 UserHandle.USER_SYSTEM)); 21423 proto.end(requiredVerifierPackageToken); 21424 21425 if (mIntentFilterVerifierComponent != null) { 21426 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21427 final long verifierPackageToken = 21428 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21429 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21430 proto.write( 21431 PackageServiceDumpProto.PackageShortProto.UID, 21432 getPackageUid( 21433 verifierPackageName, 21434 MATCH_DEBUG_TRIAGED_MISSING, 21435 UserHandle.USER_SYSTEM)); 21436 proto.end(verifierPackageToken); 21437 } 21438 21439 dumpSharedLibrariesProto(proto); 21440 dumpFeaturesProto(proto); 21441 mSettings.dumpPackagesProto(proto); 21442 mSettings.dumpSharedUsersProto(proto); 21443 dumpMessagesProto(proto); 21444 } 21445 proto.flush(); 21446 } 21447 21448 private void dumpMessagesProto(ProtoOutputStream proto) { 21449 BufferedReader in = null; 21450 String line = null; 21451 try { 21452 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21453 while ((line = in.readLine()) != null) { 21454 if (line.contains("ignored: updated version")) continue; 21455 proto.write(PackageServiceDumpProto.MESSAGES, line); 21456 } 21457 } catch (IOException ignored) { 21458 } finally { 21459 IoUtils.closeQuietly(in); 21460 } 21461 } 21462 21463 private void dumpFeaturesProto(ProtoOutputStream proto) { 21464 synchronized (mAvailableFeatures) { 21465 final int count = mAvailableFeatures.size(); 21466 for (int i = 0; i < count; i++) { 21467 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21468 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21469 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21470 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21471 proto.end(featureToken); 21472 } 21473 } 21474 } 21475 21476 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21477 final int count = mSharedLibraries.size(); 21478 for (int i = 0; i < count; i++) { 21479 final String libName = mSharedLibraries.keyAt(i); 21480 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21481 if (versionedLib == null) { 21482 continue; 21483 } 21484 final int versionCount = versionedLib.size(); 21485 for (int j = 0; j < versionCount; j++) { 21486 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21487 final long sharedLibraryToken = 21488 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21489 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21490 final boolean isJar = (libEntry.path != null); 21491 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21492 if (isJar) { 21493 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21494 } else { 21495 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21496 } 21497 proto.end(sharedLibraryToken); 21498 } 21499 } 21500 } 21501 21502 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21503 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21504 ipw.println(); 21505 ipw.println("Dexopt state:"); 21506 ipw.increaseIndent(); 21507 Collection<PackageParser.Package> packages = null; 21508 if (packageName != null) { 21509 PackageParser.Package targetPackage = mPackages.get(packageName); 21510 if (targetPackage != null) { 21511 packages = Collections.singletonList(targetPackage); 21512 } else { 21513 ipw.println("Unable to find package: " + packageName); 21514 return; 21515 } 21516 } else { 21517 packages = mPackages.values(); 21518 } 21519 21520 for (PackageParser.Package pkg : packages) { 21521 ipw.println("[" + pkg.packageName + "]"); 21522 ipw.increaseIndent(); 21523 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21524 ipw.decreaseIndent(); 21525 } 21526 } 21527 21528 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21529 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21530 ipw.println(); 21531 ipw.println("Compiler stats:"); 21532 ipw.increaseIndent(); 21533 Collection<PackageParser.Package> packages = null; 21534 if (packageName != null) { 21535 PackageParser.Package targetPackage = mPackages.get(packageName); 21536 if (targetPackage != null) { 21537 packages = Collections.singletonList(targetPackage); 21538 } else { 21539 ipw.println("Unable to find package: " + packageName); 21540 return; 21541 } 21542 } else { 21543 packages = mPackages.values(); 21544 } 21545 21546 for (PackageParser.Package pkg : packages) { 21547 ipw.println("[" + pkg.packageName + "]"); 21548 ipw.increaseIndent(); 21549 21550 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21551 if (stats == null) { 21552 ipw.println("(No recorded stats)"); 21553 } else { 21554 stats.dump(ipw); 21555 } 21556 ipw.decreaseIndent(); 21557 } 21558 } 21559 21560 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21561 pw.println("Enabled overlay paths:"); 21562 final int N = mEnabledOverlayPaths.size(); 21563 for (int i = 0; i < N; i++) { 21564 final int userId = mEnabledOverlayPaths.keyAt(i); 21565 pw.println(String.format(" User %d:", userId)); 21566 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21567 mEnabledOverlayPaths.valueAt(i); 21568 final int M = userSpecificOverlays.size(); 21569 for (int j = 0; j < M; j++) { 21570 final String targetPackageName = userSpecificOverlays.keyAt(j); 21571 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21572 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21573 } 21574 } 21575 } 21576 21577 private String dumpDomainString(String packageName) { 21578 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21579 .getList(); 21580 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21581 21582 ArraySet<String> result = new ArraySet<>(); 21583 if (iviList.size() > 0) { 21584 for (IntentFilterVerificationInfo ivi : iviList) { 21585 for (String host : ivi.getDomains()) { 21586 result.add(host); 21587 } 21588 } 21589 } 21590 if (filters != null && filters.size() > 0) { 21591 for (IntentFilter filter : filters) { 21592 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21593 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21594 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21595 result.addAll(filter.getHostsList()); 21596 } 21597 } 21598 } 21599 21600 StringBuilder sb = new StringBuilder(result.size() * 16); 21601 for (String domain : result) { 21602 if (sb.length() > 0) sb.append(" "); 21603 sb.append(domain); 21604 } 21605 return sb.toString(); 21606 } 21607 21608 // ------- apps on sdcard specific code ------- 21609 static final boolean DEBUG_SD_INSTALL = false; 21610 21611 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21612 21613 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21614 21615 private boolean mMediaMounted = false; 21616 21617 static String getEncryptKey() { 21618 try { 21619 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21620 SD_ENCRYPTION_KEYSTORE_NAME); 21621 if (sdEncKey == null) { 21622 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21623 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21624 if (sdEncKey == null) { 21625 Slog.e(TAG, "Failed to create encryption keys"); 21626 return null; 21627 } 21628 } 21629 return sdEncKey; 21630 } catch (NoSuchAlgorithmException nsae) { 21631 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21632 return null; 21633 } catch (IOException ioe) { 21634 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21635 return null; 21636 } 21637 } 21638 21639 /* 21640 * Update media status on PackageManager. 21641 */ 21642 @Override 21643 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21644 int callingUid = Binder.getCallingUid(); 21645 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21646 throw new SecurityException("Media status can only be updated by the system"); 21647 } 21648 // reader; this apparently protects mMediaMounted, but should probably 21649 // be a different lock in that case. 21650 synchronized (mPackages) { 21651 Log.i(TAG, "Updating external media status from " 21652 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21653 + (mediaStatus ? "mounted" : "unmounted")); 21654 if (DEBUG_SD_INSTALL) 21655 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21656 + ", mMediaMounted=" + mMediaMounted); 21657 if (mediaStatus == mMediaMounted) { 21658 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21659 : 0, -1); 21660 mHandler.sendMessage(msg); 21661 return; 21662 } 21663 mMediaMounted = mediaStatus; 21664 } 21665 // Queue up an async operation since the package installation may take a 21666 // little while. 21667 mHandler.post(new Runnable() { 21668 public void run() { 21669 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21670 } 21671 }); 21672 } 21673 21674 /** 21675 * Called by StorageManagerService when the initial ASECs to scan are available. 21676 * Should block until all the ASEC containers are finished being scanned. 21677 */ 21678 public void scanAvailableAsecs() { 21679 updateExternalMediaStatusInner(true, false, false); 21680 } 21681 21682 /* 21683 * Collect information of applications on external media, map them against 21684 * existing containers and update information based on current mount status. 21685 * Please note that we always have to report status if reportStatus has been 21686 * set to true especially when unloading packages. 21687 */ 21688 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21689 boolean externalStorage) { 21690 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21691 int[] uidArr = EmptyArray.INT; 21692 21693 final String[] list = PackageHelper.getSecureContainerList(); 21694 if (ArrayUtils.isEmpty(list)) { 21695 Log.i(TAG, "No secure containers found"); 21696 } else { 21697 // Process list of secure containers and categorize them 21698 // as active or stale based on their package internal state. 21699 21700 // reader 21701 synchronized (mPackages) { 21702 for (String cid : list) { 21703 // Leave stages untouched for now; installer service owns them 21704 if (PackageInstallerService.isStageName(cid)) continue; 21705 21706 if (DEBUG_SD_INSTALL) 21707 Log.i(TAG, "Processing container " + cid); 21708 String pkgName = getAsecPackageName(cid); 21709 if (pkgName == null) { 21710 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21711 continue; 21712 } 21713 if (DEBUG_SD_INSTALL) 21714 Log.i(TAG, "Looking for pkg : " + pkgName); 21715 21716 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21717 if (ps == null) { 21718 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21719 continue; 21720 } 21721 21722 /* 21723 * Skip packages that are not external if we're unmounting 21724 * external storage. 21725 */ 21726 if (externalStorage && !isMounted && !isExternal(ps)) { 21727 continue; 21728 } 21729 21730 final AsecInstallArgs args = new AsecInstallArgs(cid, 21731 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21732 // The package status is changed only if the code path 21733 // matches between settings and the container id. 21734 if (ps.codePathString != null 21735 && ps.codePathString.startsWith(args.getCodePath())) { 21736 if (DEBUG_SD_INSTALL) { 21737 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21738 + " at code path: " + ps.codePathString); 21739 } 21740 21741 // We do have a valid package installed on sdcard 21742 processCids.put(args, ps.codePathString); 21743 final int uid = ps.appId; 21744 if (uid != -1) { 21745 uidArr = ArrayUtils.appendInt(uidArr, uid); 21746 } 21747 } else { 21748 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21749 + ps.codePathString); 21750 } 21751 } 21752 } 21753 21754 Arrays.sort(uidArr); 21755 } 21756 21757 // Process packages with valid entries. 21758 if (isMounted) { 21759 if (DEBUG_SD_INSTALL) 21760 Log.i(TAG, "Loading packages"); 21761 loadMediaPackages(processCids, uidArr, externalStorage); 21762 startCleaningPackages(); 21763 mInstallerService.onSecureContainersAvailable(); 21764 } else { 21765 if (DEBUG_SD_INSTALL) 21766 Log.i(TAG, "Unloading packages"); 21767 unloadMediaPackages(processCids, uidArr, reportStatus); 21768 } 21769 } 21770 21771 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21772 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21773 final int size = infos.size(); 21774 final String[] packageNames = new String[size]; 21775 final int[] packageUids = new int[size]; 21776 for (int i = 0; i < size; i++) { 21777 final ApplicationInfo info = infos.get(i); 21778 packageNames[i] = info.packageName; 21779 packageUids[i] = info.uid; 21780 } 21781 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21782 finishedReceiver); 21783 } 21784 21785 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21786 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21787 sendResourcesChangedBroadcast(mediaStatus, replacing, 21788 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21789 } 21790 21791 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21792 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21793 int size = pkgList.length; 21794 if (size > 0) { 21795 // Send broadcasts here 21796 Bundle extras = new Bundle(); 21797 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21798 if (uidArr != null) { 21799 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21800 } 21801 if (replacing) { 21802 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21803 } 21804 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21805 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21806 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21807 } 21808 } 21809 21810 /* 21811 * Look at potentially valid container ids from processCids If package 21812 * information doesn't match the one on record or package scanning fails, 21813 * the cid is added to list of removeCids. We currently don't delete stale 21814 * containers. 21815 */ 21816 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21817 boolean externalStorage) { 21818 ArrayList<String> pkgList = new ArrayList<String>(); 21819 Set<AsecInstallArgs> keys = processCids.keySet(); 21820 21821 for (AsecInstallArgs args : keys) { 21822 String codePath = processCids.get(args); 21823 if (DEBUG_SD_INSTALL) 21824 Log.i(TAG, "Loading container : " + args.cid); 21825 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21826 try { 21827 // Make sure there are no container errors first. 21828 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21829 Slog.e(TAG, "Failed to mount cid : " + args.cid 21830 + " when installing from sdcard"); 21831 continue; 21832 } 21833 // Check code path here. 21834 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21835 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21836 + " does not match one in settings " + codePath); 21837 continue; 21838 } 21839 // Parse package 21840 int parseFlags = mDefParseFlags; 21841 if (args.isExternalAsec()) { 21842 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21843 } 21844 if (args.isFwdLocked()) { 21845 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21846 } 21847 21848 synchronized (mInstallLock) { 21849 PackageParser.Package pkg = null; 21850 try { 21851 // Sadly we don't know the package name yet to freeze it 21852 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21853 SCAN_IGNORE_FROZEN, 0, null); 21854 } catch (PackageManagerException e) { 21855 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21856 } 21857 // Scan the package 21858 if (pkg != null) { 21859 /* 21860 * TODO why is the lock being held? doPostInstall is 21861 * called in other places without the lock. This needs 21862 * to be straightened out. 21863 */ 21864 // writer 21865 synchronized (mPackages) { 21866 retCode = PackageManager.INSTALL_SUCCEEDED; 21867 pkgList.add(pkg.packageName); 21868 // Post process args 21869 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21870 pkg.applicationInfo.uid); 21871 } 21872 } else { 21873 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21874 } 21875 } 21876 21877 } finally { 21878 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21879 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21880 } 21881 } 21882 } 21883 // writer 21884 synchronized (mPackages) { 21885 // If the platform SDK has changed since the last time we booted, 21886 // we need to re-grant app permission to catch any new ones that 21887 // appear. This is really a hack, and means that apps can in some 21888 // cases get permissions that the user didn't initially explicitly 21889 // allow... it would be nice to have some better way to handle 21890 // this situation. 21891 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21892 : mSettings.getInternalVersion(); 21893 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21894 : StorageManager.UUID_PRIVATE_INTERNAL; 21895 21896 int updateFlags = UPDATE_PERMISSIONS_ALL; 21897 if (ver.sdkVersion != mSdkVersion) { 21898 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21899 + mSdkVersion + "; regranting permissions for external"); 21900 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21901 } 21902 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21903 21904 // Yay, everything is now upgraded 21905 ver.forceCurrent(); 21906 21907 // can downgrade to reader 21908 // Persist settings 21909 mSettings.writeLPr(); 21910 } 21911 // Send a broadcast to let everyone know we are done processing 21912 if (pkgList.size() > 0) { 21913 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21914 } 21915 } 21916 21917 /* 21918 * Utility method to unload a list of specified containers 21919 */ 21920 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21921 // Just unmount all valid containers. 21922 for (AsecInstallArgs arg : cidArgs) { 21923 synchronized (mInstallLock) { 21924 arg.doPostDeleteLI(false); 21925 } 21926 } 21927 } 21928 21929 /* 21930 * Unload packages mounted on external media. This involves deleting package 21931 * data from internal structures, sending broadcasts about disabled packages, 21932 * gc'ing to free up references, unmounting all secure containers 21933 * corresponding to packages on external media, and posting a 21934 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21935 * that we always have to post this message if status has been requested no 21936 * matter what. 21937 */ 21938 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21939 final boolean reportStatus) { 21940 if (DEBUG_SD_INSTALL) 21941 Log.i(TAG, "unloading media packages"); 21942 ArrayList<String> pkgList = new ArrayList<String>(); 21943 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21944 final Set<AsecInstallArgs> keys = processCids.keySet(); 21945 for (AsecInstallArgs args : keys) { 21946 String pkgName = args.getPackageName(); 21947 if (DEBUG_SD_INSTALL) 21948 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21949 // Delete package internally 21950 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21951 synchronized (mInstallLock) { 21952 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21953 final boolean res; 21954 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21955 "unloadMediaPackages")) { 21956 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21957 null); 21958 } 21959 if (res) { 21960 pkgList.add(pkgName); 21961 } else { 21962 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21963 failedList.add(args); 21964 } 21965 } 21966 } 21967 21968 // reader 21969 synchronized (mPackages) { 21970 // We didn't update the settings after removing each package; 21971 // write them now for all packages. 21972 mSettings.writeLPr(); 21973 } 21974 21975 // We have to absolutely send UPDATED_MEDIA_STATUS only 21976 // after confirming that all the receivers processed the ordered 21977 // broadcast when packages get disabled, force a gc to clean things up. 21978 // and unload all the containers. 21979 if (pkgList.size() > 0) { 21980 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21981 new IIntentReceiver.Stub() { 21982 public void performReceive(Intent intent, int resultCode, String data, 21983 Bundle extras, boolean ordered, boolean sticky, 21984 int sendingUser) throws RemoteException { 21985 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21986 reportStatus ? 1 : 0, 1, keys); 21987 mHandler.sendMessage(msg); 21988 } 21989 }); 21990 } else { 21991 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21992 keys); 21993 mHandler.sendMessage(msg); 21994 } 21995 } 21996 21997 private void loadPrivatePackages(final VolumeInfo vol) { 21998 mHandler.post(new Runnable() { 21999 @Override 22000 public void run() { 22001 loadPrivatePackagesInner(vol); 22002 } 22003 }); 22004 } 22005 22006 private void loadPrivatePackagesInner(VolumeInfo vol) { 22007 final String volumeUuid = vol.fsUuid; 22008 if (TextUtils.isEmpty(volumeUuid)) { 22009 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22010 return; 22011 } 22012 22013 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22014 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22015 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22016 22017 final VersionInfo ver; 22018 final List<PackageSetting> packages; 22019 synchronized (mPackages) { 22020 ver = mSettings.findOrCreateVersion(volumeUuid); 22021 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22022 } 22023 22024 for (PackageSetting ps : packages) { 22025 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22026 synchronized (mInstallLock) { 22027 final PackageParser.Package pkg; 22028 try { 22029 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22030 loaded.add(pkg.applicationInfo); 22031 22032 } catch (PackageManagerException e) { 22033 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22034 } 22035 22036 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22037 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 22038 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 22039 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22040 } 22041 } 22042 } 22043 22044 // Reconcile app data for all started/unlocked users 22045 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22046 final UserManager um = mContext.getSystemService(UserManager.class); 22047 UserManagerInternal umInternal = getUserManagerInternal(); 22048 for (UserInfo user : um.getUsers()) { 22049 final int flags; 22050 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22051 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22052 } else if (umInternal.isUserRunning(user.id)) { 22053 flags = StorageManager.FLAG_STORAGE_DE; 22054 } else { 22055 continue; 22056 } 22057 22058 try { 22059 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22060 synchronized (mInstallLock) { 22061 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22062 } 22063 } catch (IllegalStateException e) { 22064 // Device was probably ejected, and we'll process that event momentarily 22065 Slog.w(TAG, "Failed to prepare storage: " + e); 22066 } 22067 } 22068 22069 synchronized (mPackages) { 22070 int updateFlags = UPDATE_PERMISSIONS_ALL; 22071 if (ver.sdkVersion != mSdkVersion) { 22072 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22073 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22074 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22075 } 22076 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22077 22078 // Yay, everything is now upgraded 22079 ver.forceCurrent(); 22080 22081 mSettings.writeLPr(); 22082 } 22083 22084 for (PackageFreezer freezer : freezers) { 22085 freezer.close(); 22086 } 22087 22088 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22089 sendResourcesChangedBroadcast(true, false, loaded, null); 22090 } 22091 22092 private void unloadPrivatePackages(final VolumeInfo vol) { 22093 mHandler.post(new Runnable() { 22094 @Override 22095 public void run() { 22096 unloadPrivatePackagesInner(vol); 22097 } 22098 }); 22099 } 22100 22101 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22102 final String volumeUuid = vol.fsUuid; 22103 if (TextUtils.isEmpty(volumeUuid)) { 22104 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22105 return; 22106 } 22107 22108 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22109 synchronized (mInstallLock) { 22110 synchronized (mPackages) { 22111 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22112 for (PackageSetting ps : packages) { 22113 if (ps.pkg == null) continue; 22114 22115 final ApplicationInfo info = ps.pkg.applicationInfo; 22116 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22117 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22118 22119 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22120 "unloadPrivatePackagesInner")) { 22121 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22122 false, null)) { 22123 unloaded.add(info); 22124 } else { 22125 Slog.w(TAG, "Failed to unload " + ps.codePath); 22126 } 22127 } 22128 22129 // Try very hard to release any references to this package 22130 // so we don't risk the system server being killed due to 22131 // open FDs 22132 AttributeCache.instance().removePackage(ps.name); 22133 } 22134 22135 mSettings.writeLPr(); 22136 } 22137 } 22138 22139 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22140 sendResourcesChangedBroadcast(false, false, unloaded, null); 22141 22142 // Try very hard to release any references to this path so we don't risk 22143 // the system server being killed due to open FDs 22144 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22145 22146 for (int i = 0; i < 3; i++) { 22147 System.gc(); 22148 System.runFinalization(); 22149 } 22150 } 22151 22152 private void assertPackageKnown(String volumeUuid, String packageName) 22153 throws PackageManagerException { 22154 synchronized (mPackages) { 22155 // Normalize package name to handle renamed packages 22156 packageName = normalizePackageNameLPr(packageName); 22157 22158 final PackageSetting ps = mSettings.mPackages.get(packageName); 22159 if (ps == null) { 22160 throw new PackageManagerException("Package " + packageName + " is unknown"); 22161 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22162 throw new PackageManagerException( 22163 "Package " + packageName + " found on unknown volume " + volumeUuid 22164 + "; expected volume " + ps.volumeUuid); 22165 } 22166 } 22167 } 22168 22169 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22170 throws PackageManagerException { 22171 synchronized (mPackages) { 22172 // Normalize package name to handle renamed packages 22173 packageName = normalizePackageNameLPr(packageName); 22174 22175 final PackageSetting ps = mSettings.mPackages.get(packageName); 22176 if (ps == null) { 22177 throw new PackageManagerException("Package " + packageName + " is unknown"); 22178 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22179 throw new PackageManagerException( 22180 "Package " + packageName + " found on unknown volume " + volumeUuid 22181 + "; expected volume " + ps.volumeUuid); 22182 } else if (!ps.getInstalled(userId)) { 22183 throw new PackageManagerException( 22184 "Package " + packageName + " not installed for user " + userId); 22185 } 22186 } 22187 } 22188 22189 private List<String> collectAbsoluteCodePaths() { 22190 synchronized (mPackages) { 22191 List<String> codePaths = new ArrayList<>(); 22192 final int packageCount = mSettings.mPackages.size(); 22193 for (int i = 0; i < packageCount; i++) { 22194 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22195 codePaths.add(ps.codePath.getAbsolutePath()); 22196 } 22197 return codePaths; 22198 } 22199 } 22200 22201 /** 22202 * Examine all apps present on given mounted volume, and destroy apps that 22203 * aren't expected, either due to uninstallation or reinstallation on 22204 * another volume. 22205 */ 22206 private void reconcileApps(String volumeUuid) { 22207 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22208 List<File> filesToDelete = null; 22209 22210 final File[] files = FileUtils.listFilesOrEmpty( 22211 Environment.getDataAppDirectory(volumeUuid)); 22212 for (File file : files) { 22213 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22214 && !PackageInstallerService.isStageName(file.getName()); 22215 if (!isPackage) { 22216 // Ignore entries which are not packages 22217 continue; 22218 } 22219 22220 String absolutePath = file.getAbsolutePath(); 22221 22222 boolean pathValid = false; 22223 final int absoluteCodePathCount = absoluteCodePaths.size(); 22224 for (int i = 0; i < absoluteCodePathCount; i++) { 22225 String absoluteCodePath = absoluteCodePaths.get(i); 22226 if (absolutePath.startsWith(absoluteCodePath)) { 22227 pathValid = true; 22228 break; 22229 } 22230 } 22231 22232 if (!pathValid) { 22233 if (filesToDelete == null) { 22234 filesToDelete = new ArrayList<>(); 22235 } 22236 filesToDelete.add(file); 22237 } 22238 } 22239 22240 if (filesToDelete != null) { 22241 final int fileToDeleteCount = filesToDelete.size(); 22242 for (int i = 0; i < fileToDeleteCount; i++) { 22243 File fileToDelete = filesToDelete.get(i); 22244 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22245 synchronized (mInstallLock) { 22246 removeCodePathLI(fileToDelete); 22247 } 22248 } 22249 } 22250 } 22251 22252 /** 22253 * Reconcile all app data for the given user. 22254 * <p> 22255 * Verifies that directories exist and that ownership and labeling is 22256 * correct for all installed apps on all mounted volumes. 22257 */ 22258 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22259 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22260 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22261 final String volumeUuid = vol.getFsUuid(); 22262 synchronized (mInstallLock) { 22263 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22264 } 22265 } 22266 } 22267 22268 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22269 boolean migrateAppData) { 22270 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22271 } 22272 22273 /** 22274 * Reconcile all app data on given mounted volume. 22275 * <p> 22276 * Destroys app data that isn't expected, either due to uninstallation or 22277 * reinstallation on another volume. 22278 * <p> 22279 * Verifies that directories exist and that ownership and labeling is 22280 * correct for all installed apps. 22281 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22282 */ 22283 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22284 boolean migrateAppData, boolean onlyCoreApps) { 22285 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22286 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22287 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22288 22289 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22290 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22291 22292 // First look for stale data that doesn't belong, and check if things 22293 // have changed since we did our last restorecon 22294 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22295 if (StorageManager.isFileEncryptedNativeOrEmulated() 22296 && !StorageManager.isUserKeyUnlocked(userId)) { 22297 throw new RuntimeException( 22298 "Yikes, someone asked us to reconcile CE storage while " + userId 22299 + " was still locked; this would have caused massive data loss!"); 22300 } 22301 22302 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22303 for (File file : files) { 22304 final String packageName = file.getName(); 22305 try { 22306 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22307 } catch (PackageManagerException e) { 22308 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22309 try { 22310 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22311 StorageManager.FLAG_STORAGE_CE, 0); 22312 } catch (InstallerException e2) { 22313 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22314 } 22315 } 22316 } 22317 } 22318 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22319 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22320 for (File file : files) { 22321 final String packageName = file.getName(); 22322 try { 22323 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22324 } catch (PackageManagerException e) { 22325 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22326 try { 22327 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22328 StorageManager.FLAG_STORAGE_DE, 0); 22329 } catch (InstallerException e2) { 22330 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22331 } 22332 } 22333 } 22334 } 22335 22336 // Ensure that data directories are ready to roll for all packages 22337 // installed for this volume and user 22338 final List<PackageSetting> packages; 22339 synchronized (mPackages) { 22340 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22341 } 22342 int preparedCount = 0; 22343 for (PackageSetting ps : packages) { 22344 final String packageName = ps.name; 22345 if (ps.pkg == null) { 22346 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22347 // TODO: might be due to legacy ASEC apps; we should circle back 22348 // and reconcile again once they're scanned 22349 continue; 22350 } 22351 // Skip non-core apps if requested 22352 if (onlyCoreApps && !ps.pkg.coreApp) { 22353 result.add(packageName); 22354 continue; 22355 } 22356 22357 if (ps.getInstalled(userId)) { 22358 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22359 preparedCount++; 22360 } 22361 } 22362 22363 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22364 return result; 22365 } 22366 22367 /** 22368 * Prepare app data for the given app just after it was installed or 22369 * upgraded. This method carefully only touches users that it's installed 22370 * for, and it forces a restorecon to handle any seinfo changes. 22371 * <p> 22372 * Verifies that directories exist and that ownership and labeling is 22373 * correct for all installed apps. If there is an ownership mismatch, it 22374 * will try recovering system apps by wiping data; third-party app data is 22375 * left intact. 22376 * <p> 22377 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22378 */ 22379 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22380 final PackageSetting ps; 22381 synchronized (mPackages) { 22382 ps = mSettings.mPackages.get(pkg.packageName); 22383 mSettings.writeKernelMappingLPr(ps); 22384 } 22385 22386 final UserManager um = mContext.getSystemService(UserManager.class); 22387 UserManagerInternal umInternal = getUserManagerInternal(); 22388 for (UserInfo user : um.getUsers()) { 22389 final int flags; 22390 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22391 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22392 } else if (umInternal.isUserRunning(user.id)) { 22393 flags = StorageManager.FLAG_STORAGE_DE; 22394 } else { 22395 continue; 22396 } 22397 22398 if (ps.getInstalled(user.id)) { 22399 // TODO: when user data is locked, mark that we're still dirty 22400 prepareAppDataLIF(pkg, user.id, flags); 22401 } 22402 } 22403 } 22404 22405 /** 22406 * Prepare app data for the given app. 22407 * <p> 22408 * Verifies that directories exist and that ownership and labeling is 22409 * correct for all installed apps. If there is an ownership mismatch, this 22410 * will try recovering system apps by wiping data; third-party app data is 22411 * left intact. 22412 */ 22413 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22414 if (pkg == null) { 22415 Slog.wtf(TAG, "Package was null!", new Throwable()); 22416 return; 22417 } 22418 prepareAppDataLeafLIF(pkg, userId, flags); 22419 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22420 for (int i = 0; i < childCount; i++) { 22421 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22422 } 22423 } 22424 22425 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22426 boolean maybeMigrateAppData) { 22427 prepareAppDataLIF(pkg, userId, flags); 22428 22429 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22430 // We may have just shuffled around app data directories, so 22431 // prepare them one more time 22432 prepareAppDataLIF(pkg, userId, flags); 22433 } 22434 } 22435 22436 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22437 if (DEBUG_APP_DATA) { 22438 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22439 + Integer.toHexString(flags)); 22440 } 22441 22442 final String volumeUuid = pkg.volumeUuid; 22443 final String packageName = pkg.packageName; 22444 final ApplicationInfo app = pkg.applicationInfo; 22445 final int appId = UserHandle.getAppId(app.uid); 22446 22447 Preconditions.checkNotNull(app.seInfo); 22448 22449 long ceDataInode = -1; 22450 try { 22451 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22452 appId, app.seInfo, app.targetSdkVersion); 22453 } catch (InstallerException e) { 22454 if (app.isSystemApp()) { 22455 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22456 + ", but trying to recover: " + e); 22457 destroyAppDataLeafLIF(pkg, userId, flags); 22458 try { 22459 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22460 appId, app.seInfo, app.targetSdkVersion); 22461 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22462 } catch (InstallerException e2) { 22463 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22464 } 22465 } else { 22466 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22467 } 22468 } 22469 22470 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22471 // TODO: mark this structure as dirty so we persist it! 22472 synchronized (mPackages) { 22473 final PackageSetting ps = mSettings.mPackages.get(packageName); 22474 if (ps != null) { 22475 ps.setCeDataInode(ceDataInode, userId); 22476 } 22477 } 22478 } 22479 22480 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22481 } 22482 22483 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22484 if (pkg == null) { 22485 Slog.wtf(TAG, "Package was null!", new Throwable()); 22486 return; 22487 } 22488 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22489 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22490 for (int i = 0; i < childCount; i++) { 22491 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22492 } 22493 } 22494 22495 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22496 final String volumeUuid = pkg.volumeUuid; 22497 final String packageName = pkg.packageName; 22498 final ApplicationInfo app = pkg.applicationInfo; 22499 22500 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22501 // Create a native library symlink only if we have native libraries 22502 // and if the native libraries are 32 bit libraries. We do not provide 22503 // this symlink for 64 bit libraries. 22504 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22505 final String nativeLibPath = app.nativeLibraryDir; 22506 try { 22507 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22508 nativeLibPath, userId); 22509 } catch (InstallerException e) { 22510 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22511 } 22512 } 22513 } 22514 } 22515 22516 /** 22517 * For system apps on non-FBE devices, this method migrates any existing 22518 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22519 * requested by the app. 22520 */ 22521 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22522 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22523 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22524 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22525 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22526 try { 22527 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22528 storageTarget); 22529 } catch (InstallerException e) { 22530 logCriticalInfo(Log.WARN, 22531 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22532 } 22533 return true; 22534 } else { 22535 return false; 22536 } 22537 } 22538 22539 public PackageFreezer freezePackage(String packageName, String killReason) { 22540 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22541 } 22542 22543 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22544 return new PackageFreezer(packageName, userId, killReason); 22545 } 22546 22547 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22548 String killReason) { 22549 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22550 } 22551 22552 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22553 String killReason) { 22554 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22555 return new PackageFreezer(); 22556 } else { 22557 return freezePackage(packageName, userId, killReason); 22558 } 22559 } 22560 22561 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22562 String killReason) { 22563 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22564 } 22565 22566 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22567 String killReason) { 22568 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22569 return new PackageFreezer(); 22570 } else { 22571 return freezePackage(packageName, userId, killReason); 22572 } 22573 } 22574 22575 /** 22576 * Class that freezes and kills the given package upon creation, and 22577 * unfreezes it upon closing. This is typically used when doing surgery on 22578 * app code/data to prevent the app from running while you're working. 22579 */ 22580 private class PackageFreezer implements AutoCloseable { 22581 private final String mPackageName; 22582 private final PackageFreezer[] mChildren; 22583 22584 private final boolean mWeFroze; 22585 22586 private final AtomicBoolean mClosed = new AtomicBoolean(); 22587 private final CloseGuard mCloseGuard = CloseGuard.get(); 22588 22589 /** 22590 * Create and return a stub freezer that doesn't actually do anything, 22591 * typically used when someone requested 22592 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22593 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22594 */ 22595 public PackageFreezer() { 22596 mPackageName = null; 22597 mChildren = null; 22598 mWeFroze = false; 22599 mCloseGuard.open("close"); 22600 } 22601 22602 public PackageFreezer(String packageName, int userId, String killReason) { 22603 synchronized (mPackages) { 22604 mPackageName = packageName; 22605 mWeFroze = mFrozenPackages.add(mPackageName); 22606 22607 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22608 if (ps != null) { 22609 killApplication(ps.name, ps.appId, userId, killReason); 22610 } 22611 22612 final PackageParser.Package p = mPackages.get(packageName); 22613 if (p != null && p.childPackages != null) { 22614 final int N = p.childPackages.size(); 22615 mChildren = new PackageFreezer[N]; 22616 for (int i = 0; i < N; i++) { 22617 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22618 userId, killReason); 22619 } 22620 } else { 22621 mChildren = null; 22622 } 22623 } 22624 mCloseGuard.open("close"); 22625 } 22626 22627 @Override 22628 protected void finalize() throws Throwable { 22629 try { 22630 mCloseGuard.warnIfOpen(); 22631 close(); 22632 } finally { 22633 super.finalize(); 22634 } 22635 } 22636 22637 @Override 22638 public void close() { 22639 mCloseGuard.close(); 22640 if (mClosed.compareAndSet(false, true)) { 22641 synchronized (mPackages) { 22642 if (mWeFroze) { 22643 mFrozenPackages.remove(mPackageName); 22644 } 22645 22646 if (mChildren != null) { 22647 for (PackageFreezer freezer : mChildren) { 22648 freezer.close(); 22649 } 22650 } 22651 } 22652 } 22653 } 22654 } 22655 22656 /** 22657 * Verify that given package is currently frozen. 22658 */ 22659 private void checkPackageFrozen(String packageName) { 22660 synchronized (mPackages) { 22661 if (!mFrozenPackages.contains(packageName)) { 22662 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22663 } 22664 } 22665 } 22666 22667 @Override 22668 public int movePackage(final String packageName, final String volumeUuid) { 22669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22670 22671 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22672 final int moveId = mNextMoveId.getAndIncrement(); 22673 mHandler.post(new Runnable() { 22674 @Override 22675 public void run() { 22676 try { 22677 movePackageInternal(packageName, volumeUuid, moveId, user); 22678 } catch (PackageManagerException e) { 22679 Slog.w(TAG, "Failed to move " + packageName, e); 22680 mMoveCallbacks.notifyStatusChanged(moveId, 22681 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22682 } 22683 } 22684 }); 22685 return moveId; 22686 } 22687 22688 private void movePackageInternal(final String packageName, final String volumeUuid, 22689 final int moveId, UserHandle user) throws PackageManagerException { 22690 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22691 final PackageManager pm = mContext.getPackageManager(); 22692 22693 final boolean currentAsec; 22694 final String currentVolumeUuid; 22695 final File codeFile; 22696 final String installerPackageName; 22697 final String packageAbiOverride; 22698 final int appId; 22699 final String seinfo; 22700 final String label; 22701 final int targetSdkVersion; 22702 final PackageFreezer freezer; 22703 final int[] installedUserIds; 22704 22705 // reader 22706 synchronized (mPackages) { 22707 final PackageParser.Package pkg = mPackages.get(packageName); 22708 final PackageSetting ps = mSettings.mPackages.get(packageName); 22709 if (pkg == null || ps == null) { 22710 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22711 } 22712 22713 if (pkg.applicationInfo.isSystemApp()) { 22714 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22715 "Cannot move system application"); 22716 } 22717 22718 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22719 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22720 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22721 if (isInternalStorage && !allow3rdPartyOnInternal) { 22722 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22723 "3rd party apps are not allowed on internal storage"); 22724 } 22725 22726 if (pkg.applicationInfo.isExternalAsec()) { 22727 currentAsec = true; 22728 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22729 } else if (pkg.applicationInfo.isForwardLocked()) { 22730 currentAsec = true; 22731 currentVolumeUuid = "forward_locked"; 22732 } else { 22733 currentAsec = false; 22734 currentVolumeUuid = ps.volumeUuid; 22735 22736 final File probe = new File(pkg.codePath); 22737 final File probeOat = new File(probe, "oat"); 22738 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22739 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22740 "Move only supported for modern cluster style installs"); 22741 } 22742 } 22743 22744 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22745 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22746 "Package already moved to " + volumeUuid); 22747 } 22748 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22749 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22750 "Device admin cannot be moved"); 22751 } 22752 22753 if (mFrozenPackages.contains(packageName)) { 22754 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22755 "Failed to move already frozen package"); 22756 } 22757 22758 codeFile = new File(pkg.codePath); 22759 installerPackageName = ps.installerPackageName; 22760 packageAbiOverride = ps.cpuAbiOverrideString; 22761 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22762 seinfo = pkg.applicationInfo.seInfo; 22763 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22764 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22765 freezer = freezePackage(packageName, "movePackageInternal"); 22766 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22767 } 22768 22769 final Bundle extras = new Bundle(); 22770 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22771 extras.putString(Intent.EXTRA_TITLE, label); 22772 mMoveCallbacks.notifyCreated(moveId, extras); 22773 22774 int installFlags; 22775 final boolean moveCompleteApp; 22776 final File measurePath; 22777 22778 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22779 installFlags = INSTALL_INTERNAL; 22780 moveCompleteApp = !currentAsec; 22781 measurePath = Environment.getDataAppDirectory(volumeUuid); 22782 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22783 installFlags = INSTALL_EXTERNAL; 22784 moveCompleteApp = false; 22785 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22786 } else { 22787 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22788 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22789 || !volume.isMountedWritable()) { 22790 freezer.close(); 22791 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22792 "Move location not mounted private volume"); 22793 } 22794 22795 Preconditions.checkState(!currentAsec); 22796 22797 installFlags = INSTALL_INTERNAL; 22798 moveCompleteApp = true; 22799 measurePath = Environment.getDataAppDirectory(volumeUuid); 22800 } 22801 22802 final PackageStats stats = new PackageStats(null, -1); 22803 synchronized (mInstaller) { 22804 for (int userId : installedUserIds) { 22805 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22806 freezer.close(); 22807 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22808 "Failed to measure package size"); 22809 } 22810 } 22811 } 22812 22813 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22814 + stats.dataSize); 22815 22816 final long startFreeBytes = measurePath.getUsableSpace(); 22817 final long sizeBytes; 22818 if (moveCompleteApp) { 22819 sizeBytes = stats.codeSize + stats.dataSize; 22820 } else { 22821 sizeBytes = stats.codeSize; 22822 } 22823 22824 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22825 freezer.close(); 22826 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22827 "Not enough free space to move"); 22828 } 22829 22830 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22831 22832 final CountDownLatch installedLatch = new CountDownLatch(1); 22833 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22834 @Override 22835 public void onUserActionRequired(Intent intent) throws RemoteException { 22836 throw new IllegalStateException(); 22837 } 22838 22839 @Override 22840 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22841 Bundle extras) throws RemoteException { 22842 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22843 + PackageManager.installStatusToString(returnCode, msg)); 22844 22845 installedLatch.countDown(); 22846 freezer.close(); 22847 22848 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22849 switch (status) { 22850 case PackageInstaller.STATUS_SUCCESS: 22851 mMoveCallbacks.notifyStatusChanged(moveId, 22852 PackageManager.MOVE_SUCCEEDED); 22853 break; 22854 case PackageInstaller.STATUS_FAILURE_STORAGE: 22855 mMoveCallbacks.notifyStatusChanged(moveId, 22856 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22857 break; 22858 default: 22859 mMoveCallbacks.notifyStatusChanged(moveId, 22860 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22861 break; 22862 } 22863 } 22864 }; 22865 22866 final MoveInfo move; 22867 if (moveCompleteApp) { 22868 // Kick off a thread to report progress estimates 22869 new Thread() { 22870 @Override 22871 public void run() { 22872 while (true) { 22873 try { 22874 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22875 break; 22876 } 22877 } catch (InterruptedException ignored) { 22878 } 22879 22880 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22881 final int progress = 10 + (int) MathUtils.constrain( 22882 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22883 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22884 } 22885 } 22886 }.start(); 22887 22888 final String dataAppName = codeFile.getName(); 22889 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22890 dataAppName, appId, seinfo, targetSdkVersion); 22891 } else { 22892 move = null; 22893 } 22894 22895 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22896 22897 final Message msg = mHandler.obtainMessage(INIT_COPY); 22898 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22899 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22900 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22901 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22902 PackageManager.INSTALL_REASON_UNKNOWN); 22903 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22904 msg.obj = params; 22905 22906 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22907 System.identityHashCode(msg.obj)); 22908 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22909 System.identityHashCode(msg.obj)); 22910 22911 mHandler.sendMessage(msg); 22912 } 22913 22914 @Override 22915 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22916 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22917 22918 final int realMoveId = mNextMoveId.getAndIncrement(); 22919 final Bundle extras = new Bundle(); 22920 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22921 mMoveCallbacks.notifyCreated(realMoveId, extras); 22922 22923 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22924 @Override 22925 public void onCreated(int moveId, Bundle extras) { 22926 // Ignored 22927 } 22928 22929 @Override 22930 public void onStatusChanged(int moveId, int status, long estMillis) { 22931 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22932 } 22933 }; 22934 22935 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22936 storage.setPrimaryStorageUuid(volumeUuid, callback); 22937 return realMoveId; 22938 } 22939 22940 @Override 22941 public int getMoveStatus(int moveId) { 22942 mContext.enforceCallingOrSelfPermission( 22943 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22944 return mMoveCallbacks.mLastStatus.get(moveId); 22945 } 22946 22947 @Override 22948 public void registerMoveCallback(IPackageMoveObserver callback) { 22949 mContext.enforceCallingOrSelfPermission( 22950 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22951 mMoveCallbacks.register(callback); 22952 } 22953 22954 @Override 22955 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22956 mContext.enforceCallingOrSelfPermission( 22957 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22958 mMoveCallbacks.unregister(callback); 22959 } 22960 22961 @Override 22962 public boolean setInstallLocation(int loc) { 22963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22964 null); 22965 if (getInstallLocation() == loc) { 22966 return true; 22967 } 22968 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22969 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22970 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22971 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22972 return true; 22973 } 22974 return false; 22975 } 22976 22977 @Override 22978 public int getInstallLocation() { 22979 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22980 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22981 PackageHelper.APP_INSTALL_AUTO); 22982 } 22983 22984 /** Called by UserManagerService */ 22985 void cleanUpUser(UserManagerService userManager, int userHandle) { 22986 synchronized (mPackages) { 22987 mDirtyUsers.remove(userHandle); 22988 mUserNeedsBadging.delete(userHandle); 22989 mSettings.removeUserLPw(userHandle); 22990 mPendingBroadcasts.remove(userHandle); 22991 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22992 removeUnusedPackagesLPw(userManager, userHandle); 22993 } 22994 } 22995 22996 /** 22997 * We're removing userHandle and would like to remove any downloaded packages 22998 * that are no longer in use by any other user. 22999 * @param userHandle the user being removed 23000 */ 23001 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23002 final boolean DEBUG_CLEAN_APKS = false; 23003 int [] users = userManager.getUserIds(); 23004 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23005 while (psit.hasNext()) { 23006 PackageSetting ps = psit.next(); 23007 if (ps.pkg == null) { 23008 continue; 23009 } 23010 final String packageName = ps.pkg.packageName; 23011 // Skip over if system app 23012 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23013 continue; 23014 } 23015 if (DEBUG_CLEAN_APKS) { 23016 Slog.i(TAG, "Checking package " + packageName); 23017 } 23018 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23019 if (keep) { 23020 if (DEBUG_CLEAN_APKS) { 23021 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23022 } 23023 } else { 23024 for (int i = 0; i < users.length; i++) { 23025 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23026 keep = true; 23027 if (DEBUG_CLEAN_APKS) { 23028 Slog.i(TAG, " Keeping package " + packageName + " for user " 23029 + users[i]); 23030 } 23031 break; 23032 } 23033 } 23034 } 23035 if (!keep) { 23036 if (DEBUG_CLEAN_APKS) { 23037 Slog.i(TAG, " Removing package " + packageName); 23038 } 23039 mHandler.post(new Runnable() { 23040 public void run() { 23041 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23042 userHandle, 0); 23043 } //end run 23044 }); 23045 } 23046 } 23047 } 23048 23049 /** Called by UserManagerService */ 23050 void createNewUser(int userId, String[] disallowedPackages) { 23051 synchronized (mInstallLock) { 23052 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23053 } 23054 synchronized (mPackages) { 23055 scheduleWritePackageRestrictionsLocked(userId); 23056 scheduleWritePackageListLocked(userId); 23057 applyFactoryDefaultBrowserLPw(userId); 23058 primeDomainVerificationsLPw(userId); 23059 } 23060 } 23061 23062 void onNewUserCreated(final int userId) { 23063 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23064 // If permission review for legacy apps is required, we represent 23065 // dagerous permissions for such apps as always granted runtime 23066 // permissions to keep per user flag state whether review is needed. 23067 // Hence, if a new user is added we have to propagate dangerous 23068 // permission grants for these legacy apps. 23069 if (mPermissionReviewRequired) { 23070 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 23071 | UPDATE_PERMISSIONS_REPLACE_ALL); 23072 } 23073 } 23074 23075 @Override 23076 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23077 mContext.enforceCallingOrSelfPermission( 23078 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23079 "Only package verification agents can read the verifier device identity"); 23080 23081 synchronized (mPackages) { 23082 return mSettings.getVerifierDeviceIdentityLPw(); 23083 } 23084 } 23085 23086 @Override 23087 public void setPermissionEnforced(String permission, boolean enforced) { 23088 // TODO: Now that we no longer change GID for storage, this should to away. 23089 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23090 "setPermissionEnforced"); 23091 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23092 synchronized (mPackages) { 23093 if (mSettings.mReadExternalStorageEnforced == null 23094 || mSettings.mReadExternalStorageEnforced != enforced) { 23095 mSettings.mReadExternalStorageEnforced = enforced; 23096 mSettings.writeLPr(); 23097 } 23098 } 23099 // kill any non-foreground processes so we restart them and 23100 // grant/revoke the GID. 23101 final IActivityManager am = ActivityManager.getService(); 23102 if (am != null) { 23103 final long token = Binder.clearCallingIdentity(); 23104 try { 23105 am.killProcessesBelowForeground("setPermissionEnforcement"); 23106 } catch (RemoteException e) { 23107 } finally { 23108 Binder.restoreCallingIdentity(token); 23109 } 23110 } 23111 } else { 23112 throw new IllegalArgumentException("No selective enforcement for " + permission); 23113 } 23114 } 23115 23116 @Override 23117 @Deprecated 23118 public boolean isPermissionEnforced(String permission) { 23119 return true; 23120 } 23121 23122 @Override 23123 public boolean isStorageLow() { 23124 final long token = Binder.clearCallingIdentity(); 23125 try { 23126 final DeviceStorageMonitorInternal 23127 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23128 if (dsm != null) { 23129 return dsm.isMemoryLow(); 23130 } else { 23131 return false; 23132 } 23133 } finally { 23134 Binder.restoreCallingIdentity(token); 23135 } 23136 } 23137 23138 @Override 23139 public IPackageInstaller getPackageInstaller() { 23140 return mInstallerService; 23141 } 23142 23143 private boolean userNeedsBadging(int userId) { 23144 int index = mUserNeedsBadging.indexOfKey(userId); 23145 if (index < 0) { 23146 final UserInfo userInfo; 23147 final long token = Binder.clearCallingIdentity(); 23148 try { 23149 userInfo = sUserManager.getUserInfo(userId); 23150 } finally { 23151 Binder.restoreCallingIdentity(token); 23152 } 23153 final boolean b; 23154 if (userInfo != null && userInfo.isManagedProfile()) { 23155 b = true; 23156 } else { 23157 b = false; 23158 } 23159 mUserNeedsBadging.put(userId, b); 23160 return b; 23161 } 23162 return mUserNeedsBadging.valueAt(index); 23163 } 23164 23165 @Override 23166 public KeySet getKeySetByAlias(String packageName, String alias) { 23167 if (packageName == null || alias == null) { 23168 return null; 23169 } 23170 synchronized(mPackages) { 23171 final PackageParser.Package pkg = mPackages.get(packageName); 23172 if (pkg == null) { 23173 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23174 throw new IllegalArgumentException("Unknown package: " + packageName); 23175 } 23176 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23177 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23178 } 23179 } 23180 23181 @Override 23182 public KeySet getSigningKeySet(String packageName) { 23183 if (packageName == null) { 23184 return null; 23185 } 23186 synchronized(mPackages) { 23187 final PackageParser.Package pkg = mPackages.get(packageName); 23188 if (pkg == null) { 23189 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23190 throw new IllegalArgumentException("Unknown package: " + packageName); 23191 } 23192 if (pkg.applicationInfo.uid != Binder.getCallingUid() 23193 && Process.SYSTEM_UID != Binder.getCallingUid()) { 23194 throw new SecurityException("May not access signing KeySet of other apps."); 23195 } 23196 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23197 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23198 } 23199 } 23200 23201 @Override 23202 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23203 if (packageName == null || ks == null) { 23204 return false; 23205 } 23206 synchronized(mPackages) { 23207 final PackageParser.Package pkg = mPackages.get(packageName); 23208 if (pkg == null) { 23209 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23210 throw new IllegalArgumentException("Unknown package: " + packageName); 23211 } 23212 IBinder ksh = ks.getToken(); 23213 if (ksh instanceof KeySetHandle) { 23214 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23215 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23216 } 23217 return false; 23218 } 23219 } 23220 23221 @Override 23222 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23223 if (packageName == null || ks == null) { 23224 return false; 23225 } 23226 synchronized(mPackages) { 23227 final PackageParser.Package pkg = mPackages.get(packageName); 23228 if (pkg == null) { 23229 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23230 throw new IllegalArgumentException("Unknown package: " + packageName); 23231 } 23232 IBinder ksh = ks.getToken(); 23233 if (ksh instanceof KeySetHandle) { 23234 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23235 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23236 } 23237 return false; 23238 } 23239 } 23240 23241 private void deletePackageIfUnusedLPr(final String packageName) { 23242 PackageSetting ps = mSettings.mPackages.get(packageName); 23243 if (ps == null) { 23244 return; 23245 } 23246 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23247 // TODO Implement atomic delete if package is unused 23248 // It is currently possible that the package will be deleted even if it is installed 23249 // after this method returns. 23250 mHandler.post(new Runnable() { 23251 public void run() { 23252 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23253 0, PackageManager.DELETE_ALL_USERS); 23254 } 23255 }); 23256 } 23257 } 23258 23259 /** 23260 * Check and throw if the given before/after packages would be considered a 23261 * downgrade. 23262 */ 23263 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23264 throws PackageManagerException { 23265 if (after.versionCode < before.mVersionCode) { 23266 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23267 "Update version code " + after.versionCode + " is older than current " 23268 + before.mVersionCode); 23269 } else if (after.versionCode == before.mVersionCode) { 23270 if (after.baseRevisionCode < before.baseRevisionCode) { 23271 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23272 "Update base revision code " + after.baseRevisionCode 23273 + " is older than current " + before.baseRevisionCode); 23274 } 23275 23276 if (!ArrayUtils.isEmpty(after.splitNames)) { 23277 for (int i = 0; i < after.splitNames.length; i++) { 23278 final String splitName = after.splitNames[i]; 23279 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23280 if (j != -1) { 23281 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23282 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23283 "Update split " + splitName + " revision code " 23284 + after.splitRevisionCodes[i] + " is older than current " 23285 + before.splitRevisionCodes[j]); 23286 } 23287 } 23288 } 23289 } 23290 } 23291 } 23292 23293 private static class MoveCallbacks extends Handler { 23294 private static final int MSG_CREATED = 1; 23295 private static final int MSG_STATUS_CHANGED = 2; 23296 23297 private final RemoteCallbackList<IPackageMoveObserver> 23298 mCallbacks = new RemoteCallbackList<>(); 23299 23300 private final SparseIntArray mLastStatus = new SparseIntArray(); 23301 23302 public MoveCallbacks(Looper looper) { 23303 super(looper); 23304 } 23305 23306 public void register(IPackageMoveObserver callback) { 23307 mCallbacks.register(callback); 23308 } 23309 23310 public void unregister(IPackageMoveObserver callback) { 23311 mCallbacks.unregister(callback); 23312 } 23313 23314 @Override 23315 public void handleMessage(Message msg) { 23316 final SomeArgs args = (SomeArgs) msg.obj; 23317 final int n = mCallbacks.beginBroadcast(); 23318 for (int i = 0; i < n; i++) { 23319 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23320 try { 23321 invokeCallback(callback, msg.what, args); 23322 } catch (RemoteException ignored) { 23323 } 23324 } 23325 mCallbacks.finishBroadcast(); 23326 args.recycle(); 23327 } 23328 23329 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23330 throws RemoteException { 23331 switch (what) { 23332 case MSG_CREATED: { 23333 callback.onCreated(args.argi1, (Bundle) args.arg2); 23334 break; 23335 } 23336 case MSG_STATUS_CHANGED: { 23337 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23338 break; 23339 } 23340 } 23341 } 23342 23343 private void notifyCreated(int moveId, Bundle extras) { 23344 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23345 23346 final SomeArgs args = SomeArgs.obtain(); 23347 args.argi1 = moveId; 23348 args.arg2 = extras; 23349 obtainMessage(MSG_CREATED, args).sendToTarget(); 23350 } 23351 23352 private void notifyStatusChanged(int moveId, int status) { 23353 notifyStatusChanged(moveId, status, -1); 23354 } 23355 23356 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23357 Slog.v(TAG, "Move " + moveId + " status " + status); 23358 23359 final SomeArgs args = SomeArgs.obtain(); 23360 args.argi1 = moveId; 23361 args.argi2 = status; 23362 args.arg3 = estMillis; 23363 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23364 23365 synchronized (mLastStatus) { 23366 mLastStatus.put(moveId, status); 23367 } 23368 } 23369 } 23370 23371 private final static class OnPermissionChangeListeners extends Handler { 23372 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23373 23374 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23375 new RemoteCallbackList<>(); 23376 23377 public OnPermissionChangeListeners(Looper looper) { 23378 super(looper); 23379 } 23380 23381 @Override 23382 public void handleMessage(Message msg) { 23383 switch (msg.what) { 23384 case MSG_ON_PERMISSIONS_CHANGED: { 23385 final int uid = msg.arg1; 23386 handleOnPermissionsChanged(uid); 23387 } break; 23388 } 23389 } 23390 23391 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23392 mPermissionListeners.register(listener); 23393 23394 } 23395 23396 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23397 mPermissionListeners.unregister(listener); 23398 } 23399 23400 public void onPermissionsChanged(int uid) { 23401 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23402 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23403 } 23404 } 23405 23406 private void handleOnPermissionsChanged(int uid) { 23407 final int count = mPermissionListeners.beginBroadcast(); 23408 try { 23409 for (int i = 0; i < count; i++) { 23410 IOnPermissionsChangeListener callback = mPermissionListeners 23411 .getBroadcastItem(i); 23412 try { 23413 callback.onPermissionsChanged(uid); 23414 } catch (RemoteException e) { 23415 Log.e(TAG, "Permission listener is dead", e); 23416 } 23417 } 23418 } finally { 23419 mPermissionListeners.finishBroadcast(); 23420 } 23421 } 23422 } 23423 23424 private class PackageManagerInternalImpl extends PackageManagerInternal { 23425 @Override 23426 public void setLocationPackagesProvider(PackagesProvider provider) { 23427 synchronized (mPackages) { 23428 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23429 } 23430 } 23431 23432 @Override 23433 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23434 synchronized (mPackages) { 23435 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23436 } 23437 } 23438 23439 @Override 23440 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23441 synchronized (mPackages) { 23442 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23443 } 23444 } 23445 23446 @Override 23447 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23448 synchronized (mPackages) { 23449 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23450 } 23451 } 23452 23453 @Override 23454 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23455 synchronized (mPackages) { 23456 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23457 } 23458 } 23459 23460 @Override 23461 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23462 synchronized (mPackages) { 23463 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23464 } 23465 } 23466 23467 @Override 23468 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23469 synchronized (mPackages) { 23470 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23471 packageName, userId); 23472 } 23473 } 23474 23475 @Override 23476 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23477 synchronized (mPackages) { 23478 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23479 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23480 packageName, userId); 23481 } 23482 } 23483 23484 @Override 23485 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23486 synchronized (mPackages) { 23487 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23488 packageName, userId); 23489 } 23490 } 23491 23492 @Override 23493 public void setKeepUninstalledPackages(final List<String> packageList) { 23494 Preconditions.checkNotNull(packageList); 23495 List<String> removedFromList = null; 23496 synchronized (mPackages) { 23497 if (mKeepUninstalledPackages != null) { 23498 final int packagesCount = mKeepUninstalledPackages.size(); 23499 for (int i = 0; i < packagesCount; i++) { 23500 String oldPackage = mKeepUninstalledPackages.get(i); 23501 if (packageList != null && packageList.contains(oldPackage)) { 23502 continue; 23503 } 23504 if (removedFromList == null) { 23505 removedFromList = new ArrayList<>(); 23506 } 23507 removedFromList.add(oldPackage); 23508 } 23509 } 23510 mKeepUninstalledPackages = new ArrayList<>(packageList); 23511 if (removedFromList != null) { 23512 final int removedCount = removedFromList.size(); 23513 for (int i = 0; i < removedCount; i++) { 23514 deletePackageIfUnusedLPr(removedFromList.get(i)); 23515 } 23516 } 23517 } 23518 } 23519 23520 @Override 23521 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23522 synchronized (mPackages) { 23523 // If we do not support permission review, done. 23524 if (!mPermissionReviewRequired) { 23525 return false; 23526 } 23527 23528 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23529 if (packageSetting == null) { 23530 return false; 23531 } 23532 23533 // Permission review applies only to apps not supporting the new permission model. 23534 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23535 return false; 23536 } 23537 23538 // Legacy apps have the permission and get user consent on launch. 23539 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23540 return permissionsState.isPermissionReviewRequired(userId); 23541 } 23542 } 23543 23544 @Override 23545 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23546 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23547 } 23548 23549 @Override 23550 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23551 int userId) { 23552 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23553 } 23554 23555 @Override 23556 public void setDeviceAndProfileOwnerPackages( 23557 int deviceOwnerUserId, String deviceOwnerPackage, 23558 SparseArray<String> profileOwnerPackages) { 23559 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23560 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23561 } 23562 23563 @Override 23564 public boolean isPackageDataProtected(int userId, String packageName) { 23565 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23566 } 23567 23568 @Override 23569 public boolean isPackageEphemeral(int userId, String packageName) { 23570 synchronized (mPackages) { 23571 final PackageSetting ps = mSettings.mPackages.get(packageName); 23572 return ps != null ? ps.getInstantApp(userId) : false; 23573 } 23574 } 23575 23576 @Override 23577 public boolean wasPackageEverLaunched(String packageName, int userId) { 23578 synchronized (mPackages) { 23579 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23580 } 23581 } 23582 23583 @Override 23584 public void grantRuntimePermission(String packageName, String name, int userId, 23585 boolean overridePolicy) { 23586 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23587 overridePolicy); 23588 } 23589 23590 @Override 23591 public void revokeRuntimePermission(String packageName, String name, int userId, 23592 boolean overridePolicy) { 23593 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23594 overridePolicy); 23595 } 23596 23597 @Override 23598 public String getNameForUid(int uid) { 23599 return PackageManagerService.this.getNameForUid(uid); 23600 } 23601 23602 @Override 23603 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23604 Intent origIntent, String resolvedType, String callingPackage, 23605 Bundle verificationBundle, int userId) { 23606 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23607 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23608 userId); 23609 } 23610 23611 @Override 23612 public void grantEphemeralAccess(int userId, Intent intent, 23613 int targetAppId, int ephemeralAppId) { 23614 synchronized (mPackages) { 23615 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23616 targetAppId, ephemeralAppId); 23617 } 23618 } 23619 23620 @Override 23621 public boolean isInstantAppInstallerComponent(ComponentName component) { 23622 synchronized (mPackages) { 23623 return mInstantAppInstallerActivity != null 23624 && mInstantAppInstallerActivity.getComponentName().equals(component); 23625 } 23626 } 23627 23628 @Override 23629 public void pruneInstantApps() { 23630 synchronized (mPackages) { 23631 mInstantAppRegistry.pruneInstantAppsLPw(); 23632 } 23633 } 23634 23635 @Override 23636 public String getSetupWizardPackageName() { 23637 return mSetupWizardPackage; 23638 } 23639 23640 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23641 if (policy != null) { 23642 mExternalSourcesPolicy = policy; 23643 } 23644 } 23645 23646 @Override 23647 public boolean isPackagePersistent(String packageName) { 23648 synchronized (mPackages) { 23649 PackageParser.Package pkg = mPackages.get(packageName); 23650 return pkg != null 23651 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23652 | ApplicationInfo.FLAG_PERSISTENT)) == 23653 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23654 : false; 23655 } 23656 } 23657 23658 @Override 23659 public List<PackageInfo> getOverlayPackages(int userId) { 23660 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23661 synchronized (mPackages) { 23662 for (PackageParser.Package p : mPackages.values()) { 23663 if (p.mOverlayTarget != null) { 23664 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23665 if (pkg != null) { 23666 overlayPackages.add(pkg); 23667 } 23668 } 23669 } 23670 } 23671 return overlayPackages; 23672 } 23673 23674 @Override 23675 public List<String> getTargetPackageNames(int userId) { 23676 List<String> targetPackages = new ArrayList<>(); 23677 synchronized (mPackages) { 23678 for (PackageParser.Package p : mPackages.values()) { 23679 if (p.mOverlayTarget == null) { 23680 targetPackages.add(p.packageName); 23681 } 23682 } 23683 } 23684 return targetPackages; 23685 } 23686 23687 @Override 23688 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23689 @Nullable List<String> overlayPackageNames) { 23690 synchronized (mPackages) { 23691 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23692 Slog.e(TAG, "failed to find package " + targetPackageName); 23693 return false; 23694 } 23695 23696 ArrayList<String> paths = null; 23697 if (overlayPackageNames != null) { 23698 final int N = overlayPackageNames.size(); 23699 paths = new ArrayList<>(N); 23700 for (int i = 0; i < N; i++) { 23701 final String packageName = overlayPackageNames.get(i); 23702 final PackageParser.Package pkg = mPackages.get(packageName); 23703 if (pkg == null) { 23704 Slog.e(TAG, "failed to find package " + packageName); 23705 return false; 23706 } 23707 paths.add(pkg.baseCodePath); 23708 } 23709 } 23710 23711 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23712 mEnabledOverlayPaths.get(userId); 23713 if (userSpecificOverlays == null) { 23714 userSpecificOverlays = new ArrayMap<>(); 23715 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23716 } 23717 23718 if (paths != null && paths.size() > 0) { 23719 userSpecificOverlays.put(targetPackageName, paths); 23720 } else { 23721 userSpecificOverlays.remove(targetPackageName); 23722 } 23723 return true; 23724 } 23725 } 23726 23727 @Override 23728 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23729 int flags, int userId) { 23730 return resolveIntentInternal( 23731 intent, resolvedType, flags, userId, true /*resolveForStart*/); 23732 } 23733 23734 @Override 23735 public ResolveInfo resolveService(Intent intent, String resolvedType, 23736 int flags, int userId, int callingUid) { 23737 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23738 } 23739 23740 @Override 23741 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23742 synchronized (mPackages) { 23743 mIsolatedOwners.put(isolatedUid, ownerUid); 23744 } 23745 } 23746 23747 @Override 23748 public void removeIsolatedUid(int isolatedUid) { 23749 synchronized (mPackages) { 23750 mIsolatedOwners.delete(isolatedUid); 23751 } 23752 } 23753 23754 @Override 23755 public int getUidTargetSdkVersion(int uid) { 23756 synchronized (mPackages) { 23757 return getUidTargetSdkVersionLockedLPr(uid); 23758 } 23759 } 23760 } 23761 23762 @Override 23763 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23764 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23765 synchronized (mPackages) { 23766 final long identity = Binder.clearCallingIdentity(); 23767 try { 23768 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23769 packageNames, userId); 23770 } finally { 23771 Binder.restoreCallingIdentity(identity); 23772 } 23773 } 23774 } 23775 23776 @Override 23777 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23778 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23779 synchronized (mPackages) { 23780 final long identity = Binder.clearCallingIdentity(); 23781 try { 23782 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23783 packageNames, userId); 23784 } finally { 23785 Binder.restoreCallingIdentity(identity); 23786 } 23787 } 23788 } 23789 23790 private static void enforceSystemOrPhoneCaller(String tag) { 23791 int callingUid = Binder.getCallingUid(); 23792 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23793 throw new SecurityException( 23794 "Cannot call " + tag + " from UID " + callingUid); 23795 } 23796 } 23797 23798 boolean isHistoricalPackageUsageAvailable() { 23799 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23800 } 23801 23802 /** 23803 * Return a <b>copy</b> of the collection of packages known to the package manager. 23804 * @return A copy of the values of mPackages. 23805 */ 23806 Collection<PackageParser.Package> getPackages() { 23807 synchronized (mPackages) { 23808 return new ArrayList<>(mPackages.values()); 23809 } 23810 } 23811 23812 /** 23813 * Logs process start information (including base APK hash) to the security log. 23814 * @hide 23815 */ 23816 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23817 String apkFile, int pid) { 23818 if (!SecurityLog.isLoggingEnabled()) { 23819 return; 23820 } 23821 Bundle data = new Bundle(); 23822 data.putLong("startTimestamp", System.currentTimeMillis()); 23823 data.putString("processName", processName); 23824 data.putInt("uid", uid); 23825 data.putString("seinfo", seinfo); 23826 data.putString("apkFile", apkFile); 23827 data.putInt("pid", pid); 23828 Message msg = mProcessLoggingHandler.obtainMessage( 23829 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23830 msg.setData(data); 23831 mProcessLoggingHandler.sendMessage(msg); 23832 } 23833 23834 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23835 return mCompilerStats.getPackageStats(pkgName); 23836 } 23837 23838 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23839 return getOrCreateCompilerPackageStats(pkg.packageName); 23840 } 23841 23842 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23843 return mCompilerStats.getOrCreatePackageStats(pkgName); 23844 } 23845 23846 public void deleteCompilerPackageStats(String pkgName) { 23847 mCompilerStats.deletePackageStats(pkgName); 23848 } 23849 23850 @Override 23851 public int getInstallReason(String packageName, int userId) { 23852 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23853 true /* requireFullPermission */, false /* checkShell */, 23854 "get install reason"); 23855 synchronized (mPackages) { 23856 final PackageSetting ps = mSettings.mPackages.get(packageName); 23857 if (ps != null) { 23858 return ps.getInstallReason(userId); 23859 } 23860 } 23861 return PackageManager.INSTALL_REASON_UNKNOWN; 23862 } 23863 23864 @Override 23865 public boolean canRequestPackageInstalls(String packageName, int userId) { 23866 int callingUid = Binder.getCallingUid(); 23867 int uid = getPackageUid(packageName, 0, userId); 23868 if (callingUid != uid && callingUid != Process.ROOT_UID 23869 && callingUid != Process.SYSTEM_UID) { 23870 throw new SecurityException( 23871 "Caller uid " + callingUid + " does not own package " + packageName); 23872 } 23873 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23874 if (info == null) { 23875 return false; 23876 } 23877 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23878 throw new UnsupportedOperationException( 23879 "Operation only supported on apps targeting Android O or higher"); 23880 } 23881 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23882 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23883 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23884 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23885 } 23886 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23887 return false; 23888 } 23889 if (mExternalSourcesPolicy != null) { 23890 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23891 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23892 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23893 } 23894 } 23895 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23896 } 23897 23898 @Override 23899 public ComponentName getInstantAppResolverSettingsComponent() { 23900 return mInstantAppResolverSettingsComponent; 23901 } 23902 23903 @Override 23904 public ComponentName getInstantAppInstallerComponent() { 23905 return mInstantAppInstallerActivity == null 23906 ? null : mInstantAppInstallerActivity.getComponentName(); 23907 } 23908 23909 @Override 23910 public String getInstantAppAndroidId(String packageName, int userId) { 23911 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23912 "getInstantAppAndroidId"); 23913 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23914 true /* requireFullPermission */, false /* checkShell */, 23915 "getInstantAppAndroidId"); 23916 // Make sure the target is an Instant App. 23917 if (!isInstantApp(packageName, userId)) { 23918 return null; 23919 } 23920 synchronized (mPackages) { 23921 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23922 } 23923 } 23924} 23925 23926interface PackageSender { 23927 void sendPackageBroadcast(final String action, final String pkg, 23928 final Bundle extras, final int flags, final String targetPkg, 23929 final IIntentReceiver finishedReceiver, final int[] userIds); 23930 void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 23931 int appId, int... userIds); 23932} 23933