PackageManagerService.java revision 9b5a06037f80dff46218b1611862c1fd2b3df8b2
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.PermissionsState.PERMISSION_OPERATION_FAILURE; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 103 104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppRequest; 132import android.content.pm.AuxiliaryResolveInfo; 133import android.content.pm.FallbackCategoryProvider; 134import android.content.pm.FeatureInfo; 135import android.content.pm.IOnPermissionsChangeListener; 136import android.content.pm.IPackageDataObserver; 137import android.content.pm.IPackageDeleteObserver; 138import android.content.pm.IPackageDeleteObserver2; 139import android.content.pm.IPackageInstallObserver2; 140import android.content.pm.IPackageInstaller; 141import android.content.pm.IPackageManager; 142import android.content.pm.IPackageMoveObserver; 143import android.content.pm.IPackageStatsObserver; 144import android.content.pm.InstantAppInfo; 145import android.content.pm.InstantAppResolveInfo; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.ServiceInfo; 168import android.content.pm.SharedLibraryInfo; 169import android.content.pm.Signature; 170import android.content.pm.UserInfo; 171import android.content.pm.VerifierDeviceIdentity; 172import android.content.pm.VerifierInfo; 173import android.content.pm.VersionedPackage; 174import android.content.res.Resources; 175import android.database.ContentObserver; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.BootTimingsTraceLog; 225import android.util.DisplayMetrics; 226import android.util.EventLog; 227import android.util.ExceptionUtils; 228import android.util.Log; 229import android.util.LogPrinter; 230import android.util.MathUtils; 231import android.util.PackageUtils; 232import android.util.Pair; 233import android.util.PrintStreamPrinter; 234import android.util.Slog; 235import android.util.SparseArray; 236import android.util.SparseBooleanArray; 237import android.util.SparseIntArray; 238import android.util.Xml; 239import android.util.jar.StrictJarFile; 240import android.util.proto.ProtoOutputStream; 241import android.view.Display; 242 243import com.android.internal.R; 244import com.android.internal.annotations.GuardedBy; 245import com.android.internal.app.IMediaContainerService; 246import com.android.internal.app.ResolverActivity; 247import com.android.internal.content.NativeLibraryHelper; 248import com.android.internal.content.PackageHelper; 249import com.android.internal.logging.MetricsLogger; 250import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 251import com.android.internal.os.IParcelFileDescriptorFactory; 252import com.android.internal.os.RoSystemProperties; 253import com.android.internal.os.SomeArgs; 254import com.android.internal.os.Zygote; 255import com.android.internal.telephony.CarrierAppUtils; 256import com.android.internal.util.ArrayUtils; 257import com.android.internal.util.ConcurrentUtils; 258import com.android.internal.util.DumpUtils; 259import com.android.internal.util.FastPrintWriter; 260import com.android.internal.util.FastXmlSerializer; 261import com.android.internal.util.IndentingPrintWriter; 262import com.android.internal.util.Preconditions; 263import com.android.internal.util.XmlUtils; 264import com.android.server.AttributeCache; 265import com.android.server.DeviceIdleController; 266import com.android.server.EventLogTags; 267import com.android.server.FgThread; 268import com.android.server.IntentResolver; 269import com.android.server.LocalServices; 270import com.android.server.LockGuard; 271import com.android.server.ServiceThread; 272import com.android.server.SystemConfig; 273import com.android.server.SystemServerInitThreadPool; 274import com.android.server.Watchdog; 275import com.android.server.net.NetworkPolicyManagerInternal; 276import com.android.server.pm.Installer.InstallerException; 277import com.android.server.pm.PermissionsState.PermissionState; 278import com.android.server.pm.Settings.DatabaseVersion; 279import com.android.server.pm.Settings.VersionInfo; 280import com.android.server.pm.dex.DexManager; 281import com.android.server.storage.DeviceStorageMonitorInternal; 282 283import dalvik.system.CloseGuard; 284import dalvik.system.DexFile; 285import dalvik.system.VMRuntime; 286 287import libcore.io.IoUtils; 288import libcore.util.EmptyArray; 289 290import org.xmlpull.v1.XmlPullParser; 291import org.xmlpull.v1.XmlPullParserException; 292import org.xmlpull.v1.XmlSerializer; 293 294import java.io.BufferedOutputStream; 295import java.io.BufferedReader; 296import java.io.ByteArrayInputStream; 297import java.io.ByteArrayOutputStream; 298import java.io.File; 299import java.io.FileDescriptor; 300import java.io.FileInputStream; 301import java.io.FileOutputStream; 302import java.io.FileReader; 303import java.io.FilenameFilter; 304import java.io.IOException; 305import java.io.PrintWriter; 306import java.nio.charset.StandardCharsets; 307import java.security.DigestInputStream; 308import java.security.MessageDigest; 309import java.security.NoSuchAlgorithmException; 310import java.security.PublicKey; 311import java.security.SecureRandom; 312import java.security.cert.Certificate; 313import java.security.cert.CertificateEncodingException; 314import java.security.cert.CertificateException; 315import java.text.SimpleDateFormat; 316import java.util.ArrayList; 317import java.util.Arrays; 318import java.util.Collection; 319import java.util.Collections; 320import java.util.Comparator; 321import java.util.Date; 322import java.util.HashMap; 323import java.util.HashSet; 324import java.util.Iterator; 325import java.util.List; 326import java.util.Map; 327import java.util.Objects; 328import java.util.Set; 329import java.util.concurrent.CountDownLatch; 330import java.util.concurrent.Future; 331import java.util.concurrent.TimeUnit; 332import java.util.concurrent.atomic.AtomicBoolean; 333import java.util.concurrent.atomic.AtomicInteger; 334 335/** 336 * Keep track of all those APKs everywhere. 337 * <p> 338 * Internally there are two important locks: 339 * <ul> 340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 341 * and other related state. It is a fine-grained lock that should only be held 342 * momentarily, as it's one of the most contended locks in the system. 343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 344 * operations typically involve heavy lifting of application data on disk. Since 345 * {@code installd} is single-threaded, and it's operations can often be slow, 346 * this lock should never be acquired while already holding {@link #mPackages}. 347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 348 * holding {@link #mInstallLock}. 349 * </ul> 350 * Many internal methods rely on the caller to hold the appropriate locks, and 351 * this contract is expressed through method name suffixes: 352 * <ul> 353 * <li>fooLI(): the caller must hold {@link #mInstallLock} 354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 355 * being modified must be frozen 356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 358 * </ul> 359 * <p> 360 * Because this class is very central to the platform's security; please run all 361 * CTS and unit tests whenever making modifications: 362 * 363 * <pre> 364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 366 * </pre> 367 */ 368public class PackageManagerService extends IPackageManager.Stub 369 implements PackageSender { 370 static final String TAG = "PackageManager"; 371 static final boolean DEBUG_SETTINGS = false; 372 static final boolean DEBUG_PREFERRED = false; 373 static final boolean DEBUG_UPGRADE = false; 374 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 375 private static final boolean DEBUG_BACKUP = false; 376 private static final boolean DEBUG_INSTALL = false; 377 private static final boolean DEBUG_REMOVE = false; 378 private static final boolean DEBUG_BROADCASTS = false; 379 private static final boolean DEBUG_SHOW_INFO = false; 380 private static final boolean DEBUG_PACKAGE_INFO = false; 381 private static final boolean DEBUG_INTENT_MATCHING = false; 382 private static final boolean DEBUG_PACKAGE_SCANNING = false; 383 private static final boolean DEBUG_VERIFY = false; 384 private static final boolean DEBUG_FILTERS = false; 385 386 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 387 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 388 // user, but by default initialize to this. 389 public static final boolean DEBUG_DEXOPT = false; 390 391 private static final boolean DEBUG_ABI_SELECTION = false; 392 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 393 private static final boolean DEBUG_TRIAGED_MISSING = false; 394 private static final boolean DEBUG_APP_DATA = false; 395 396 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 397 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 398 399 private static final boolean HIDE_EPHEMERAL_APIS = false; 400 401 private static final boolean ENABLE_FREE_CACHE_V2 = 402 SystemProperties.getBoolean("fw.free_cache_v2", true); 403 404 private static final int RADIO_UID = Process.PHONE_UID; 405 private static final int LOG_UID = Process.LOG_UID; 406 private static final int NFC_UID = Process.NFC_UID; 407 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 408 private static final int SHELL_UID = Process.SHELL_UID; 409 410 // Cap the size of permission trees that 3rd party apps can define 411 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 412 413 // Suffix used during package installation when copying/moving 414 // package apks to install directory. 415 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 416 417 static final int SCAN_NO_DEX = 1<<1; 418 static final int SCAN_FORCE_DEX = 1<<2; 419 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 420 static final int SCAN_NEW_INSTALL = 1<<4; 421 static final int SCAN_UPDATE_TIME = 1<<5; 422 static final int SCAN_BOOTING = 1<<6; 423 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 424 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 425 static final int SCAN_REPLACING = 1<<9; 426 static final int SCAN_REQUIRE_KNOWN = 1<<10; 427 static final int SCAN_MOVE = 1<<11; 428 static final int SCAN_INITIAL = 1<<12; 429 static final int SCAN_CHECK_ONLY = 1<<13; 430 static final int SCAN_DONT_KILL_APP = 1<<14; 431 static final int SCAN_IGNORE_FROZEN = 1<<15; 432 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 433 static final int SCAN_AS_INSTANT_APP = 1<<17; 434 static final int SCAN_AS_FULL_APP = 1<<18; 435 /** Should not be with the scan flags */ 436 static final int FLAGS_REMOVE_CHATTY = 1<<31; 437 438 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 439 440 private static final int[] EMPTY_INT_ARRAY = new int[0]; 441 442 /** 443 * Timeout (in milliseconds) after which the watchdog should declare that 444 * our handler thread is wedged. The usual default for such things is one 445 * minute but we sometimes do very lengthy I/O operations on this thread, 446 * such as installing multi-gigabyte applications, so ours needs to be longer. 447 */ 448 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 449 450 /** 451 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 452 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 453 * settings entry if available, otherwise we use the hardcoded default. If it's been 454 * more than this long since the last fstrim, we force one during the boot sequence. 455 * 456 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 457 * one gets run at the next available charging+idle time. This final mandatory 458 * no-fstrim check kicks in only of the other scheduling criteria is never met. 459 */ 460 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 461 462 /** 463 * Whether verification is enabled by default. 464 */ 465 private static final boolean DEFAULT_VERIFY_ENABLE = true; 466 467 /** 468 * The default maximum time to wait for the verification agent to return in 469 * milliseconds. 470 */ 471 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 472 473 /** 474 * The default response for package verification timeout. 475 * 476 * This can be either PackageManager.VERIFICATION_ALLOW or 477 * PackageManager.VERIFICATION_REJECT. 478 */ 479 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 480 481 static final String PLATFORM_PACKAGE_NAME = "android"; 482 483 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 484 485 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 486 DEFAULT_CONTAINER_PACKAGE, 487 "com.android.defcontainer.DefaultContainerService"); 488 489 private static final String KILL_APP_REASON_GIDS_CHANGED = 490 "permission grant or revoke changed gids"; 491 492 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 493 "permissions revoked"; 494 495 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 496 497 private static final String PACKAGE_SCHEME = "package"; 498 499 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 500 501 /** Permission grant: not grant the permission. */ 502 private static final int GRANT_DENIED = 1; 503 504 /** Permission grant: grant the permission as an install permission. */ 505 private static final int GRANT_INSTALL = 2; 506 507 /** Permission grant: grant the permission as a runtime one. */ 508 private static final int GRANT_RUNTIME = 3; 509 510 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 511 private static final int GRANT_UPGRADE = 4; 512 513 /** Canonical intent used to identify what counts as a "web browser" app */ 514 private static final Intent sBrowserIntent; 515 static { 516 sBrowserIntent = new Intent(); 517 sBrowserIntent.setAction(Intent.ACTION_VIEW); 518 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 519 sBrowserIntent.setData(Uri.parse("http:")); 520 } 521 522 /** 523 * The set of all protected actions [i.e. those actions for which a high priority 524 * intent filter is disallowed]. 525 */ 526 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 527 static { 528 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 531 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 532 } 533 534 // Compilation reasons. 535 public static final int REASON_FIRST_BOOT = 0; 536 public static final int REASON_BOOT = 1; 537 public static final int REASON_INSTALL = 2; 538 public static final int REASON_BACKGROUND_DEXOPT = 3; 539 public static final int REASON_AB_OTA = 4; 540 541 public static final int REASON_LAST = REASON_AB_OTA; 542 543 /** All dangerous permission names in the same order as the events in MetricsEvent */ 544 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 545 Manifest.permission.READ_CALENDAR, 546 Manifest.permission.WRITE_CALENDAR, 547 Manifest.permission.CAMERA, 548 Manifest.permission.READ_CONTACTS, 549 Manifest.permission.WRITE_CONTACTS, 550 Manifest.permission.GET_ACCOUNTS, 551 Manifest.permission.ACCESS_FINE_LOCATION, 552 Manifest.permission.ACCESS_COARSE_LOCATION, 553 Manifest.permission.RECORD_AUDIO, 554 Manifest.permission.READ_PHONE_STATE, 555 Manifest.permission.CALL_PHONE, 556 Manifest.permission.READ_CALL_LOG, 557 Manifest.permission.WRITE_CALL_LOG, 558 Manifest.permission.ADD_VOICEMAIL, 559 Manifest.permission.USE_SIP, 560 Manifest.permission.PROCESS_OUTGOING_CALLS, 561 Manifest.permission.READ_CELL_BROADCASTS, 562 Manifest.permission.BODY_SENSORS, 563 Manifest.permission.SEND_SMS, 564 Manifest.permission.RECEIVE_SMS, 565 Manifest.permission.READ_SMS, 566 Manifest.permission.RECEIVE_WAP_PUSH, 567 Manifest.permission.RECEIVE_MMS, 568 Manifest.permission.READ_EXTERNAL_STORAGE, 569 Manifest.permission.WRITE_EXTERNAL_STORAGE, 570 Manifest.permission.READ_PHONE_NUMBERS, 571 Manifest.permission.ANSWER_PHONE_CALLS); 572 573 574 /** 575 * Version number for the package parser cache. Increment this whenever the format or 576 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 577 */ 578 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 579 580 /** 581 * Whether the package parser cache is enabled. 582 */ 583 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 584 585 final ServiceThread mHandlerThread; 586 587 final PackageHandler mHandler; 588 589 private final ProcessLoggingHandler mProcessLoggingHandler; 590 591 /** 592 * Messages for {@link #mHandler} that need to wait for system ready before 593 * being dispatched. 594 */ 595 private ArrayList<Message> mPostSystemReadyMessages; 596 597 final int mSdkVersion = Build.VERSION.SDK_INT; 598 599 final Context mContext; 600 final boolean mFactoryTest; 601 final boolean mOnlyCore; 602 final DisplayMetrics mMetrics; 603 final int mDefParseFlags; 604 final String[] mSeparateProcesses; 605 final boolean mIsUpgrade; 606 final boolean mIsPreNUpgrade; 607 final boolean mIsPreNMR1Upgrade; 608 609 // Have we told the Activity Manager to whitelist the default container service by uid yet? 610 @GuardedBy("mPackages") 611 boolean mDefaultContainerWhitelisted = false; 612 613 @GuardedBy("mPackages") 614 private boolean mDexOptDialogShown; 615 616 /** The location for ASEC container files on internal storage. */ 617 final String mAsecInternalPath; 618 619 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 620 // LOCK HELD. Can be called with mInstallLock held. 621 @GuardedBy("mInstallLock") 622 final Installer mInstaller; 623 624 /** Directory where installed third-party apps stored */ 625 final File mAppInstallDir; 626 627 /** 628 * Directory to which applications installed internally have their 629 * 32 bit native libraries copied. 630 */ 631 private File mAppLib32InstallDir; 632 633 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 634 // apps. 635 final File mDrmAppPrivateInstallDir; 636 637 // ---------------------------------------------------------------- 638 639 // Lock for state used when installing and doing other long running 640 // operations. Methods that must be called with this lock held have 641 // the suffix "LI". 642 final Object mInstallLock = new Object(); 643 644 // ---------------------------------------------------------------- 645 646 // Keys are String (package name), values are Package. This also serves 647 // as the lock for the global state. Methods that must be called with 648 // this lock held have the prefix "LP". 649 @GuardedBy("mPackages") 650 final ArrayMap<String, PackageParser.Package> mPackages = 651 new ArrayMap<String, PackageParser.Package>(); 652 653 final ArrayMap<String, Set<String>> mKnownCodebase = 654 new ArrayMap<String, Set<String>>(); 655 656 // Keys are isolated uids and values are the uid of the application 657 // that created the isolated proccess. 658 @GuardedBy("mPackages") 659 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 660 661 // List of APK paths to load for each user and package. This data is never 662 // persisted by the package manager. Instead, the overlay manager will 663 // ensure the data is up-to-date in runtime. 664 @GuardedBy("mPackages") 665 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 666 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 667 668 /** 669 * Tracks new system packages [received in an OTA] that we expect to 670 * find updated user-installed versions. Keys are package name, values 671 * are package location. 672 */ 673 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 674 /** 675 * Tracks high priority intent filters for protected actions. During boot, certain 676 * filter actions are protected and should never be allowed to have a high priority 677 * intent filter for them. However, there is one, and only one exception -- the 678 * setup wizard. It must be able to define a high priority intent filter for these 679 * actions to ensure there are no escapes from the wizard. We need to delay processing 680 * of these during boot as we need to look at all of the system packages in order 681 * to know which component is the setup wizard. 682 */ 683 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 684 /** 685 * Whether or not processing protected filters should be deferred. 686 */ 687 private boolean mDeferProtectedFilters = true; 688 689 /** 690 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 691 */ 692 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 693 /** 694 * Whether or not system app permissions should be promoted from install to runtime. 695 */ 696 boolean mPromoteSystemApps; 697 698 @GuardedBy("mPackages") 699 final Settings mSettings; 700 701 /** 702 * Set of package names that are currently "frozen", which means active 703 * surgery is being done on the code/data for that package. The platform 704 * will refuse to launch frozen packages to avoid race conditions. 705 * 706 * @see PackageFreezer 707 */ 708 @GuardedBy("mPackages") 709 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 710 711 final ProtectedPackages mProtectedPackages; 712 713 boolean mFirstBoot; 714 715 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 716 717 // System configuration read by SystemConfig. 718 final int[] mGlobalGids; 719 final SparseArray<ArraySet<String>> mSystemPermissions; 720 @GuardedBy("mAvailableFeatures") 721 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 722 723 // If mac_permissions.xml was found for seinfo labeling. 724 boolean mFoundPolicyFile; 725 726 private final InstantAppRegistry mInstantAppRegistry; 727 728 @GuardedBy("mPackages") 729 int mChangedPackagesSequenceNumber; 730 /** 731 * List of changed [installed, removed or updated] packages. 732 * mapping from user id -> sequence number -> package name 733 */ 734 @GuardedBy("mPackages") 735 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 736 /** 737 * The sequence number of the last change to a package. 738 * mapping from user id -> package name -> sequence number 739 */ 740 @GuardedBy("mPackages") 741 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 742 743 class PackageParserCallback implements PackageParser.Callback { 744 @Override public final boolean hasFeature(String feature) { 745 return PackageManagerService.this.hasSystemFeature(feature, 0); 746 } 747 748 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 749 Collection<PackageParser.Package> allPackages, String targetPackageName) { 750 List<PackageParser.Package> overlayPackages = null; 751 for (PackageParser.Package p : allPackages) { 752 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 753 if (overlayPackages == null) { 754 overlayPackages = new ArrayList<PackageParser.Package>(); 755 } 756 overlayPackages.add(p); 757 } 758 } 759 if (overlayPackages != null) { 760 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 761 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 762 return p1.mOverlayPriority - p2.mOverlayPriority; 763 } 764 }; 765 Collections.sort(overlayPackages, cmp); 766 } 767 return overlayPackages; 768 } 769 770 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 771 String targetPackageName, String targetPath) { 772 if ("android".equals(targetPackageName)) { 773 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 774 // native AssetManager. 775 return null; 776 } 777 List<PackageParser.Package> overlayPackages = 778 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 779 if (overlayPackages == null || overlayPackages.isEmpty()) { 780 return null; 781 } 782 List<String> overlayPathList = null; 783 for (PackageParser.Package overlayPackage : overlayPackages) { 784 if (targetPath == null) { 785 if (overlayPathList == null) { 786 overlayPathList = new ArrayList<String>(); 787 } 788 overlayPathList.add(overlayPackage.baseCodePath); 789 continue; 790 } 791 792 try { 793 // Creates idmaps for system to parse correctly the Android manifest of the 794 // target package. 795 // 796 // OverlayManagerService will update each of them with a correct gid from its 797 // target package app id. 798 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 799 UserHandle.getSharedAppGid( 800 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 801 if (overlayPathList == null) { 802 overlayPathList = new ArrayList<String>(); 803 } 804 overlayPathList.add(overlayPackage.baseCodePath); 805 } catch (InstallerException e) { 806 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 807 overlayPackage.baseCodePath); 808 } 809 } 810 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 811 } 812 813 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 814 synchronized (mPackages) { 815 return getStaticOverlayPathsLocked( 816 mPackages.values(), targetPackageName, targetPath); 817 } 818 } 819 820 @Override public final String[] getOverlayApks(String targetPackageName) { 821 return getStaticOverlayPaths(targetPackageName, null); 822 } 823 824 @Override public final String[] getOverlayPaths(String targetPackageName, 825 String targetPath) { 826 return getStaticOverlayPaths(targetPackageName, targetPath); 827 } 828 }; 829 830 class ParallelPackageParserCallback extends PackageParserCallback { 831 List<PackageParser.Package> mOverlayPackages = null; 832 833 void findStaticOverlayPackages() { 834 synchronized (mPackages) { 835 for (PackageParser.Package p : mPackages.values()) { 836 if (p.mIsStaticOverlay) { 837 if (mOverlayPackages == null) { 838 mOverlayPackages = new ArrayList<PackageParser.Package>(); 839 } 840 mOverlayPackages.add(p); 841 } 842 } 843 } 844 } 845 846 @Override 847 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 848 // We can trust mOverlayPackages without holding mPackages because package uninstall 849 // can't happen while running parallel parsing. 850 // Moreover holding mPackages on each parsing thread causes dead-lock. 851 return mOverlayPackages == null ? null : 852 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 853 } 854 } 855 856 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 857 final ParallelPackageParserCallback mParallelPackageParserCallback = 858 new ParallelPackageParserCallback(); 859 860 public static final class SharedLibraryEntry { 861 public final String path; 862 public final String apk; 863 public final SharedLibraryInfo info; 864 865 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 866 String declaringPackageName, int declaringPackageVersionCode) { 867 path = _path; 868 apk = _apk; 869 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 870 declaringPackageName, declaringPackageVersionCode), null); 871 } 872 } 873 874 // Currently known shared libraries. 875 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 876 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 877 new ArrayMap<>(); 878 879 // All available activities, for your resolving pleasure. 880 final ActivityIntentResolver mActivities = 881 new ActivityIntentResolver(); 882 883 // All available receivers, for your resolving pleasure. 884 final ActivityIntentResolver mReceivers = 885 new ActivityIntentResolver(); 886 887 // All available services, for your resolving pleasure. 888 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 889 890 // All available providers, for your resolving pleasure. 891 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 892 893 // Mapping from provider base names (first directory in content URI codePath) 894 // to the provider information. 895 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 896 new ArrayMap<String, PackageParser.Provider>(); 897 898 // Mapping from instrumentation class names to info about them. 899 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 900 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 901 902 // Mapping from permission names to info about them. 903 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 904 new ArrayMap<String, PackageParser.PermissionGroup>(); 905 906 // Packages whose data we have transfered into another package, thus 907 // should no longer exist. 908 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 909 910 // Broadcast actions that are only available to the system. 911 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 912 913 /** List of packages waiting for verification. */ 914 final SparseArray<PackageVerificationState> mPendingVerification 915 = new SparseArray<PackageVerificationState>(); 916 917 /** Set of packages associated with each app op permission. */ 918 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 919 920 final PackageInstallerService mInstallerService; 921 922 private final PackageDexOptimizer mPackageDexOptimizer; 923 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 924 // is used by other apps). 925 private final DexManager mDexManager; 926 927 private AtomicInteger mNextMoveId = new AtomicInteger(); 928 private final MoveCallbacks mMoveCallbacks; 929 930 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 931 932 // Cache of users who need badging. 933 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 934 935 /** Token for keys in mPendingVerification. */ 936 private int mPendingVerificationToken = 0; 937 938 volatile boolean mSystemReady; 939 volatile boolean mSafeMode; 940 volatile boolean mHasSystemUidErrors; 941 private volatile boolean mEphemeralAppsDisabled; 942 943 ApplicationInfo mAndroidApplication; 944 final ActivityInfo mResolveActivity = new ActivityInfo(); 945 final ResolveInfo mResolveInfo = new ResolveInfo(); 946 ComponentName mResolveComponentName; 947 PackageParser.Package mPlatformPackage; 948 ComponentName mCustomResolverComponentName; 949 950 boolean mResolverReplaced = false; 951 952 private final @Nullable ComponentName mIntentFilterVerifierComponent; 953 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 954 955 private int mIntentFilterVerificationToken = 0; 956 957 /** The service connection to the ephemeral resolver */ 958 final EphemeralResolverConnection mInstantAppResolverConnection; 959 /** Component used to show resolver settings for Instant Apps */ 960 final ComponentName mInstantAppResolverSettingsComponent; 961 962 /** Activity used to install instant applications */ 963 ActivityInfo mInstantAppInstallerActivity; 964 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 965 966 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 967 = new SparseArray<IntentFilterVerificationState>(); 968 969 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 970 971 // List of packages names to keep cached, even if they are uninstalled for all users 972 private List<String> mKeepUninstalledPackages; 973 974 private UserManagerInternal mUserManagerInternal; 975 976 private DeviceIdleController.LocalService mDeviceIdleController; 977 978 private File mCacheDir; 979 980 private ArraySet<String> mPrivappPermissionsViolations; 981 982 private Future<?> mPrepareAppDataFuture; 983 984 private static class IFVerificationParams { 985 PackageParser.Package pkg; 986 boolean replacing; 987 int userId; 988 int verifierUid; 989 990 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 991 int _userId, int _verifierUid) { 992 pkg = _pkg; 993 replacing = _replacing; 994 userId = _userId; 995 replacing = _replacing; 996 verifierUid = _verifierUid; 997 } 998 } 999 1000 private interface IntentFilterVerifier<T extends IntentFilter> { 1001 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1002 T filter, String packageName); 1003 void startVerifications(int userId); 1004 void receiveVerificationResponse(int verificationId); 1005 } 1006 1007 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1008 private Context mContext; 1009 private ComponentName mIntentFilterVerifierComponent; 1010 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1011 1012 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1013 mContext = context; 1014 mIntentFilterVerifierComponent = verifierComponent; 1015 } 1016 1017 private String getDefaultScheme() { 1018 return IntentFilter.SCHEME_HTTPS; 1019 } 1020 1021 @Override 1022 public void startVerifications(int userId) { 1023 // Launch verifications requests 1024 int count = mCurrentIntentFilterVerifications.size(); 1025 for (int n=0; n<count; n++) { 1026 int verificationId = mCurrentIntentFilterVerifications.get(n); 1027 final IntentFilterVerificationState ivs = 1028 mIntentFilterVerificationStates.get(verificationId); 1029 1030 String packageName = ivs.getPackageName(); 1031 1032 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1033 final int filterCount = filters.size(); 1034 ArraySet<String> domainsSet = new ArraySet<>(); 1035 for (int m=0; m<filterCount; m++) { 1036 PackageParser.ActivityIntentInfo filter = filters.get(m); 1037 domainsSet.addAll(filter.getHostsList()); 1038 } 1039 synchronized (mPackages) { 1040 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1041 packageName, domainsSet) != null) { 1042 scheduleWriteSettingsLocked(); 1043 } 1044 } 1045 sendVerificationRequest(userId, verificationId, ivs); 1046 } 1047 mCurrentIntentFilterVerifications.clear(); 1048 } 1049 1050 private void sendVerificationRequest(int userId, int verificationId, 1051 IntentFilterVerificationState ivs) { 1052 1053 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1054 verificationIntent.putExtra( 1055 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1056 verificationId); 1057 verificationIntent.putExtra( 1058 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1059 getDefaultScheme()); 1060 verificationIntent.putExtra( 1061 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1062 ivs.getHostsString()); 1063 verificationIntent.putExtra( 1064 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1065 ivs.getPackageName()); 1066 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1067 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1068 1069 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1070 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1071 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1072 userId, false, "intent filter verifier"); 1073 1074 UserHandle user = new UserHandle(userId); 1075 mContext.sendBroadcastAsUser(verificationIntent, user); 1076 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1077 "Sending IntentFilter verification broadcast"); 1078 } 1079 1080 public void receiveVerificationResponse(int verificationId) { 1081 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1082 1083 final boolean verified = ivs.isVerified(); 1084 1085 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1086 final int count = filters.size(); 1087 if (DEBUG_DOMAIN_VERIFICATION) { 1088 Slog.i(TAG, "Received verification response " + verificationId 1089 + " for " + count + " filters, verified=" + verified); 1090 } 1091 for (int n=0; n<count; n++) { 1092 PackageParser.ActivityIntentInfo filter = filters.get(n); 1093 filter.setVerified(verified); 1094 1095 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1096 + " verified with result:" + verified + " and hosts:" 1097 + ivs.getHostsString()); 1098 } 1099 1100 mIntentFilterVerificationStates.remove(verificationId); 1101 1102 final String packageName = ivs.getPackageName(); 1103 IntentFilterVerificationInfo ivi = null; 1104 1105 synchronized (mPackages) { 1106 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1107 } 1108 if (ivi == null) { 1109 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1110 + verificationId + " packageName:" + packageName); 1111 return; 1112 } 1113 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1114 "Updating IntentFilterVerificationInfo for package " + packageName 1115 +" verificationId:" + verificationId); 1116 1117 synchronized (mPackages) { 1118 if (verified) { 1119 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1120 } else { 1121 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1122 } 1123 scheduleWriteSettingsLocked(); 1124 1125 final int userId = ivs.getUserId(); 1126 if (userId != UserHandle.USER_ALL) { 1127 final int userStatus = 1128 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1129 1130 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1131 boolean needUpdate = false; 1132 1133 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1134 // already been set by the User thru the Disambiguation dialog 1135 switch (userStatus) { 1136 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1137 if (verified) { 1138 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1139 } else { 1140 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1141 } 1142 needUpdate = true; 1143 break; 1144 1145 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1146 if (verified) { 1147 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1148 needUpdate = true; 1149 } 1150 break; 1151 1152 default: 1153 // Nothing to do 1154 } 1155 1156 if (needUpdate) { 1157 mSettings.updateIntentFilterVerificationStatusLPw( 1158 packageName, updatedStatus, userId); 1159 scheduleWritePackageRestrictionsLocked(userId); 1160 } 1161 } 1162 } 1163 } 1164 1165 @Override 1166 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1167 ActivityIntentInfo filter, String packageName) { 1168 if (!hasValidDomains(filter)) { 1169 return false; 1170 } 1171 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1172 if (ivs == null) { 1173 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1174 packageName); 1175 } 1176 if (DEBUG_DOMAIN_VERIFICATION) { 1177 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1178 } 1179 ivs.addFilter(filter); 1180 return true; 1181 } 1182 1183 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1184 int userId, int verificationId, String packageName) { 1185 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1186 verifierUid, userId, packageName); 1187 ivs.setPendingState(); 1188 synchronized (mPackages) { 1189 mIntentFilterVerificationStates.append(verificationId, ivs); 1190 mCurrentIntentFilterVerifications.add(verificationId); 1191 } 1192 return ivs; 1193 } 1194 } 1195 1196 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1197 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1198 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1199 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1200 } 1201 1202 // Set of pending broadcasts for aggregating enable/disable of components. 1203 static class PendingPackageBroadcasts { 1204 // for each user id, a map of <package name -> components within that package> 1205 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1206 1207 public PendingPackageBroadcasts() { 1208 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1209 } 1210 1211 public ArrayList<String> get(int userId, String packageName) { 1212 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1213 return packages.get(packageName); 1214 } 1215 1216 public void put(int userId, String packageName, ArrayList<String> components) { 1217 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1218 packages.put(packageName, components); 1219 } 1220 1221 public void remove(int userId, String packageName) { 1222 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1223 if (packages != null) { 1224 packages.remove(packageName); 1225 } 1226 } 1227 1228 public void remove(int userId) { 1229 mUidMap.remove(userId); 1230 } 1231 1232 public int userIdCount() { 1233 return mUidMap.size(); 1234 } 1235 1236 public int userIdAt(int n) { 1237 return mUidMap.keyAt(n); 1238 } 1239 1240 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1241 return mUidMap.get(userId); 1242 } 1243 1244 public int size() { 1245 // total number of pending broadcast entries across all userIds 1246 int num = 0; 1247 for (int i = 0; i< mUidMap.size(); i++) { 1248 num += mUidMap.valueAt(i).size(); 1249 } 1250 return num; 1251 } 1252 1253 public void clear() { 1254 mUidMap.clear(); 1255 } 1256 1257 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1258 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1259 if (map == null) { 1260 map = new ArrayMap<String, ArrayList<String>>(); 1261 mUidMap.put(userId, map); 1262 } 1263 return map; 1264 } 1265 } 1266 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1267 1268 // Service Connection to remote media container service to copy 1269 // package uri's from external media onto secure containers 1270 // or internal storage. 1271 private IMediaContainerService mContainerService = null; 1272 1273 static final int SEND_PENDING_BROADCAST = 1; 1274 static final int MCS_BOUND = 3; 1275 static final int END_COPY = 4; 1276 static final int INIT_COPY = 5; 1277 static final int MCS_UNBIND = 6; 1278 static final int START_CLEANING_PACKAGE = 7; 1279 static final int FIND_INSTALL_LOC = 8; 1280 static final int POST_INSTALL = 9; 1281 static final int MCS_RECONNECT = 10; 1282 static final int MCS_GIVE_UP = 11; 1283 static final int UPDATED_MEDIA_STATUS = 12; 1284 static final int WRITE_SETTINGS = 13; 1285 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1286 static final int PACKAGE_VERIFIED = 15; 1287 static final int CHECK_PENDING_VERIFICATION = 16; 1288 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1289 static final int INTENT_FILTER_VERIFIED = 18; 1290 static final int WRITE_PACKAGE_LIST = 19; 1291 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1292 1293 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1294 1295 // Delay time in millisecs 1296 static final int BROADCAST_DELAY = 10 * 1000; 1297 1298 static UserManagerService sUserManager; 1299 1300 // Stores a list of users whose package restrictions file needs to be updated 1301 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1302 1303 final private DefaultContainerConnection mDefContainerConn = 1304 new DefaultContainerConnection(); 1305 class DefaultContainerConnection implements ServiceConnection { 1306 public void onServiceConnected(ComponentName name, IBinder service) { 1307 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1308 final IMediaContainerService imcs = IMediaContainerService.Stub 1309 .asInterface(Binder.allowBlocking(service)); 1310 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1311 } 1312 1313 public void onServiceDisconnected(ComponentName name) { 1314 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1315 } 1316 } 1317 1318 // Recordkeeping of restore-after-install operations that are currently in flight 1319 // between the Package Manager and the Backup Manager 1320 static class PostInstallData { 1321 public InstallArgs args; 1322 public PackageInstalledInfo res; 1323 1324 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1325 args = _a; 1326 res = _r; 1327 } 1328 } 1329 1330 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1331 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1332 1333 // XML tags for backup/restore of various bits of state 1334 private static final String TAG_PREFERRED_BACKUP = "pa"; 1335 private static final String TAG_DEFAULT_APPS = "da"; 1336 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1337 1338 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1339 private static final String TAG_ALL_GRANTS = "rt-grants"; 1340 private static final String TAG_GRANT = "grant"; 1341 private static final String ATTR_PACKAGE_NAME = "pkg"; 1342 1343 private static final String TAG_PERMISSION = "perm"; 1344 private static final String ATTR_PERMISSION_NAME = "name"; 1345 private static final String ATTR_IS_GRANTED = "g"; 1346 private static final String ATTR_USER_SET = "set"; 1347 private static final String ATTR_USER_FIXED = "fixed"; 1348 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1349 1350 // System/policy permission grants are not backed up 1351 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1352 FLAG_PERMISSION_POLICY_FIXED 1353 | FLAG_PERMISSION_SYSTEM_FIXED 1354 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1355 1356 // And we back up these user-adjusted states 1357 private static final int USER_RUNTIME_GRANT_MASK = 1358 FLAG_PERMISSION_USER_SET 1359 | FLAG_PERMISSION_USER_FIXED 1360 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1361 1362 final @Nullable String mRequiredVerifierPackage; 1363 final @NonNull String mRequiredInstallerPackage; 1364 final @NonNull String mRequiredUninstallerPackage; 1365 final @Nullable String mSetupWizardPackage; 1366 final @Nullable String mStorageManagerPackage; 1367 final @NonNull String mServicesSystemSharedLibraryPackageName; 1368 final @NonNull String mSharedSystemSharedLibraryPackageName; 1369 1370 final boolean mPermissionReviewRequired; 1371 1372 private final PackageUsage mPackageUsage = new PackageUsage(); 1373 private final CompilerStats mCompilerStats = new CompilerStats(); 1374 1375 class PackageHandler extends Handler { 1376 private boolean mBound = false; 1377 final ArrayList<HandlerParams> mPendingInstalls = 1378 new ArrayList<HandlerParams>(); 1379 1380 private boolean connectToService() { 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1382 " DefaultContainerService"); 1383 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1384 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1385 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1386 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1387 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1388 mBound = true; 1389 return true; 1390 } 1391 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1392 return false; 1393 } 1394 1395 private void disconnectService() { 1396 mContainerService = null; 1397 mBound = false; 1398 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1399 mContext.unbindService(mDefContainerConn); 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1401 } 1402 1403 PackageHandler(Looper looper) { 1404 super(looper); 1405 } 1406 1407 public void handleMessage(Message msg) { 1408 try { 1409 doHandleMessage(msg); 1410 } finally { 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 } 1413 } 1414 1415 void doHandleMessage(Message msg) { 1416 switch (msg.what) { 1417 case INIT_COPY: { 1418 HandlerParams params = (HandlerParams) msg.obj; 1419 int idx = mPendingInstalls.size(); 1420 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1421 // If a bind was already initiated we dont really 1422 // need to do anything. The pending install 1423 // will be processed later on. 1424 if (!mBound) { 1425 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1426 System.identityHashCode(mHandler)); 1427 // If this is the only one pending we might 1428 // have to bind to the service again. 1429 if (!connectToService()) { 1430 Slog.e(TAG, "Failed to bind to media container service"); 1431 params.serviceError(); 1432 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1433 System.identityHashCode(mHandler)); 1434 if (params.traceMethod != null) { 1435 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1436 params.traceCookie); 1437 } 1438 return; 1439 } else { 1440 // Once we bind to the service, the first 1441 // pending request will be processed. 1442 mPendingInstalls.add(idx, params); 1443 } 1444 } else { 1445 mPendingInstalls.add(idx, params); 1446 // Already bound to the service. Just make 1447 // sure we trigger off processing the first request. 1448 if (idx == 0) { 1449 mHandler.sendEmptyMessage(MCS_BOUND); 1450 } 1451 } 1452 break; 1453 } 1454 case MCS_BOUND: { 1455 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1456 if (msg.obj != null) { 1457 mContainerService = (IMediaContainerService) msg.obj; 1458 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1459 System.identityHashCode(mHandler)); 1460 } 1461 if (mContainerService == null) { 1462 if (!mBound) { 1463 // Something seriously wrong since we are not bound and we are not 1464 // waiting for connection. Bail out. 1465 Slog.e(TAG, "Cannot bind to media container service"); 1466 for (HandlerParams params : mPendingInstalls) { 1467 // Indicate service bind error 1468 params.serviceError(); 1469 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1470 System.identityHashCode(params)); 1471 if (params.traceMethod != null) { 1472 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1473 params.traceMethod, params.traceCookie); 1474 } 1475 return; 1476 } 1477 mPendingInstalls.clear(); 1478 } else { 1479 Slog.w(TAG, "Waiting to connect to media container service"); 1480 } 1481 } else if (mPendingInstalls.size() > 0) { 1482 HandlerParams params = mPendingInstalls.get(0); 1483 if (params != null) { 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1487 if (params.startCopy()) { 1488 // We are done... look for more work or to 1489 // go idle. 1490 if (DEBUG_SD_INSTALL) Log.i(TAG, 1491 "Checking for more work or unbind..."); 1492 // Delete pending install 1493 if (mPendingInstalls.size() > 0) { 1494 mPendingInstalls.remove(0); 1495 } 1496 if (mPendingInstalls.size() == 0) { 1497 if (mBound) { 1498 if (DEBUG_SD_INSTALL) Log.i(TAG, 1499 "Posting delayed MCS_UNBIND"); 1500 removeMessages(MCS_UNBIND); 1501 Message ubmsg = obtainMessage(MCS_UNBIND); 1502 // Unbind after a little delay, to avoid 1503 // continual thrashing. 1504 sendMessageDelayed(ubmsg, 10000); 1505 } 1506 } else { 1507 // There are more pending requests in queue. 1508 // Just post MCS_BOUND message to trigger processing 1509 // of next pending install. 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, 1511 "Posting MCS_BOUND for next work"); 1512 mHandler.sendEmptyMessage(MCS_BOUND); 1513 } 1514 } 1515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1516 } 1517 } else { 1518 // Should never happen ideally. 1519 Slog.w(TAG, "Empty queue"); 1520 } 1521 break; 1522 } 1523 case MCS_RECONNECT: { 1524 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1525 if (mPendingInstalls.size() > 0) { 1526 if (mBound) { 1527 disconnectService(); 1528 } 1529 if (!connectToService()) { 1530 Slog.e(TAG, "Failed to bind to media container service"); 1531 for (HandlerParams params : mPendingInstalls) { 1532 // Indicate service bind error 1533 params.serviceError(); 1534 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1535 System.identityHashCode(params)); 1536 } 1537 mPendingInstalls.clear(); 1538 } 1539 } 1540 break; 1541 } 1542 case MCS_UNBIND: { 1543 // If there is no actual work left, then time to unbind. 1544 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1545 1546 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1547 if (mBound) { 1548 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1549 1550 disconnectService(); 1551 } 1552 } else if (mPendingInstalls.size() > 0) { 1553 // There are more pending requests in queue. 1554 // Just post MCS_BOUND message to trigger processing 1555 // of next pending install. 1556 mHandler.sendEmptyMessage(MCS_BOUND); 1557 } 1558 1559 break; 1560 } 1561 case MCS_GIVE_UP: { 1562 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1563 HandlerParams params = mPendingInstalls.remove(0); 1564 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1565 System.identityHashCode(params)); 1566 break; 1567 } 1568 case SEND_PENDING_BROADCAST: { 1569 String packages[]; 1570 ArrayList<String> components[]; 1571 int size = 0; 1572 int uids[]; 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1574 synchronized (mPackages) { 1575 if (mPendingBroadcasts == null) { 1576 return; 1577 } 1578 size = mPendingBroadcasts.size(); 1579 if (size <= 0) { 1580 // Nothing to be done. Just return 1581 return; 1582 } 1583 packages = new String[size]; 1584 components = new ArrayList[size]; 1585 uids = new int[size]; 1586 int i = 0; // filling out the above arrays 1587 1588 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1589 int packageUserId = mPendingBroadcasts.userIdAt(n); 1590 Iterator<Map.Entry<String, ArrayList<String>>> it 1591 = mPendingBroadcasts.packagesForUserId(packageUserId) 1592 .entrySet().iterator(); 1593 while (it.hasNext() && i < size) { 1594 Map.Entry<String, ArrayList<String>> ent = it.next(); 1595 packages[i] = ent.getKey(); 1596 components[i] = ent.getValue(); 1597 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1598 uids[i] = (ps != null) 1599 ? UserHandle.getUid(packageUserId, ps.appId) 1600 : -1; 1601 i++; 1602 } 1603 } 1604 size = i; 1605 mPendingBroadcasts.clear(); 1606 } 1607 // Send broadcasts 1608 for (int i = 0; i < size; i++) { 1609 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1610 } 1611 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1612 break; 1613 } 1614 case START_CLEANING_PACKAGE: { 1615 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1616 final String packageName = (String)msg.obj; 1617 final int userId = msg.arg1; 1618 final boolean andCode = msg.arg2 != 0; 1619 synchronized (mPackages) { 1620 if (userId == UserHandle.USER_ALL) { 1621 int[] users = sUserManager.getUserIds(); 1622 for (int user : users) { 1623 mSettings.addPackageToCleanLPw( 1624 new PackageCleanItem(user, packageName, andCode)); 1625 } 1626 } else { 1627 mSettings.addPackageToCleanLPw( 1628 new PackageCleanItem(userId, packageName, andCode)); 1629 } 1630 } 1631 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1632 startCleaningPackages(); 1633 } break; 1634 case POST_INSTALL: { 1635 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1636 1637 PostInstallData data = mRunningInstalls.get(msg.arg1); 1638 final boolean didRestore = (msg.arg2 != 0); 1639 mRunningInstalls.delete(msg.arg1); 1640 1641 if (data != null) { 1642 InstallArgs args = data.args; 1643 PackageInstalledInfo parentRes = data.res; 1644 1645 final boolean grantPermissions = (args.installFlags 1646 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1647 final boolean killApp = (args.installFlags 1648 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1649 final String[] grantedPermissions = args.installGrantPermissions; 1650 1651 // Handle the parent package 1652 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1653 grantedPermissions, didRestore, args.installerPackageName, 1654 args.observer); 1655 1656 // Handle the child packages 1657 final int childCount = (parentRes.addedChildPackages != null) 1658 ? parentRes.addedChildPackages.size() : 0; 1659 for (int i = 0; i < childCount; i++) { 1660 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1661 handlePackagePostInstall(childRes, grantPermissions, killApp, 1662 grantedPermissions, false, args.installerPackageName, 1663 args.observer); 1664 } 1665 1666 // Log tracing if needed 1667 if (args.traceMethod != null) { 1668 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1669 args.traceCookie); 1670 } 1671 } else { 1672 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1673 } 1674 1675 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1676 } break; 1677 case UPDATED_MEDIA_STATUS: { 1678 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1679 boolean reportStatus = msg.arg1 == 1; 1680 boolean doGc = msg.arg2 == 1; 1681 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1682 if (doGc) { 1683 // Force a gc to clear up stale containers. 1684 Runtime.getRuntime().gc(); 1685 } 1686 if (msg.obj != null) { 1687 @SuppressWarnings("unchecked") 1688 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1689 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1690 // Unload containers 1691 unloadAllContainers(args); 1692 } 1693 if (reportStatus) { 1694 try { 1695 if (DEBUG_SD_INSTALL) Log.i(TAG, 1696 "Invoking StorageManagerService call back"); 1697 PackageHelper.getStorageManager().finishMediaUpdate(); 1698 } catch (RemoteException e) { 1699 Log.e(TAG, "StorageManagerService not running?"); 1700 } 1701 } 1702 } break; 1703 case WRITE_SETTINGS: { 1704 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1705 synchronized (mPackages) { 1706 removeMessages(WRITE_SETTINGS); 1707 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1708 mSettings.writeLPr(); 1709 mDirtyUsers.clear(); 1710 } 1711 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1712 } break; 1713 case WRITE_PACKAGE_RESTRICTIONS: { 1714 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1715 synchronized (mPackages) { 1716 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1717 for (int userId : mDirtyUsers) { 1718 mSettings.writePackageRestrictionsLPr(userId); 1719 } 1720 mDirtyUsers.clear(); 1721 } 1722 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1723 } break; 1724 case WRITE_PACKAGE_LIST: { 1725 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1726 synchronized (mPackages) { 1727 removeMessages(WRITE_PACKAGE_LIST); 1728 mSettings.writePackageListLPr(msg.arg1); 1729 } 1730 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1731 } break; 1732 case CHECK_PENDING_VERIFICATION: { 1733 final int verificationId = msg.arg1; 1734 final PackageVerificationState state = mPendingVerification.get(verificationId); 1735 1736 if ((state != null) && !state.timeoutExtended()) { 1737 final InstallArgs args = state.getInstallArgs(); 1738 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1739 1740 Slog.i(TAG, "Verification timed out for " + originUri); 1741 mPendingVerification.remove(verificationId); 1742 1743 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1744 1745 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1746 Slog.i(TAG, "Continuing with installation of " + originUri); 1747 state.setVerifierResponse(Binder.getCallingUid(), 1748 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1749 broadcastPackageVerified(verificationId, originUri, 1750 PackageManager.VERIFICATION_ALLOW, 1751 state.getInstallArgs().getUser()); 1752 try { 1753 ret = args.copyApk(mContainerService, true); 1754 } catch (RemoteException e) { 1755 Slog.e(TAG, "Could not contact the ContainerService"); 1756 } 1757 } else { 1758 broadcastPackageVerified(verificationId, originUri, 1759 PackageManager.VERIFICATION_REJECT, 1760 state.getInstallArgs().getUser()); 1761 } 1762 1763 Trace.asyncTraceEnd( 1764 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1765 1766 processPendingInstall(args, ret); 1767 mHandler.sendEmptyMessage(MCS_UNBIND); 1768 } 1769 break; 1770 } 1771 case PACKAGE_VERIFIED: { 1772 final int verificationId = msg.arg1; 1773 1774 final PackageVerificationState state = mPendingVerification.get(verificationId); 1775 if (state == null) { 1776 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1777 break; 1778 } 1779 1780 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1781 1782 state.setVerifierResponse(response.callerUid, response.code); 1783 1784 if (state.isVerificationComplete()) { 1785 mPendingVerification.remove(verificationId); 1786 1787 final InstallArgs args = state.getInstallArgs(); 1788 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1789 1790 int ret; 1791 if (state.isInstallAllowed()) { 1792 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1793 broadcastPackageVerified(verificationId, originUri, 1794 response.code, state.getInstallArgs().getUser()); 1795 try { 1796 ret = args.copyApk(mContainerService, true); 1797 } catch (RemoteException e) { 1798 Slog.e(TAG, "Could not contact the ContainerService"); 1799 } 1800 } else { 1801 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1802 } 1803 1804 Trace.asyncTraceEnd( 1805 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1806 1807 processPendingInstall(args, ret); 1808 mHandler.sendEmptyMessage(MCS_UNBIND); 1809 } 1810 1811 break; 1812 } 1813 case START_INTENT_FILTER_VERIFICATIONS: { 1814 IFVerificationParams params = (IFVerificationParams) msg.obj; 1815 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1816 params.replacing, params.pkg); 1817 break; 1818 } 1819 case INTENT_FILTER_VERIFIED: { 1820 final int verificationId = msg.arg1; 1821 1822 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1823 verificationId); 1824 if (state == null) { 1825 Slog.w(TAG, "Invalid IntentFilter verification token " 1826 + verificationId + " received"); 1827 break; 1828 } 1829 1830 final int userId = state.getUserId(); 1831 1832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1833 "Processing IntentFilter verification with token:" 1834 + verificationId + " and userId:" + userId); 1835 1836 final IntentFilterVerificationResponse response = 1837 (IntentFilterVerificationResponse) msg.obj; 1838 1839 state.setVerifierResponse(response.callerUid, response.code); 1840 1841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1842 "IntentFilter verification with token:" + verificationId 1843 + " and userId:" + userId 1844 + " is settings verifier response with response code:" 1845 + response.code); 1846 1847 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1849 + response.getFailedDomainsString()); 1850 } 1851 1852 if (state.isVerificationComplete()) { 1853 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1854 } else { 1855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1856 "IntentFilter verification with token:" + verificationId 1857 + " was not said to be complete"); 1858 } 1859 1860 break; 1861 } 1862 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1863 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1864 mInstantAppResolverConnection, 1865 (InstantAppRequest) msg.obj, 1866 mInstantAppInstallerActivity, 1867 mHandler); 1868 } 1869 } 1870 } 1871 } 1872 1873 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1874 boolean killApp, String[] grantedPermissions, 1875 boolean launchedForRestore, String installerPackage, 1876 IPackageInstallObserver2 installObserver) { 1877 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1878 // Send the removed broadcasts 1879 if (res.removedInfo != null) { 1880 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1881 } 1882 1883 // Now that we successfully installed the package, grant runtime 1884 // permissions if requested before broadcasting the install. Also 1885 // for legacy apps in permission review mode we clear the permission 1886 // review flag which is used to emulate runtime permissions for 1887 // legacy apps. 1888 if (grantPermissions) { 1889 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1890 } 1891 1892 final boolean update = res.removedInfo != null 1893 && res.removedInfo.removedPackage != null; 1894 final String origInstallerPackageName = res.removedInfo != null 1895 ? res.removedInfo.installerPackageName : null; 1896 1897 // If this is the first time we have child packages for a disabled privileged 1898 // app that had no children, we grant requested runtime permissions to the new 1899 // children if the parent on the system image had them already granted. 1900 if (res.pkg.parentPackage != null) { 1901 synchronized (mPackages) { 1902 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1903 } 1904 } 1905 1906 synchronized (mPackages) { 1907 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1908 } 1909 1910 final String packageName = res.pkg.applicationInfo.packageName; 1911 1912 // Determine the set of users who are adding this package for 1913 // the first time vs. those who are seeing an update. 1914 int[] firstUsers = EMPTY_INT_ARRAY; 1915 int[] updateUsers = EMPTY_INT_ARRAY; 1916 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1917 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1918 for (int newUser : res.newUsers) { 1919 if (ps.getInstantApp(newUser)) { 1920 continue; 1921 } 1922 if (allNewUsers) { 1923 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1924 continue; 1925 } 1926 boolean isNew = true; 1927 for (int origUser : res.origUsers) { 1928 if (origUser == newUser) { 1929 isNew = false; 1930 break; 1931 } 1932 } 1933 if (isNew) { 1934 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1935 } else { 1936 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1937 } 1938 } 1939 1940 // Send installed broadcasts if the package is not a static shared lib. 1941 if (res.pkg.staticSharedLibName == null) { 1942 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1943 1944 // Send added for users that see the package for the first time 1945 // sendPackageAddedForNewUsers also deals with system apps 1946 int appId = UserHandle.getAppId(res.uid); 1947 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1948 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1949 1950 // Send added for users that don't see the package for the first time 1951 Bundle extras = new Bundle(1); 1952 extras.putInt(Intent.EXTRA_UID, res.uid); 1953 if (update) { 1954 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1955 } 1956 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1957 extras, 0 /*flags*/, 1958 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 1959 if (origInstallerPackageName != null) { 1960 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1961 extras, 0 /*flags*/, 1962 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1963 } 1964 1965 // Send replaced for users that don't see the package for the first time 1966 if (update) { 1967 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1968 packageName, extras, 0 /*flags*/, 1969 null /*targetPackage*/, null /*finishedReceiver*/, 1970 updateUsers); 1971 if (origInstallerPackageName != null) { 1972 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1973 extras, 0 /*flags*/, 1974 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1975 } 1976 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1977 null /*package*/, null /*extras*/, 0 /*flags*/, 1978 packageName /*targetPackage*/, 1979 null /*finishedReceiver*/, updateUsers); 1980 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1981 // First-install and we did a restore, so we're responsible for the 1982 // first-launch broadcast. 1983 if (DEBUG_BACKUP) { 1984 Slog.i(TAG, "Post-restore of " + packageName 1985 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1986 } 1987 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1988 } 1989 1990 // Send broadcast package appeared if forward locked/external for all users 1991 // treat asec-hosted packages like removable media on upgrade 1992 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1993 if (DEBUG_INSTALL) { 1994 Slog.i(TAG, "upgrading pkg " + res.pkg 1995 + " is ASEC-hosted -> AVAILABLE"); 1996 } 1997 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1998 ArrayList<String> pkgList = new ArrayList<>(1); 1999 pkgList.add(packageName); 2000 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2001 } 2002 } 2003 2004 // Work that needs to happen on first install within each user 2005 if (firstUsers != null && firstUsers.length > 0) { 2006 synchronized (mPackages) { 2007 for (int userId : firstUsers) { 2008 // If this app is a browser and it's newly-installed for some 2009 // users, clear any default-browser state in those users. The 2010 // app's nature doesn't depend on the user, so we can just check 2011 // its browser nature in any user and generalize. 2012 if (packageIsBrowser(packageName, userId)) { 2013 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2014 } 2015 2016 // We may also need to apply pending (restored) runtime 2017 // permission grants within these users. 2018 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2019 } 2020 } 2021 } 2022 2023 // Log current value of "unknown sources" setting 2024 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2025 getUnknownSourcesSettings()); 2026 2027 // Force a gc to clear up things 2028 Runtime.getRuntime().gc(); 2029 2030 // Remove the replaced package's older resources safely now 2031 // We delete after a gc for applications on sdcard. 2032 if (res.removedInfo != null && res.removedInfo.args != null) { 2033 synchronized (mInstallLock) { 2034 res.removedInfo.args.doPostDeleteLI(true); 2035 } 2036 } 2037 2038 // Notify DexManager that the package was installed for new users. 2039 // The updated users should already be indexed and the package code paths 2040 // should not change. 2041 // Don't notify the manager for ephemeral apps as they are not expected to 2042 // survive long enough to benefit of background optimizations. 2043 for (int userId : firstUsers) { 2044 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2045 // There's a race currently where some install events may interleave with an uninstall. 2046 // This can lead to package info being null (b/36642664). 2047 if (info != null) { 2048 mDexManager.notifyPackageInstalled(info, userId); 2049 } 2050 } 2051 } 2052 2053 // If someone is watching installs - notify them 2054 if (installObserver != null) { 2055 try { 2056 Bundle extras = extrasForInstallResult(res); 2057 installObserver.onPackageInstalled(res.name, res.returnCode, 2058 res.returnMsg, extras); 2059 } catch (RemoteException e) { 2060 Slog.i(TAG, "Observer no longer exists."); 2061 } 2062 } 2063 } 2064 2065 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2066 PackageParser.Package pkg) { 2067 if (pkg.parentPackage == null) { 2068 return; 2069 } 2070 if (pkg.requestedPermissions == null) { 2071 return; 2072 } 2073 final PackageSetting disabledSysParentPs = mSettings 2074 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2075 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2076 || !disabledSysParentPs.isPrivileged() 2077 || (disabledSysParentPs.childPackageNames != null 2078 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2079 return; 2080 } 2081 final int[] allUserIds = sUserManager.getUserIds(); 2082 final int permCount = pkg.requestedPermissions.size(); 2083 for (int i = 0; i < permCount; i++) { 2084 String permission = pkg.requestedPermissions.get(i); 2085 BasePermission bp = mSettings.mPermissions.get(permission); 2086 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2087 continue; 2088 } 2089 for (int userId : allUserIds) { 2090 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2091 permission, userId)) { 2092 grantRuntimePermission(pkg.packageName, permission, userId); 2093 } 2094 } 2095 } 2096 } 2097 2098 private StorageEventListener mStorageListener = new StorageEventListener() { 2099 @Override 2100 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2101 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2102 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2103 final String volumeUuid = vol.getFsUuid(); 2104 2105 // Clean up any users or apps that were removed or recreated 2106 // while this volume was missing 2107 sUserManager.reconcileUsers(volumeUuid); 2108 reconcileApps(volumeUuid); 2109 2110 // Clean up any install sessions that expired or were 2111 // cancelled while this volume was missing 2112 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2113 2114 loadPrivatePackages(vol); 2115 2116 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2117 unloadPrivatePackages(vol); 2118 } 2119 } 2120 2121 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2122 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2123 updateExternalMediaStatus(true, false); 2124 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2125 updateExternalMediaStatus(false, false); 2126 } 2127 } 2128 } 2129 2130 @Override 2131 public void onVolumeForgotten(String fsUuid) { 2132 if (TextUtils.isEmpty(fsUuid)) { 2133 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2134 return; 2135 } 2136 2137 // Remove any apps installed on the forgotten volume 2138 synchronized (mPackages) { 2139 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2140 for (PackageSetting ps : packages) { 2141 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2142 deletePackageVersioned(new VersionedPackage(ps.name, 2143 PackageManager.VERSION_CODE_HIGHEST), 2144 new LegacyPackageDeleteObserver(null).getBinder(), 2145 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2146 // Try very hard to release any references to this package 2147 // so we don't risk the system server being killed due to 2148 // open FDs 2149 AttributeCache.instance().removePackage(ps.name); 2150 } 2151 2152 mSettings.onVolumeForgotten(fsUuid); 2153 mSettings.writeLPr(); 2154 } 2155 } 2156 }; 2157 2158 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2159 String[] grantedPermissions) { 2160 for (int userId : userIds) { 2161 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2162 } 2163 } 2164 2165 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2166 String[] grantedPermissions) { 2167 SettingBase sb = (SettingBase) pkg.mExtras; 2168 if (sb == null) { 2169 return; 2170 } 2171 2172 PermissionsState permissionsState = sb.getPermissionsState(); 2173 2174 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2175 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2176 2177 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2178 >= Build.VERSION_CODES.M; 2179 2180 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2181 2182 for (String permission : pkg.requestedPermissions) { 2183 final BasePermission bp; 2184 synchronized (mPackages) { 2185 bp = mSettings.mPermissions.get(permission); 2186 } 2187 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2188 && (!instantApp || bp.isInstant()) 2189 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2190 && (grantedPermissions == null 2191 || ArrayUtils.contains(grantedPermissions, permission))) { 2192 final int flags = permissionsState.getPermissionFlags(permission, userId); 2193 if (supportsRuntimePermissions) { 2194 // Installer cannot change immutable permissions. 2195 if ((flags & immutableFlags) == 0) { 2196 grantRuntimePermission(pkg.packageName, permission, userId); 2197 } 2198 } else if (mPermissionReviewRequired) { 2199 // In permission review mode we clear the review flag when we 2200 // are asked to install the app with all permissions granted. 2201 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2202 updatePermissionFlags(permission, pkg.packageName, 2203 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2204 } 2205 } 2206 } 2207 } 2208 } 2209 2210 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2211 Bundle extras = null; 2212 switch (res.returnCode) { 2213 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2214 extras = new Bundle(); 2215 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2216 res.origPermission); 2217 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2218 res.origPackage); 2219 break; 2220 } 2221 case PackageManager.INSTALL_SUCCEEDED: { 2222 extras = new Bundle(); 2223 extras.putBoolean(Intent.EXTRA_REPLACING, 2224 res.removedInfo != null && res.removedInfo.removedPackage != null); 2225 break; 2226 } 2227 } 2228 return extras; 2229 } 2230 2231 void scheduleWriteSettingsLocked() { 2232 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2233 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2234 } 2235 } 2236 2237 void scheduleWritePackageListLocked(int userId) { 2238 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2239 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2240 msg.arg1 = userId; 2241 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2242 } 2243 } 2244 2245 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2246 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2247 scheduleWritePackageRestrictionsLocked(userId); 2248 } 2249 2250 void scheduleWritePackageRestrictionsLocked(int userId) { 2251 final int[] userIds = (userId == UserHandle.USER_ALL) 2252 ? sUserManager.getUserIds() : new int[]{userId}; 2253 for (int nextUserId : userIds) { 2254 if (!sUserManager.exists(nextUserId)) return; 2255 mDirtyUsers.add(nextUserId); 2256 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2257 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2258 } 2259 } 2260 } 2261 2262 public static PackageManagerService main(Context context, Installer installer, 2263 boolean factoryTest, boolean onlyCore) { 2264 // Self-check for initial settings. 2265 PackageManagerServiceCompilerMapping.checkProperties(); 2266 2267 PackageManagerService m = new PackageManagerService(context, installer, 2268 factoryTest, onlyCore); 2269 m.enableSystemUserPackages(); 2270 ServiceManager.addService("package", m); 2271 return m; 2272 } 2273 2274 private void enableSystemUserPackages() { 2275 if (!UserManager.isSplitSystemUser()) { 2276 return; 2277 } 2278 // For system user, enable apps based on the following conditions: 2279 // - app is whitelisted or belong to one of these groups: 2280 // -- system app which has no launcher icons 2281 // -- system app which has INTERACT_ACROSS_USERS permission 2282 // -- system IME app 2283 // - app is not in the blacklist 2284 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2285 Set<String> enableApps = new ArraySet<>(); 2286 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2287 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2288 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2289 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2290 enableApps.addAll(wlApps); 2291 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2292 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2293 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2294 enableApps.removeAll(blApps); 2295 Log.i(TAG, "Applications installed for system user: " + enableApps); 2296 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2297 UserHandle.SYSTEM); 2298 final int allAppsSize = allAps.size(); 2299 synchronized (mPackages) { 2300 for (int i = 0; i < allAppsSize; i++) { 2301 String pName = allAps.get(i); 2302 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2303 // Should not happen, but we shouldn't be failing if it does 2304 if (pkgSetting == null) { 2305 continue; 2306 } 2307 boolean install = enableApps.contains(pName); 2308 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2309 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2310 + " for system user"); 2311 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2312 } 2313 } 2314 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2315 } 2316 } 2317 2318 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2319 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2320 Context.DISPLAY_SERVICE); 2321 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2322 } 2323 2324 /** 2325 * Requests that files preopted on a secondary system partition be copied to the data partition 2326 * if possible. Note that the actual copying of the files is accomplished by init for security 2327 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2328 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2329 */ 2330 private static void requestCopyPreoptedFiles() { 2331 final int WAIT_TIME_MS = 100; 2332 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2333 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2334 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2335 // We will wait for up to 100 seconds. 2336 final long timeStart = SystemClock.uptimeMillis(); 2337 final long timeEnd = timeStart + 100 * 1000; 2338 long timeNow = timeStart; 2339 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2340 try { 2341 Thread.sleep(WAIT_TIME_MS); 2342 } catch (InterruptedException e) { 2343 // Do nothing 2344 } 2345 timeNow = SystemClock.uptimeMillis(); 2346 if (timeNow > timeEnd) { 2347 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2348 Slog.wtf(TAG, "cppreopt did not finish!"); 2349 break; 2350 } 2351 } 2352 2353 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2354 } 2355 } 2356 2357 public PackageManagerService(Context context, Installer installer, 2358 boolean factoryTest, boolean onlyCore) { 2359 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2361 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2362 SystemClock.uptimeMillis()); 2363 2364 if (mSdkVersion <= 0) { 2365 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2366 } 2367 2368 mContext = context; 2369 2370 mPermissionReviewRequired = context.getResources().getBoolean( 2371 R.bool.config_permissionReviewRequired); 2372 2373 mFactoryTest = factoryTest; 2374 mOnlyCore = onlyCore; 2375 mMetrics = new DisplayMetrics(); 2376 mSettings = new Settings(mPackages); 2377 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2378 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2379 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2380 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2381 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2382 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2383 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2384 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2385 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2386 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2387 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2388 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2389 2390 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2391 if (separateProcesses != null && separateProcesses.length() > 0) { 2392 if ("*".equals(separateProcesses)) { 2393 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2394 mSeparateProcesses = null; 2395 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2396 } else { 2397 mDefParseFlags = 0; 2398 mSeparateProcesses = separateProcesses.split(","); 2399 Slog.w(TAG, "Running with debug.separate_processes: " 2400 + separateProcesses); 2401 } 2402 } else { 2403 mDefParseFlags = 0; 2404 mSeparateProcesses = null; 2405 } 2406 2407 mInstaller = installer; 2408 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2409 "*dexopt*"); 2410 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2411 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2412 2413 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2414 FgThread.get().getLooper()); 2415 2416 getDefaultDisplayMetrics(context, mMetrics); 2417 2418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2419 SystemConfig systemConfig = SystemConfig.getInstance(); 2420 mGlobalGids = systemConfig.getGlobalGids(); 2421 mSystemPermissions = systemConfig.getSystemPermissions(); 2422 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2423 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2424 2425 mProtectedPackages = new ProtectedPackages(mContext); 2426 2427 synchronized (mInstallLock) { 2428 // writer 2429 synchronized (mPackages) { 2430 mHandlerThread = new ServiceThread(TAG, 2431 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2432 mHandlerThread.start(); 2433 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2434 mProcessLoggingHandler = new ProcessLoggingHandler(); 2435 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2436 2437 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2438 mInstantAppRegistry = new InstantAppRegistry(this); 2439 2440 File dataDir = Environment.getDataDirectory(); 2441 mAppInstallDir = new File(dataDir, "app"); 2442 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2443 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2444 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2445 sUserManager = new UserManagerService(context, this, 2446 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2447 2448 // Propagate permission configuration in to package manager. 2449 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2450 = systemConfig.getPermissions(); 2451 for (int i=0; i<permConfig.size(); i++) { 2452 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2453 BasePermission bp = mSettings.mPermissions.get(perm.name); 2454 if (bp == null) { 2455 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2456 mSettings.mPermissions.put(perm.name, bp); 2457 } 2458 if (perm.gids != null) { 2459 bp.setGids(perm.gids, perm.perUser); 2460 } 2461 } 2462 2463 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2464 final int builtInLibCount = libConfig.size(); 2465 for (int i = 0; i < builtInLibCount; i++) { 2466 String name = libConfig.keyAt(i); 2467 String path = libConfig.valueAt(i); 2468 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2469 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2470 } 2471 2472 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2473 2474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2475 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2477 2478 // Clean up orphaned packages for which the code path doesn't exist 2479 // and they are an update to a system app - caused by bug/32321269 2480 final int packageSettingCount = mSettings.mPackages.size(); 2481 for (int i = packageSettingCount - 1; i >= 0; i--) { 2482 PackageSetting ps = mSettings.mPackages.valueAt(i); 2483 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2484 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2485 mSettings.mPackages.removeAt(i); 2486 mSettings.enableSystemPackageLPw(ps.name); 2487 } 2488 } 2489 2490 if (mFirstBoot) { 2491 requestCopyPreoptedFiles(); 2492 } 2493 2494 String customResolverActivity = Resources.getSystem().getString( 2495 R.string.config_customResolverActivity); 2496 if (TextUtils.isEmpty(customResolverActivity)) { 2497 customResolverActivity = null; 2498 } else { 2499 mCustomResolverComponentName = ComponentName.unflattenFromString( 2500 customResolverActivity); 2501 } 2502 2503 long startTime = SystemClock.uptimeMillis(); 2504 2505 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2506 startTime); 2507 2508 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2509 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2510 2511 if (bootClassPath == null) { 2512 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2513 } 2514 2515 if (systemServerClassPath == null) { 2516 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2517 } 2518 2519 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2520 2521 final VersionInfo ver = mSettings.getInternalVersion(); 2522 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2523 if (mIsUpgrade) { 2524 logCriticalInfo(Log.INFO, 2525 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2526 } 2527 2528 // when upgrading from pre-M, promote system app permissions from install to runtime 2529 mPromoteSystemApps = 2530 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2531 2532 // When upgrading from pre-N, we need to handle package extraction like first boot, 2533 // as there is no profiling data available. 2534 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2535 2536 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2537 2538 // save off the names of pre-existing system packages prior to scanning; we don't 2539 // want to automatically grant runtime permissions for new system apps 2540 if (mPromoteSystemApps) { 2541 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2542 while (pkgSettingIter.hasNext()) { 2543 PackageSetting ps = pkgSettingIter.next(); 2544 if (isSystemApp(ps)) { 2545 mExistingSystemPackages.add(ps.name); 2546 } 2547 } 2548 } 2549 2550 mCacheDir = preparePackageParserCache(mIsUpgrade); 2551 2552 // Set flag to monitor and not change apk file paths when 2553 // scanning install directories. 2554 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2555 2556 if (mIsUpgrade || mFirstBoot) { 2557 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2558 } 2559 2560 // Collect vendor overlay packages. (Do this before scanning any apps.) 2561 // For security and version matching reason, only consider 2562 // overlay packages if they reside in the right directory. 2563 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2564 | PackageParser.PARSE_IS_SYSTEM 2565 | PackageParser.PARSE_IS_SYSTEM_DIR 2566 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2567 2568 mParallelPackageParserCallback.findStaticOverlayPackages(); 2569 2570 // Find base frameworks (resource packages without code). 2571 scanDirTracedLI(frameworkDir, mDefParseFlags 2572 | PackageParser.PARSE_IS_SYSTEM 2573 | PackageParser.PARSE_IS_SYSTEM_DIR 2574 | PackageParser.PARSE_IS_PRIVILEGED, 2575 scanFlags | SCAN_NO_DEX, 0); 2576 2577 // Collected privileged system packages. 2578 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2579 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2580 | PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR 2582 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2583 2584 // Collect ordinary system packages. 2585 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2586 scanDirTracedLI(systemAppDir, mDefParseFlags 2587 | PackageParser.PARSE_IS_SYSTEM 2588 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2589 2590 // Collect all vendor packages. 2591 File vendorAppDir = new File("/vendor/app"); 2592 try { 2593 vendorAppDir = vendorAppDir.getCanonicalFile(); 2594 } catch (IOException e) { 2595 // failed to look up canonical path, continue with original one 2596 } 2597 scanDirTracedLI(vendorAppDir, mDefParseFlags 2598 | PackageParser.PARSE_IS_SYSTEM 2599 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2600 2601 // Collect all OEM packages. 2602 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2603 scanDirTracedLI(oemAppDir, mDefParseFlags 2604 | PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2606 2607 // Prune any system packages that no longer exist. 2608 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2609 if (!mOnlyCore) { 2610 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2611 while (psit.hasNext()) { 2612 PackageSetting ps = psit.next(); 2613 2614 /* 2615 * If this is not a system app, it can't be a 2616 * disable system app. 2617 */ 2618 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2619 continue; 2620 } 2621 2622 /* 2623 * If the package is scanned, it's not erased. 2624 */ 2625 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2626 if (scannedPkg != null) { 2627 /* 2628 * If the system app is both scanned and in the 2629 * disabled packages list, then it must have been 2630 * added via OTA. Remove it from the currently 2631 * scanned package so the previously user-installed 2632 * application can be scanned. 2633 */ 2634 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2635 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2636 + ps.name + "; removing system app. Last known codePath=" 2637 + ps.codePathString + ", installStatus=" + ps.installStatus 2638 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2639 + scannedPkg.mVersionCode); 2640 removePackageLI(scannedPkg, true); 2641 mExpectingBetter.put(ps.name, ps.codePath); 2642 } 2643 2644 continue; 2645 } 2646 2647 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2648 psit.remove(); 2649 logCriticalInfo(Log.WARN, "System package " + ps.name 2650 + " no longer exists; it's data will be wiped"); 2651 // Actual deletion of code and data will be handled by later 2652 // reconciliation step 2653 } else { 2654 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2655 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2656 possiblyDeletedUpdatedSystemApps.add(ps.name); 2657 } 2658 } 2659 } 2660 } 2661 2662 //look for any incomplete package installations 2663 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2664 for (int i = 0; i < deletePkgsList.size(); i++) { 2665 // Actual deletion of code and data will be handled by later 2666 // reconciliation step 2667 final String packageName = deletePkgsList.get(i).name; 2668 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2669 synchronized (mPackages) { 2670 mSettings.removePackageLPw(packageName); 2671 } 2672 } 2673 2674 //delete tmp files 2675 deleteTempPackageFiles(); 2676 2677 // Remove any shared userIDs that have no associated packages 2678 mSettings.pruneSharedUsersLPw(); 2679 2680 if (!mOnlyCore) { 2681 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2682 SystemClock.uptimeMillis()); 2683 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2684 2685 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2686 | PackageParser.PARSE_FORWARD_LOCK, 2687 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2688 2689 /** 2690 * Remove disable package settings for any updated system 2691 * apps that were removed via an OTA. If they're not a 2692 * previously-updated app, remove them completely. 2693 * Otherwise, just revoke their system-level permissions. 2694 */ 2695 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2696 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2697 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2698 2699 String msg; 2700 if (deletedPkg == null) { 2701 msg = "Updated system package " + deletedAppName 2702 + " no longer exists; it's data will be wiped"; 2703 // Actual deletion of code and data will be handled by later 2704 // reconciliation step 2705 } else { 2706 msg = "Updated system app + " + deletedAppName 2707 + " no longer present; removing system privileges for " 2708 + deletedAppName; 2709 2710 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2711 2712 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2713 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2714 } 2715 logCriticalInfo(Log.WARN, msg); 2716 } 2717 2718 /** 2719 * Make sure all system apps that we expected to appear on 2720 * the userdata partition actually showed up. If they never 2721 * appeared, crawl back and revive the system version. 2722 */ 2723 for (int i = 0; i < mExpectingBetter.size(); i++) { 2724 final String packageName = mExpectingBetter.keyAt(i); 2725 if (!mPackages.containsKey(packageName)) { 2726 final File scanFile = mExpectingBetter.valueAt(i); 2727 2728 logCriticalInfo(Log.WARN, "Expected better " + packageName 2729 + " but never showed up; reverting to system"); 2730 2731 int reparseFlags = mDefParseFlags; 2732 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2733 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2734 | PackageParser.PARSE_IS_SYSTEM_DIR 2735 | PackageParser.PARSE_IS_PRIVILEGED; 2736 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2737 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2738 | PackageParser.PARSE_IS_SYSTEM_DIR; 2739 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2740 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2741 | PackageParser.PARSE_IS_SYSTEM_DIR; 2742 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2743 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2744 | PackageParser.PARSE_IS_SYSTEM_DIR; 2745 } else { 2746 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2747 continue; 2748 } 2749 2750 mSettings.enableSystemPackageLPw(packageName); 2751 2752 try { 2753 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2754 } catch (PackageManagerException e) { 2755 Slog.e(TAG, "Failed to parse original system package: " 2756 + e.getMessage()); 2757 } 2758 } 2759 } 2760 } 2761 mExpectingBetter.clear(); 2762 2763 // Resolve the storage manager. 2764 mStorageManagerPackage = getStorageManagerPackageName(); 2765 2766 // Resolve protected action filters. Only the setup wizard is allowed to 2767 // have a high priority filter for these actions. 2768 mSetupWizardPackage = getSetupWizardPackageName(); 2769 if (mProtectedFilters.size() > 0) { 2770 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2771 Slog.i(TAG, "No setup wizard;" 2772 + " All protected intents capped to priority 0"); 2773 } 2774 for (ActivityIntentInfo filter : mProtectedFilters) { 2775 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2776 if (DEBUG_FILTERS) { 2777 Slog.i(TAG, "Found setup wizard;" 2778 + " allow priority " + filter.getPriority() + ";" 2779 + " package: " + filter.activity.info.packageName 2780 + " activity: " + filter.activity.className 2781 + " priority: " + filter.getPriority()); 2782 } 2783 // skip setup wizard; allow it to keep the high priority filter 2784 continue; 2785 } 2786 Slog.w(TAG, "Protected action; cap priority to 0;" 2787 + " package: " + filter.activity.info.packageName 2788 + " activity: " + filter.activity.className 2789 + " origPrio: " + filter.getPriority()); 2790 filter.setPriority(0); 2791 } 2792 } 2793 mDeferProtectedFilters = false; 2794 mProtectedFilters.clear(); 2795 2796 // Now that we know all of the shared libraries, update all clients to have 2797 // the correct library paths. 2798 updateAllSharedLibrariesLPw(null); 2799 2800 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2801 // NOTE: We ignore potential failures here during a system scan (like 2802 // the rest of the commands above) because there's precious little we 2803 // can do about it. A settings error is reported, though. 2804 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2805 } 2806 2807 // Now that we know all the packages we are keeping, 2808 // read and update their last usage times. 2809 mPackageUsage.read(mPackages); 2810 mCompilerStats.read(); 2811 2812 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2813 SystemClock.uptimeMillis()); 2814 Slog.i(TAG, "Time to scan packages: " 2815 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2816 + " seconds"); 2817 2818 // If the platform SDK has changed since the last time we booted, 2819 // we need to re-grant app permission to catch any new ones that 2820 // appear. This is really a hack, and means that apps can in some 2821 // cases get permissions that the user didn't initially explicitly 2822 // allow... it would be nice to have some better way to handle 2823 // this situation. 2824 int updateFlags = UPDATE_PERMISSIONS_ALL; 2825 if (ver.sdkVersion != mSdkVersion) { 2826 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2827 + mSdkVersion + "; regranting permissions for internal storage"); 2828 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2829 } 2830 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2831 ver.sdkVersion = mSdkVersion; 2832 2833 // If this is the first boot or an update from pre-M, and it is a normal 2834 // boot, then we need to initialize the default preferred apps across 2835 // all defined users. 2836 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2837 for (UserInfo user : sUserManager.getUsers(true)) { 2838 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2839 applyFactoryDefaultBrowserLPw(user.id); 2840 primeDomainVerificationsLPw(user.id); 2841 } 2842 } 2843 2844 // Prepare storage for system user really early during boot, 2845 // since core system apps like SettingsProvider and SystemUI 2846 // can't wait for user to start 2847 final int storageFlags; 2848 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2849 storageFlags = StorageManager.FLAG_STORAGE_DE; 2850 } else { 2851 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2852 } 2853 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2854 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2855 true /* onlyCoreApps */); 2856 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2857 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2858 Trace.TRACE_TAG_PACKAGE_MANAGER); 2859 traceLog.traceBegin("AppDataFixup"); 2860 try { 2861 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2862 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2863 } catch (InstallerException e) { 2864 Slog.w(TAG, "Trouble fixing GIDs", e); 2865 } 2866 traceLog.traceEnd(); 2867 2868 traceLog.traceBegin("AppDataPrepare"); 2869 if (deferPackages == null || deferPackages.isEmpty()) { 2870 return; 2871 } 2872 int count = 0; 2873 for (String pkgName : deferPackages) { 2874 PackageParser.Package pkg = null; 2875 synchronized (mPackages) { 2876 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2877 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2878 pkg = ps.pkg; 2879 } 2880 } 2881 if (pkg != null) { 2882 synchronized (mInstallLock) { 2883 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2884 true /* maybeMigrateAppData */); 2885 } 2886 count++; 2887 } 2888 } 2889 traceLog.traceEnd(); 2890 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2891 }, "prepareAppData"); 2892 2893 // If this is first boot after an OTA, and a normal boot, then 2894 // we need to clear code cache directories. 2895 // Note that we do *not* clear the application profiles. These remain valid 2896 // across OTAs and are used to drive profile verification (post OTA) and 2897 // profile compilation (without waiting to collect a fresh set of profiles). 2898 if (mIsUpgrade && !onlyCore) { 2899 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2900 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2901 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2902 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2903 // No apps are running this early, so no need to freeze 2904 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2905 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2906 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2907 } 2908 } 2909 ver.fingerprint = Build.FINGERPRINT; 2910 } 2911 2912 checkDefaultBrowser(); 2913 2914 // clear only after permissions and other defaults have been updated 2915 mExistingSystemPackages.clear(); 2916 mPromoteSystemApps = false; 2917 2918 // All the changes are done during package scanning. 2919 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2920 2921 // can downgrade to reader 2922 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2923 mSettings.writeLPr(); 2924 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2925 2926 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2927 SystemClock.uptimeMillis()); 2928 2929 if (!mOnlyCore) { 2930 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2931 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2932 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2933 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2934 if (mIntentFilterVerifierComponent != null) { 2935 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2936 mIntentFilterVerifierComponent); 2937 } else { 2938 mIntentFilterVerifier = null; 2939 } 2940 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2941 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2942 SharedLibraryInfo.VERSION_UNDEFINED); 2943 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2944 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2945 SharedLibraryInfo.VERSION_UNDEFINED); 2946 } else { 2947 mRequiredVerifierPackage = null; 2948 mRequiredInstallerPackage = null; 2949 mRequiredUninstallerPackage = null; 2950 mIntentFilterVerifierComponent = null; 2951 mIntentFilterVerifier = null; 2952 mServicesSystemSharedLibraryPackageName = null; 2953 mSharedSystemSharedLibraryPackageName = null; 2954 } 2955 2956 mInstallerService = new PackageInstallerService(context, this); 2957 final Pair<ComponentName, String> instantAppResolverComponent = 2958 getInstantAppResolverLPr(); 2959 if (instantAppResolverComponent != null) { 2960 if (DEBUG_EPHEMERAL) { 2961 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2962 } 2963 mInstantAppResolverConnection = new EphemeralResolverConnection( 2964 mContext, instantAppResolverComponent.first, 2965 instantAppResolverComponent.second); 2966 mInstantAppResolverSettingsComponent = 2967 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2968 } else { 2969 mInstantAppResolverConnection = null; 2970 mInstantAppResolverSettingsComponent = null; 2971 } 2972 updateInstantAppInstallerLocked(null); 2973 2974 // Read and update the usage of dex files. 2975 // Do this at the end of PM init so that all the packages have their 2976 // data directory reconciled. 2977 // At this point we know the code paths of the packages, so we can validate 2978 // the disk file and build the internal cache. 2979 // The usage file is expected to be small so loading and verifying it 2980 // should take a fairly small time compare to the other activities (e.g. package 2981 // scanning). 2982 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2983 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2984 for (int userId : currentUserIds) { 2985 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2986 } 2987 mDexManager.load(userPackages); 2988 } // synchronized (mPackages) 2989 } // synchronized (mInstallLock) 2990 2991 // Now after opening every single application zip, make sure they 2992 // are all flushed. Not really needed, but keeps things nice and 2993 // tidy. 2994 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2995 Runtime.getRuntime().gc(); 2996 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2997 2998 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2999 FallbackCategoryProvider.loadFallbacks(); 3000 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3001 3002 // The initial scanning above does many calls into installd while 3003 // holding the mPackages lock, but we're mostly interested in yelling 3004 // once we have a booted system. 3005 mInstaller.setWarnIfHeld(mPackages); 3006 3007 // Expose private service for system components to use. 3008 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3009 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3010 } 3011 3012 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3013 // we're only interested in updating the installer appliction when 1) it's not 3014 // already set or 2) the modified package is the installer 3015 if (mInstantAppInstallerActivity != null 3016 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3017 .equals(modifiedPackage)) { 3018 return; 3019 } 3020 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3021 } 3022 3023 private static File preparePackageParserCache(boolean isUpgrade) { 3024 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3025 return null; 3026 } 3027 3028 // Disable package parsing on eng builds to allow for faster incremental development. 3029 if ("eng".equals(Build.TYPE)) { 3030 return null; 3031 } 3032 3033 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3034 Slog.i(TAG, "Disabling package parser cache due to system property."); 3035 return null; 3036 } 3037 3038 // The base directory for the package parser cache lives under /data/system/. 3039 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3040 "package_cache"); 3041 if (cacheBaseDir == null) { 3042 return null; 3043 } 3044 3045 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3046 // This also serves to "GC" unused entries when the package cache version changes (which 3047 // can only happen during upgrades). 3048 if (isUpgrade) { 3049 FileUtils.deleteContents(cacheBaseDir); 3050 } 3051 3052 3053 // Return the versioned package cache directory. This is something like 3054 // "/data/system/package_cache/1" 3055 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3056 3057 // The following is a workaround to aid development on non-numbered userdebug 3058 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3059 // the system partition is newer. 3060 // 3061 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3062 // that starts with "eng." to signify that this is an engineering build and not 3063 // destined for release. 3064 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3065 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3066 3067 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3068 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3069 // in general and should not be used for production changes. In this specific case, 3070 // we know that they will work. 3071 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3072 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3073 FileUtils.deleteContents(cacheBaseDir); 3074 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3075 } 3076 } 3077 3078 return cacheDir; 3079 } 3080 3081 @Override 3082 public boolean isFirstBoot() { 3083 return mFirstBoot; 3084 } 3085 3086 @Override 3087 public boolean isOnlyCoreApps() { 3088 return mOnlyCore; 3089 } 3090 3091 @Override 3092 public boolean isUpgrade() { 3093 return mIsUpgrade; 3094 } 3095 3096 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3097 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3098 3099 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3100 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3101 UserHandle.USER_SYSTEM); 3102 if (matches.size() == 1) { 3103 return matches.get(0).getComponentInfo().packageName; 3104 } else if (matches.size() == 0) { 3105 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3106 return null; 3107 } 3108 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3109 } 3110 3111 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3112 synchronized (mPackages) { 3113 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3114 if (libraryEntry == null) { 3115 throw new IllegalStateException("Missing required shared library:" + name); 3116 } 3117 return libraryEntry.apk; 3118 } 3119 } 3120 3121 private @NonNull String getRequiredInstallerLPr() { 3122 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3123 intent.addCategory(Intent.CATEGORY_DEFAULT); 3124 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3125 3126 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3127 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3128 UserHandle.USER_SYSTEM); 3129 if (matches.size() == 1) { 3130 ResolveInfo resolveInfo = matches.get(0); 3131 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3132 throw new RuntimeException("The installer must be a privileged app"); 3133 } 3134 return matches.get(0).getComponentInfo().packageName; 3135 } else { 3136 throw new RuntimeException("There must be exactly one installer; found " + matches); 3137 } 3138 } 3139 3140 private @NonNull String getRequiredUninstallerLPr() { 3141 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3142 intent.addCategory(Intent.CATEGORY_DEFAULT); 3143 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3144 3145 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3146 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3147 UserHandle.USER_SYSTEM); 3148 if (resolveInfo == null || 3149 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3150 throw new RuntimeException("There must be exactly one uninstaller; found " 3151 + resolveInfo); 3152 } 3153 return resolveInfo.getComponentInfo().packageName; 3154 } 3155 3156 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3157 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3158 3159 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3160 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3161 UserHandle.USER_SYSTEM); 3162 ResolveInfo best = null; 3163 final int N = matches.size(); 3164 for (int i = 0; i < N; i++) { 3165 final ResolveInfo cur = matches.get(i); 3166 final String packageName = cur.getComponentInfo().packageName; 3167 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3168 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3169 continue; 3170 } 3171 3172 if (best == null || cur.priority > best.priority) { 3173 best = cur; 3174 } 3175 } 3176 3177 if (best != null) { 3178 return best.getComponentInfo().getComponentName(); 3179 } 3180 Slog.w(TAG, "Intent filter verifier not found"); 3181 return null; 3182 } 3183 3184 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3185 final String[] packageArray = 3186 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3187 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3188 if (DEBUG_EPHEMERAL) { 3189 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3190 } 3191 return null; 3192 } 3193 3194 final int callingUid = Binder.getCallingUid(); 3195 final int resolveFlags = 3196 MATCH_DIRECT_BOOT_AWARE 3197 | MATCH_DIRECT_BOOT_UNAWARE 3198 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3199 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3200 final Intent resolverIntent = new Intent(actionName); 3201 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3202 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3203 // temporarily look for the old action 3204 if (resolvers.size() == 0) { 3205 if (DEBUG_EPHEMERAL) { 3206 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3207 } 3208 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3209 resolverIntent.setAction(actionName); 3210 resolvers = queryIntentServicesInternal(resolverIntent, null, 3211 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3212 } 3213 final int N = resolvers.size(); 3214 if (N == 0) { 3215 if (DEBUG_EPHEMERAL) { 3216 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3217 } 3218 return null; 3219 } 3220 3221 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3222 for (int i = 0; i < N; i++) { 3223 final ResolveInfo info = resolvers.get(i); 3224 3225 if (info.serviceInfo == null) { 3226 continue; 3227 } 3228 3229 final String packageName = info.serviceInfo.packageName; 3230 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3231 if (DEBUG_EPHEMERAL) { 3232 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3233 + " pkg: " + packageName + ", info:" + info); 3234 } 3235 continue; 3236 } 3237 3238 if (DEBUG_EPHEMERAL) { 3239 Slog.v(TAG, "Ephemeral resolver found;" 3240 + " pkg: " + packageName + ", info:" + info); 3241 } 3242 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3243 } 3244 if (DEBUG_EPHEMERAL) { 3245 Slog.v(TAG, "Ephemeral resolver NOT found"); 3246 } 3247 return null; 3248 } 3249 3250 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3251 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3252 intent.addCategory(Intent.CATEGORY_DEFAULT); 3253 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3254 3255 final int resolveFlags = 3256 MATCH_DIRECT_BOOT_AWARE 3257 | MATCH_DIRECT_BOOT_UNAWARE 3258 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3259 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3260 resolveFlags, UserHandle.USER_SYSTEM); 3261 // temporarily look for the old action 3262 if (matches.isEmpty()) { 3263 if (DEBUG_EPHEMERAL) { 3264 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3265 } 3266 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3267 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3268 resolveFlags, UserHandle.USER_SYSTEM); 3269 } 3270 Iterator<ResolveInfo> iter = matches.iterator(); 3271 while (iter.hasNext()) { 3272 final ResolveInfo rInfo = iter.next(); 3273 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3274 if (ps != null) { 3275 final PermissionsState permissionsState = ps.getPermissionsState(); 3276 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3277 continue; 3278 } 3279 } 3280 iter.remove(); 3281 } 3282 if (matches.size() == 0) { 3283 return null; 3284 } else if (matches.size() == 1) { 3285 return (ActivityInfo) matches.get(0).getComponentInfo(); 3286 } else { 3287 throw new RuntimeException( 3288 "There must be at most one ephemeral installer; found " + matches); 3289 } 3290 } 3291 3292 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3293 @NonNull ComponentName resolver) { 3294 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3295 .addCategory(Intent.CATEGORY_DEFAULT) 3296 .setPackage(resolver.getPackageName()); 3297 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3298 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3299 UserHandle.USER_SYSTEM); 3300 // temporarily look for the old action 3301 if (matches.isEmpty()) { 3302 if (DEBUG_EPHEMERAL) { 3303 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3304 } 3305 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3306 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3307 UserHandle.USER_SYSTEM); 3308 } 3309 if (matches.isEmpty()) { 3310 return null; 3311 } 3312 return matches.get(0).getComponentInfo().getComponentName(); 3313 } 3314 3315 private void primeDomainVerificationsLPw(int userId) { 3316 if (DEBUG_DOMAIN_VERIFICATION) { 3317 Slog.d(TAG, "Priming domain verifications in user " + userId); 3318 } 3319 3320 SystemConfig systemConfig = SystemConfig.getInstance(); 3321 ArraySet<String> packages = systemConfig.getLinkedApps(); 3322 3323 for (String packageName : packages) { 3324 PackageParser.Package pkg = mPackages.get(packageName); 3325 if (pkg != null) { 3326 if (!pkg.isSystemApp()) { 3327 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3328 continue; 3329 } 3330 3331 ArraySet<String> domains = null; 3332 for (PackageParser.Activity a : pkg.activities) { 3333 for (ActivityIntentInfo filter : a.intents) { 3334 if (hasValidDomains(filter)) { 3335 if (domains == null) { 3336 domains = new ArraySet<String>(); 3337 } 3338 domains.addAll(filter.getHostsList()); 3339 } 3340 } 3341 } 3342 3343 if (domains != null && domains.size() > 0) { 3344 if (DEBUG_DOMAIN_VERIFICATION) { 3345 Slog.v(TAG, " + " + packageName); 3346 } 3347 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3348 // state w.r.t. the formal app-linkage "no verification attempted" state; 3349 // and then 'always' in the per-user state actually used for intent resolution. 3350 final IntentFilterVerificationInfo ivi; 3351 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3352 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3353 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3354 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3355 } else { 3356 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3357 + "' does not handle web links"); 3358 } 3359 } else { 3360 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3361 } 3362 } 3363 3364 scheduleWritePackageRestrictionsLocked(userId); 3365 scheduleWriteSettingsLocked(); 3366 } 3367 3368 private void applyFactoryDefaultBrowserLPw(int userId) { 3369 // The default browser app's package name is stored in a string resource, 3370 // with a product-specific overlay used for vendor customization. 3371 String browserPkg = mContext.getResources().getString( 3372 com.android.internal.R.string.default_browser); 3373 if (!TextUtils.isEmpty(browserPkg)) { 3374 // non-empty string => required to be a known package 3375 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3376 if (ps == null) { 3377 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3378 browserPkg = null; 3379 } else { 3380 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3381 } 3382 } 3383 3384 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3385 // default. If there's more than one, just leave everything alone. 3386 if (browserPkg == null) { 3387 calculateDefaultBrowserLPw(userId); 3388 } 3389 } 3390 3391 private void calculateDefaultBrowserLPw(int userId) { 3392 List<String> allBrowsers = resolveAllBrowserApps(userId); 3393 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3394 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3395 } 3396 3397 private List<String> resolveAllBrowserApps(int userId) { 3398 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3399 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3400 PackageManager.MATCH_ALL, userId); 3401 3402 final int count = list.size(); 3403 List<String> result = new ArrayList<String>(count); 3404 for (int i=0; i<count; i++) { 3405 ResolveInfo info = list.get(i); 3406 if (info.activityInfo == null 3407 || !info.handleAllWebDataURI 3408 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3409 || result.contains(info.activityInfo.packageName)) { 3410 continue; 3411 } 3412 result.add(info.activityInfo.packageName); 3413 } 3414 3415 return result; 3416 } 3417 3418 private boolean packageIsBrowser(String packageName, int userId) { 3419 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3420 PackageManager.MATCH_ALL, userId); 3421 final int N = list.size(); 3422 for (int i = 0; i < N; i++) { 3423 ResolveInfo info = list.get(i); 3424 if (packageName.equals(info.activityInfo.packageName)) { 3425 return true; 3426 } 3427 } 3428 return false; 3429 } 3430 3431 private void checkDefaultBrowser() { 3432 final int myUserId = UserHandle.myUserId(); 3433 final String packageName = getDefaultBrowserPackageName(myUserId); 3434 if (packageName != null) { 3435 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3436 if (info == null) { 3437 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3438 synchronized (mPackages) { 3439 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3440 } 3441 } 3442 } 3443 } 3444 3445 @Override 3446 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3447 throws RemoteException { 3448 try { 3449 return super.onTransact(code, data, reply, flags); 3450 } catch (RuntimeException e) { 3451 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3452 Slog.wtf(TAG, "Package Manager Crash", e); 3453 } 3454 throw e; 3455 } 3456 } 3457 3458 static int[] appendInts(int[] cur, int[] add) { 3459 if (add == null) return cur; 3460 if (cur == null) return add; 3461 final int N = add.length; 3462 for (int i=0; i<N; i++) { 3463 cur = appendInt(cur, add[i]); 3464 } 3465 return cur; 3466 } 3467 3468 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3469 if (!sUserManager.exists(userId)) return null; 3470 if (ps == null) { 3471 return null; 3472 } 3473 final PackageParser.Package p = ps.pkg; 3474 if (p == null) { 3475 return null; 3476 } 3477 // Filter out ephemeral app metadata: 3478 // * The system/shell/root can see metadata for any app 3479 // * An installed app can see metadata for 1) other installed apps 3480 // and 2) ephemeral apps that have explicitly interacted with it 3481 // * Ephemeral apps can only see their own data and exposed installed apps 3482 // * Holding a signature permission allows seeing instant apps 3483 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3484 if (callingAppId != Process.SYSTEM_UID 3485 && callingAppId != Process.SHELL_UID 3486 && callingAppId != Process.ROOT_UID 3487 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3488 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3489 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3490 if (instantAppPackageName != null) { 3491 // ephemeral apps can only get information on themselves or 3492 // installed apps that are exposed. 3493 if (!instantAppPackageName.equals(p.packageName) 3494 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3495 return null; 3496 } 3497 } else { 3498 if (ps.getInstantApp(userId)) { 3499 // only get access to the ephemeral app if we've been granted access 3500 if (!mInstantAppRegistry.isInstantAccessGranted( 3501 userId, callingAppId, ps.appId)) { 3502 return null; 3503 } 3504 } 3505 } 3506 } 3507 3508 final PermissionsState permissionsState = ps.getPermissionsState(); 3509 3510 // Compute GIDs only if requested 3511 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3512 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3513 // Compute granted permissions only if package has requested permissions 3514 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3515 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3516 final PackageUserState state = ps.readUserState(userId); 3517 3518 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3519 && ps.isSystem()) { 3520 flags |= MATCH_ANY_USER; 3521 } 3522 3523 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3524 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3525 3526 if (packageInfo == null) { 3527 return null; 3528 } 3529 3530 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3531 3532 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3533 resolveExternalPackageNameLPr(p); 3534 3535 return packageInfo; 3536 } 3537 3538 @Override 3539 public void checkPackageStartable(String packageName, int userId) { 3540 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3541 3542 synchronized (mPackages) { 3543 final PackageSetting ps = mSettings.mPackages.get(packageName); 3544 if (ps == null) { 3545 throw new SecurityException("Package " + packageName + " was not found!"); 3546 } 3547 3548 if (!ps.getInstalled(userId)) { 3549 throw new SecurityException( 3550 "Package " + packageName + " was not installed for user " + userId + "!"); 3551 } 3552 3553 if (mSafeMode && !ps.isSystem()) { 3554 throw new SecurityException("Package " + packageName + " not a system app!"); 3555 } 3556 3557 if (mFrozenPackages.contains(packageName)) { 3558 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3559 } 3560 3561 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3562 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3563 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3564 } 3565 } 3566 } 3567 3568 @Override 3569 public boolean isPackageAvailable(String packageName, int userId) { 3570 if (!sUserManager.exists(userId)) return false; 3571 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3572 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3573 synchronized (mPackages) { 3574 PackageParser.Package p = mPackages.get(packageName); 3575 if (p != null) { 3576 final PackageSetting ps = (PackageSetting) p.mExtras; 3577 if (ps != null) { 3578 final PackageUserState state = ps.readUserState(userId); 3579 if (state != null) { 3580 return PackageParser.isAvailable(state); 3581 } 3582 } 3583 } 3584 } 3585 return false; 3586 } 3587 3588 @Override 3589 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3590 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3591 flags, userId); 3592 } 3593 3594 @Override 3595 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3596 int flags, int userId) { 3597 return getPackageInfoInternal(versionedPackage.getPackageName(), 3598 // TODO: We will change version code to long, so in the new API it is long 3599 (int) versionedPackage.getVersionCode(), flags, userId); 3600 } 3601 3602 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3603 int flags, int userId) { 3604 if (!sUserManager.exists(userId)) return null; 3605 flags = updateFlagsForPackage(flags, userId, packageName); 3606 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3607 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3608 3609 // reader 3610 synchronized (mPackages) { 3611 // Normalize package name to handle renamed packages and static libs 3612 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3613 3614 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3615 if (matchFactoryOnly) { 3616 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3617 if (ps != null) { 3618 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3619 return null; 3620 } 3621 return generatePackageInfo(ps, flags, userId); 3622 } 3623 } 3624 3625 PackageParser.Package p = mPackages.get(packageName); 3626 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3627 return null; 3628 } 3629 if (DEBUG_PACKAGE_INFO) 3630 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3631 if (p != null) { 3632 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3633 Binder.getCallingUid(), userId)) { 3634 return null; 3635 } 3636 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3637 } 3638 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3639 final PackageSetting ps = mSettings.mPackages.get(packageName); 3640 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3641 return null; 3642 } 3643 return generatePackageInfo(ps, flags, userId); 3644 } 3645 } 3646 return null; 3647 } 3648 3649 3650 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3651 // System/shell/root get to see all static libs 3652 final int appId = UserHandle.getAppId(uid); 3653 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3654 || appId == Process.ROOT_UID) { 3655 return false; 3656 } 3657 3658 // No package means no static lib as it is always on internal storage 3659 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3660 return false; 3661 } 3662 3663 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3664 ps.pkg.staticSharedLibVersion); 3665 if (libEntry == null) { 3666 return false; 3667 } 3668 3669 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3670 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3671 if (uidPackageNames == null) { 3672 return true; 3673 } 3674 3675 for (String uidPackageName : uidPackageNames) { 3676 if (ps.name.equals(uidPackageName)) { 3677 return false; 3678 } 3679 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3680 if (uidPs != null) { 3681 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3682 libEntry.info.getName()); 3683 if (index < 0) { 3684 continue; 3685 } 3686 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3687 return false; 3688 } 3689 } 3690 } 3691 return true; 3692 } 3693 3694 @Override 3695 public String[] currentToCanonicalPackageNames(String[] names) { 3696 String[] out = new String[names.length]; 3697 // reader 3698 synchronized (mPackages) { 3699 for (int i=names.length-1; i>=0; i--) { 3700 PackageSetting ps = mSettings.mPackages.get(names[i]); 3701 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3702 } 3703 } 3704 return out; 3705 } 3706 3707 @Override 3708 public String[] canonicalToCurrentPackageNames(String[] names) { 3709 String[] out = new String[names.length]; 3710 // reader 3711 synchronized (mPackages) { 3712 for (int i=names.length-1; i>=0; i--) { 3713 String cur = mSettings.getRenamedPackageLPr(names[i]); 3714 out[i] = cur != null ? cur : names[i]; 3715 } 3716 } 3717 return out; 3718 } 3719 3720 @Override 3721 public int getPackageUid(String packageName, int flags, int userId) { 3722 if (!sUserManager.exists(userId)) return -1; 3723 flags = updateFlagsForPackage(flags, userId, packageName); 3724 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3725 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3726 3727 // reader 3728 synchronized (mPackages) { 3729 final PackageParser.Package p = mPackages.get(packageName); 3730 if (p != null && p.isMatch(flags)) { 3731 return UserHandle.getUid(userId, p.applicationInfo.uid); 3732 } 3733 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3734 final PackageSetting ps = mSettings.mPackages.get(packageName); 3735 if (ps != null && ps.isMatch(flags)) { 3736 return UserHandle.getUid(userId, ps.appId); 3737 } 3738 } 3739 } 3740 3741 return -1; 3742 } 3743 3744 @Override 3745 public int[] getPackageGids(String packageName, int flags, int userId) { 3746 if (!sUserManager.exists(userId)) return null; 3747 flags = updateFlagsForPackage(flags, userId, packageName); 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3749 false /* requireFullPermission */, false /* checkShell */, 3750 "getPackageGids"); 3751 3752 // reader 3753 synchronized (mPackages) { 3754 final PackageParser.Package p = mPackages.get(packageName); 3755 if (p != null && p.isMatch(flags)) { 3756 PackageSetting ps = (PackageSetting) p.mExtras; 3757 // TODO: Shouldn't this be checking for package installed state for userId and 3758 // return null? 3759 return ps.getPermissionsState().computeGids(userId); 3760 } 3761 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3762 final PackageSetting ps = mSettings.mPackages.get(packageName); 3763 if (ps != null && ps.isMatch(flags)) { 3764 return ps.getPermissionsState().computeGids(userId); 3765 } 3766 } 3767 } 3768 3769 return null; 3770 } 3771 3772 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3773 if (bp.perm != null) { 3774 return PackageParser.generatePermissionInfo(bp.perm, flags); 3775 } 3776 PermissionInfo pi = new PermissionInfo(); 3777 pi.name = bp.name; 3778 pi.packageName = bp.sourcePackage; 3779 pi.nonLocalizedLabel = bp.name; 3780 pi.protectionLevel = bp.protectionLevel; 3781 return pi; 3782 } 3783 3784 @Override 3785 public PermissionInfo getPermissionInfo(String name, int flags) { 3786 // reader 3787 synchronized (mPackages) { 3788 final BasePermission p = mSettings.mPermissions.get(name); 3789 if (p != null) { 3790 return generatePermissionInfo(p, flags); 3791 } 3792 return null; 3793 } 3794 } 3795 3796 @Override 3797 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3798 int flags) { 3799 // reader 3800 synchronized (mPackages) { 3801 if (group != null && !mPermissionGroups.containsKey(group)) { 3802 // This is thrown as NameNotFoundException 3803 return null; 3804 } 3805 3806 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3807 for (BasePermission p : mSettings.mPermissions.values()) { 3808 if (group == null) { 3809 if (p.perm == null || p.perm.info.group == null) { 3810 out.add(generatePermissionInfo(p, flags)); 3811 } 3812 } else { 3813 if (p.perm != null && group.equals(p.perm.info.group)) { 3814 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3815 } 3816 } 3817 } 3818 return new ParceledListSlice<>(out); 3819 } 3820 } 3821 3822 @Override 3823 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3824 // reader 3825 synchronized (mPackages) { 3826 return PackageParser.generatePermissionGroupInfo( 3827 mPermissionGroups.get(name), flags); 3828 } 3829 } 3830 3831 @Override 3832 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3833 // reader 3834 synchronized (mPackages) { 3835 final int N = mPermissionGroups.size(); 3836 ArrayList<PermissionGroupInfo> out 3837 = new ArrayList<PermissionGroupInfo>(N); 3838 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3839 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3840 } 3841 return new ParceledListSlice<>(out); 3842 } 3843 } 3844 3845 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3846 int uid, int userId) { 3847 if (!sUserManager.exists(userId)) return null; 3848 PackageSetting ps = mSettings.mPackages.get(packageName); 3849 if (ps != null) { 3850 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3851 return null; 3852 } 3853 if (ps.pkg == null) { 3854 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3855 if (pInfo != null) { 3856 return pInfo.applicationInfo; 3857 } 3858 return null; 3859 } 3860 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3861 ps.readUserState(userId), userId); 3862 if (ai != null) { 3863 rebaseEnabledOverlays(ai, userId); 3864 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3865 } 3866 return ai; 3867 } 3868 return null; 3869 } 3870 3871 @Override 3872 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3873 if (!sUserManager.exists(userId)) return null; 3874 flags = updateFlagsForApplication(flags, userId, packageName); 3875 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3876 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3877 3878 // writer 3879 synchronized (mPackages) { 3880 // Normalize package name to handle renamed packages and static libs 3881 packageName = resolveInternalPackageNameLPr(packageName, 3882 PackageManager.VERSION_CODE_HIGHEST); 3883 3884 PackageParser.Package p = mPackages.get(packageName); 3885 if (DEBUG_PACKAGE_INFO) Log.v( 3886 TAG, "getApplicationInfo " + packageName 3887 + ": " + p); 3888 if (p != null) { 3889 PackageSetting ps = mSettings.mPackages.get(packageName); 3890 if (ps == null) return null; 3891 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3892 return null; 3893 } 3894 // Note: isEnabledLP() does not apply here - always return info 3895 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3896 p, flags, ps.readUserState(userId), userId); 3897 if (ai != null) { 3898 rebaseEnabledOverlays(ai, userId); 3899 ai.packageName = resolveExternalPackageNameLPr(p); 3900 } 3901 return ai; 3902 } 3903 if ("android".equals(packageName)||"system".equals(packageName)) { 3904 return mAndroidApplication; 3905 } 3906 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3907 // Already generates the external package name 3908 return generateApplicationInfoFromSettingsLPw(packageName, 3909 Binder.getCallingUid(), flags, userId); 3910 } 3911 } 3912 return null; 3913 } 3914 3915 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3916 List<String> paths = new ArrayList<>(); 3917 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3918 mEnabledOverlayPaths.get(userId); 3919 if (userSpecificOverlays != null) { 3920 if (!"android".equals(ai.packageName)) { 3921 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3922 if (frameworkOverlays != null) { 3923 paths.addAll(frameworkOverlays); 3924 } 3925 } 3926 3927 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3928 if (appOverlays != null) { 3929 paths.addAll(appOverlays); 3930 } 3931 } 3932 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3933 } 3934 3935 private String normalizePackageNameLPr(String packageName) { 3936 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3937 return normalizedPackageName != null ? normalizedPackageName : packageName; 3938 } 3939 3940 @Override 3941 public void deletePreloadsFileCache() { 3942 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3943 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3944 } 3945 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3946 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3947 FileUtils.deleteContents(dir); 3948 } 3949 3950 @Override 3951 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3952 final IPackageDataObserver observer) { 3953 mContext.enforceCallingOrSelfPermission( 3954 android.Manifest.permission.CLEAR_APP_CACHE, null); 3955 mHandler.post(() -> { 3956 boolean success = false; 3957 try { 3958 freeStorage(volumeUuid, freeStorageSize, 0); 3959 success = true; 3960 } catch (IOException e) { 3961 Slog.w(TAG, e); 3962 } 3963 if (observer != null) { 3964 try { 3965 observer.onRemoveCompleted(null, success); 3966 } catch (RemoteException e) { 3967 Slog.w(TAG, e); 3968 } 3969 } 3970 }); 3971 } 3972 3973 @Override 3974 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3975 final IntentSender pi) { 3976 mContext.enforceCallingOrSelfPermission( 3977 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3978 mHandler.post(() -> { 3979 boolean success = false; 3980 try { 3981 freeStorage(volumeUuid, freeStorageSize, 0); 3982 success = true; 3983 } catch (IOException e) { 3984 Slog.w(TAG, e); 3985 } 3986 if (pi != null) { 3987 try { 3988 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3989 } catch (SendIntentException e) { 3990 Slog.w(TAG, e); 3991 } 3992 } 3993 }); 3994 } 3995 3996 /** 3997 * Blocking call to clear various types of cached data across the system 3998 * until the requested bytes are available. 3999 */ 4000 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4001 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4002 final File file = storage.findPathForUuid(volumeUuid); 4003 if (file.getUsableSpace() >= bytes) return; 4004 4005 if (ENABLE_FREE_CACHE_V2) { 4006 final boolean aggressive = (storageFlags 4007 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4008 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4009 volumeUuid); 4010 4011 // 1. Pre-flight to determine if we have any chance to succeed 4012 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4013 if (internalVolume && (aggressive || SystemProperties 4014 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4015 deletePreloadsFileCache(); 4016 if (file.getUsableSpace() >= bytes) return; 4017 } 4018 4019 // 3. Consider parsed APK data (aggressive only) 4020 if (internalVolume && aggressive) { 4021 FileUtils.deleteContents(mCacheDir); 4022 if (file.getUsableSpace() >= bytes) return; 4023 } 4024 4025 // 4. Consider cached app data (above quotas) 4026 try { 4027 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 4028 } catch (InstallerException ignored) { 4029 } 4030 if (file.getUsableSpace() >= bytes) return; 4031 4032 // 5. Consider shared libraries with refcount=0 and age>2h 4033 // 6. Consider dexopt output (aggressive only) 4034 // 7. Consider ephemeral apps not used in last week 4035 4036 // 8. Consider cached app data (below quotas) 4037 try { 4038 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 4039 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4040 } catch (InstallerException ignored) { 4041 } 4042 if (file.getUsableSpace() >= bytes) return; 4043 4044 // 9. Consider DropBox entries 4045 // 10. Consider ephemeral cookies 4046 4047 } else { 4048 try { 4049 mInstaller.freeCache(volumeUuid, bytes, 0); 4050 } catch (InstallerException ignored) { 4051 } 4052 if (file.getUsableSpace() >= bytes) return; 4053 } 4054 4055 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4056 } 4057 4058 /** 4059 * Update given flags based on encryption status of current user. 4060 */ 4061 private int updateFlags(int flags, int userId) { 4062 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4063 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4064 // Caller expressed an explicit opinion about what encryption 4065 // aware/unaware components they want to see, so fall through and 4066 // give them what they want 4067 } else { 4068 // Caller expressed no opinion, so match based on user state 4069 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4070 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4071 } else { 4072 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4073 } 4074 } 4075 return flags; 4076 } 4077 4078 private UserManagerInternal getUserManagerInternal() { 4079 if (mUserManagerInternal == null) { 4080 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4081 } 4082 return mUserManagerInternal; 4083 } 4084 4085 private DeviceIdleController.LocalService getDeviceIdleController() { 4086 if (mDeviceIdleController == null) { 4087 mDeviceIdleController = 4088 LocalServices.getService(DeviceIdleController.LocalService.class); 4089 } 4090 return mDeviceIdleController; 4091 } 4092 4093 /** 4094 * Update given flags when being used to request {@link PackageInfo}. 4095 */ 4096 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4097 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4098 boolean triaged = true; 4099 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4100 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4101 // Caller is asking for component details, so they'd better be 4102 // asking for specific encryption matching behavior, or be triaged 4103 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4104 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4105 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4106 triaged = false; 4107 } 4108 } 4109 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4110 | PackageManager.MATCH_SYSTEM_ONLY 4111 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4112 triaged = false; 4113 } 4114 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4115 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4116 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4117 + Debug.getCallers(5)); 4118 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4119 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4120 // If the caller wants all packages and has a restricted profile associated with it, 4121 // then match all users. This is to make sure that launchers that need to access work 4122 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4123 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4124 flags |= PackageManager.MATCH_ANY_USER; 4125 } 4126 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4127 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4128 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4129 } 4130 return updateFlags(flags, userId); 4131 } 4132 4133 /** 4134 * Update given flags when being used to request {@link ApplicationInfo}. 4135 */ 4136 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4137 return updateFlagsForPackage(flags, userId, cookie); 4138 } 4139 4140 /** 4141 * Update given flags when being used to request {@link ComponentInfo}. 4142 */ 4143 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4144 if (cookie instanceof Intent) { 4145 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4146 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4147 } 4148 } 4149 4150 boolean triaged = true; 4151 // Caller is asking for component details, so they'd better be 4152 // asking for specific encryption matching behavior, or be triaged 4153 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4154 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4155 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4156 triaged = false; 4157 } 4158 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4159 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4160 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4161 } 4162 4163 return updateFlags(flags, userId); 4164 } 4165 4166 /** 4167 * Update given intent when being used to request {@link ResolveInfo}. 4168 */ 4169 private Intent updateIntentForResolve(Intent intent) { 4170 if (intent.getSelector() != null) { 4171 intent = intent.getSelector(); 4172 } 4173 if (DEBUG_PREFERRED) { 4174 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4175 } 4176 return intent; 4177 } 4178 4179 /** 4180 * Update given flags when being used to request {@link ResolveInfo}. 4181 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4182 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4183 * flag set. However, this flag is only honoured in three circumstances: 4184 * <ul> 4185 * <li>when called from a system process</li> 4186 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4187 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4188 * action and a {@code android.intent.category.BROWSABLE} category</li> 4189 * </ul> 4190 */ 4191 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4192 return updateFlagsForResolve(flags, userId, intent, callingUid, 4193 false /*includeInstantApps*/, false /*onlyExposedExplicitly*/); 4194 } 4195 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4196 boolean includeInstantApps) { 4197 return updateFlagsForResolve(flags, userId, intent, callingUid, 4198 includeInstantApps, false /*onlyExposedExplicitly*/); 4199 } 4200 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4201 boolean includeInstantApps, boolean onlyExposedExplicitly) { 4202 // Safe mode means we shouldn't match any third-party components 4203 if (mSafeMode) { 4204 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4205 } 4206 if (getInstantAppPackageName(callingUid) != null) { 4207 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4208 if (onlyExposedExplicitly) { 4209 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4210 } 4211 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4212 flags |= PackageManager.MATCH_INSTANT; 4213 } else { 4214 // Otherwise, prevent leaking ephemeral components 4215 final boolean isSpecialProcess = 4216 callingUid == Process.SYSTEM_UID 4217 || callingUid == Process.SHELL_UID 4218 || callingUid == 0; 4219 final boolean allowMatchInstant = 4220 (includeInstantApps 4221 && Intent.ACTION_VIEW.equals(intent.getAction()) 4222 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4223 && hasWebURI(intent)) 4224 || isSpecialProcess 4225 || mContext.checkCallingOrSelfPermission( 4226 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4227 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4228 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4229 if (!allowMatchInstant) { 4230 flags &= ~PackageManager.MATCH_INSTANT; 4231 } 4232 } 4233 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4234 } 4235 4236 private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state, 4237 int userId) { 4238 ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId); 4239 if (ret != null) { 4240 rebaseEnabledOverlays(ret.applicationInfo, userId); 4241 } 4242 return ret; 4243 } 4244 4245 private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags, 4246 PackageUserState state, int userId) { 4247 ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId); 4248 if (ai != null) { 4249 rebaseEnabledOverlays(ai.applicationInfo, userId); 4250 } 4251 return ai; 4252 } 4253 4254 @Override 4255 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4256 if (!sUserManager.exists(userId)) return null; 4257 flags = updateFlagsForComponent(flags, userId, component); 4258 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4259 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4260 synchronized (mPackages) { 4261 PackageParser.Activity a = mActivities.mActivities.get(component); 4262 4263 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4264 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4265 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4266 if (ps == null) return null; 4267 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4268 } 4269 if (mResolveComponentName.equals(component)) { 4270 return generateActivityInfo(mResolveActivity, flags, new PackageUserState(), 4271 userId); 4272 } 4273 } 4274 return null; 4275 } 4276 4277 @Override 4278 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4279 String resolvedType) { 4280 synchronized (mPackages) { 4281 if (component.equals(mResolveComponentName)) { 4282 // The resolver supports EVERYTHING! 4283 return true; 4284 } 4285 PackageParser.Activity a = mActivities.mActivities.get(component); 4286 if (a == null) { 4287 return false; 4288 } 4289 for (int i=0; i<a.intents.size(); i++) { 4290 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4291 intent.getData(), intent.getCategories(), TAG) >= 0) { 4292 return true; 4293 } 4294 } 4295 return false; 4296 } 4297 } 4298 4299 @Override 4300 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4301 if (!sUserManager.exists(userId)) return null; 4302 flags = updateFlagsForComponent(flags, userId, component); 4303 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4304 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4305 synchronized (mPackages) { 4306 PackageParser.Activity a = mReceivers.mActivities.get(component); 4307 if (DEBUG_PACKAGE_INFO) Log.v( 4308 TAG, "getReceiverInfo " + component + ": " + a); 4309 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4310 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4311 if (ps == null) return null; 4312 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4313 } 4314 } 4315 return null; 4316 } 4317 4318 @Override 4319 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4320 if (!sUserManager.exists(userId)) return null; 4321 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4322 4323 flags = updateFlagsForPackage(flags, userId, null); 4324 4325 final boolean canSeeStaticLibraries = 4326 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4327 == PERMISSION_GRANTED 4328 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4329 == PERMISSION_GRANTED 4330 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4331 == PERMISSION_GRANTED 4332 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4333 == PERMISSION_GRANTED; 4334 4335 synchronized (mPackages) { 4336 List<SharedLibraryInfo> result = null; 4337 4338 final int libCount = mSharedLibraries.size(); 4339 for (int i = 0; i < libCount; i++) { 4340 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4341 if (versionedLib == null) { 4342 continue; 4343 } 4344 4345 final int versionCount = versionedLib.size(); 4346 for (int j = 0; j < versionCount; j++) { 4347 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4348 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4349 break; 4350 } 4351 final long identity = Binder.clearCallingIdentity(); 4352 try { 4353 // TODO: We will change version code to long, so in the new API it is long 4354 PackageInfo packageInfo = getPackageInfoVersioned( 4355 libInfo.getDeclaringPackage(), flags, userId); 4356 if (packageInfo == null) { 4357 continue; 4358 } 4359 } finally { 4360 Binder.restoreCallingIdentity(identity); 4361 } 4362 4363 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4364 libInfo.getVersion(), libInfo.getType(), 4365 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4366 flags, userId)); 4367 4368 if (result == null) { 4369 result = new ArrayList<>(); 4370 } 4371 result.add(resLibInfo); 4372 } 4373 } 4374 4375 return result != null ? new ParceledListSlice<>(result) : null; 4376 } 4377 } 4378 4379 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4380 SharedLibraryInfo libInfo, int flags, int userId) { 4381 List<VersionedPackage> versionedPackages = null; 4382 final int packageCount = mSettings.mPackages.size(); 4383 for (int i = 0; i < packageCount; i++) { 4384 PackageSetting ps = mSettings.mPackages.valueAt(i); 4385 4386 if (ps == null) { 4387 continue; 4388 } 4389 4390 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4391 continue; 4392 } 4393 4394 final String libName = libInfo.getName(); 4395 if (libInfo.isStatic()) { 4396 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4397 if (libIdx < 0) { 4398 continue; 4399 } 4400 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4401 continue; 4402 } 4403 if (versionedPackages == null) { 4404 versionedPackages = new ArrayList<>(); 4405 } 4406 // If the dependent is a static shared lib, use the public package name 4407 String dependentPackageName = ps.name; 4408 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4409 dependentPackageName = ps.pkg.manifestPackageName; 4410 } 4411 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4412 } else if (ps.pkg != null) { 4413 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4414 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4415 if (versionedPackages == null) { 4416 versionedPackages = new ArrayList<>(); 4417 } 4418 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4419 } 4420 } 4421 } 4422 4423 return versionedPackages; 4424 } 4425 4426 @Override 4427 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4428 if (!sUserManager.exists(userId)) return null; 4429 flags = updateFlagsForComponent(flags, userId, component); 4430 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4431 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4432 synchronized (mPackages) { 4433 PackageParser.Service s = mServices.mServices.get(component); 4434 if (DEBUG_PACKAGE_INFO) Log.v( 4435 TAG, "getServiceInfo " + component + ": " + s); 4436 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4437 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4438 if (ps == null) return null; 4439 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4440 ps.readUserState(userId), userId); 4441 if (si != null) { 4442 rebaseEnabledOverlays(si.applicationInfo, userId); 4443 } 4444 return si; 4445 } 4446 } 4447 return null; 4448 } 4449 4450 @Override 4451 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4452 if (!sUserManager.exists(userId)) return null; 4453 flags = updateFlagsForComponent(flags, userId, component); 4454 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4455 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4456 synchronized (mPackages) { 4457 PackageParser.Provider p = mProviders.mProviders.get(component); 4458 if (DEBUG_PACKAGE_INFO) Log.v( 4459 TAG, "getProviderInfo " + component + ": " + p); 4460 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4461 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4462 if (ps == null) return null; 4463 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4464 ps.readUserState(userId), userId); 4465 if (pi != null) { 4466 rebaseEnabledOverlays(pi.applicationInfo, userId); 4467 } 4468 return pi; 4469 } 4470 } 4471 return null; 4472 } 4473 4474 @Override 4475 public String[] getSystemSharedLibraryNames() { 4476 synchronized (mPackages) { 4477 Set<String> libs = null; 4478 final int libCount = mSharedLibraries.size(); 4479 for (int i = 0; i < libCount; i++) { 4480 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4481 if (versionedLib == null) { 4482 continue; 4483 } 4484 final int versionCount = versionedLib.size(); 4485 for (int j = 0; j < versionCount; j++) { 4486 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4487 if (!libEntry.info.isStatic()) { 4488 if (libs == null) { 4489 libs = new ArraySet<>(); 4490 } 4491 libs.add(libEntry.info.getName()); 4492 break; 4493 } 4494 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4495 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4496 UserHandle.getUserId(Binder.getCallingUid()))) { 4497 if (libs == null) { 4498 libs = new ArraySet<>(); 4499 } 4500 libs.add(libEntry.info.getName()); 4501 break; 4502 } 4503 } 4504 } 4505 4506 if (libs != null) { 4507 String[] libsArray = new String[libs.size()]; 4508 libs.toArray(libsArray); 4509 return libsArray; 4510 } 4511 4512 return null; 4513 } 4514 } 4515 4516 @Override 4517 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4518 synchronized (mPackages) { 4519 return mServicesSystemSharedLibraryPackageName; 4520 } 4521 } 4522 4523 @Override 4524 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4525 synchronized (mPackages) { 4526 return mSharedSystemSharedLibraryPackageName; 4527 } 4528 } 4529 4530 private void updateSequenceNumberLP(String packageName, int[] userList) { 4531 for (int i = userList.length - 1; i >= 0; --i) { 4532 final int userId = userList[i]; 4533 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4534 if (changedPackages == null) { 4535 changedPackages = new SparseArray<>(); 4536 mChangedPackages.put(userId, changedPackages); 4537 } 4538 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4539 if (sequenceNumbers == null) { 4540 sequenceNumbers = new HashMap<>(); 4541 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4542 } 4543 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4544 if (sequenceNumber != null) { 4545 changedPackages.remove(sequenceNumber); 4546 } 4547 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4548 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4549 } 4550 mChangedPackagesSequenceNumber++; 4551 } 4552 4553 @Override 4554 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4555 synchronized (mPackages) { 4556 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4557 return null; 4558 } 4559 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4560 if (changedPackages == null) { 4561 return null; 4562 } 4563 final List<String> packageNames = 4564 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4565 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4566 final String packageName = changedPackages.get(i); 4567 if (packageName != null) { 4568 packageNames.add(packageName); 4569 } 4570 } 4571 return packageNames.isEmpty() 4572 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4573 } 4574 } 4575 4576 @Override 4577 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4578 ArrayList<FeatureInfo> res; 4579 synchronized (mAvailableFeatures) { 4580 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4581 res.addAll(mAvailableFeatures.values()); 4582 } 4583 final FeatureInfo fi = new FeatureInfo(); 4584 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4585 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4586 res.add(fi); 4587 4588 return new ParceledListSlice<>(res); 4589 } 4590 4591 @Override 4592 public boolean hasSystemFeature(String name, int version) { 4593 synchronized (mAvailableFeatures) { 4594 final FeatureInfo feat = mAvailableFeatures.get(name); 4595 if (feat == null) { 4596 return false; 4597 } else { 4598 return feat.version >= version; 4599 } 4600 } 4601 } 4602 4603 @Override 4604 public int checkPermission(String permName, String pkgName, int userId) { 4605 if (!sUserManager.exists(userId)) { 4606 return PackageManager.PERMISSION_DENIED; 4607 } 4608 4609 synchronized (mPackages) { 4610 final PackageParser.Package p = mPackages.get(pkgName); 4611 if (p != null && p.mExtras != null) { 4612 final PackageSetting ps = (PackageSetting) p.mExtras; 4613 final PermissionsState permissionsState = ps.getPermissionsState(); 4614 if (permissionsState.hasPermission(permName, userId)) { 4615 return PackageManager.PERMISSION_GRANTED; 4616 } 4617 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4618 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4619 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4620 return PackageManager.PERMISSION_GRANTED; 4621 } 4622 } 4623 } 4624 4625 return PackageManager.PERMISSION_DENIED; 4626 } 4627 4628 @Override 4629 public int checkUidPermission(String permName, int uid) { 4630 final int userId = UserHandle.getUserId(uid); 4631 4632 if (!sUserManager.exists(userId)) { 4633 return PackageManager.PERMISSION_DENIED; 4634 } 4635 4636 synchronized (mPackages) { 4637 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4638 if (obj != null) { 4639 final SettingBase ps = (SettingBase) obj; 4640 final PermissionsState permissionsState = ps.getPermissionsState(); 4641 if (permissionsState.hasPermission(permName, userId)) { 4642 return PackageManager.PERMISSION_GRANTED; 4643 } 4644 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4645 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4646 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4647 return PackageManager.PERMISSION_GRANTED; 4648 } 4649 } else { 4650 ArraySet<String> perms = mSystemPermissions.get(uid); 4651 if (perms != null) { 4652 if (perms.contains(permName)) { 4653 return PackageManager.PERMISSION_GRANTED; 4654 } 4655 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4656 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4657 return PackageManager.PERMISSION_GRANTED; 4658 } 4659 } 4660 } 4661 } 4662 4663 return PackageManager.PERMISSION_DENIED; 4664 } 4665 4666 @Override 4667 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4668 if (UserHandle.getCallingUserId() != userId) { 4669 mContext.enforceCallingPermission( 4670 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4671 "isPermissionRevokedByPolicy for user " + userId); 4672 } 4673 4674 if (checkPermission(permission, packageName, userId) 4675 == PackageManager.PERMISSION_GRANTED) { 4676 return false; 4677 } 4678 4679 final long identity = Binder.clearCallingIdentity(); 4680 try { 4681 final int flags = getPermissionFlags(permission, packageName, userId); 4682 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4683 } finally { 4684 Binder.restoreCallingIdentity(identity); 4685 } 4686 } 4687 4688 @Override 4689 public String getPermissionControllerPackageName() { 4690 synchronized (mPackages) { 4691 return mRequiredInstallerPackage; 4692 } 4693 } 4694 4695 /** 4696 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4697 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4698 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4699 * @param message the message to log on security exception 4700 */ 4701 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4702 boolean checkShell, String message) { 4703 if (userId < 0) { 4704 throw new IllegalArgumentException("Invalid userId " + userId); 4705 } 4706 if (checkShell) { 4707 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4708 } 4709 if (userId == UserHandle.getUserId(callingUid)) return; 4710 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4711 if (requireFullPermission) { 4712 mContext.enforceCallingOrSelfPermission( 4713 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4714 } else { 4715 try { 4716 mContext.enforceCallingOrSelfPermission( 4717 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4718 } catch (SecurityException se) { 4719 mContext.enforceCallingOrSelfPermission( 4720 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4721 } 4722 } 4723 } 4724 } 4725 4726 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4727 if (callingUid == Process.SHELL_UID) { 4728 if (userHandle >= 0 4729 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4730 throw new SecurityException("Shell does not have permission to access user " 4731 + userHandle); 4732 } else if (userHandle < 0) { 4733 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4734 + Debug.getCallers(3)); 4735 } 4736 } 4737 } 4738 4739 private BasePermission findPermissionTreeLP(String permName) { 4740 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4741 if (permName.startsWith(bp.name) && 4742 permName.length() > bp.name.length() && 4743 permName.charAt(bp.name.length()) == '.') { 4744 return bp; 4745 } 4746 } 4747 return null; 4748 } 4749 4750 private BasePermission checkPermissionTreeLP(String permName) { 4751 if (permName != null) { 4752 BasePermission bp = findPermissionTreeLP(permName); 4753 if (bp != null) { 4754 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4755 return bp; 4756 } 4757 throw new SecurityException("Calling uid " 4758 + Binder.getCallingUid() 4759 + " is not allowed to add to permission tree " 4760 + bp.name + " owned by uid " + bp.uid); 4761 } 4762 } 4763 throw new SecurityException("No permission tree found for " + permName); 4764 } 4765 4766 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4767 if (s1 == null) { 4768 return s2 == null; 4769 } 4770 if (s2 == null) { 4771 return false; 4772 } 4773 if (s1.getClass() != s2.getClass()) { 4774 return false; 4775 } 4776 return s1.equals(s2); 4777 } 4778 4779 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4780 if (pi1.icon != pi2.icon) return false; 4781 if (pi1.logo != pi2.logo) return false; 4782 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4783 if (!compareStrings(pi1.name, pi2.name)) return false; 4784 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4785 // We'll take care of setting this one. 4786 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4787 // These are not currently stored in settings. 4788 //if (!compareStrings(pi1.group, pi2.group)) return false; 4789 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4790 //if (pi1.labelRes != pi2.labelRes) return false; 4791 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4792 return true; 4793 } 4794 4795 int permissionInfoFootprint(PermissionInfo info) { 4796 int size = info.name.length(); 4797 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4798 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4799 return size; 4800 } 4801 4802 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4803 int size = 0; 4804 for (BasePermission perm : mSettings.mPermissions.values()) { 4805 if (perm.uid == tree.uid) { 4806 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4807 } 4808 } 4809 return size; 4810 } 4811 4812 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4813 // We calculate the max size of permissions defined by this uid and throw 4814 // if that plus the size of 'info' would exceed our stated maximum. 4815 if (tree.uid != Process.SYSTEM_UID) { 4816 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4817 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4818 throw new SecurityException("Permission tree size cap exceeded"); 4819 } 4820 } 4821 } 4822 4823 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4824 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4825 throw new SecurityException("Label must be specified in permission"); 4826 } 4827 BasePermission tree = checkPermissionTreeLP(info.name); 4828 BasePermission bp = mSettings.mPermissions.get(info.name); 4829 boolean added = bp == null; 4830 boolean changed = true; 4831 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4832 if (added) { 4833 enforcePermissionCapLocked(info, tree); 4834 bp = new BasePermission(info.name, tree.sourcePackage, 4835 BasePermission.TYPE_DYNAMIC); 4836 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4837 throw new SecurityException( 4838 "Not allowed to modify non-dynamic permission " 4839 + info.name); 4840 } else { 4841 if (bp.protectionLevel == fixedLevel 4842 && bp.perm.owner.equals(tree.perm.owner) 4843 && bp.uid == tree.uid 4844 && comparePermissionInfos(bp.perm.info, info)) { 4845 changed = false; 4846 } 4847 } 4848 bp.protectionLevel = fixedLevel; 4849 info = new PermissionInfo(info); 4850 info.protectionLevel = fixedLevel; 4851 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4852 bp.perm.info.packageName = tree.perm.info.packageName; 4853 bp.uid = tree.uid; 4854 if (added) { 4855 mSettings.mPermissions.put(info.name, bp); 4856 } 4857 if (changed) { 4858 if (!async) { 4859 mSettings.writeLPr(); 4860 } else { 4861 scheduleWriteSettingsLocked(); 4862 } 4863 } 4864 return added; 4865 } 4866 4867 @Override 4868 public boolean addPermission(PermissionInfo info) { 4869 synchronized (mPackages) { 4870 return addPermissionLocked(info, false); 4871 } 4872 } 4873 4874 @Override 4875 public boolean addPermissionAsync(PermissionInfo info) { 4876 synchronized (mPackages) { 4877 return addPermissionLocked(info, true); 4878 } 4879 } 4880 4881 @Override 4882 public void removePermission(String name) { 4883 synchronized (mPackages) { 4884 checkPermissionTreeLP(name); 4885 BasePermission bp = mSettings.mPermissions.get(name); 4886 if (bp != null) { 4887 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4888 throw new SecurityException( 4889 "Not allowed to modify non-dynamic permission " 4890 + name); 4891 } 4892 mSettings.mPermissions.remove(name); 4893 mSettings.writeLPr(); 4894 } 4895 } 4896 } 4897 4898 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4899 BasePermission bp) { 4900 int index = pkg.requestedPermissions.indexOf(bp.name); 4901 if (index == -1) { 4902 throw new SecurityException("Package " + pkg.packageName 4903 + " has not requested permission " + bp.name); 4904 } 4905 if (!bp.isRuntime() && !bp.isDevelopment()) { 4906 throw new SecurityException("Permission " + bp.name 4907 + " is not a changeable permission type"); 4908 } 4909 } 4910 4911 @Override 4912 public void grantRuntimePermission(String packageName, String name, final int userId) { 4913 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4914 } 4915 4916 private void grantRuntimePermission(String packageName, String name, final int userId, 4917 boolean overridePolicy) { 4918 if (!sUserManager.exists(userId)) { 4919 Log.e(TAG, "No such user:" + userId); 4920 return; 4921 } 4922 4923 mContext.enforceCallingOrSelfPermission( 4924 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4925 "grantRuntimePermission"); 4926 4927 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4928 true /* requireFullPermission */, true /* checkShell */, 4929 "grantRuntimePermission"); 4930 4931 final int uid; 4932 final SettingBase sb; 4933 4934 synchronized (mPackages) { 4935 final PackageParser.Package pkg = mPackages.get(packageName); 4936 if (pkg == null) { 4937 throw new IllegalArgumentException("Unknown package: " + packageName); 4938 } 4939 4940 final BasePermission bp = mSettings.mPermissions.get(name); 4941 if (bp == null) { 4942 throw new IllegalArgumentException("Unknown permission: " + name); 4943 } 4944 4945 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4946 4947 // If a permission review is required for legacy apps we represent 4948 // their permissions as always granted runtime ones since we need 4949 // to keep the review required permission flag per user while an 4950 // install permission's state is shared across all users. 4951 if (mPermissionReviewRequired 4952 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4953 && bp.isRuntime()) { 4954 return; 4955 } 4956 4957 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4958 sb = (SettingBase) pkg.mExtras; 4959 if (sb == null) { 4960 throw new IllegalArgumentException("Unknown package: " + packageName); 4961 } 4962 4963 final PermissionsState permissionsState = sb.getPermissionsState(); 4964 4965 final int flags = permissionsState.getPermissionFlags(name, userId); 4966 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4967 throw new SecurityException("Cannot grant system fixed permission " 4968 + name + " for package " + packageName); 4969 } 4970 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4971 throw new SecurityException("Cannot grant policy fixed permission " 4972 + name + " for package " + packageName); 4973 } 4974 4975 if (bp.isDevelopment()) { 4976 // Development permissions must be handled specially, since they are not 4977 // normal runtime permissions. For now they apply to all users. 4978 if (permissionsState.grantInstallPermission(bp) != 4979 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4980 scheduleWriteSettingsLocked(); 4981 } 4982 return; 4983 } 4984 4985 final PackageSetting ps = mSettings.mPackages.get(packageName); 4986 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4987 throw new SecurityException("Cannot grant non-ephemeral permission" 4988 + name + " for package " + packageName); 4989 } 4990 4991 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4992 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4993 return; 4994 } 4995 4996 final int result = permissionsState.grantRuntimePermission(bp, userId); 4997 switch (result) { 4998 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4999 return; 5000 } 5001 5002 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 5003 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5004 mHandler.post(new Runnable() { 5005 @Override 5006 public void run() { 5007 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 5008 } 5009 }); 5010 } 5011 break; 5012 } 5013 5014 if (bp.isRuntime()) { 5015 logPermissionGranted(mContext, name, packageName); 5016 } 5017 5018 mOnPermissionChangeListeners.onPermissionsChanged(uid); 5019 5020 // Not critical if that is lost - app has to request again. 5021 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5022 } 5023 5024 // Only need to do this if user is initialized. Otherwise it's a new user 5025 // and there are no processes running as the user yet and there's no need 5026 // to make an expensive call to remount processes for the changed permissions. 5027 if (READ_EXTERNAL_STORAGE.equals(name) 5028 || WRITE_EXTERNAL_STORAGE.equals(name)) { 5029 final long token = Binder.clearCallingIdentity(); 5030 try { 5031 if (sUserManager.isInitialized(userId)) { 5032 StorageManagerInternal storageManagerInternal = LocalServices.getService( 5033 StorageManagerInternal.class); 5034 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 5035 } 5036 } finally { 5037 Binder.restoreCallingIdentity(token); 5038 } 5039 } 5040 } 5041 5042 @Override 5043 public void revokeRuntimePermission(String packageName, String name, int userId) { 5044 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 5045 } 5046 5047 private void revokeRuntimePermission(String packageName, String name, int userId, 5048 boolean overridePolicy) { 5049 if (!sUserManager.exists(userId)) { 5050 Log.e(TAG, "No such user:" + userId); 5051 return; 5052 } 5053 5054 mContext.enforceCallingOrSelfPermission( 5055 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5056 "revokeRuntimePermission"); 5057 5058 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5059 true /* requireFullPermission */, true /* checkShell */, 5060 "revokeRuntimePermission"); 5061 5062 final int appId; 5063 5064 synchronized (mPackages) { 5065 final PackageParser.Package pkg = mPackages.get(packageName); 5066 if (pkg == null) { 5067 throw new IllegalArgumentException("Unknown package: " + packageName); 5068 } 5069 5070 final BasePermission bp = mSettings.mPermissions.get(name); 5071 if (bp == null) { 5072 throw new IllegalArgumentException("Unknown permission: " + name); 5073 } 5074 5075 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 5076 5077 // If a permission review is required for legacy apps we represent 5078 // their permissions as always granted runtime ones since we need 5079 // to keep the review required permission flag per user while an 5080 // install permission's state is shared across all users. 5081 if (mPermissionReviewRequired 5082 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 5083 && bp.isRuntime()) { 5084 return; 5085 } 5086 5087 SettingBase sb = (SettingBase) pkg.mExtras; 5088 if (sb == null) { 5089 throw new IllegalArgumentException("Unknown package: " + packageName); 5090 } 5091 5092 final PermissionsState permissionsState = sb.getPermissionsState(); 5093 5094 final int flags = permissionsState.getPermissionFlags(name, userId); 5095 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 5096 throw new SecurityException("Cannot revoke system fixed permission " 5097 + name + " for package " + packageName); 5098 } 5099 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 5100 throw new SecurityException("Cannot revoke policy fixed permission " 5101 + name + " for package " + packageName); 5102 } 5103 5104 if (bp.isDevelopment()) { 5105 // Development permissions must be handled specially, since they are not 5106 // normal runtime permissions. For now they apply to all users. 5107 if (permissionsState.revokeInstallPermission(bp) != 5108 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5109 scheduleWriteSettingsLocked(); 5110 } 5111 return; 5112 } 5113 5114 if (permissionsState.revokeRuntimePermission(bp, userId) == 5115 PermissionsState.PERMISSION_OPERATION_FAILURE) { 5116 return; 5117 } 5118 5119 if (bp.isRuntime()) { 5120 logPermissionRevoked(mContext, name, packageName); 5121 } 5122 5123 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 5124 5125 // Critical, after this call app should never have the permission. 5126 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 5127 5128 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 5129 } 5130 5131 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 5132 } 5133 5134 /** 5135 * Get the first event id for the permission. 5136 * 5137 * <p>There are four events for each permission: <ul> 5138 * <li>Request permission: first id + 0</li> 5139 * <li>Grant permission: first id + 1</li> 5140 * <li>Request for permission denied: first id + 2</li> 5141 * <li>Revoke permission: first id + 3</li> 5142 * </ul></p> 5143 * 5144 * @param name name of the permission 5145 * 5146 * @return The first event id for the permission 5147 */ 5148 private static int getBaseEventId(@NonNull String name) { 5149 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 5150 5151 if (eventIdIndex == -1) { 5152 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 5153 || "user".equals(Build.TYPE)) { 5154 Log.i(TAG, "Unknown permission " + name); 5155 5156 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 5157 } else { 5158 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 5159 // 5160 // Also update 5161 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 5162 // - metrics_constants.proto 5163 throw new IllegalStateException("Unknown permission " + name); 5164 } 5165 } 5166 5167 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5168 } 5169 5170 /** 5171 * Log that a permission was revoked. 5172 * 5173 * @param context Context of the caller 5174 * @param name name of the permission 5175 * @param packageName package permission if for 5176 */ 5177 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5178 @NonNull String packageName) { 5179 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5180 } 5181 5182 /** 5183 * Log that a permission request was granted. 5184 * 5185 * @param context Context of the caller 5186 * @param name name of the permission 5187 * @param packageName package permission if for 5188 */ 5189 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5190 @NonNull String packageName) { 5191 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5192 } 5193 5194 @Override 5195 public void resetRuntimePermissions() { 5196 mContext.enforceCallingOrSelfPermission( 5197 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5198 "revokeRuntimePermission"); 5199 5200 int callingUid = Binder.getCallingUid(); 5201 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5202 mContext.enforceCallingOrSelfPermission( 5203 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5204 "resetRuntimePermissions"); 5205 } 5206 5207 synchronized (mPackages) { 5208 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5209 for (int userId : UserManagerService.getInstance().getUserIds()) { 5210 final int packageCount = mPackages.size(); 5211 for (int i = 0; i < packageCount; i++) { 5212 PackageParser.Package pkg = mPackages.valueAt(i); 5213 if (!(pkg.mExtras instanceof PackageSetting)) { 5214 continue; 5215 } 5216 PackageSetting ps = (PackageSetting) pkg.mExtras; 5217 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5218 } 5219 } 5220 } 5221 } 5222 5223 @Override 5224 public int getPermissionFlags(String name, String packageName, int userId) { 5225 if (!sUserManager.exists(userId)) { 5226 return 0; 5227 } 5228 5229 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5230 5231 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5232 true /* requireFullPermission */, false /* checkShell */, 5233 "getPermissionFlags"); 5234 5235 synchronized (mPackages) { 5236 final PackageParser.Package pkg = mPackages.get(packageName); 5237 if (pkg == null) { 5238 return 0; 5239 } 5240 5241 final BasePermission bp = mSettings.mPermissions.get(name); 5242 if (bp == null) { 5243 return 0; 5244 } 5245 5246 SettingBase sb = (SettingBase) pkg.mExtras; 5247 if (sb == null) { 5248 return 0; 5249 } 5250 5251 PermissionsState permissionsState = sb.getPermissionsState(); 5252 return permissionsState.getPermissionFlags(name, userId); 5253 } 5254 } 5255 5256 @Override 5257 public void updatePermissionFlags(String name, String packageName, int flagMask, 5258 int flagValues, int userId) { 5259 if (!sUserManager.exists(userId)) { 5260 return; 5261 } 5262 5263 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5264 5265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5266 true /* requireFullPermission */, true /* checkShell */, 5267 "updatePermissionFlags"); 5268 5269 // Only the system can change these flags and nothing else. 5270 if (getCallingUid() != Process.SYSTEM_UID) { 5271 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5272 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5273 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5274 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5275 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5276 } 5277 5278 synchronized (mPackages) { 5279 final PackageParser.Package pkg = mPackages.get(packageName); 5280 if (pkg == null) { 5281 throw new IllegalArgumentException("Unknown package: " + packageName); 5282 } 5283 5284 final BasePermission bp = mSettings.mPermissions.get(name); 5285 if (bp == null) { 5286 throw new IllegalArgumentException("Unknown permission: " + name); 5287 } 5288 5289 SettingBase sb = (SettingBase) pkg.mExtras; 5290 if (sb == null) { 5291 throw new IllegalArgumentException("Unknown package: " + packageName); 5292 } 5293 5294 PermissionsState permissionsState = sb.getPermissionsState(); 5295 5296 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5297 5298 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5299 // Install and runtime permissions are stored in different places, 5300 // so figure out what permission changed and persist the change. 5301 if (permissionsState.getInstallPermissionState(name) != null) { 5302 scheduleWriteSettingsLocked(); 5303 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5304 || hadState) { 5305 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5306 } 5307 } 5308 } 5309 } 5310 5311 /** 5312 * Update the permission flags for all packages and runtime permissions of a user in order 5313 * to allow device or profile owner to remove POLICY_FIXED. 5314 */ 5315 @Override 5316 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5317 if (!sUserManager.exists(userId)) { 5318 return; 5319 } 5320 5321 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5322 5323 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5324 true /* requireFullPermission */, true /* checkShell */, 5325 "updatePermissionFlagsForAllApps"); 5326 5327 // Only the system can change system fixed flags. 5328 if (getCallingUid() != Process.SYSTEM_UID) { 5329 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5330 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5331 } 5332 5333 synchronized (mPackages) { 5334 boolean changed = false; 5335 final int packageCount = mPackages.size(); 5336 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5337 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5338 SettingBase sb = (SettingBase) pkg.mExtras; 5339 if (sb == null) { 5340 continue; 5341 } 5342 PermissionsState permissionsState = sb.getPermissionsState(); 5343 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5344 userId, flagMask, flagValues); 5345 } 5346 if (changed) { 5347 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5348 } 5349 } 5350 } 5351 5352 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5353 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5354 != PackageManager.PERMISSION_GRANTED 5355 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5356 != PackageManager.PERMISSION_GRANTED) { 5357 throw new SecurityException(message + " requires " 5358 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5359 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5360 } 5361 } 5362 5363 @Override 5364 public boolean shouldShowRequestPermissionRationale(String permissionName, 5365 String packageName, int userId) { 5366 if (UserHandle.getCallingUserId() != userId) { 5367 mContext.enforceCallingPermission( 5368 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5369 "canShowRequestPermissionRationale for user " + userId); 5370 } 5371 5372 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5373 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5374 return false; 5375 } 5376 5377 if (checkPermission(permissionName, packageName, userId) 5378 == PackageManager.PERMISSION_GRANTED) { 5379 return false; 5380 } 5381 5382 final int flags; 5383 5384 final long identity = Binder.clearCallingIdentity(); 5385 try { 5386 flags = getPermissionFlags(permissionName, 5387 packageName, userId); 5388 } finally { 5389 Binder.restoreCallingIdentity(identity); 5390 } 5391 5392 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5393 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5394 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5395 5396 if ((flags & fixedFlags) != 0) { 5397 return false; 5398 } 5399 5400 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5401 } 5402 5403 @Override 5404 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5405 mContext.enforceCallingOrSelfPermission( 5406 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5407 "addOnPermissionsChangeListener"); 5408 5409 synchronized (mPackages) { 5410 mOnPermissionChangeListeners.addListenerLocked(listener); 5411 } 5412 } 5413 5414 @Override 5415 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5416 synchronized (mPackages) { 5417 mOnPermissionChangeListeners.removeListenerLocked(listener); 5418 } 5419 } 5420 5421 @Override 5422 public boolean isProtectedBroadcast(String actionName) { 5423 synchronized (mPackages) { 5424 if (mProtectedBroadcasts.contains(actionName)) { 5425 return true; 5426 } else if (actionName != null) { 5427 // TODO: remove these terrible hacks 5428 if (actionName.startsWith("android.net.netmon.lingerExpired") 5429 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5430 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5431 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5432 return true; 5433 } 5434 } 5435 } 5436 return false; 5437 } 5438 5439 @Override 5440 public int checkSignatures(String pkg1, String pkg2) { 5441 synchronized (mPackages) { 5442 final PackageParser.Package p1 = mPackages.get(pkg1); 5443 final PackageParser.Package p2 = mPackages.get(pkg2); 5444 if (p1 == null || p1.mExtras == null 5445 || p2 == null || p2.mExtras == null) { 5446 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5447 } 5448 return compareSignatures(p1.mSignatures, p2.mSignatures); 5449 } 5450 } 5451 5452 @Override 5453 public int checkUidSignatures(int uid1, int uid2) { 5454 // Map to base uids. 5455 uid1 = UserHandle.getAppId(uid1); 5456 uid2 = UserHandle.getAppId(uid2); 5457 // reader 5458 synchronized (mPackages) { 5459 Signature[] s1; 5460 Signature[] s2; 5461 Object obj = mSettings.getUserIdLPr(uid1); 5462 if (obj != null) { 5463 if (obj instanceof SharedUserSetting) { 5464 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5465 } else if (obj instanceof PackageSetting) { 5466 s1 = ((PackageSetting)obj).signatures.mSignatures; 5467 } else { 5468 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5469 } 5470 } else { 5471 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5472 } 5473 obj = mSettings.getUserIdLPr(uid2); 5474 if (obj != null) { 5475 if (obj instanceof SharedUserSetting) { 5476 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5477 } else if (obj instanceof PackageSetting) { 5478 s2 = ((PackageSetting)obj).signatures.mSignatures; 5479 } else { 5480 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5481 } 5482 } else { 5483 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5484 } 5485 return compareSignatures(s1, s2); 5486 } 5487 } 5488 5489 /** 5490 * This method should typically only be used when granting or revoking 5491 * permissions, since the app may immediately restart after this call. 5492 * <p> 5493 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5494 * guard your work against the app being relaunched. 5495 */ 5496 private void killUid(int appId, int userId, String reason) { 5497 final long identity = Binder.clearCallingIdentity(); 5498 try { 5499 IActivityManager am = ActivityManager.getService(); 5500 if (am != null) { 5501 try { 5502 am.killUid(appId, userId, reason); 5503 } catch (RemoteException e) { 5504 /* ignore - same process */ 5505 } 5506 } 5507 } finally { 5508 Binder.restoreCallingIdentity(identity); 5509 } 5510 } 5511 5512 /** 5513 * Compares two sets of signatures. Returns: 5514 * <br /> 5515 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5516 * <br /> 5517 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5518 * <br /> 5519 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5520 * <br /> 5521 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5522 * <br /> 5523 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5524 */ 5525 static int compareSignatures(Signature[] s1, Signature[] s2) { 5526 if (s1 == null) { 5527 return s2 == null 5528 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5529 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5530 } 5531 5532 if (s2 == null) { 5533 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5534 } 5535 5536 if (s1.length != s2.length) { 5537 return PackageManager.SIGNATURE_NO_MATCH; 5538 } 5539 5540 // Since both signature sets are of size 1, we can compare without HashSets. 5541 if (s1.length == 1) { 5542 return s1[0].equals(s2[0]) ? 5543 PackageManager.SIGNATURE_MATCH : 5544 PackageManager.SIGNATURE_NO_MATCH; 5545 } 5546 5547 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5548 for (Signature sig : s1) { 5549 set1.add(sig); 5550 } 5551 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5552 for (Signature sig : s2) { 5553 set2.add(sig); 5554 } 5555 // Make sure s2 contains all signatures in s1. 5556 if (set1.equals(set2)) { 5557 return PackageManager.SIGNATURE_MATCH; 5558 } 5559 return PackageManager.SIGNATURE_NO_MATCH; 5560 } 5561 5562 /** 5563 * If the database version for this type of package (internal storage or 5564 * external storage) is less than the version where package signatures 5565 * were updated, return true. 5566 */ 5567 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5568 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5569 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5570 } 5571 5572 /** 5573 * Used for backward compatibility to make sure any packages with 5574 * certificate chains get upgraded to the new style. {@code existingSigs} 5575 * will be in the old format (since they were stored on disk from before the 5576 * system upgrade) and {@code scannedSigs} will be in the newer format. 5577 */ 5578 private int compareSignaturesCompat(PackageSignatures existingSigs, 5579 PackageParser.Package scannedPkg) { 5580 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5581 return PackageManager.SIGNATURE_NO_MATCH; 5582 } 5583 5584 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5585 for (Signature sig : existingSigs.mSignatures) { 5586 existingSet.add(sig); 5587 } 5588 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5589 for (Signature sig : scannedPkg.mSignatures) { 5590 try { 5591 Signature[] chainSignatures = sig.getChainSignatures(); 5592 for (Signature chainSig : chainSignatures) { 5593 scannedCompatSet.add(chainSig); 5594 } 5595 } catch (CertificateEncodingException e) { 5596 scannedCompatSet.add(sig); 5597 } 5598 } 5599 /* 5600 * Make sure the expanded scanned set contains all signatures in the 5601 * existing one. 5602 */ 5603 if (scannedCompatSet.equals(existingSet)) { 5604 // Migrate the old signatures to the new scheme. 5605 existingSigs.assignSignatures(scannedPkg.mSignatures); 5606 // The new KeySets will be re-added later in the scanning process. 5607 synchronized (mPackages) { 5608 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5609 } 5610 return PackageManager.SIGNATURE_MATCH; 5611 } 5612 return PackageManager.SIGNATURE_NO_MATCH; 5613 } 5614 5615 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5616 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5617 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5618 } 5619 5620 private int compareSignaturesRecover(PackageSignatures existingSigs, 5621 PackageParser.Package scannedPkg) { 5622 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5623 return PackageManager.SIGNATURE_NO_MATCH; 5624 } 5625 5626 String msg = null; 5627 try { 5628 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5629 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5630 + scannedPkg.packageName); 5631 return PackageManager.SIGNATURE_MATCH; 5632 } 5633 } catch (CertificateException e) { 5634 msg = e.getMessage(); 5635 } 5636 5637 logCriticalInfo(Log.INFO, 5638 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5639 return PackageManager.SIGNATURE_NO_MATCH; 5640 } 5641 5642 @Override 5643 public List<String> getAllPackages() { 5644 synchronized (mPackages) { 5645 return new ArrayList<String>(mPackages.keySet()); 5646 } 5647 } 5648 5649 @Override 5650 public String[] getPackagesForUid(int uid) { 5651 final int userId = UserHandle.getUserId(uid); 5652 uid = UserHandle.getAppId(uid); 5653 // reader 5654 synchronized (mPackages) { 5655 Object obj = mSettings.getUserIdLPr(uid); 5656 if (obj instanceof SharedUserSetting) { 5657 final SharedUserSetting sus = (SharedUserSetting) obj; 5658 final int N = sus.packages.size(); 5659 String[] res = new String[N]; 5660 final Iterator<PackageSetting> it = sus.packages.iterator(); 5661 int i = 0; 5662 while (it.hasNext()) { 5663 PackageSetting ps = it.next(); 5664 if (ps.getInstalled(userId)) { 5665 res[i++] = ps.name; 5666 } else { 5667 res = ArrayUtils.removeElement(String.class, res, res[i]); 5668 } 5669 } 5670 return res; 5671 } else if (obj instanceof PackageSetting) { 5672 final PackageSetting ps = (PackageSetting) obj; 5673 if (ps.getInstalled(userId)) { 5674 return new String[]{ps.name}; 5675 } 5676 } 5677 } 5678 return null; 5679 } 5680 5681 @Override 5682 public String getNameForUid(int uid) { 5683 // reader 5684 synchronized (mPackages) { 5685 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5686 if (obj instanceof SharedUserSetting) { 5687 final SharedUserSetting sus = (SharedUserSetting) obj; 5688 return sus.name + ":" + sus.userId; 5689 } else if (obj instanceof PackageSetting) { 5690 final PackageSetting ps = (PackageSetting) obj; 5691 return ps.name; 5692 } 5693 } 5694 return null; 5695 } 5696 5697 @Override 5698 public int getUidForSharedUser(String sharedUserName) { 5699 if(sharedUserName == null) { 5700 return -1; 5701 } 5702 // reader 5703 synchronized (mPackages) { 5704 SharedUserSetting suid; 5705 try { 5706 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5707 if (suid != null) { 5708 return suid.userId; 5709 } 5710 } catch (PackageManagerException ignore) { 5711 // can't happen, but, still need to catch it 5712 } 5713 return -1; 5714 } 5715 } 5716 5717 @Override 5718 public int getFlagsForUid(int uid) { 5719 synchronized (mPackages) { 5720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5721 if (obj instanceof SharedUserSetting) { 5722 final SharedUserSetting sus = (SharedUserSetting) obj; 5723 return sus.pkgFlags; 5724 } else if (obj instanceof PackageSetting) { 5725 final PackageSetting ps = (PackageSetting) obj; 5726 return ps.pkgFlags; 5727 } 5728 } 5729 return 0; 5730 } 5731 5732 @Override 5733 public int getPrivateFlagsForUid(int uid) { 5734 synchronized (mPackages) { 5735 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5736 if (obj instanceof SharedUserSetting) { 5737 final SharedUserSetting sus = (SharedUserSetting) obj; 5738 return sus.pkgPrivateFlags; 5739 } else if (obj instanceof PackageSetting) { 5740 final PackageSetting ps = (PackageSetting) obj; 5741 return ps.pkgPrivateFlags; 5742 } 5743 } 5744 return 0; 5745 } 5746 5747 @Override 5748 public boolean isUidPrivileged(int uid) { 5749 uid = UserHandle.getAppId(uid); 5750 // reader 5751 synchronized (mPackages) { 5752 Object obj = mSettings.getUserIdLPr(uid); 5753 if (obj instanceof SharedUserSetting) { 5754 final SharedUserSetting sus = (SharedUserSetting) obj; 5755 final Iterator<PackageSetting> it = sus.packages.iterator(); 5756 while (it.hasNext()) { 5757 if (it.next().isPrivileged()) { 5758 return true; 5759 } 5760 } 5761 } else if (obj instanceof PackageSetting) { 5762 final PackageSetting ps = (PackageSetting) obj; 5763 return ps.isPrivileged(); 5764 } 5765 } 5766 return false; 5767 } 5768 5769 @Override 5770 public String[] getAppOpPermissionPackages(String permissionName) { 5771 synchronized (mPackages) { 5772 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5773 if (pkgs == null) { 5774 return null; 5775 } 5776 return pkgs.toArray(new String[pkgs.size()]); 5777 } 5778 } 5779 5780 @Override 5781 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5782 int flags, int userId) { 5783 return resolveIntentInternal( 5784 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5785 } 5786 5787 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5788 int flags, int userId, boolean resolveForStart) { 5789 try { 5790 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5791 5792 if (!sUserManager.exists(userId)) return null; 5793 final int callingUid = Binder.getCallingUid(); 5794 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5795 enforceCrossUserPermission(callingUid, userId, 5796 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5797 5798 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5799 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5800 flags, userId, resolveForStart); 5801 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5802 5803 final ResolveInfo bestChoice = 5804 chooseBestActivity(intent, resolvedType, flags, query, userId); 5805 return bestChoice; 5806 } finally { 5807 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5808 } 5809 } 5810 5811 @Override 5812 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5813 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5814 throw new SecurityException( 5815 "findPersistentPreferredActivity can only be run by the system"); 5816 } 5817 if (!sUserManager.exists(userId)) { 5818 return null; 5819 } 5820 final int callingUid = Binder.getCallingUid(); 5821 intent = updateIntentForResolve(intent); 5822 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5823 final int flags = updateFlagsForResolve( 5824 0, userId, intent, callingUid, false /*includeInstantApps*/); 5825 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5826 userId); 5827 synchronized (mPackages) { 5828 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5829 userId); 5830 } 5831 } 5832 5833 @Override 5834 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5835 IntentFilter filter, int match, ComponentName activity) { 5836 final int userId = UserHandle.getCallingUserId(); 5837 if (DEBUG_PREFERRED) { 5838 Log.v(TAG, "setLastChosenActivity intent=" + intent 5839 + " resolvedType=" + resolvedType 5840 + " flags=" + flags 5841 + " filter=" + filter 5842 + " match=" + match 5843 + " activity=" + activity); 5844 filter.dump(new PrintStreamPrinter(System.out), " "); 5845 } 5846 intent.setComponent(null); 5847 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5848 userId); 5849 // Find any earlier preferred or last chosen entries and nuke them 5850 findPreferredActivity(intent, resolvedType, 5851 flags, query, 0, false, true, false, userId); 5852 // Add the new activity as the last chosen for this filter 5853 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5854 "Setting last chosen"); 5855 } 5856 5857 @Override 5858 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5859 final int userId = UserHandle.getCallingUserId(); 5860 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5861 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5862 userId); 5863 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5864 false, false, false, userId); 5865 } 5866 5867 /** 5868 * Returns whether or not instant apps have been disabled remotely. 5869 */ 5870 private boolean isEphemeralDisabled() { 5871 return mEphemeralAppsDisabled; 5872 } 5873 5874 private boolean isInstantAppAllowed( 5875 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5876 boolean skipPackageCheck) { 5877 if (mInstantAppResolverConnection == null) { 5878 return false; 5879 } 5880 if (mInstantAppInstallerActivity == null) { 5881 return false; 5882 } 5883 if (intent.getComponent() != null) { 5884 return false; 5885 } 5886 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5887 return false; 5888 } 5889 if (!skipPackageCheck && intent.getPackage() != null) { 5890 return false; 5891 } 5892 final boolean isWebUri = hasWebURI(intent); 5893 if (!isWebUri || intent.getData().getHost() == null) { 5894 return false; 5895 } 5896 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5897 // Or if there's already an ephemeral app installed that handles the action 5898 synchronized (mPackages) { 5899 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5900 for (int n = 0; n < count; n++) { 5901 final ResolveInfo info = resolvedActivities.get(n); 5902 final String packageName = info.activityInfo.packageName; 5903 final PackageSetting ps = mSettings.mPackages.get(packageName); 5904 if (ps != null) { 5905 // only check domain verification status if the app is not a browser 5906 if (!info.handleAllWebDataURI) { 5907 // Try to get the status from User settings first 5908 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5909 final int status = (int) (packedStatus >> 32); 5910 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5911 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5912 if (DEBUG_EPHEMERAL) { 5913 Slog.v(TAG, "DENY instant app;" 5914 + " pkg: " + packageName + ", status: " + status); 5915 } 5916 return false; 5917 } 5918 } 5919 if (ps.getInstantApp(userId)) { 5920 if (DEBUG_EPHEMERAL) { 5921 Slog.v(TAG, "DENY instant app installed;" 5922 + " pkg: " + packageName); 5923 } 5924 return false; 5925 } 5926 } 5927 } 5928 } 5929 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5930 return true; 5931 } 5932 5933 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5934 Intent origIntent, String resolvedType, String callingPackage, 5935 Bundle verificationBundle, int userId) { 5936 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5937 new InstantAppRequest(responseObj, origIntent, resolvedType, 5938 callingPackage, userId, verificationBundle)); 5939 mHandler.sendMessage(msg); 5940 } 5941 5942 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5943 int flags, List<ResolveInfo> query, int userId) { 5944 if (query != null) { 5945 final int N = query.size(); 5946 if (N == 1) { 5947 return query.get(0); 5948 } else if (N > 1) { 5949 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5950 // If there is more than one activity with the same priority, 5951 // then let the user decide between them. 5952 ResolveInfo r0 = query.get(0); 5953 ResolveInfo r1 = query.get(1); 5954 if (DEBUG_INTENT_MATCHING || debug) { 5955 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5956 + r1.activityInfo.name + "=" + r1.priority); 5957 } 5958 // If the first activity has a higher priority, or a different 5959 // default, then it is always desirable to pick it. 5960 if (r0.priority != r1.priority 5961 || r0.preferredOrder != r1.preferredOrder 5962 || r0.isDefault != r1.isDefault) { 5963 return query.get(0); 5964 } 5965 // If we have saved a preference for a preferred activity for 5966 // this Intent, use that. 5967 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5968 flags, query, r0.priority, true, false, debug, userId); 5969 if (ri != null) { 5970 return ri; 5971 } 5972 // If we have an ephemeral app, use it 5973 for (int i = 0; i < N; i++) { 5974 ri = query.get(i); 5975 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5976 final String packageName = ri.activityInfo.packageName; 5977 final PackageSetting ps = mSettings.mPackages.get(packageName); 5978 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5979 final int status = (int)(packedStatus >> 32); 5980 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5981 return ri; 5982 } 5983 } 5984 } 5985 ri = new ResolveInfo(mResolveInfo); 5986 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5987 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5988 // If all of the options come from the same package, show the application's 5989 // label and icon instead of the generic resolver's. 5990 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5991 // and then throw away the ResolveInfo itself, meaning that the caller loses 5992 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5993 // a fallback for this case; we only set the target package's resources on 5994 // the ResolveInfo, not the ActivityInfo. 5995 final String intentPackage = intent.getPackage(); 5996 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5997 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5998 ri.resolvePackageName = intentPackage; 5999 if (userNeedsBadging(userId)) { 6000 ri.noResourceId = true; 6001 } else { 6002 ri.icon = appi.icon; 6003 } 6004 ri.iconResourceId = appi.icon; 6005 ri.labelRes = appi.labelRes; 6006 } 6007 ri.activityInfo.applicationInfo = new ApplicationInfo( 6008 ri.activityInfo.applicationInfo); 6009 if (userId != 0) { 6010 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6011 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6012 } 6013 // Make sure that the resolver is displayable in car mode 6014 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6015 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6016 return ri; 6017 } 6018 } 6019 return null; 6020 } 6021 6022 /** 6023 * Return true if the given list is not empty and all of its contents have 6024 * an activityInfo with the given package name. 6025 */ 6026 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6027 if (ArrayUtils.isEmpty(list)) { 6028 return false; 6029 } 6030 for (int i = 0, N = list.size(); i < N; i++) { 6031 final ResolveInfo ri = list.get(i); 6032 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6033 if (ai == null || !packageName.equals(ai.packageName)) { 6034 return false; 6035 } 6036 } 6037 return true; 6038 } 6039 6040 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6041 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6042 final int N = query.size(); 6043 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6044 .get(userId); 6045 // Get the list of persistent preferred activities that handle the intent 6046 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6047 List<PersistentPreferredActivity> pprefs = ppir != null 6048 ? ppir.queryIntent(intent, resolvedType, 6049 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6050 userId) 6051 : null; 6052 if (pprefs != null && pprefs.size() > 0) { 6053 final int M = pprefs.size(); 6054 for (int i=0; i<M; i++) { 6055 final PersistentPreferredActivity ppa = pprefs.get(i); 6056 if (DEBUG_PREFERRED || debug) { 6057 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6058 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6059 + "\n component=" + ppa.mComponent); 6060 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6061 } 6062 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6063 flags | MATCH_DISABLED_COMPONENTS, userId); 6064 if (DEBUG_PREFERRED || debug) { 6065 Slog.v(TAG, "Found persistent preferred activity:"); 6066 if (ai != null) { 6067 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6068 } else { 6069 Slog.v(TAG, " null"); 6070 } 6071 } 6072 if (ai == null) { 6073 // This previously registered persistent preferred activity 6074 // component is no longer known. Ignore it and do NOT remove it. 6075 continue; 6076 } 6077 for (int j=0; j<N; j++) { 6078 final ResolveInfo ri = query.get(j); 6079 if (!ri.activityInfo.applicationInfo.packageName 6080 .equals(ai.applicationInfo.packageName)) { 6081 continue; 6082 } 6083 if (!ri.activityInfo.name.equals(ai.name)) { 6084 continue; 6085 } 6086 // Found a persistent preference that can handle the intent. 6087 if (DEBUG_PREFERRED || debug) { 6088 Slog.v(TAG, "Returning persistent preferred activity: " + 6089 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6090 } 6091 return ri; 6092 } 6093 } 6094 } 6095 return null; 6096 } 6097 6098 // TODO: handle preferred activities missing while user has amnesia 6099 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6100 List<ResolveInfo> query, int priority, boolean always, 6101 boolean removeMatches, boolean debug, int userId) { 6102 if (!sUserManager.exists(userId)) return null; 6103 final int callingUid = Binder.getCallingUid(); 6104 flags = updateFlagsForResolve( 6105 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6106 intent = updateIntentForResolve(intent); 6107 // writer 6108 synchronized (mPackages) { 6109 // Try to find a matching persistent preferred activity. 6110 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6111 debug, userId); 6112 6113 // If a persistent preferred activity matched, use it. 6114 if (pri != null) { 6115 return pri; 6116 } 6117 6118 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6119 // Get the list of preferred activities that handle the intent 6120 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6121 List<PreferredActivity> prefs = pir != null 6122 ? pir.queryIntent(intent, resolvedType, 6123 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6124 userId) 6125 : null; 6126 if (prefs != null && prefs.size() > 0) { 6127 boolean changed = false; 6128 try { 6129 // First figure out how good the original match set is. 6130 // We will only allow preferred activities that came 6131 // from the same match quality. 6132 int match = 0; 6133 6134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6135 6136 final int N = query.size(); 6137 for (int j=0; j<N; j++) { 6138 final ResolveInfo ri = query.get(j); 6139 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6140 + ": 0x" + Integer.toHexString(match)); 6141 if (ri.match > match) { 6142 match = ri.match; 6143 } 6144 } 6145 6146 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6147 + Integer.toHexString(match)); 6148 6149 match &= IntentFilter.MATCH_CATEGORY_MASK; 6150 final int M = prefs.size(); 6151 for (int i=0; i<M; i++) { 6152 final PreferredActivity pa = prefs.get(i); 6153 if (DEBUG_PREFERRED || debug) { 6154 Slog.v(TAG, "Checking PreferredActivity ds=" 6155 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6156 + "\n component=" + pa.mPref.mComponent); 6157 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6158 } 6159 if (pa.mPref.mMatch != match) { 6160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6161 + Integer.toHexString(pa.mPref.mMatch)); 6162 continue; 6163 } 6164 // If it's not an "always" type preferred activity and that's what we're 6165 // looking for, skip it. 6166 if (always && !pa.mPref.mAlways) { 6167 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6168 continue; 6169 } 6170 final ActivityInfo ai = getActivityInfo( 6171 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6172 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6173 userId); 6174 if (DEBUG_PREFERRED || debug) { 6175 Slog.v(TAG, "Found preferred activity:"); 6176 if (ai != null) { 6177 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6178 } else { 6179 Slog.v(TAG, " null"); 6180 } 6181 } 6182 if (ai == null) { 6183 // This previously registered preferred activity 6184 // component is no longer known. Most likely an update 6185 // to the app was installed and in the new version this 6186 // component no longer exists. Clean it up by removing 6187 // it from the preferred activities list, and skip it. 6188 Slog.w(TAG, "Removing dangling preferred activity: " 6189 + pa.mPref.mComponent); 6190 pir.removeFilter(pa); 6191 changed = true; 6192 continue; 6193 } 6194 for (int j=0; j<N; j++) { 6195 final ResolveInfo ri = query.get(j); 6196 if (!ri.activityInfo.applicationInfo.packageName 6197 .equals(ai.applicationInfo.packageName)) { 6198 continue; 6199 } 6200 if (!ri.activityInfo.name.equals(ai.name)) { 6201 continue; 6202 } 6203 6204 if (removeMatches) { 6205 pir.removeFilter(pa); 6206 changed = true; 6207 if (DEBUG_PREFERRED) { 6208 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6209 } 6210 break; 6211 } 6212 6213 // Okay we found a previously set preferred or last chosen app. 6214 // If the result set is different from when this 6215 // was created, we need to clear it and re-ask the 6216 // user their preference, if we're looking for an "always" type entry. 6217 if (always && !pa.mPref.sameSet(query)) { 6218 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6219 + intent + " type " + resolvedType); 6220 if (DEBUG_PREFERRED) { 6221 Slog.v(TAG, "Removing preferred activity since set changed " 6222 + pa.mPref.mComponent); 6223 } 6224 pir.removeFilter(pa); 6225 // Re-add the filter as a "last chosen" entry (!always) 6226 PreferredActivity lastChosen = new PreferredActivity( 6227 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6228 pir.addFilter(lastChosen); 6229 changed = true; 6230 return null; 6231 } 6232 6233 // Yay! Either the set matched or we're looking for the last chosen 6234 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6235 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6236 return ri; 6237 } 6238 } 6239 } finally { 6240 if (changed) { 6241 if (DEBUG_PREFERRED) { 6242 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6243 } 6244 scheduleWritePackageRestrictionsLocked(userId); 6245 } 6246 } 6247 } 6248 } 6249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6250 return null; 6251 } 6252 6253 /* 6254 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6255 */ 6256 @Override 6257 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6258 int targetUserId) { 6259 mContext.enforceCallingOrSelfPermission( 6260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6261 List<CrossProfileIntentFilter> matches = 6262 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6263 if (matches != null) { 6264 int size = matches.size(); 6265 for (int i = 0; i < size; i++) { 6266 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6267 } 6268 } 6269 if (hasWebURI(intent)) { 6270 // cross-profile app linking works only towards the parent. 6271 final int callingUid = Binder.getCallingUid(); 6272 final UserInfo parent = getProfileParent(sourceUserId); 6273 synchronized(mPackages) { 6274 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6275 false /*includeInstantApps*/); 6276 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6277 intent, resolvedType, flags, sourceUserId, parent.id); 6278 return xpDomainInfo != null; 6279 } 6280 } 6281 return false; 6282 } 6283 6284 private UserInfo getProfileParent(int userId) { 6285 final long identity = Binder.clearCallingIdentity(); 6286 try { 6287 return sUserManager.getProfileParent(userId); 6288 } finally { 6289 Binder.restoreCallingIdentity(identity); 6290 } 6291 } 6292 6293 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6294 String resolvedType, int userId) { 6295 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6296 if (resolver != null) { 6297 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6298 } 6299 return null; 6300 } 6301 6302 @Override 6303 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6304 String resolvedType, int flags, int userId) { 6305 try { 6306 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6307 6308 return new ParceledListSlice<>( 6309 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6310 } finally { 6311 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6312 } 6313 } 6314 6315 /** 6316 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6317 * instant, returns {@code null}. 6318 */ 6319 private String getInstantAppPackageName(int callingUid) { 6320 // If the caller is an isolated app use the owner's uid for the lookup. 6321 if (Process.isIsolated(callingUid)) { 6322 callingUid = mIsolatedOwners.get(callingUid); 6323 } 6324 final int appId = UserHandle.getAppId(callingUid); 6325 synchronized (mPackages) { 6326 final Object obj = mSettings.getUserIdLPr(appId); 6327 if (obj instanceof PackageSetting) { 6328 final PackageSetting ps = (PackageSetting) obj; 6329 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6330 return isInstantApp ? ps.pkg.packageName : null; 6331 } 6332 } 6333 return null; 6334 } 6335 6336 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6337 String resolvedType, int flags, int userId) { 6338 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6339 } 6340 6341 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6342 String resolvedType, int flags, int userId, boolean resolveForStart) { 6343 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6344 final int callingUid = Binder.getCallingUid(); 6345 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6346 enforceCrossUserPermission(callingUid, userId, 6347 false /* requireFullPermission */, false /* checkShell */, 6348 "query intent activities"); 6349 final String pkgName = intent.getPackage(); 6350 ComponentName comp = intent.getComponent(); 6351 if (comp == null) { 6352 if (intent.getSelector() != null) { 6353 intent = intent.getSelector(); 6354 comp = intent.getComponent(); 6355 } 6356 } 6357 6358 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart, 6359 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6360 if (comp != null) { 6361 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6362 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6363 if (ai != null) { 6364 // When specifying an explicit component, we prevent the activity from being 6365 // used when either 1) the calling package is normal and the activity is within 6366 // an ephemeral application or 2) the calling package is ephemeral and the 6367 // activity is not visible to ephemeral applications. 6368 final boolean matchInstantApp = 6369 (flags & PackageManager.MATCH_INSTANT) != 0; 6370 final boolean matchVisibleToInstantAppOnly = 6371 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6372 final boolean matchExplicitlyVisibleOnly = 6373 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6374 final boolean isCallerInstantApp = 6375 instantAppPkgName != null; 6376 final boolean isTargetSameInstantApp = 6377 comp.getPackageName().equals(instantAppPkgName); 6378 final boolean isTargetInstantApp = 6379 (ai.applicationInfo.privateFlags 6380 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6381 final boolean isTargetVisibleToInstantApp = 6382 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6383 final boolean isTargetExplicitlyVisibleToInstantApp = 6384 isTargetVisibleToInstantApp 6385 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6386 final boolean isTargetHiddenFromInstantApp = 6387 !isTargetVisibleToInstantApp 6388 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6389 final boolean blockResolution = 6390 !isTargetSameInstantApp 6391 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6392 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6393 && isTargetHiddenFromInstantApp)); 6394 if (!blockResolution) { 6395 final ResolveInfo ri = new ResolveInfo(); 6396 ri.activityInfo = ai; 6397 list.add(ri); 6398 } 6399 } 6400 return applyPostResolutionFilter(list, instantAppPkgName); 6401 } 6402 6403 // reader 6404 boolean sortResult = false; 6405 boolean addEphemeral = false; 6406 List<ResolveInfo> result; 6407 final boolean ephemeralDisabled = isEphemeralDisabled(); 6408 synchronized (mPackages) { 6409 if (pkgName == null) { 6410 List<CrossProfileIntentFilter> matchingFilters = 6411 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6412 // Check for results that need to skip the current profile. 6413 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6414 resolvedType, flags, userId); 6415 if (xpResolveInfo != null) { 6416 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6417 xpResult.add(xpResolveInfo); 6418 return applyPostResolutionFilter( 6419 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6420 } 6421 6422 // Check for results in the current profile. 6423 result = filterIfNotSystemUser(mActivities.queryIntent( 6424 intent, resolvedType, flags, userId), userId); 6425 addEphemeral = !ephemeralDisabled 6426 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6427 // Check for cross profile results. 6428 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6429 xpResolveInfo = queryCrossProfileIntents( 6430 matchingFilters, intent, resolvedType, flags, userId, 6431 hasNonNegativePriorityResult); 6432 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6433 boolean isVisibleToUser = filterIfNotSystemUser( 6434 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6435 if (isVisibleToUser) { 6436 result.add(xpResolveInfo); 6437 sortResult = true; 6438 } 6439 } 6440 if (hasWebURI(intent)) { 6441 CrossProfileDomainInfo xpDomainInfo = null; 6442 final UserInfo parent = getProfileParent(userId); 6443 if (parent != null) { 6444 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6445 flags, userId, parent.id); 6446 } 6447 if (xpDomainInfo != null) { 6448 if (xpResolveInfo != null) { 6449 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6450 // in the result. 6451 result.remove(xpResolveInfo); 6452 } 6453 if (result.size() == 0 && !addEphemeral) { 6454 // No result in current profile, but found candidate in parent user. 6455 // And we are not going to add emphemeral app, so we can return the 6456 // result straight away. 6457 result.add(xpDomainInfo.resolveInfo); 6458 return applyPostResolutionFilter(result, instantAppPkgName); 6459 } 6460 } else if (result.size() <= 1 && !addEphemeral) { 6461 // No result in parent user and <= 1 result in current profile, and we 6462 // are not going to add emphemeral app, so we can return the result without 6463 // further processing. 6464 return applyPostResolutionFilter(result, instantAppPkgName); 6465 } 6466 // We have more than one candidate (combining results from current and parent 6467 // profile), so we need filtering and sorting. 6468 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6469 intent, flags, result, xpDomainInfo, userId); 6470 sortResult = true; 6471 } 6472 } else { 6473 final PackageParser.Package pkg = mPackages.get(pkgName); 6474 if (pkg != null) { 6475 return applyPostResolutionFilter(filterIfNotSystemUser( 6476 mActivities.queryIntentForPackage( 6477 intent, resolvedType, flags, pkg.activities, userId), 6478 userId), instantAppPkgName); 6479 } else { 6480 // the caller wants to resolve for a particular package; however, there 6481 // were no installed results, so, try to find an ephemeral result 6482 addEphemeral = !ephemeralDisabled 6483 && isInstantAppAllowed( 6484 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6485 result = new ArrayList<ResolveInfo>(); 6486 } 6487 } 6488 } 6489 if (addEphemeral) { 6490 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId); 6491 } 6492 if (sortResult) { 6493 Collections.sort(result, mResolvePrioritySorter); 6494 } 6495 return applyPostResolutionFilter(result, instantAppPkgName); 6496 } 6497 6498 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6499 String resolvedType, int flags, int userId) { 6500 // first, check to see if we've got an instant app already installed 6501 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6502 ResolveInfo localInstantApp = null; 6503 boolean blockResolution = false; 6504 if (!alreadyResolvedLocally) { 6505 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6506 flags 6507 | PackageManager.GET_RESOLVED_FILTER 6508 | PackageManager.MATCH_INSTANT 6509 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6510 userId); 6511 for (int i = instantApps.size() - 1; i >= 0; --i) { 6512 final ResolveInfo info = instantApps.get(i); 6513 final String packageName = info.activityInfo.packageName; 6514 final PackageSetting ps = mSettings.mPackages.get(packageName); 6515 if (ps.getInstantApp(userId)) { 6516 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6517 final int status = (int)(packedStatus >> 32); 6518 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6519 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6520 // there's a local instant application installed, but, the user has 6521 // chosen to never use it; skip resolution and don't acknowledge 6522 // an instant application is even available 6523 if (DEBUG_EPHEMERAL) { 6524 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6525 } 6526 blockResolution = true; 6527 break; 6528 } else { 6529 // we have a locally installed instant application; skip resolution 6530 // but acknowledge there's an instant application available 6531 if (DEBUG_EPHEMERAL) { 6532 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6533 } 6534 localInstantApp = info; 6535 break; 6536 } 6537 } 6538 } 6539 } 6540 // no app installed, let's see if one's available 6541 AuxiliaryResolveInfo auxiliaryResponse = null; 6542 if (!blockResolution) { 6543 if (localInstantApp == null) { 6544 // we don't have an instant app locally, resolve externally 6545 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6546 final InstantAppRequest requestObject = new InstantAppRequest( 6547 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6548 null /*callingPackage*/, userId, null /*verificationBundle*/); 6549 auxiliaryResponse = 6550 InstantAppResolver.doInstantAppResolutionPhaseOne( 6551 mContext, mInstantAppResolverConnection, requestObject); 6552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6553 } else { 6554 // we have an instant application locally, but, we can't admit that since 6555 // callers shouldn't be able to determine prior browsing. create a dummy 6556 // auxiliary response so the downstream code behaves as if there's an 6557 // instant application available externally. when it comes time to start 6558 // the instant application, we'll do the right thing. 6559 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6560 auxiliaryResponse = new AuxiliaryResolveInfo( 6561 ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/); 6562 } 6563 } 6564 if (auxiliaryResponse != null) { 6565 if (DEBUG_EPHEMERAL) { 6566 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6567 } 6568 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6569 final PackageSetting ps = 6570 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6571 if (ps != null) { 6572 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6573 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6574 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6575 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6576 // make sure this resolver is the default 6577 ephemeralInstaller.isDefault = true; 6578 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6579 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6580 // add a non-generic filter 6581 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6582 ephemeralInstaller.filter.addDataPath( 6583 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6584 ephemeralInstaller.isInstantAppAvailable = true; 6585 result.add(ephemeralInstaller); 6586 } 6587 } 6588 return result; 6589 } 6590 6591 private static class CrossProfileDomainInfo { 6592 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6593 ResolveInfo resolveInfo; 6594 /* Best domain verification status of the activities found in the other profile */ 6595 int bestDomainVerificationStatus; 6596 } 6597 6598 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6599 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6600 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6601 sourceUserId)) { 6602 return null; 6603 } 6604 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6605 resolvedType, flags, parentUserId); 6606 6607 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6608 return null; 6609 } 6610 CrossProfileDomainInfo result = null; 6611 int size = resultTargetUser.size(); 6612 for (int i = 0; i < size; i++) { 6613 ResolveInfo riTargetUser = resultTargetUser.get(i); 6614 // Intent filter verification is only for filters that specify a host. So don't return 6615 // those that handle all web uris. 6616 if (riTargetUser.handleAllWebDataURI) { 6617 continue; 6618 } 6619 String packageName = riTargetUser.activityInfo.packageName; 6620 PackageSetting ps = mSettings.mPackages.get(packageName); 6621 if (ps == null) { 6622 continue; 6623 } 6624 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6625 int status = (int)(verificationState >> 32); 6626 if (result == null) { 6627 result = new CrossProfileDomainInfo(); 6628 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6629 sourceUserId, parentUserId); 6630 result.bestDomainVerificationStatus = status; 6631 } else { 6632 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6633 result.bestDomainVerificationStatus); 6634 } 6635 } 6636 // Don't consider matches with status NEVER across profiles. 6637 if (result != null && result.bestDomainVerificationStatus 6638 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6639 return null; 6640 } 6641 return result; 6642 } 6643 6644 /** 6645 * Verification statuses are ordered from the worse to the best, except for 6646 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6647 */ 6648 private int bestDomainVerificationStatus(int status1, int status2) { 6649 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6650 return status2; 6651 } 6652 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6653 return status1; 6654 } 6655 return (int) MathUtils.max(status1, status2); 6656 } 6657 6658 private boolean isUserEnabled(int userId) { 6659 long callingId = Binder.clearCallingIdentity(); 6660 try { 6661 UserInfo userInfo = sUserManager.getUserInfo(userId); 6662 return userInfo != null && userInfo.isEnabled(); 6663 } finally { 6664 Binder.restoreCallingIdentity(callingId); 6665 } 6666 } 6667 6668 /** 6669 * Filter out activities with systemUserOnly flag set, when current user is not System. 6670 * 6671 * @return filtered list 6672 */ 6673 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6674 if (userId == UserHandle.USER_SYSTEM) { 6675 return resolveInfos; 6676 } 6677 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6678 ResolveInfo info = resolveInfos.get(i); 6679 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6680 resolveInfos.remove(i); 6681 } 6682 } 6683 return resolveInfos; 6684 } 6685 6686 /** 6687 * Filters out ephemeral activities. 6688 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6689 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6690 * 6691 * @param resolveInfos The pre-filtered list of resolved activities 6692 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6693 * is performed. 6694 * @return A filtered list of resolved activities. 6695 */ 6696 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6697 String ephemeralPkgName) { 6698 // TODO: When adding on-demand split support for non-instant apps, remove this check 6699 // and always apply post filtering 6700 if (ephemeralPkgName == null) { 6701 return resolveInfos; 6702 } 6703 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6704 final ResolveInfo info = resolveInfos.get(i); 6705 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6706 // allow activities that are defined in the provided package 6707 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6708 if (info.activityInfo.splitName != null 6709 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6710 info.activityInfo.splitName)) { 6711 // requested activity is defined in a split that hasn't been installed yet. 6712 // add the installer to the resolve list 6713 if (DEBUG_EPHEMERAL) { 6714 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6715 } 6716 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6717 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6718 info.activityInfo.packageName, info.activityInfo.splitName, 6719 info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/); 6720 // make sure this resolver is the default 6721 installerInfo.isDefault = true; 6722 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6723 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6724 // add a non-generic filter 6725 installerInfo.filter = new IntentFilter(); 6726 // load resources from the correct package 6727 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6728 resolveInfos.set(i, installerInfo); 6729 } 6730 continue; 6731 } 6732 // allow activities that have been explicitly exposed to ephemeral apps 6733 if (!isEphemeralApp 6734 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6735 continue; 6736 } 6737 resolveInfos.remove(i); 6738 } 6739 return resolveInfos; 6740 } 6741 6742 /** 6743 * @param resolveInfos list of resolve infos in descending priority order 6744 * @return if the list contains a resolve info with non-negative priority 6745 */ 6746 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6747 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6748 } 6749 6750 private static boolean hasWebURI(Intent intent) { 6751 if (intent.getData() == null) { 6752 return false; 6753 } 6754 final String scheme = intent.getScheme(); 6755 if (TextUtils.isEmpty(scheme)) { 6756 return false; 6757 } 6758 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6759 } 6760 6761 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6762 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6763 int userId) { 6764 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6765 6766 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6767 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6768 candidates.size()); 6769 } 6770 6771 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6772 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6773 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6774 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6775 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6776 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6777 6778 synchronized (mPackages) { 6779 final int count = candidates.size(); 6780 // First, try to use linked apps. Partition the candidates into four lists: 6781 // one for the final results, one for the "do not use ever", one for "undefined status" 6782 // and finally one for "browser app type". 6783 for (int n=0; n<count; n++) { 6784 ResolveInfo info = candidates.get(n); 6785 String packageName = info.activityInfo.packageName; 6786 PackageSetting ps = mSettings.mPackages.get(packageName); 6787 if (ps != null) { 6788 // Add to the special match all list (Browser use case) 6789 if (info.handleAllWebDataURI) { 6790 matchAllList.add(info); 6791 continue; 6792 } 6793 // Try to get the status from User settings first 6794 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6795 int status = (int)(packedStatus >> 32); 6796 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6797 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6798 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6799 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6800 + " : linkgen=" + linkGeneration); 6801 } 6802 // Use link-enabled generation as preferredOrder, i.e. 6803 // prefer newly-enabled over earlier-enabled. 6804 info.preferredOrder = linkGeneration; 6805 alwaysList.add(info); 6806 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6807 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6808 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6809 } 6810 neverList.add(info); 6811 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6812 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6813 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6814 } 6815 alwaysAskList.add(info); 6816 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6817 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6818 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6819 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6820 } 6821 undefinedList.add(info); 6822 } 6823 } 6824 } 6825 6826 // We'll want to include browser possibilities in a few cases 6827 boolean includeBrowser = false; 6828 6829 // First try to add the "always" resolution(s) for the current user, if any 6830 if (alwaysList.size() > 0) { 6831 result.addAll(alwaysList); 6832 } else { 6833 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6834 result.addAll(undefinedList); 6835 // Maybe add one for the other profile. 6836 if (xpDomainInfo != null && ( 6837 xpDomainInfo.bestDomainVerificationStatus 6838 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6839 result.add(xpDomainInfo.resolveInfo); 6840 } 6841 includeBrowser = true; 6842 } 6843 6844 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6845 // If there were 'always' entries their preferred order has been set, so we also 6846 // back that off to make the alternatives equivalent 6847 if (alwaysAskList.size() > 0) { 6848 for (ResolveInfo i : result) { 6849 i.preferredOrder = 0; 6850 } 6851 result.addAll(alwaysAskList); 6852 includeBrowser = true; 6853 } 6854 6855 if (includeBrowser) { 6856 // Also add browsers (all of them or only the default one) 6857 if (DEBUG_DOMAIN_VERIFICATION) { 6858 Slog.v(TAG, " ...including browsers in candidate set"); 6859 } 6860 if ((matchFlags & MATCH_ALL) != 0) { 6861 result.addAll(matchAllList); 6862 } else { 6863 // Browser/generic handling case. If there's a default browser, go straight 6864 // to that (but only if there is no other higher-priority match). 6865 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6866 int maxMatchPrio = 0; 6867 ResolveInfo defaultBrowserMatch = null; 6868 final int numCandidates = matchAllList.size(); 6869 for (int n = 0; n < numCandidates; n++) { 6870 ResolveInfo info = matchAllList.get(n); 6871 // track the highest overall match priority... 6872 if (info.priority > maxMatchPrio) { 6873 maxMatchPrio = info.priority; 6874 } 6875 // ...and the highest-priority default browser match 6876 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6877 if (defaultBrowserMatch == null 6878 || (defaultBrowserMatch.priority < info.priority)) { 6879 if (debug) { 6880 Slog.v(TAG, "Considering default browser match " + info); 6881 } 6882 defaultBrowserMatch = info; 6883 } 6884 } 6885 } 6886 if (defaultBrowserMatch != null 6887 && defaultBrowserMatch.priority >= maxMatchPrio 6888 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6889 { 6890 if (debug) { 6891 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6892 } 6893 result.add(defaultBrowserMatch); 6894 } else { 6895 result.addAll(matchAllList); 6896 } 6897 } 6898 6899 // If there is nothing selected, add all candidates and remove the ones that the user 6900 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6901 if (result.size() == 0) { 6902 result.addAll(candidates); 6903 result.removeAll(neverList); 6904 } 6905 } 6906 } 6907 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6908 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6909 result.size()); 6910 for (ResolveInfo info : result) { 6911 Slog.v(TAG, " + " + info.activityInfo); 6912 } 6913 } 6914 return result; 6915 } 6916 6917 // Returns a packed value as a long: 6918 // 6919 // high 'int'-sized word: link status: undefined/ask/never/always. 6920 // low 'int'-sized word: relative priority among 'always' results. 6921 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6922 long result = ps.getDomainVerificationStatusForUser(userId); 6923 // if none available, get the master status 6924 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6925 if (ps.getIntentFilterVerificationInfo() != null) { 6926 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6927 } 6928 } 6929 return result; 6930 } 6931 6932 private ResolveInfo querySkipCurrentProfileIntents( 6933 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6934 int flags, int sourceUserId) { 6935 if (matchingFilters != null) { 6936 int size = matchingFilters.size(); 6937 for (int i = 0; i < size; i ++) { 6938 CrossProfileIntentFilter filter = matchingFilters.get(i); 6939 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6940 // Checking if there are activities in the target user that can handle the 6941 // intent. 6942 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6943 resolvedType, flags, sourceUserId); 6944 if (resolveInfo != null) { 6945 return resolveInfo; 6946 } 6947 } 6948 } 6949 } 6950 return null; 6951 } 6952 6953 // Return matching ResolveInfo in target user if any. 6954 private ResolveInfo queryCrossProfileIntents( 6955 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6956 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6957 if (matchingFilters != null) { 6958 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6959 // match the same intent. For performance reasons, it is better not to 6960 // run queryIntent twice for the same userId 6961 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6962 int size = matchingFilters.size(); 6963 for (int i = 0; i < size; i++) { 6964 CrossProfileIntentFilter filter = matchingFilters.get(i); 6965 int targetUserId = filter.getTargetUserId(); 6966 boolean skipCurrentProfile = 6967 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6968 boolean skipCurrentProfileIfNoMatchFound = 6969 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6970 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6971 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6972 // Checking if there are activities in the target user that can handle the 6973 // intent. 6974 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6975 resolvedType, flags, sourceUserId); 6976 if (resolveInfo != null) return resolveInfo; 6977 alreadyTriedUserIds.put(targetUserId, true); 6978 } 6979 } 6980 } 6981 return null; 6982 } 6983 6984 /** 6985 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6986 * will forward the intent to the filter's target user. 6987 * Otherwise, returns null. 6988 */ 6989 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6990 String resolvedType, int flags, int sourceUserId) { 6991 int targetUserId = filter.getTargetUserId(); 6992 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6993 resolvedType, flags, targetUserId); 6994 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6995 // If all the matches in the target profile are suspended, return null. 6996 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6997 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6998 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6999 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7000 targetUserId); 7001 } 7002 } 7003 } 7004 return null; 7005 } 7006 7007 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7008 int sourceUserId, int targetUserId) { 7009 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7010 long ident = Binder.clearCallingIdentity(); 7011 boolean targetIsProfile; 7012 try { 7013 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7014 } finally { 7015 Binder.restoreCallingIdentity(ident); 7016 } 7017 String className; 7018 if (targetIsProfile) { 7019 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7020 } else { 7021 className = FORWARD_INTENT_TO_PARENT; 7022 } 7023 ComponentName forwardingActivityComponentName = new ComponentName( 7024 mAndroidApplication.packageName, className); 7025 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7026 sourceUserId); 7027 if (!targetIsProfile) { 7028 forwardingActivityInfo.showUserIcon = targetUserId; 7029 forwardingResolveInfo.noResourceId = true; 7030 } 7031 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7032 forwardingResolveInfo.priority = 0; 7033 forwardingResolveInfo.preferredOrder = 0; 7034 forwardingResolveInfo.match = 0; 7035 forwardingResolveInfo.isDefault = true; 7036 forwardingResolveInfo.filter = filter; 7037 forwardingResolveInfo.targetUserId = targetUserId; 7038 return forwardingResolveInfo; 7039 } 7040 7041 @Override 7042 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7043 Intent[] specifics, String[] specificTypes, Intent intent, 7044 String resolvedType, int flags, int userId) { 7045 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7046 specificTypes, intent, resolvedType, flags, userId)); 7047 } 7048 7049 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7050 Intent[] specifics, String[] specificTypes, Intent intent, 7051 String resolvedType, int flags, int userId) { 7052 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7053 final int callingUid = Binder.getCallingUid(); 7054 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7055 false /*includeInstantApps*/); 7056 enforceCrossUserPermission(callingUid, userId, 7057 false /*requireFullPermission*/, false /*checkShell*/, 7058 "query intent activity options"); 7059 final String resultsAction = intent.getAction(); 7060 7061 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7062 | PackageManager.GET_RESOLVED_FILTER, userId); 7063 7064 if (DEBUG_INTENT_MATCHING) { 7065 Log.v(TAG, "Query " + intent + ": " + results); 7066 } 7067 7068 int specificsPos = 0; 7069 int N; 7070 7071 // todo: note that the algorithm used here is O(N^2). This 7072 // isn't a problem in our current environment, but if we start running 7073 // into situations where we have more than 5 or 10 matches then this 7074 // should probably be changed to something smarter... 7075 7076 // First we go through and resolve each of the specific items 7077 // that were supplied, taking care of removing any corresponding 7078 // duplicate items in the generic resolve list. 7079 if (specifics != null) { 7080 for (int i=0; i<specifics.length; i++) { 7081 final Intent sintent = specifics[i]; 7082 if (sintent == null) { 7083 continue; 7084 } 7085 7086 if (DEBUG_INTENT_MATCHING) { 7087 Log.v(TAG, "Specific #" + i + ": " + sintent); 7088 } 7089 7090 String action = sintent.getAction(); 7091 if (resultsAction != null && resultsAction.equals(action)) { 7092 // If this action was explicitly requested, then don't 7093 // remove things that have it. 7094 action = null; 7095 } 7096 7097 ResolveInfo ri = null; 7098 ActivityInfo ai = null; 7099 7100 ComponentName comp = sintent.getComponent(); 7101 if (comp == null) { 7102 ri = resolveIntent( 7103 sintent, 7104 specificTypes != null ? specificTypes[i] : null, 7105 flags, userId); 7106 if (ri == null) { 7107 continue; 7108 } 7109 if (ri == mResolveInfo) { 7110 // ACK! Must do something better with this. 7111 } 7112 ai = ri.activityInfo; 7113 comp = new ComponentName(ai.applicationInfo.packageName, 7114 ai.name); 7115 } else { 7116 ai = getActivityInfo(comp, flags, userId); 7117 if (ai == null) { 7118 continue; 7119 } 7120 } 7121 7122 // Look for any generic query activities that are duplicates 7123 // of this specific one, and remove them from the results. 7124 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7125 N = results.size(); 7126 int j; 7127 for (j=specificsPos; j<N; j++) { 7128 ResolveInfo sri = results.get(j); 7129 if ((sri.activityInfo.name.equals(comp.getClassName()) 7130 && sri.activityInfo.applicationInfo.packageName.equals( 7131 comp.getPackageName())) 7132 || (action != null && sri.filter.matchAction(action))) { 7133 results.remove(j); 7134 if (DEBUG_INTENT_MATCHING) Log.v( 7135 TAG, "Removing duplicate item from " + j 7136 + " due to specific " + specificsPos); 7137 if (ri == null) { 7138 ri = sri; 7139 } 7140 j--; 7141 N--; 7142 } 7143 } 7144 7145 // Add this specific item to its proper place. 7146 if (ri == null) { 7147 ri = new ResolveInfo(); 7148 ri.activityInfo = ai; 7149 } 7150 results.add(specificsPos, ri); 7151 ri.specificIndex = i; 7152 specificsPos++; 7153 } 7154 } 7155 7156 // Now we go through the remaining generic results and remove any 7157 // duplicate actions that are found here. 7158 N = results.size(); 7159 for (int i=specificsPos; i<N-1; i++) { 7160 final ResolveInfo rii = results.get(i); 7161 if (rii.filter == null) { 7162 continue; 7163 } 7164 7165 // Iterate over all of the actions of this result's intent 7166 // filter... typically this should be just one. 7167 final Iterator<String> it = rii.filter.actionsIterator(); 7168 if (it == null) { 7169 continue; 7170 } 7171 while (it.hasNext()) { 7172 final String action = it.next(); 7173 if (resultsAction != null && resultsAction.equals(action)) { 7174 // If this action was explicitly requested, then don't 7175 // remove things that have it. 7176 continue; 7177 } 7178 for (int j=i+1; j<N; j++) { 7179 final ResolveInfo rij = results.get(j); 7180 if (rij.filter != null && rij.filter.hasAction(action)) { 7181 results.remove(j); 7182 if (DEBUG_INTENT_MATCHING) Log.v( 7183 TAG, "Removing duplicate item from " + j 7184 + " due to action " + action + " at " + i); 7185 j--; 7186 N--; 7187 } 7188 } 7189 } 7190 7191 // If the caller didn't request filter information, drop it now 7192 // so we don't have to marshall/unmarshall it. 7193 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7194 rii.filter = null; 7195 } 7196 } 7197 7198 // Filter out the caller activity if so requested. 7199 if (caller != null) { 7200 N = results.size(); 7201 for (int i=0; i<N; i++) { 7202 ActivityInfo ainfo = results.get(i).activityInfo; 7203 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7204 && caller.getClassName().equals(ainfo.name)) { 7205 results.remove(i); 7206 break; 7207 } 7208 } 7209 } 7210 7211 // If the caller didn't request filter information, 7212 // drop them now so we don't have to 7213 // marshall/unmarshall it. 7214 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7215 N = results.size(); 7216 for (int i=0; i<N; i++) { 7217 results.get(i).filter = null; 7218 } 7219 } 7220 7221 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7222 return results; 7223 } 7224 7225 @Override 7226 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7227 String resolvedType, int flags, int userId) { 7228 return new ParceledListSlice<>( 7229 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7230 } 7231 7232 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7233 String resolvedType, int flags, int userId) { 7234 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7235 final int callingUid = Binder.getCallingUid(); 7236 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7237 false /*includeInstantApps*/); 7238 ComponentName comp = intent.getComponent(); 7239 if (comp == null) { 7240 if (intent.getSelector() != null) { 7241 intent = intent.getSelector(); 7242 comp = intent.getComponent(); 7243 } 7244 } 7245 if (comp != null) { 7246 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7247 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7248 if (ai != null) { 7249 ResolveInfo ri = new ResolveInfo(); 7250 ri.activityInfo = ai; 7251 list.add(ri); 7252 } 7253 return list; 7254 } 7255 7256 // reader 7257 synchronized (mPackages) { 7258 String pkgName = intent.getPackage(); 7259 if (pkgName == null) { 7260 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7261 } 7262 final PackageParser.Package pkg = mPackages.get(pkgName); 7263 if (pkg != null) { 7264 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7265 userId); 7266 } 7267 return Collections.emptyList(); 7268 } 7269 } 7270 7271 @Override 7272 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7273 final int callingUid = Binder.getCallingUid(); 7274 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7275 } 7276 7277 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7278 int userId, int callingUid) { 7279 if (!sUserManager.exists(userId)) return null; 7280 flags = updateFlagsForResolve( 7281 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7282 List<ResolveInfo> query = queryIntentServicesInternal( 7283 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7284 if (query != null) { 7285 if (query.size() >= 1) { 7286 // If there is more than one service with the same priority, 7287 // just arbitrarily pick the first one. 7288 return query.get(0); 7289 } 7290 } 7291 return null; 7292 } 7293 7294 @Override 7295 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7296 String resolvedType, int flags, int userId) { 7297 final int callingUid = Binder.getCallingUid(); 7298 return new ParceledListSlice<>(queryIntentServicesInternal( 7299 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7300 } 7301 7302 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7303 String resolvedType, int flags, int userId, int callingUid, 7304 boolean includeInstantApps) { 7305 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7306 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7307 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7308 ComponentName comp = intent.getComponent(); 7309 if (comp == null) { 7310 if (intent.getSelector() != null) { 7311 intent = intent.getSelector(); 7312 comp = intent.getComponent(); 7313 } 7314 } 7315 if (comp != null) { 7316 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7317 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7318 if (si != null) { 7319 // When specifying an explicit component, we prevent the service from being 7320 // used when either 1) the service is in an instant application and the 7321 // caller is not the same instant application or 2) the calling package is 7322 // ephemeral and the activity is not visible to ephemeral applications. 7323 final boolean matchInstantApp = 7324 (flags & PackageManager.MATCH_INSTANT) != 0; 7325 final boolean matchVisibleToInstantAppOnly = 7326 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7327 final boolean isCallerInstantApp = 7328 instantAppPkgName != null; 7329 final boolean isTargetSameInstantApp = 7330 comp.getPackageName().equals(instantAppPkgName); 7331 final boolean isTargetInstantApp = 7332 (si.applicationInfo.privateFlags 7333 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7334 final boolean isTargetHiddenFromInstantApp = 7335 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7336 final boolean blockResolution = 7337 !isTargetSameInstantApp 7338 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7339 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7340 && isTargetHiddenFromInstantApp)); 7341 if (!blockResolution) { 7342 final ResolveInfo ri = new ResolveInfo(); 7343 ri.serviceInfo = si; 7344 list.add(ri); 7345 } 7346 } 7347 return list; 7348 } 7349 7350 // reader 7351 synchronized (mPackages) { 7352 String pkgName = intent.getPackage(); 7353 if (pkgName == null) { 7354 return applyPostServiceResolutionFilter( 7355 mServices.queryIntent(intent, resolvedType, flags, userId), 7356 instantAppPkgName); 7357 } 7358 final PackageParser.Package pkg = mPackages.get(pkgName); 7359 if (pkg != null) { 7360 return applyPostServiceResolutionFilter( 7361 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7362 userId), 7363 instantAppPkgName); 7364 } 7365 return Collections.emptyList(); 7366 } 7367 } 7368 7369 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7370 String instantAppPkgName) { 7371 // TODO: When adding on-demand split support for non-instant apps, remove this check 7372 // and always apply post filtering 7373 if (instantAppPkgName == null) { 7374 return resolveInfos; 7375 } 7376 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7377 final ResolveInfo info = resolveInfos.get(i); 7378 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7379 // allow services that are defined in the provided package 7380 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7381 if (info.serviceInfo.splitName != null 7382 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7383 info.serviceInfo.splitName)) { 7384 // requested service is defined in a split that hasn't been installed yet. 7385 // add the installer to the resolve list 7386 if (DEBUG_EPHEMERAL) { 7387 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7388 } 7389 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7390 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7391 info.serviceInfo.packageName, info.serviceInfo.splitName, 7392 info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/); 7393 // make sure this resolver is the default 7394 installerInfo.isDefault = true; 7395 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7396 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7397 // add a non-generic filter 7398 installerInfo.filter = new IntentFilter(); 7399 // load resources from the correct package 7400 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7401 resolveInfos.set(i, installerInfo); 7402 } 7403 continue; 7404 } 7405 // allow services that have been explicitly exposed to ephemeral apps 7406 if (!isEphemeralApp 7407 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7408 continue; 7409 } 7410 resolveInfos.remove(i); 7411 } 7412 return resolveInfos; 7413 } 7414 7415 @Override 7416 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7417 String resolvedType, int flags, int userId) { 7418 return new ParceledListSlice<>( 7419 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7420 } 7421 7422 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7423 Intent intent, String resolvedType, int flags, int userId) { 7424 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7425 final int callingUid = Binder.getCallingUid(); 7426 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7427 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7428 false /*includeInstantApps*/); 7429 ComponentName comp = intent.getComponent(); 7430 if (comp == null) { 7431 if (intent.getSelector() != null) { 7432 intent = intent.getSelector(); 7433 comp = intent.getComponent(); 7434 } 7435 } 7436 if (comp != null) { 7437 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7438 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7439 if (pi != null) { 7440 // When specifying an explicit component, we prevent the provider from being 7441 // used when either 1) the provider is in an instant application and the 7442 // caller is not the same instant application or 2) the calling package is an 7443 // instant application and the provider is not visible to instant applications. 7444 final boolean matchInstantApp = 7445 (flags & PackageManager.MATCH_INSTANT) != 0; 7446 final boolean matchVisibleToInstantAppOnly = 7447 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7448 final boolean isCallerInstantApp = 7449 instantAppPkgName != null; 7450 final boolean isTargetSameInstantApp = 7451 comp.getPackageName().equals(instantAppPkgName); 7452 final boolean isTargetInstantApp = 7453 (pi.applicationInfo.privateFlags 7454 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7455 final boolean isTargetHiddenFromInstantApp = 7456 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7457 final boolean blockResolution = 7458 !isTargetSameInstantApp 7459 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7460 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7461 && isTargetHiddenFromInstantApp)); 7462 if (!blockResolution) { 7463 final ResolveInfo ri = new ResolveInfo(); 7464 ri.providerInfo = pi; 7465 list.add(ri); 7466 } 7467 } 7468 return list; 7469 } 7470 7471 // reader 7472 synchronized (mPackages) { 7473 String pkgName = intent.getPackage(); 7474 if (pkgName == null) { 7475 return applyPostContentProviderResolutionFilter( 7476 mProviders.queryIntent(intent, resolvedType, flags, userId), 7477 instantAppPkgName); 7478 } 7479 final PackageParser.Package pkg = mPackages.get(pkgName); 7480 if (pkg != null) { 7481 return applyPostContentProviderResolutionFilter( 7482 mProviders.queryIntentForPackage( 7483 intent, resolvedType, flags, pkg.providers, userId), 7484 instantAppPkgName); 7485 } 7486 return Collections.emptyList(); 7487 } 7488 } 7489 7490 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7491 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7492 // TODO: When adding on-demand split support for non-instant applications, remove 7493 // this check and always apply post filtering 7494 if (instantAppPkgName == null) { 7495 return resolveInfos; 7496 } 7497 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7498 final ResolveInfo info = resolveInfos.get(i); 7499 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7500 // allow providers that are defined in the provided package 7501 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7502 if (info.providerInfo.splitName != null 7503 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7504 info.providerInfo.splitName)) { 7505 // requested provider is defined in a split that hasn't been installed yet. 7506 // add the installer to the resolve list 7507 if (DEBUG_EPHEMERAL) { 7508 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7509 } 7510 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7511 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7512 info.providerInfo.packageName, info.providerInfo.splitName, 7513 info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/); 7514 // make sure this resolver is the default 7515 installerInfo.isDefault = true; 7516 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7517 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7518 // add a non-generic filter 7519 installerInfo.filter = new IntentFilter(); 7520 // load resources from the correct package 7521 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7522 resolveInfos.set(i, installerInfo); 7523 } 7524 continue; 7525 } 7526 // allow providers that have been explicitly exposed to instant applications 7527 if (!isEphemeralApp 7528 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7529 continue; 7530 } 7531 resolveInfos.remove(i); 7532 } 7533 return resolveInfos; 7534 } 7535 7536 @Override 7537 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7538 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7539 flags = updateFlagsForPackage(flags, userId, null); 7540 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7541 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7542 true /* requireFullPermission */, false /* checkShell */, 7543 "get installed packages"); 7544 7545 // writer 7546 synchronized (mPackages) { 7547 ArrayList<PackageInfo> list; 7548 if (listUninstalled) { 7549 list = new ArrayList<>(mSettings.mPackages.size()); 7550 for (PackageSetting ps : mSettings.mPackages.values()) { 7551 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7552 continue; 7553 } 7554 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7555 if (pi != null) { 7556 list.add(pi); 7557 } 7558 } 7559 } else { 7560 list = new ArrayList<>(mPackages.size()); 7561 for (PackageParser.Package p : mPackages.values()) { 7562 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7563 Binder.getCallingUid(), userId)) { 7564 continue; 7565 } 7566 final PackageInfo pi = generatePackageInfo((PackageSetting) 7567 p.mExtras, flags, userId); 7568 if (pi != null) { 7569 list.add(pi); 7570 } 7571 } 7572 } 7573 7574 return new ParceledListSlice<>(list); 7575 } 7576 } 7577 7578 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7579 String[] permissions, boolean[] tmp, int flags, int userId) { 7580 int numMatch = 0; 7581 final PermissionsState permissionsState = ps.getPermissionsState(); 7582 for (int i=0; i<permissions.length; i++) { 7583 final String permission = permissions[i]; 7584 if (permissionsState.hasPermission(permission, userId)) { 7585 tmp[i] = true; 7586 numMatch++; 7587 } else { 7588 tmp[i] = false; 7589 } 7590 } 7591 if (numMatch == 0) { 7592 return; 7593 } 7594 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7595 7596 // The above might return null in cases of uninstalled apps or install-state 7597 // skew across users/profiles. 7598 if (pi != null) { 7599 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7600 if (numMatch == permissions.length) { 7601 pi.requestedPermissions = permissions; 7602 } else { 7603 pi.requestedPermissions = new String[numMatch]; 7604 numMatch = 0; 7605 for (int i=0; i<permissions.length; i++) { 7606 if (tmp[i]) { 7607 pi.requestedPermissions[numMatch] = permissions[i]; 7608 numMatch++; 7609 } 7610 } 7611 } 7612 } 7613 list.add(pi); 7614 } 7615 } 7616 7617 @Override 7618 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7619 String[] permissions, int flags, int userId) { 7620 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7621 flags = updateFlagsForPackage(flags, userId, permissions); 7622 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7623 true /* requireFullPermission */, false /* checkShell */, 7624 "get packages holding permissions"); 7625 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7626 7627 // writer 7628 synchronized (mPackages) { 7629 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7630 boolean[] tmpBools = new boolean[permissions.length]; 7631 if (listUninstalled) { 7632 for (PackageSetting ps : mSettings.mPackages.values()) { 7633 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7634 userId); 7635 } 7636 } else { 7637 for (PackageParser.Package pkg : mPackages.values()) { 7638 PackageSetting ps = (PackageSetting)pkg.mExtras; 7639 if (ps != null) { 7640 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7641 userId); 7642 } 7643 } 7644 } 7645 7646 return new ParceledListSlice<PackageInfo>(list); 7647 } 7648 } 7649 7650 @Override 7651 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7652 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7653 flags = updateFlagsForApplication(flags, userId, null); 7654 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7655 7656 // writer 7657 synchronized (mPackages) { 7658 ArrayList<ApplicationInfo> list; 7659 if (listUninstalled) { 7660 list = new ArrayList<>(mSettings.mPackages.size()); 7661 for (PackageSetting ps : mSettings.mPackages.values()) { 7662 ApplicationInfo ai; 7663 int effectiveFlags = flags; 7664 if (ps.isSystem()) { 7665 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7666 } 7667 if (ps.pkg != null) { 7668 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7669 continue; 7670 } 7671 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7672 ps.readUserState(userId), userId); 7673 if (ai != null) { 7674 rebaseEnabledOverlays(ai, userId); 7675 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7676 } 7677 } else { 7678 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7679 // and already converts to externally visible package name 7680 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7681 Binder.getCallingUid(), effectiveFlags, userId); 7682 } 7683 if (ai != null) { 7684 list.add(ai); 7685 } 7686 } 7687 } else { 7688 list = new ArrayList<>(mPackages.size()); 7689 for (PackageParser.Package p : mPackages.values()) { 7690 if (p.mExtras != null) { 7691 PackageSetting ps = (PackageSetting) p.mExtras; 7692 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7693 continue; 7694 } 7695 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7696 ps.readUserState(userId), userId); 7697 if (ai != null) { 7698 rebaseEnabledOverlays(ai, userId); 7699 ai.packageName = resolveExternalPackageNameLPr(p); 7700 list.add(ai); 7701 } 7702 } 7703 } 7704 } 7705 7706 return new ParceledListSlice<>(list); 7707 } 7708 } 7709 7710 @Override 7711 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7712 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7713 return null; 7714 } 7715 7716 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7717 "getEphemeralApplications"); 7718 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7719 true /* requireFullPermission */, false /* checkShell */, 7720 "getEphemeralApplications"); 7721 synchronized (mPackages) { 7722 List<InstantAppInfo> instantApps = mInstantAppRegistry 7723 .getInstantAppsLPr(userId); 7724 if (instantApps != null) { 7725 return new ParceledListSlice<>(instantApps); 7726 } 7727 } 7728 return null; 7729 } 7730 7731 @Override 7732 public boolean isInstantApp(String packageName, int userId) { 7733 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7734 true /* requireFullPermission */, false /* checkShell */, 7735 "isInstantApp"); 7736 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7737 return false; 7738 } 7739 int uid = Binder.getCallingUid(); 7740 if (Process.isIsolated(uid)) { 7741 uid = mIsolatedOwners.get(uid); 7742 } 7743 7744 synchronized (mPackages) { 7745 final PackageSetting ps = mSettings.mPackages.get(packageName); 7746 PackageParser.Package pkg = mPackages.get(packageName); 7747 final boolean returnAllowed = 7748 ps != null 7749 && (isCallerSameApp(packageName, uid) 7750 || mContext.checkCallingOrSelfPermission( 7751 android.Manifest.permission.ACCESS_INSTANT_APPS) 7752 == PERMISSION_GRANTED 7753 || mInstantAppRegistry.isInstantAccessGranted( 7754 userId, UserHandle.getAppId(uid), ps.appId)); 7755 if (returnAllowed) { 7756 return ps.getInstantApp(userId); 7757 } 7758 } 7759 return false; 7760 } 7761 7762 @Override 7763 public byte[] getInstantAppCookie(String packageName, int userId) { 7764 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7765 return null; 7766 } 7767 7768 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7769 true /* requireFullPermission */, false /* checkShell */, 7770 "getInstantAppCookie"); 7771 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7772 return null; 7773 } 7774 synchronized (mPackages) { 7775 return mInstantAppRegistry.getInstantAppCookieLPw( 7776 packageName, userId); 7777 } 7778 } 7779 7780 @Override 7781 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7782 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7783 return true; 7784 } 7785 7786 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7787 true /* requireFullPermission */, true /* checkShell */, 7788 "setInstantAppCookie"); 7789 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7790 return false; 7791 } 7792 synchronized (mPackages) { 7793 return mInstantAppRegistry.setInstantAppCookieLPw( 7794 packageName, cookie, userId); 7795 } 7796 } 7797 7798 @Override 7799 public Bitmap getInstantAppIcon(String packageName, int userId) { 7800 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7801 return null; 7802 } 7803 7804 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7805 "getInstantAppIcon"); 7806 7807 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7808 true /* requireFullPermission */, false /* checkShell */, 7809 "getInstantAppIcon"); 7810 7811 synchronized (mPackages) { 7812 return mInstantAppRegistry.getInstantAppIconLPw( 7813 packageName, userId); 7814 } 7815 } 7816 7817 private boolean isCallerSameApp(String packageName, int uid) { 7818 PackageParser.Package pkg = mPackages.get(packageName); 7819 return pkg != null 7820 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7821 } 7822 7823 @Override 7824 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7825 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7826 } 7827 7828 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7829 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7830 7831 // reader 7832 synchronized (mPackages) { 7833 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7834 final int userId = UserHandle.getCallingUserId(); 7835 while (i.hasNext()) { 7836 final PackageParser.Package p = i.next(); 7837 if (p.applicationInfo == null) continue; 7838 7839 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7840 && !p.applicationInfo.isDirectBootAware(); 7841 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7842 && p.applicationInfo.isDirectBootAware(); 7843 7844 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7845 && (!mSafeMode || isSystemApp(p)) 7846 && (matchesUnaware || matchesAware)) { 7847 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7848 if (ps != null) { 7849 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7850 ps.readUserState(userId), userId); 7851 if (ai != null) { 7852 rebaseEnabledOverlays(ai, userId); 7853 finalList.add(ai); 7854 } 7855 } 7856 } 7857 } 7858 } 7859 7860 return finalList; 7861 } 7862 7863 @Override 7864 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7865 if (!sUserManager.exists(userId)) return null; 7866 flags = updateFlagsForComponent(flags, userId, name); 7867 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 7868 // reader 7869 synchronized (mPackages) { 7870 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7871 PackageSetting ps = provider != null 7872 ? mSettings.mPackages.get(provider.owner.packageName) 7873 : null; 7874 if (ps != null) { 7875 final boolean isInstantApp = ps.getInstantApp(userId); 7876 // normal application; filter out instant application provider 7877 if (instantAppPkgName == null && isInstantApp) { 7878 return null; 7879 } 7880 // instant application; filter out other instant applications 7881 if (instantAppPkgName != null 7882 && isInstantApp 7883 && !provider.owner.packageName.equals(instantAppPkgName)) { 7884 return null; 7885 } 7886 // instant application; filter out non-exposed provider 7887 if (instantAppPkgName != null 7888 && !isInstantApp 7889 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 7890 return null; 7891 } 7892 // provider not enabled 7893 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 7894 return null; 7895 } 7896 return PackageParser.generateProviderInfo( 7897 provider, flags, ps.readUserState(userId), userId); 7898 } 7899 return null; 7900 } 7901 } 7902 7903 /** 7904 * @deprecated 7905 */ 7906 @Deprecated 7907 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7908 // reader 7909 synchronized (mPackages) { 7910 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7911 .entrySet().iterator(); 7912 final int userId = UserHandle.getCallingUserId(); 7913 while (i.hasNext()) { 7914 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7915 PackageParser.Provider p = entry.getValue(); 7916 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7917 7918 if (ps != null && p.syncable 7919 && (!mSafeMode || (p.info.applicationInfo.flags 7920 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7921 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7922 ps.readUserState(userId), userId); 7923 if (info != null) { 7924 outNames.add(entry.getKey()); 7925 outInfo.add(info); 7926 } 7927 } 7928 } 7929 } 7930 } 7931 7932 @Override 7933 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7934 int uid, int flags, String metaDataKey) { 7935 final int userId = processName != null ? UserHandle.getUserId(uid) 7936 : UserHandle.getCallingUserId(); 7937 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7938 flags = updateFlagsForComponent(flags, userId, processName); 7939 7940 ArrayList<ProviderInfo> finalList = null; 7941 // reader 7942 synchronized (mPackages) { 7943 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7944 while (i.hasNext()) { 7945 final PackageParser.Provider p = i.next(); 7946 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7947 if (ps != null && p.info.authority != null 7948 && (processName == null 7949 || (p.info.processName.equals(processName) 7950 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7951 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7952 7953 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7954 // parameter. 7955 if (metaDataKey != null 7956 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7957 continue; 7958 } 7959 7960 if (finalList == null) { 7961 finalList = new ArrayList<ProviderInfo>(3); 7962 } 7963 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7964 ps.readUserState(userId), userId); 7965 if (info != null) { 7966 finalList.add(info); 7967 } 7968 } 7969 } 7970 } 7971 7972 if (finalList != null) { 7973 Collections.sort(finalList, mProviderInitOrderSorter); 7974 return new ParceledListSlice<ProviderInfo>(finalList); 7975 } 7976 7977 return ParceledListSlice.emptyList(); 7978 } 7979 7980 @Override 7981 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7982 // reader 7983 synchronized (mPackages) { 7984 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7985 return PackageParser.generateInstrumentationInfo(i, flags); 7986 } 7987 } 7988 7989 @Override 7990 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7991 String targetPackage, int flags) { 7992 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7993 } 7994 7995 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7996 int flags) { 7997 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7998 7999 // reader 8000 synchronized (mPackages) { 8001 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8002 while (i.hasNext()) { 8003 final PackageParser.Instrumentation p = i.next(); 8004 if (targetPackage == null 8005 || targetPackage.equals(p.info.targetPackage)) { 8006 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8007 flags); 8008 if (ii != null) { 8009 finalList.add(ii); 8010 } 8011 } 8012 } 8013 } 8014 8015 return finalList; 8016 } 8017 8018 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 8019 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 8020 try { 8021 scanDirLI(dir, parseFlags, scanFlags, currentTime); 8022 } finally { 8023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8024 } 8025 } 8026 8027 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 8028 final File[] files = dir.listFiles(); 8029 if (ArrayUtils.isEmpty(files)) { 8030 Log.d(TAG, "No files in app dir " + dir); 8031 return; 8032 } 8033 8034 if (DEBUG_PACKAGE_SCANNING) { 8035 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 8036 + " flags=0x" + Integer.toHexString(parseFlags)); 8037 } 8038 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8039 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8040 mParallelPackageParserCallback); 8041 8042 // Submit files for parsing in parallel 8043 int fileCount = 0; 8044 for (File file : files) { 8045 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8046 && !PackageInstallerService.isStageName(file.getName()); 8047 if (!isPackage) { 8048 // Ignore entries which are not packages 8049 continue; 8050 } 8051 parallelPackageParser.submit(file, parseFlags); 8052 fileCount++; 8053 } 8054 8055 // Process results one by one 8056 for (; fileCount > 0; fileCount--) { 8057 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8058 Throwable throwable = parseResult.throwable; 8059 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8060 8061 if (throwable == null) { 8062 // Static shared libraries have synthetic package names 8063 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8064 renameStaticSharedLibraryPackage(parseResult.pkg); 8065 } 8066 try { 8067 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8068 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8069 currentTime, null); 8070 } 8071 } catch (PackageManagerException e) { 8072 errorCode = e.error; 8073 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8074 } 8075 } else if (throwable instanceof PackageParser.PackageParserException) { 8076 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8077 throwable; 8078 errorCode = e.error; 8079 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8080 } else { 8081 throw new IllegalStateException("Unexpected exception occurred while parsing " 8082 + parseResult.scanFile, throwable); 8083 } 8084 8085 // Delete invalid userdata apps 8086 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8087 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8088 logCriticalInfo(Log.WARN, 8089 "Deleting invalid package at " + parseResult.scanFile); 8090 removeCodePathLI(parseResult.scanFile); 8091 } 8092 } 8093 parallelPackageParser.close(); 8094 } 8095 8096 private static File getSettingsProblemFile() { 8097 File dataDir = Environment.getDataDirectory(); 8098 File systemDir = new File(dataDir, "system"); 8099 File fname = new File(systemDir, "uiderrors.txt"); 8100 return fname; 8101 } 8102 8103 static void reportSettingsProblem(int priority, String msg) { 8104 logCriticalInfo(priority, msg); 8105 } 8106 8107 public static void logCriticalInfo(int priority, String msg) { 8108 Slog.println(priority, TAG, msg); 8109 EventLogTags.writePmCriticalInfo(msg); 8110 try { 8111 File fname = getSettingsProblemFile(); 8112 FileOutputStream out = new FileOutputStream(fname, true); 8113 PrintWriter pw = new FastPrintWriter(out); 8114 SimpleDateFormat formatter = new SimpleDateFormat(); 8115 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8116 pw.println(dateString + ": " + msg); 8117 pw.close(); 8118 FileUtils.setPermissions( 8119 fname.toString(), 8120 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8121 -1, -1); 8122 } catch (java.io.IOException e) { 8123 } 8124 } 8125 8126 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8127 if (srcFile.isDirectory()) { 8128 final File baseFile = new File(pkg.baseCodePath); 8129 long maxModifiedTime = baseFile.lastModified(); 8130 if (pkg.splitCodePaths != null) { 8131 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8132 final File splitFile = new File(pkg.splitCodePaths[i]); 8133 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8134 } 8135 } 8136 return maxModifiedTime; 8137 } 8138 return srcFile.lastModified(); 8139 } 8140 8141 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8142 final int policyFlags) throws PackageManagerException { 8143 // When upgrading from pre-N MR1, verify the package time stamp using the package 8144 // directory and not the APK file. 8145 final long lastModifiedTime = mIsPreNMR1Upgrade 8146 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8147 if (ps != null 8148 && ps.codePath.equals(srcFile) 8149 && ps.timeStamp == lastModifiedTime 8150 && !isCompatSignatureUpdateNeeded(pkg) 8151 && !isRecoverSignatureUpdateNeeded(pkg)) { 8152 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8153 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8154 ArraySet<PublicKey> signingKs; 8155 synchronized (mPackages) { 8156 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8157 } 8158 if (ps.signatures.mSignatures != null 8159 && ps.signatures.mSignatures.length != 0 8160 && signingKs != null) { 8161 // Optimization: reuse the existing cached certificates 8162 // if the package appears to be unchanged. 8163 pkg.mSignatures = ps.signatures.mSignatures; 8164 pkg.mSigningKeys = signingKs; 8165 return; 8166 } 8167 8168 Slog.w(TAG, "PackageSetting for " + ps.name 8169 + " is missing signatures. Collecting certs again to recover them."); 8170 } else { 8171 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8172 } 8173 8174 try { 8175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8176 PackageParser.collectCertificates(pkg, policyFlags); 8177 } catch (PackageParserException e) { 8178 throw PackageManagerException.from(e); 8179 } finally { 8180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8181 } 8182 } 8183 8184 /** 8185 * Traces a package scan. 8186 * @see #scanPackageLI(File, int, int, long, UserHandle) 8187 */ 8188 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8189 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8190 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8191 try { 8192 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8193 } finally { 8194 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8195 } 8196 } 8197 8198 /** 8199 * Scans a package and returns the newly parsed package. 8200 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8201 */ 8202 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8203 long currentTime, UserHandle user) throws PackageManagerException { 8204 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8205 PackageParser pp = new PackageParser(); 8206 pp.setSeparateProcesses(mSeparateProcesses); 8207 pp.setOnlyCoreApps(mOnlyCore); 8208 pp.setDisplayMetrics(mMetrics); 8209 pp.setCallback(mPackageParserCallback); 8210 8211 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8212 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8213 } 8214 8215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8216 final PackageParser.Package pkg; 8217 try { 8218 pkg = pp.parsePackage(scanFile, parseFlags); 8219 } catch (PackageParserException e) { 8220 throw PackageManagerException.from(e); 8221 } finally { 8222 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8223 } 8224 8225 // Static shared libraries have synthetic package names 8226 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8227 renameStaticSharedLibraryPackage(pkg); 8228 } 8229 8230 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8231 } 8232 8233 /** 8234 * Scans a package and returns the newly parsed package. 8235 * @throws PackageManagerException on a parse error. 8236 */ 8237 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8238 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8239 throws PackageManagerException { 8240 // If the package has children and this is the first dive in the function 8241 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8242 // packages (parent and children) would be successfully scanned before the 8243 // actual scan since scanning mutates internal state and we want to atomically 8244 // install the package and its children. 8245 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8246 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8247 scanFlags |= SCAN_CHECK_ONLY; 8248 } 8249 } else { 8250 scanFlags &= ~SCAN_CHECK_ONLY; 8251 } 8252 8253 // Scan the parent 8254 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8255 scanFlags, currentTime, user); 8256 8257 // Scan the children 8258 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8259 for (int i = 0; i < childCount; i++) { 8260 PackageParser.Package childPackage = pkg.childPackages.get(i); 8261 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8262 currentTime, user); 8263 } 8264 8265 8266 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8267 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8268 } 8269 8270 return scannedPkg; 8271 } 8272 8273 /** 8274 * Scans a package and returns the newly parsed package. 8275 * @throws PackageManagerException on a parse error. 8276 */ 8277 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8278 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8279 throws PackageManagerException { 8280 PackageSetting ps = null; 8281 PackageSetting updatedPkg; 8282 // reader 8283 synchronized (mPackages) { 8284 // Look to see if we already know about this package. 8285 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8286 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8287 // This package has been renamed to its original name. Let's 8288 // use that. 8289 ps = mSettings.getPackageLPr(oldName); 8290 } 8291 // If there was no original package, see one for the real package name. 8292 if (ps == null) { 8293 ps = mSettings.getPackageLPr(pkg.packageName); 8294 } 8295 // Check to see if this package could be hiding/updating a system 8296 // package. Must look for it either under the original or real 8297 // package name depending on our state. 8298 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8299 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8300 8301 // If this is a package we don't know about on the system partition, we 8302 // may need to remove disabled child packages on the system partition 8303 // or may need to not add child packages if the parent apk is updated 8304 // on the data partition and no longer defines this child package. 8305 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8306 // If this is a parent package for an updated system app and this system 8307 // app got an OTA update which no longer defines some of the child packages 8308 // we have to prune them from the disabled system packages. 8309 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8310 if (disabledPs != null) { 8311 final int scannedChildCount = (pkg.childPackages != null) 8312 ? pkg.childPackages.size() : 0; 8313 final int disabledChildCount = disabledPs.childPackageNames != null 8314 ? disabledPs.childPackageNames.size() : 0; 8315 for (int i = 0; i < disabledChildCount; i++) { 8316 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8317 boolean disabledPackageAvailable = false; 8318 for (int j = 0; j < scannedChildCount; j++) { 8319 PackageParser.Package childPkg = pkg.childPackages.get(j); 8320 if (childPkg.packageName.equals(disabledChildPackageName)) { 8321 disabledPackageAvailable = true; 8322 break; 8323 } 8324 } 8325 if (!disabledPackageAvailable) { 8326 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8327 } 8328 } 8329 } 8330 } 8331 } 8332 8333 boolean updatedPkgBetter = false; 8334 // First check if this is a system package that may involve an update 8335 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8336 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8337 // it needs to drop FLAG_PRIVILEGED. 8338 if (locationIsPrivileged(scanFile)) { 8339 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8340 } else { 8341 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8342 } 8343 8344 if (ps != null && !ps.codePath.equals(scanFile)) { 8345 // The path has changed from what was last scanned... check the 8346 // version of the new path against what we have stored to determine 8347 // what to do. 8348 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8349 if (pkg.mVersionCode <= ps.versionCode) { 8350 // The system package has been updated and the code path does not match 8351 // Ignore entry. Skip it. 8352 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8353 + " ignored: updated version " + ps.versionCode 8354 + " better than this " + pkg.mVersionCode); 8355 if (!updatedPkg.codePath.equals(scanFile)) { 8356 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8357 + ps.name + " changing from " + updatedPkg.codePathString 8358 + " to " + scanFile); 8359 updatedPkg.codePath = scanFile; 8360 updatedPkg.codePathString = scanFile.toString(); 8361 updatedPkg.resourcePath = scanFile; 8362 updatedPkg.resourcePathString = scanFile.toString(); 8363 } 8364 updatedPkg.pkg = pkg; 8365 updatedPkg.versionCode = pkg.mVersionCode; 8366 8367 // Update the disabled system child packages to point to the package too. 8368 final int childCount = updatedPkg.childPackageNames != null 8369 ? updatedPkg.childPackageNames.size() : 0; 8370 for (int i = 0; i < childCount; i++) { 8371 String childPackageName = updatedPkg.childPackageNames.get(i); 8372 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8373 childPackageName); 8374 if (updatedChildPkg != null) { 8375 updatedChildPkg.pkg = pkg; 8376 updatedChildPkg.versionCode = pkg.mVersionCode; 8377 } 8378 } 8379 8380 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8381 + scanFile + " ignored: updated version " + ps.versionCode 8382 + " better than this " + pkg.mVersionCode); 8383 } else { 8384 // The current app on the system partition is better than 8385 // what we have updated to on the data partition; switch 8386 // back to the system partition version. 8387 // At this point, its safely assumed that package installation for 8388 // apps in system partition will go through. If not there won't be a working 8389 // version of the app 8390 // writer 8391 synchronized (mPackages) { 8392 // Just remove the loaded entries from package lists. 8393 mPackages.remove(ps.name); 8394 } 8395 8396 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8397 + " reverting from " + ps.codePathString 8398 + ": new version " + pkg.mVersionCode 8399 + " better than installed " + ps.versionCode); 8400 8401 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8402 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8403 synchronized (mInstallLock) { 8404 args.cleanUpResourcesLI(); 8405 } 8406 synchronized (mPackages) { 8407 mSettings.enableSystemPackageLPw(ps.name); 8408 } 8409 updatedPkgBetter = true; 8410 } 8411 } 8412 } 8413 8414 if (updatedPkg != null) { 8415 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8416 // initially 8417 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8418 8419 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8420 // flag set initially 8421 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8422 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8423 } 8424 } 8425 8426 // Verify certificates against what was last scanned 8427 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8428 8429 /* 8430 * A new system app appeared, but we already had a non-system one of the 8431 * same name installed earlier. 8432 */ 8433 boolean shouldHideSystemApp = false; 8434 if (updatedPkg == null && ps != null 8435 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8436 /* 8437 * Check to make sure the signatures match first. If they don't, 8438 * wipe the installed application and its data. 8439 */ 8440 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8441 != PackageManager.SIGNATURE_MATCH) { 8442 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8443 + " signatures don't match existing userdata copy; removing"); 8444 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8445 "scanPackageInternalLI")) { 8446 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8447 } 8448 ps = null; 8449 } else { 8450 /* 8451 * If the newly-added system app is an older version than the 8452 * already installed version, hide it. It will be scanned later 8453 * and re-added like an update. 8454 */ 8455 if (pkg.mVersionCode <= ps.versionCode) { 8456 shouldHideSystemApp = true; 8457 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8458 + " but new version " + pkg.mVersionCode + " better than installed " 8459 + ps.versionCode + "; hiding system"); 8460 } else { 8461 /* 8462 * The newly found system app is a newer version that the 8463 * one previously installed. Simply remove the 8464 * already-installed application and replace it with our own 8465 * while keeping the application data. 8466 */ 8467 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8468 + " reverting from " + ps.codePathString + ": new version " 8469 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8470 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8471 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8472 synchronized (mInstallLock) { 8473 args.cleanUpResourcesLI(); 8474 } 8475 } 8476 } 8477 } 8478 8479 // The apk is forward locked (not public) if its code and resources 8480 // are kept in different files. (except for app in either system or 8481 // vendor path). 8482 // TODO grab this value from PackageSettings 8483 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8484 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8485 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8486 } 8487 } 8488 8489 // TODO: extend to support forward-locked splits 8490 String resourcePath = null; 8491 String baseResourcePath = null; 8492 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8493 if (ps != null && ps.resourcePathString != null) { 8494 resourcePath = ps.resourcePathString; 8495 baseResourcePath = ps.resourcePathString; 8496 } else { 8497 // Should not happen at all. Just log an error. 8498 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8499 } 8500 } else { 8501 resourcePath = pkg.codePath; 8502 baseResourcePath = pkg.baseCodePath; 8503 } 8504 8505 // Set application objects path explicitly. 8506 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8507 pkg.setApplicationInfoCodePath(pkg.codePath); 8508 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8509 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8510 pkg.setApplicationInfoResourcePath(resourcePath); 8511 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8512 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8513 8514 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8515 if (ps != null && ps.getInstantApp(userId)) { 8516 scanFlags |= SCAN_AS_INSTANT_APP; 8517 } 8518 8519 // Note that we invoke the following method only if we are about to unpack an application 8520 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8521 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8522 8523 /* 8524 * If the system app should be overridden by a previously installed 8525 * data, hide the system app now and let the /data/app scan pick it up 8526 * again. 8527 */ 8528 if (shouldHideSystemApp) { 8529 synchronized (mPackages) { 8530 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8531 } 8532 } 8533 8534 return scannedPkg; 8535 } 8536 8537 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8538 // Derive the new package synthetic package name 8539 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8540 + pkg.staticSharedLibVersion); 8541 } 8542 8543 private static String fixProcessName(String defProcessName, 8544 String processName) { 8545 if (processName == null) { 8546 return defProcessName; 8547 } 8548 return processName; 8549 } 8550 8551 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8552 throws PackageManagerException { 8553 if (pkgSetting.signatures.mSignatures != null) { 8554 // Already existing package. Make sure signatures match 8555 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8556 == PackageManager.SIGNATURE_MATCH; 8557 if (!match) { 8558 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8559 == PackageManager.SIGNATURE_MATCH; 8560 } 8561 if (!match) { 8562 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8563 == PackageManager.SIGNATURE_MATCH; 8564 } 8565 if (!match) { 8566 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8567 + pkg.packageName + " signatures do not match the " 8568 + "previously installed version; ignoring!"); 8569 } 8570 } 8571 8572 // Check for shared user signatures 8573 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8574 // Already existing package. Make sure signatures match 8575 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8576 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8577 if (!match) { 8578 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8579 == PackageManager.SIGNATURE_MATCH; 8580 } 8581 if (!match) { 8582 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8583 == PackageManager.SIGNATURE_MATCH; 8584 } 8585 if (!match) { 8586 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8587 "Package " + pkg.packageName 8588 + " has no signatures that match those in shared user " 8589 + pkgSetting.sharedUser.name + "; ignoring!"); 8590 } 8591 } 8592 } 8593 8594 /** 8595 * Enforces that only the system UID or root's UID can call a method exposed 8596 * via Binder. 8597 * 8598 * @param message used as message if SecurityException is thrown 8599 * @throws SecurityException if the caller is not system or root 8600 */ 8601 private static final void enforceSystemOrRoot(String message) { 8602 final int uid = Binder.getCallingUid(); 8603 if (uid != Process.SYSTEM_UID && uid != 0) { 8604 throw new SecurityException(message); 8605 } 8606 } 8607 8608 @Override 8609 public void performFstrimIfNeeded() { 8610 enforceSystemOrRoot("Only the system can request fstrim"); 8611 8612 // Before everything else, see whether we need to fstrim. 8613 try { 8614 IStorageManager sm = PackageHelper.getStorageManager(); 8615 if (sm != null) { 8616 boolean doTrim = false; 8617 final long interval = android.provider.Settings.Global.getLong( 8618 mContext.getContentResolver(), 8619 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8620 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8621 if (interval > 0) { 8622 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8623 if (timeSinceLast > interval) { 8624 doTrim = true; 8625 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8626 + "; running immediately"); 8627 } 8628 } 8629 if (doTrim) { 8630 final boolean dexOptDialogShown; 8631 synchronized (mPackages) { 8632 dexOptDialogShown = mDexOptDialogShown; 8633 } 8634 if (!isFirstBoot() && dexOptDialogShown) { 8635 try { 8636 ActivityManager.getService().showBootMessage( 8637 mContext.getResources().getString( 8638 R.string.android_upgrading_fstrim), true); 8639 } catch (RemoteException e) { 8640 } 8641 } 8642 sm.runMaintenance(); 8643 } 8644 } else { 8645 Slog.e(TAG, "storageManager service unavailable!"); 8646 } 8647 } catch (RemoteException e) { 8648 // Can't happen; StorageManagerService is local 8649 } 8650 } 8651 8652 @Override 8653 public void updatePackagesIfNeeded() { 8654 enforceSystemOrRoot("Only the system can request package update"); 8655 8656 // We need to re-extract after an OTA. 8657 boolean causeUpgrade = isUpgrade(); 8658 8659 // First boot or factory reset. 8660 // Note: we also handle devices that are upgrading to N right now as if it is their 8661 // first boot, as they do not have profile data. 8662 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8663 8664 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8665 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8666 8667 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8668 return; 8669 } 8670 8671 List<PackageParser.Package> pkgs; 8672 synchronized (mPackages) { 8673 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8674 } 8675 8676 final long startTime = System.nanoTime(); 8677 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8678 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8679 8680 final int elapsedTimeSeconds = 8681 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8682 8683 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8684 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8685 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8686 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8687 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8688 } 8689 8690 /** 8691 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8692 * containing statistics about the invocation. The array consists of three elements, 8693 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8694 * and {@code numberOfPackagesFailed}. 8695 */ 8696 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8697 String compilerFilter) { 8698 8699 int numberOfPackagesVisited = 0; 8700 int numberOfPackagesOptimized = 0; 8701 int numberOfPackagesSkipped = 0; 8702 int numberOfPackagesFailed = 0; 8703 final int numberOfPackagesToDexopt = pkgs.size(); 8704 8705 for (PackageParser.Package pkg : pkgs) { 8706 numberOfPackagesVisited++; 8707 8708 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8709 if (DEBUG_DEXOPT) { 8710 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8711 } 8712 numberOfPackagesSkipped++; 8713 continue; 8714 } 8715 8716 if (DEBUG_DEXOPT) { 8717 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8718 numberOfPackagesToDexopt + ": " + pkg.packageName); 8719 } 8720 8721 if (showDialog) { 8722 try { 8723 ActivityManager.getService().showBootMessage( 8724 mContext.getResources().getString(R.string.android_upgrading_apk, 8725 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8726 } catch (RemoteException e) { 8727 } 8728 synchronized (mPackages) { 8729 mDexOptDialogShown = true; 8730 } 8731 } 8732 8733 // If the OTA updates a system app which was previously preopted to a non-preopted state 8734 // the app might end up being verified at runtime. That's because by default the apps 8735 // are verify-profile but for preopted apps there's no profile. 8736 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8737 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8738 // filter (by default 'quicken'). 8739 // Note that at this stage unused apps are already filtered. 8740 if (isSystemApp(pkg) && 8741 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8742 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8743 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8744 } 8745 8746 // checkProfiles is false to avoid merging profiles during boot which 8747 // might interfere with background compilation (b/28612421). 8748 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8749 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8750 // trade-off worth doing to save boot time work. 8751 int dexOptStatus = performDexOptTraced(pkg.packageName, 8752 false /* checkProfiles */, 8753 compilerFilter, 8754 false /* force */); 8755 switch (dexOptStatus) { 8756 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8757 numberOfPackagesOptimized++; 8758 break; 8759 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8760 numberOfPackagesSkipped++; 8761 break; 8762 case PackageDexOptimizer.DEX_OPT_FAILED: 8763 numberOfPackagesFailed++; 8764 break; 8765 default: 8766 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8767 break; 8768 } 8769 } 8770 8771 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8772 numberOfPackagesFailed }; 8773 } 8774 8775 @Override 8776 public void notifyPackageUse(String packageName, int reason) { 8777 synchronized (mPackages) { 8778 PackageParser.Package p = mPackages.get(packageName); 8779 if (p == null) { 8780 return; 8781 } 8782 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8783 } 8784 } 8785 8786 @Override 8787 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8788 int userId = UserHandle.getCallingUserId(); 8789 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8790 if (ai == null) { 8791 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8792 + loadingPackageName + ", user=" + userId); 8793 return; 8794 } 8795 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8796 } 8797 8798 @Override 8799 public boolean performDexOpt(String packageName, 8800 boolean checkProfiles, int compileReason, boolean force) { 8801 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8802 getCompilerFilterForReason(compileReason), force); 8803 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8804 } 8805 8806 @Override 8807 public boolean performDexOptMode(String packageName, 8808 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8809 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8810 targetCompilerFilter, force); 8811 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8812 } 8813 8814 private int performDexOptTraced(String packageName, 8815 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8817 try { 8818 return performDexOptInternal(packageName, checkProfiles, 8819 targetCompilerFilter, force); 8820 } finally { 8821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8822 } 8823 } 8824 8825 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8826 // if the package can now be considered up to date for the given filter. 8827 private int performDexOptInternal(String packageName, 8828 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8829 PackageParser.Package p; 8830 synchronized (mPackages) { 8831 p = mPackages.get(packageName); 8832 if (p == null) { 8833 // Package could not be found. Report failure. 8834 return PackageDexOptimizer.DEX_OPT_FAILED; 8835 } 8836 mPackageUsage.maybeWriteAsync(mPackages); 8837 mCompilerStats.maybeWriteAsync(); 8838 } 8839 long callingId = Binder.clearCallingIdentity(); 8840 try { 8841 synchronized (mInstallLock) { 8842 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8843 targetCompilerFilter, force); 8844 } 8845 } finally { 8846 Binder.restoreCallingIdentity(callingId); 8847 } 8848 } 8849 8850 public ArraySet<String> getOptimizablePackages() { 8851 ArraySet<String> pkgs = new ArraySet<String>(); 8852 synchronized (mPackages) { 8853 for (PackageParser.Package p : mPackages.values()) { 8854 if (PackageDexOptimizer.canOptimizePackage(p)) { 8855 pkgs.add(p.packageName); 8856 } 8857 } 8858 } 8859 return pkgs; 8860 } 8861 8862 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8863 boolean checkProfiles, String targetCompilerFilter, 8864 boolean force) { 8865 // Select the dex optimizer based on the force parameter. 8866 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8867 // allocate an object here. 8868 PackageDexOptimizer pdo = force 8869 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8870 : mPackageDexOptimizer; 8871 8872 // Dexopt all dependencies first. Note: we ignore the return value and march on 8873 // on errors. 8874 // Note that we are going to call performDexOpt on those libraries as many times as 8875 // they are referenced in packages. When we do a batch of performDexOpt (for example 8876 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8877 // and the first package that uses the library will dexopt it. The 8878 // others will see that the compiled code for the library is up to date. 8879 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8880 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8881 if (!deps.isEmpty()) { 8882 for (PackageParser.Package depPackage : deps) { 8883 // TODO: Analyze and investigate if we (should) profile libraries. 8884 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8885 false /* checkProfiles */, 8886 targetCompilerFilter, 8887 getOrCreateCompilerPackageStats(depPackage), 8888 true /* isUsedByOtherApps */); 8889 } 8890 } 8891 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8892 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8893 mDexManager.isUsedByOtherApps(p.packageName)); 8894 } 8895 8896 // Performs dexopt on the used secondary dex files belonging to the given package. 8897 // Returns true if all dex files were process successfully (which could mean either dexopt or 8898 // skip). Returns false if any of the files caused errors. 8899 @Override 8900 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8901 boolean force) { 8902 mDexManager.reconcileSecondaryDexFiles(packageName); 8903 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8904 } 8905 8906 public boolean performDexOptSecondary(String packageName, int compileReason, 8907 boolean force) { 8908 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8909 } 8910 8911 /** 8912 * Reconcile the information we have about the secondary dex files belonging to 8913 * {@code packagName} and the actual dex files. For all dex files that were 8914 * deleted, update the internal records and delete the generated oat files. 8915 */ 8916 @Override 8917 public void reconcileSecondaryDexFiles(String packageName) { 8918 mDexManager.reconcileSecondaryDexFiles(packageName); 8919 } 8920 8921 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8922 // a reference there. 8923 /*package*/ DexManager getDexManager() { 8924 return mDexManager; 8925 } 8926 8927 /** 8928 * Execute the background dexopt job immediately. 8929 */ 8930 @Override 8931 public boolean runBackgroundDexoptJob() { 8932 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8933 } 8934 8935 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8936 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8937 || p.usesStaticLibraries != null) { 8938 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8939 Set<String> collectedNames = new HashSet<>(); 8940 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8941 8942 retValue.remove(p); 8943 8944 return retValue; 8945 } else { 8946 return Collections.emptyList(); 8947 } 8948 } 8949 8950 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8951 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8952 if (!collectedNames.contains(p.packageName)) { 8953 collectedNames.add(p.packageName); 8954 collected.add(p); 8955 8956 if (p.usesLibraries != null) { 8957 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8958 null, collected, collectedNames); 8959 } 8960 if (p.usesOptionalLibraries != null) { 8961 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8962 null, collected, collectedNames); 8963 } 8964 if (p.usesStaticLibraries != null) { 8965 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8966 p.usesStaticLibrariesVersions, collected, collectedNames); 8967 } 8968 } 8969 } 8970 8971 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8972 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8973 final int libNameCount = libs.size(); 8974 for (int i = 0; i < libNameCount; i++) { 8975 String libName = libs.get(i); 8976 int version = (versions != null && versions.length == libNameCount) 8977 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8978 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8979 if (libPkg != null) { 8980 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8981 } 8982 } 8983 } 8984 8985 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8986 synchronized (mPackages) { 8987 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8988 if (libEntry != null) { 8989 return mPackages.get(libEntry.apk); 8990 } 8991 return null; 8992 } 8993 } 8994 8995 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8996 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8997 if (versionedLib == null) { 8998 return null; 8999 } 9000 return versionedLib.get(version); 9001 } 9002 9003 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9004 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9005 pkg.staticSharedLibName); 9006 if (versionedLib == null) { 9007 return null; 9008 } 9009 int previousLibVersion = -1; 9010 final int versionCount = versionedLib.size(); 9011 for (int i = 0; i < versionCount; i++) { 9012 final int libVersion = versionedLib.keyAt(i); 9013 if (libVersion < pkg.staticSharedLibVersion) { 9014 previousLibVersion = Math.max(previousLibVersion, libVersion); 9015 } 9016 } 9017 if (previousLibVersion >= 0) { 9018 return versionedLib.get(previousLibVersion); 9019 } 9020 return null; 9021 } 9022 9023 public void shutdown() { 9024 mPackageUsage.writeNow(mPackages); 9025 mCompilerStats.writeNow(); 9026 } 9027 9028 @Override 9029 public void dumpProfiles(String packageName) { 9030 PackageParser.Package pkg; 9031 synchronized (mPackages) { 9032 pkg = mPackages.get(packageName); 9033 if (pkg == null) { 9034 throw new IllegalArgumentException("Unknown package: " + packageName); 9035 } 9036 } 9037 /* Only the shell, root, or the app user should be able to dump profiles. */ 9038 int callingUid = Binder.getCallingUid(); 9039 if (callingUid != Process.SHELL_UID && 9040 callingUid != Process.ROOT_UID && 9041 callingUid != pkg.applicationInfo.uid) { 9042 throw new SecurityException("dumpProfiles"); 9043 } 9044 9045 synchronized (mInstallLock) { 9046 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9047 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9048 try { 9049 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9050 String codePaths = TextUtils.join(";", allCodePaths); 9051 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9052 } catch (InstallerException e) { 9053 Slog.w(TAG, "Failed to dump profiles", e); 9054 } 9055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9056 } 9057 } 9058 9059 @Override 9060 public void forceDexOpt(String packageName) { 9061 enforceSystemOrRoot("forceDexOpt"); 9062 9063 PackageParser.Package pkg; 9064 synchronized (mPackages) { 9065 pkg = mPackages.get(packageName); 9066 if (pkg == null) { 9067 throw new IllegalArgumentException("Unknown package: " + packageName); 9068 } 9069 } 9070 9071 synchronized (mInstallLock) { 9072 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9073 9074 // Whoever is calling forceDexOpt wants a compiled package. 9075 // Don't use profiles since that may cause compilation to be skipped. 9076 final int res = performDexOptInternalWithDependenciesLI(pkg, 9077 false /* checkProfiles */, getDefaultCompilerFilter(), 9078 true /* force */); 9079 9080 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9081 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9082 throw new IllegalStateException("Failed to dexopt: " + res); 9083 } 9084 } 9085 } 9086 9087 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9088 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9089 Slog.w(TAG, "Unable to update from " + oldPkg.name 9090 + " to " + newPkg.packageName 9091 + ": old package not in system partition"); 9092 return false; 9093 } else if (mPackages.get(oldPkg.name) != null) { 9094 Slog.w(TAG, "Unable to update from " + oldPkg.name 9095 + " to " + newPkg.packageName 9096 + ": old package still exists"); 9097 return false; 9098 } 9099 return true; 9100 } 9101 9102 void removeCodePathLI(File codePath) { 9103 if (codePath.isDirectory()) { 9104 try { 9105 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9106 } catch (InstallerException e) { 9107 Slog.w(TAG, "Failed to remove code path", e); 9108 } 9109 } else { 9110 codePath.delete(); 9111 } 9112 } 9113 9114 private int[] resolveUserIds(int userId) { 9115 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9116 } 9117 9118 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9119 if (pkg == null) { 9120 Slog.wtf(TAG, "Package was null!", new Throwable()); 9121 return; 9122 } 9123 clearAppDataLeafLIF(pkg, userId, flags); 9124 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9125 for (int i = 0; i < childCount; i++) { 9126 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9127 } 9128 } 9129 9130 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9131 final PackageSetting ps; 9132 synchronized (mPackages) { 9133 ps = mSettings.mPackages.get(pkg.packageName); 9134 } 9135 for (int realUserId : resolveUserIds(userId)) { 9136 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9137 try { 9138 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9139 ceDataInode); 9140 } catch (InstallerException e) { 9141 Slog.w(TAG, String.valueOf(e)); 9142 } 9143 } 9144 } 9145 9146 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9147 if (pkg == null) { 9148 Slog.wtf(TAG, "Package was null!", new Throwable()); 9149 return; 9150 } 9151 destroyAppDataLeafLIF(pkg, userId, flags); 9152 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9153 for (int i = 0; i < childCount; i++) { 9154 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9155 } 9156 } 9157 9158 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9159 final PackageSetting ps; 9160 synchronized (mPackages) { 9161 ps = mSettings.mPackages.get(pkg.packageName); 9162 } 9163 for (int realUserId : resolveUserIds(userId)) { 9164 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9165 try { 9166 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9167 ceDataInode); 9168 } catch (InstallerException e) { 9169 Slog.w(TAG, String.valueOf(e)); 9170 } 9171 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9172 } 9173 } 9174 9175 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9176 if (pkg == null) { 9177 Slog.wtf(TAG, "Package was null!", new Throwable()); 9178 return; 9179 } 9180 destroyAppProfilesLeafLIF(pkg); 9181 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9182 for (int i = 0; i < childCount; i++) { 9183 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9184 } 9185 } 9186 9187 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9188 try { 9189 mInstaller.destroyAppProfiles(pkg.packageName); 9190 } catch (InstallerException e) { 9191 Slog.w(TAG, String.valueOf(e)); 9192 } 9193 } 9194 9195 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9196 if (pkg == null) { 9197 Slog.wtf(TAG, "Package was null!", new Throwable()); 9198 return; 9199 } 9200 clearAppProfilesLeafLIF(pkg); 9201 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9202 for (int i = 0; i < childCount; i++) { 9203 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9204 } 9205 } 9206 9207 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9208 try { 9209 mInstaller.clearAppProfiles(pkg.packageName); 9210 } catch (InstallerException e) { 9211 Slog.w(TAG, String.valueOf(e)); 9212 } 9213 } 9214 9215 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9216 long lastUpdateTime) { 9217 // Set parent install/update time 9218 PackageSetting ps = (PackageSetting) pkg.mExtras; 9219 if (ps != null) { 9220 ps.firstInstallTime = firstInstallTime; 9221 ps.lastUpdateTime = lastUpdateTime; 9222 } 9223 // Set children install/update time 9224 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9225 for (int i = 0; i < childCount; i++) { 9226 PackageParser.Package childPkg = pkg.childPackages.get(i); 9227 ps = (PackageSetting) childPkg.mExtras; 9228 if (ps != null) { 9229 ps.firstInstallTime = firstInstallTime; 9230 ps.lastUpdateTime = lastUpdateTime; 9231 } 9232 } 9233 } 9234 9235 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 9236 PackageParser.Package changingLib) { 9237 if (file.path != null) { 9238 usesLibraryFiles.add(file.path); 9239 return; 9240 } 9241 PackageParser.Package p = mPackages.get(file.apk); 9242 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9243 // If we are doing this while in the middle of updating a library apk, 9244 // then we need to make sure to use that new apk for determining the 9245 // dependencies here. (We haven't yet finished committing the new apk 9246 // to the package manager state.) 9247 if (p == null || p.packageName.equals(changingLib.packageName)) { 9248 p = changingLib; 9249 } 9250 } 9251 if (p != null) { 9252 usesLibraryFiles.addAll(p.getAllCodePaths()); 9253 } 9254 } 9255 9256 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9257 PackageParser.Package changingLib) throws PackageManagerException { 9258 if (pkg == null) { 9259 return; 9260 } 9261 ArraySet<String> usesLibraryFiles = null; 9262 if (pkg.usesLibraries != null) { 9263 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9264 null, null, pkg.packageName, changingLib, true, null); 9265 } 9266 if (pkg.usesStaticLibraries != null) { 9267 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9268 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9269 pkg.packageName, changingLib, true, usesLibraryFiles); 9270 } 9271 if (pkg.usesOptionalLibraries != null) { 9272 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9273 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 9274 } 9275 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9276 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9277 } else { 9278 pkg.usesLibraryFiles = null; 9279 } 9280 } 9281 9282 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9283 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 9284 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9285 boolean required, @Nullable ArraySet<String> outUsedLibraries) 9286 throws PackageManagerException { 9287 final int libCount = requestedLibraries.size(); 9288 for (int i = 0; i < libCount; i++) { 9289 final String libName = requestedLibraries.get(i); 9290 final int libVersion = requiredVersions != null ? requiredVersions[i] 9291 : SharedLibraryInfo.VERSION_UNDEFINED; 9292 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9293 if (libEntry == null) { 9294 if (required) { 9295 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9296 "Package " + packageName + " requires unavailable shared library " 9297 + libName + "; failing!"); 9298 } else { 9299 Slog.w(TAG, "Package " + packageName 9300 + " desires unavailable shared library " 9301 + libName + "; ignoring!"); 9302 } 9303 } else { 9304 if (requiredVersions != null && requiredCertDigests != null) { 9305 if (libEntry.info.getVersion() != requiredVersions[i]) { 9306 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9307 "Package " + packageName + " requires unavailable static shared" 9308 + " library " + libName + " version " 9309 + libEntry.info.getVersion() + "; failing!"); 9310 } 9311 9312 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9313 if (libPkg == null) { 9314 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9315 "Package " + packageName + " requires unavailable static shared" 9316 + " library; failing!"); 9317 } 9318 9319 String expectedCertDigest = requiredCertDigests[i]; 9320 String libCertDigest = PackageUtils.computeCertSha256Digest( 9321 libPkg.mSignatures[0]); 9322 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9323 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9324 "Package " + packageName + " requires differently signed" + 9325 " static shared library; failing!"); 9326 } 9327 } 9328 9329 if (outUsedLibraries == null) { 9330 outUsedLibraries = new ArraySet<>(); 9331 } 9332 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9333 } 9334 } 9335 return outUsedLibraries; 9336 } 9337 9338 private static boolean hasString(List<String> list, List<String> which) { 9339 if (list == null) { 9340 return false; 9341 } 9342 for (int i=list.size()-1; i>=0; i--) { 9343 for (int j=which.size()-1; j>=0; j--) { 9344 if (which.get(j).equals(list.get(i))) { 9345 return true; 9346 } 9347 } 9348 } 9349 return false; 9350 } 9351 9352 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9353 PackageParser.Package changingPkg) { 9354 ArrayList<PackageParser.Package> res = null; 9355 for (PackageParser.Package pkg : mPackages.values()) { 9356 if (changingPkg != null 9357 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9358 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9359 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9360 changingPkg.staticSharedLibName)) { 9361 return null; 9362 } 9363 if (res == null) { 9364 res = new ArrayList<>(); 9365 } 9366 res.add(pkg); 9367 try { 9368 updateSharedLibrariesLPr(pkg, changingPkg); 9369 } catch (PackageManagerException e) { 9370 // If a system app update or an app and a required lib missing we 9371 // delete the package and for updated system apps keep the data as 9372 // it is better for the user to reinstall than to be in an limbo 9373 // state. Also libs disappearing under an app should never happen 9374 // - just in case. 9375 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9376 final int flags = pkg.isUpdatedSystemApp() 9377 ? PackageManager.DELETE_KEEP_DATA : 0; 9378 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9379 flags , null, true, null); 9380 } 9381 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9382 } 9383 } 9384 return res; 9385 } 9386 9387 /** 9388 * Derive the value of the {@code cpuAbiOverride} based on the provided 9389 * value and an optional stored value from the package settings. 9390 */ 9391 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9392 String cpuAbiOverride = null; 9393 9394 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9395 cpuAbiOverride = null; 9396 } else if (abiOverride != null) { 9397 cpuAbiOverride = abiOverride; 9398 } else if (settings != null) { 9399 cpuAbiOverride = settings.cpuAbiOverrideString; 9400 } 9401 9402 return cpuAbiOverride; 9403 } 9404 9405 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9406 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9407 throws PackageManagerException { 9408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9409 // If the package has children and this is the first dive in the function 9410 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9411 // whether all packages (parent and children) would be successfully scanned 9412 // before the actual scan since scanning mutates internal state and we want 9413 // to atomically install the package and its children. 9414 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9415 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9416 scanFlags |= SCAN_CHECK_ONLY; 9417 } 9418 } else { 9419 scanFlags &= ~SCAN_CHECK_ONLY; 9420 } 9421 9422 final PackageParser.Package scannedPkg; 9423 try { 9424 // Scan the parent 9425 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9426 // Scan the children 9427 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9428 for (int i = 0; i < childCount; i++) { 9429 PackageParser.Package childPkg = pkg.childPackages.get(i); 9430 scanPackageLI(childPkg, policyFlags, 9431 scanFlags, currentTime, user); 9432 } 9433 } finally { 9434 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9435 } 9436 9437 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9438 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9439 } 9440 9441 return scannedPkg; 9442 } 9443 9444 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9445 int scanFlags, long currentTime, @Nullable UserHandle user) 9446 throws PackageManagerException { 9447 boolean success = false; 9448 try { 9449 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9450 currentTime, user); 9451 success = true; 9452 return res; 9453 } finally { 9454 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9455 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9456 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9457 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9458 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9459 } 9460 } 9461 } 9462 9463 /** 9464 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9465 */ 9466 private static boolean apkHasCode(String fileName) { 9467 StrictJarFile jarFile = null; 9468 try { 9469 jarFile = new StrictJarFile(fileName, 9470 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9471 return jarFile.findEntry("classes.dex") != null; 9472 } catch (IOException ignore) { 9473 } finally { 9474 try { 9475 if (jarFile != null) { 9476 jarFile.close(); 9477 } 9478 } catch (IOException ignore) {} 9479 } 9480 return false; 9481 } 9482 9483 /** 9484 * Enforces code policy for the package. This ensures that if an APK has 9485 * declared hasCode="true" in its manifest that the APK actually contains 9486 * code. 9487 * 9488 * @throws PackageManagerException If bytecode could not be found when it should exist 9489 */ 9490 private static void assertCodePolicy(PackageParser.Package pkg) 9491 throws PackageManagerException { 9492 final boolean shouldHaveCode = 9493 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9494 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9495 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9496 "Package " + pkg.baseCodePath + " code is missing"); 9497 } 9498 9499 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9500 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9501 final boolean splitShouldHaveCode = 9502 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9503 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9504 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9505 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9506 } 9507 } 9508 } 9509 } 9510 9511 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9512 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9513 throws PackageManagerException { 9514 if (DEBUG_PACKAGE_SCANNING) { 9515 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9516 Log.d(TAG, "Scanning package " + pkg.packageName); 9517 } 9518 9519 applyPolicy(pkg, policyFlags); 9520 9521 assertPackageIsValid(pkg, policyFlags, scanFlags); 9522 9523 // Initialize package source and resource directories 9524 final File scanFile = new File(pkg.codePath); 9525 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9526 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9527 9528 SharedUserSetting suid = null; 9529 PackageSetting pkgSetting = null; 9530 9531 // Getting the package setting may have a side-effect, so if we 9532 // are only checking if scan would succeed, stash a copy of the 9533 // old setting to restore at the end. 9534 PackageSetting nonMutatedPs = null; 9535 9536 // We keep references to the derived CPU Abis from settings in oder to reuse 9537 // them in the case where we're not upgrading or booting for the first time. 9538 String primaryCpuAbiFromSettings = null; 9539 String secondaryCpuAbiFromSettings = null; 9540 9541 // writer 9542 synchronized (mPackages) { 9543 if (pkg.mSharedUserId != null) { 9544 // SIDE EFFECTS; may potentially allocate a new shared user 9545 suid = mSettings.getSharedUserLPw( 9546 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9547 if (DEBUG_PACKAGE_SCANNING) { 9548 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9549 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9550 + "): packages=" + suid.packages); 9551 } 9552 } 9553 9554 // Check if we are renaming from an original package name. 9555 PackageSetting origPackage = null; 9556 String realName = null; 9557 if (pkg.mOriginalPackages != null) { 9558 // This package may need to be renamed to a previously 9559 // installed name. Let's check on that... 9560 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9561 if (pkg.mOriginalPackages.contains(renamed)) { 9562 // This package had originally been installed as the 9563 // original name, and we have already taken care of 9564 // transitioning to the new one. Just update the new 9565 // one to continue using the old name. 9566 realName = pkg.mRealPackage; 9567 if (!pkg.packageName.equals(renamed)) { 9568 // Callers into this function may have already taken 9569 // care of renaming the package; only do it here if 9570 // it is not already done. 9571 pkg.setPackageName(renamed); 9572 } 9573 } else { 9574 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9575 if ((origPackage = mSettings.getPackageLPr( 9576 pkg.mOriginalPackages.get(i))) != null) { 9577 // We do have the package already installed under its 9578 // original name... should we use it? 9579 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9580 // New package is not compatible with original. 9581 origPackage = null; 9582 continue; 9583 } else if (origPackage.sharedUser != null) { 9584 // Make sure uid is compatible between packages. 9585 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9586 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9587 + " to " + pkg.packageName + ": old uid " 9588 + origPackage.sharedUser.name 9589 + " differs from " + pkg.mSharedUserId); 9590 origPackage = null; 9591 continue; 9592 } 9593 // TODO: Add case when shared user id is added [b/28144775] 9594 } else { 9595 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9596 + pkg.packageName + " to old name " + origPackage.name); 9597 } 9598 break; 9599 } 9600 } 9601 } 9602 } 9603 9604 if (mTransferedPackages.contains(pkg.packageName)) { 9605 Slog.w(TAG, "Package " + pkg.packageName 9606 + " was transferred to another, but its .apk remains"); 9607 } 9608 9609 // See comments in nonMutatedPs declaration 9610 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9611 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9612 if (foundPs != null) { 9613 nonMutatedPs = new PackageSetting(foundPs); 9614 } 9615 } 9616 9617 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9618 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9619 if (foundPs != null) { 9620 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9621 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9622 } 9623 } 9624 9625 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9626 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9627 PackageManagerService.reportSettingsProblem(Log.WARN, 9628 "Package " + pkg.packageName + " shared user changed from " 9629 + (pkgSetting.sharedUser != null 9630 ? pkgSetting.sharedUser.name : "<nothing>") 9631 + " to " 9632 + (suid != null ? suid.name : "<nothing>") 9633 + "; replacing with new"); 9634 pkgSetting = null; 9635 } 9636 final PackageSetting oldPkgSetting = 9637 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9638 final PackageSetting disabledPkgSetting = 9639 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9640 9641 String[] usesStaticLibraries = null; 9642 if (pkg.usesStaticLibraries != null) { 9643 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9644 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9645 } 9646 9647 if (pkgSetting == null) { 9648 final String parentPackageName = (pkg.parentPackage != null) 9649 ? pkg.parentPackage.packageName : null; 9650 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9651 // REMOVE SharedUserSetting from method; update in a separate call 9652 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9653 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9654 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9655 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9656 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9657 true /*allowInstall*/, instantApp, parentPackageName, 9658 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9659 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9660 // SIDE EFFECTS; updates system state; move elsewhere 9661 if (origPackage != null) { 9662 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9663 } 9664 mSettings.addUserToSettingLPw(pkgSetting); 9665 } else { 9666 // REMOVE SharedUserSetting from method; update in a separate call. 9667 // 9668 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9669 // secondaryCpuAbi are not known at this point so we always update them 9670 // to null here, only to reset them at a later point. 9671 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9672 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9673 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9674 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9675 UserManagerService.getInstance(), usesStaticLibraries, 9676 pkg.usesStaticLibrariesVersions); 9677 } 9678 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9679 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9680 9681 // SIDE EFFECTS; modifies system state; move elsewhere 9682 if (pkgSetting.origPackage != null) { 9683 // If we are first transitioning from an original package, 9684 // fix up the new package's name now. We need to do this after 9685 // looking up the package under its new name, so getPackageLP 9686 // can take care of fiddling things correctly. 9687 pkg.setPackageName(origPackage.name); 9688 9689 // File a report about this. 9690 String msg = "New package " + pkgSetting.realName 9691 + " renamed to replace old package " + pkgSetting.name; 9692 reportSettingsProblem(Log.WARN, msg); 9693 9694 // Make a note of it. 9695 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9696 mTransferedPackages.add(origPackage.name); 9697 } 9698 9699 // No longer need to retain this. 9700 pkgSetting.origPackage = null; 9701 } 9702 9703 // SIDE EFFECTS; modifies system state; move elsewhere 9704 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9705 // Make a note of it. 9706 mTransferedPackages.add(pkg.packageName); 9707 } 9708 9709 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9710 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9711 } 9712 9713 if ((scanFlags & SCAN_BOOTING) == 0 9714 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9715 // Check all shared libraries and map to their actual file path. 9716 // We only do this here for apps not on a system dir, because those 9717 // are the only ones that can fail an install due to this. We 9718 // will take care of the system apps by updating all of their 9719 // library paths after the scan is done. Also during the initial 9720 // scan don't update any libs as we do this wholesale after all 9721 // apps are scanned to avoid dependency based scanning. 9722 updateSharedLibrariesLPr(pkg, null); 9723 } 9724 9725 if (mFoundPolicyFile) { 9726 SELinuxMMAC.assignSeInfoValue(pkg); 9727 } 9728 pkg.applicationInfo.uid = pkgSetting.appId; 9729 pkg.mExtras = pkgSetting; 9730 9731 9732 // Static shared libs have same package with different versions where 9733 // we internally use a synthetic package name to allow multiple versions 9734 // of the same package, therefore we need to compare signatures against 9735 // the package setting for the latest library version. 9736 PackageSetting signatureCheckPs = pkgSetting; 9737 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9738 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9739 if (libraryEntry != null) { 9740 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9741 } 9742 } 9743 9744 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9745 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9746 // We just determined the app is signed correctly, so bring 9747 // over the latest parsed certs. 9748 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9749 } else { 9750 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9751 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9752 "Package " + pkg.packageName + " upgrade keys do not match the " 9753 + "previously installed version"); 9754 } else { 9755 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9756 String msg = "System package " + pkg.packageName 9757 + " signature changed; retaining data."; 9758 reportSettingsProblem(Log.WARN, msg); 9759 } 9760 } 9761 } else { 9762 try { 9763 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9764 verifySignaturesLP(signatureCheckPs, pkg); 9765 // We just determined the app is signed correctly, so bring 9766 // over the latest parsed certs. 9767 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9768 } catch (PackageManagerException e) { 9769 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9770 throw e; 9771 } 9772 // The signature has changed, but this package is in the system 9773 // image... let's recover! 9774 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9775 // However... if this package is part of a shared user, but it 9776 // doesn't match the signature of the shared user, let's fail. 9777 // What this means is that you can't change the signatures 9778 // associated with an overall shared user, which doesn't seem all 9779 // that unreasonable. 9780 if (signatureCheckPs.sharedUser != null) { 9781 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9782 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9783 throw new PackageManagerException( 9784 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9785 "Signature mismatch for shared user: " 9786 + pkgSetting.sharedUser); 9787 } 9788 } 9789 // File a report about this. 9790 String msg = "System package " + pkg.packageName 9791 + " signature changed; retaining data."; 9792 reportSettingsProblem(Log.WARN, msg); 9793 } 9794 } 9795 9796 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9797 // This package wants to adopt ownership of permissions from 9798 // another package. 9799 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9800 final String origName = pkg.mAdoptPermissions.get(i); 9801 final PackageSetting orig = mSettings.getPackageLPr(origName); 9802 if (orig != null) { 9803 if (verifyPackageUpdateLPr(orig, pkg)) { 9804 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9805 + pkg.packageName); 9806 // SIDE EFFECTS; updates permissions system state; move elsewhere 9807 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9808 } 9809 } 9810 } 9811 } 9812 } 9813 9814 pkg.applicationInfo.processName = fixProcessName( 9815 pkg.applicationInfo.packageName, 9816 pkg.applicationInfo.processName); 9817 9818 if (pkg != mPlatformPackage) { 9819 // Get all of our default paths setup 9820 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9821 } 9822 9823 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9824 9825 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9826 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9828 derivePackageAbi( 9829 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9831 9832 // Some system apps still use directory structure for native libraries 9833 // in which case we might end up not detecting abi solely based on apk 9834 // structure. Try to detect abi based on directory structure. 9835 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9836 pkg.applicationInfo.primaryCpuAbi == null) { 9837 setBundledAppAbisAndRoots(pkg, pkgSetting); 9838 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9839 } 9840 } else { 9841 // This is not a first boot or an upgrade, don't bother deriving the 9842 // ABI during the scan. Instead, trust the value that was stored in the 9843 // package setting. 9844 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9845 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9846 9847 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9848 9849 if (DEBUG_ABI_SELECTION) { 9850 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9851 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9852 pkg.applicationInfo.secondaryCpuAbi); 9853 } 9854 } 9855 } else { 9856 if ((scanFlags & SCAN_MOVE) != 0) { 9857 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9858 // but we already have this packages package info in the PackageSetting. We just 9859 // use that and derive the native library path based on the new codepath. 9860 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9861 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9862 } 9863 9864 // Set native library paths again. For moves, the path will be updated based on the 9865 // ABIs we've determined above. For non-moves, the path will be updated based on the 9866 // ABIs we determined during compilation, but the path will depend on the final 9867 // package path (after the rename away from the stage path). 9868 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9869 } 9870 9871 // This is a special case for the "system" package, where the ABI is 9872 // dictated by the zygote configuration (and init.rc). We should keep track 9873 // of this ABI so that we can deal with "normal" applications that run under 9874 // the same UID correctly. 9875 if (mPlatformPackage == pkg) { 9876 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9877 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9878 } 9879 9880 // If there's a mismatch between the abi-override in the package setting 9881 // and the abiOverride specified for the install. Warn about this because we 9882 // would've already compiled the app without taking the package setting into 9883 // account. 9884 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9885 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9886 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9887 " for package " + pkg.packageName); 9888 } 9889 } 9890 9891 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9892 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9893 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9894 9895 // Copy the derived override back to the parsed package, so that we can 9896 // update the package settings accordingly. 9897 pkg.cpuAbiOverride = cpuAbiOverride; 9898 9899 if (DEBUG_ABI_SELECTION) { 9900 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9901 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9902 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9903 } 9904 9905 // Push the derived path down into PackageSettings so we know what to 9906 // clean up at uninstall time. 9907 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9908 9909 if (DEBUG_ABI_SELECTION) { 9910 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9911 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9912 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9913 } 9914 9915 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9916 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9917 // We don't do this here during boot because we can do it all 9918 // at once after scanning all existing packages. 9919 // 9920 // We also do this *before* we perform dexopt on this package, so that 9921 // we can avoid redundant dexopts, and also to make sure we've got the 9922 // code and package path correct. 9923 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9924 } 9925 9926 if (mFactoryTest && pkg.requestedPermissions.contains( 9927 android.Manifest.permission.FACTORY_TEST)) { 9928 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9929 } 9930 9931 if (isSystemApp(pkg)) { 9932 pkgSetting.isOrphaned = true; 9933 } 9934 9935 // Take care of first install / last update times. 9936 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9937 if (currentTime != 0) { 9938 if (pkgSetting.firstInstallTime == 0) { 9939 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9940 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9941 pkgSetting.lastUpdateTime = currentTime; 9942 } 9943 } else if (pkgSetting.firstInstallTime == 0) { 9944 // We need *something*. Take time time stamp of the file. 9945 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9946 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9947 if (scanFileTime != pkgSetting.timeStamp) { 9948 // A package on the system image has changed; consider this 9949 // to be an update. 9950 pkgSetting.lastUpdateTime = scanFileTime; 9951 } 9952 } 9953 pkgSetting.setTimeStamp(scanFileTime); 9954 9955 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9956 if (nonMutatedPs != null) { 9957 synchronized (mPackages) { 9958 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9959 } 9960 } 9961 } else { 9962 final int userId = user == null ? 0 : user.getIdentifier(); 9963 // Modify state for the given package setting 9964 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9965 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9966 if (pkgSetting.getInstantApp(userId)) { 9967 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9968 } 9969 } 9970 return pkg; 9971 } 9972 9973 /** 9974 * Applies policy to the parsed package based upon the given policy flags. 9975 * Ensures the package is in a good state. 9976 * <p> 9977 * Implementation detail: This method must NOT have any side effect. It would 9978 * ideally be static, but, it requires locks to read system state. 9979 */ 9980 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9981 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9982 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9983 if (pkg.applicationInfo.isDirectBootAware()) { 9984 // we're direct boot aware; set for all components 9985 for (PackageParser.Service s : pkg.services) { 9986 s.info.encryptionAware = s.info.directBootAware = true; 9987 } 9988 for (PackageParser.Provider p : pkg.providers) { 9989 p.info.encryptionAware = p.info.directBootAware = true; 9990 } 9991 for (PackageParser.Activity a : pkg.activities) { 9992 a.info.encryptionAware = a.info.directBootAware = true; 9993 } 9994 for (PackageParser.Activity r : pkg.receivers) { 9995 r.info.encryptionAware = r.info.directBootAware = true; 9996 } 9997 } 9998 } else { 9999 // Only allow system apps to be flagged as core apps. 10000 pkg.coreApp = false; 10001 // clear flags not applicable to regular apps 10002 pkg.applicationInfo.privateFlags &= 10003 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10004 pkg.applicationInfo.privateFlags &= 10005 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10006 } 10007 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 10008 10009 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 10010 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10011 } 10012 10013 if (!isSystemApp(pkg)) { 10014 // Only system apps can use these features. 10015 pkg.mOriginalPackages = null; 10016 pkg.mRealPackage = null; 10017 pkg.mAdoptPermissions = null; 10018 } 10019 } 10020 10021 /** 10022 * Asserts the parsed package is valid according to the given policy. If the 10023 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10024 * <p> 10025 * Implementation detail: This method must NOT have any side effects. It would 10026 * ideally be static, but, it requires locks to read system state. 10027 * 10028 * @throws PackageManagerException If the package fails any of the validation checks 10029 */ 10030 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 10031 throws PackageManagerException { 10032 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10033 assertCodePolicy(pkg); 10034 } 10035 10036 if (pkg.applicationInfo.getCodePath() == null || 10037 pkg.applicationInfo.getResourcePath() == null) { 10038 // Bail out. The resource and code paths haven't been set. 10039 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10040 "Code and resource paths haven't been set correctly"); 10041 } 10042 10043 // Make sure we're not adding any bogus keyset info 10044 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10045 ksms.assertScannedPackageValid(pkg); 10046 10047 synchronized (mPackages) { 10048 // The special "android" package can only be defined once 10049 if (pkg.packageName.equals("android")) { 10050 if (mAndroidApplication != null) { 10051 Slog.w(TAG, "*************************************************"); 10052 Slog.w(TAG, "Core android package being redefined. Skipping."); 10053 Slog.w(TAG, " codePath=" + pkg.codePath); 10054 Slog.w(TAG, "*************************************************"); 10055 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10056 "Core android package being redefined. Skipping."); 10057 } 10058 } 10059 10060 // A package name must be unique; don't allow duplicates 10061 if (mPackages.containsKey(pkg.packageName)) { 10062 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10063 "Application package " + pkg.packageName 10064 + " already installed. Skipping duplicate."); 10065 } 10066 10067 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10068 // Static libs have a synthetic package name containing the version 10069 // but we still want the base name to be unique. 10070 if (mPackages.containsKey(pkg.manifestPackageName)) { 10071 throw new PackageManagerException( 10072 "Duplicate static shared lib provider package"); 10073 } 10074 10075 // Static shared libraries should have at least O target SDK 10076 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10077 throw new PackageManagerException( 10078 "Packages declaring static-shared libs must target O SDK or higher"); 10079 } 10080 10081 // Package declaring static a shared lib cannot be instant apps 10082 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10083 throw new PackageManagerException( 10084 "Packages declaring static-shared libs cannot be instant apps"); 10085 } 10086 10087 // Package declaring static a shared lib cannot be renamed since the package 10088 // name is synthetic and apps can't code around package manager internals. 10089 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10090 throw new PackageManagerException( 10091 "Packages declaring static-shared libs cannot be renamed"); 10092 } 10093 10094 // Package declaring static a shared lib cannot declare child packages 10095 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10096 throw new PackageManagerException( 10097 "Packages declaring static-shared libs cannot have child packages"); 10098 } 10099 10100 // Package declaring static a shared lib cannot declare dynamic libs 10101 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10102 throw new PackageManagerException( 10103 "Packages declaring static-shared libs cannot declare dynamic libs"); 10104 } 10105 10106 // Package declaring static a shared lib cannot declare shared users 10107 if (pkg.mSharedUserId != null) { 10108 throw new PackageManagerException( 10109 "Packages declaring static-shared libs cannot declare shared users"); 10110 } 10111 10112 // Static shared libs cannot declare activities 10113 if (!pkg.activities.isEmpty()) { 10114 throw new PackageManagerException( 10115 "Static shared libs cannot declare activities"); 10116 } 10117 10118 // Static shared libs cannot declare services 10119 if (!pkg.services.isEmpty()) { 10120 throw new PackageManagerException( 10121 "Static shared libs cannot declare services"); 10122 } 10123 10124 // Static shared libs cannot declare providers 10125 if (!pkg.providers.isEmpty()) { 10126 throw new PackageManagerException( 10127 "Static shared libs cannot declare content providers"); 10128 } 10129 10130 // Static shared libs cannot declare receivers 10131 if (!pkg.receivers.isEmpty()) { 10132 throw new PackageManagerException( 10133 "Static shared libs cannot declare broadcast receivers"); 10134 } 10135 10136 // Static shared libs cannot declare permission groups 10137 if (!pkg.permissionGroups.isEmpty()) { 10138 throw new PackageManagerException( 10139 "Static shared libs cannot declare permission groups"); 10140 } 10141 10142 // Static shared libs cannot declare permissions 10143 if (!pkg.permissions.isEmpty()) { 10144 throw new PackageManagerException( 10145 "Static shared libs cannot declare permissions"); 10146 } 10147 10148 // Static shared libs cannot declare protected broadcasts 10149 if (pkg.protectedBroadcasts != null) { 10150 throw new PackageManagerException( 10151 "Static shared libs cannot declare protected broadcasts"); 10152 } 10153 10154 // Static shared libs cannot be overlay targets 10155 if (pkg.mOverlayTarget != null) { 10156 throw new PackageManagerException( 10157 "Static shared libs cannot be overlay targets"); 10158 } 10159 10160 // The version codes must be ordered as lib versions 10161 int minVersionCode = Integer.MIN_VALUE; 10162 int maxVersionCode = Integer.MAX_VALUE; 10163 10164 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10165 pkg.staticSharedLibName); 10166 if (versionedLib != null) { 10167 final int versionCount = versionedLib.size(); 10168 for (int i = 0; i < versionCount; i++) { 10169 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10170 // TODO: We will change version code to long, so in the new API it is long 10171 final int libVersionCode = (int) libInfo.getDeclaringPackage() 10172 .getVersionCode(); 10173 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10174 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10175 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10176 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10177 } else { 10178 minVersionCode = maxVersionCode = libVersionCode; 10179 break; 10180 } 10181 } 10182 } 10183 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10184 throw new PackageManagerException("Static shared" 10185 + " lib version codes must be ordered as lib versions"); 10186 } 10187 } 10188 10189 // Only privileged apps and updated privileged apps can add child packages. 10190 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10191 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10192 throw new PackageManagerException("Only privileged apps can add child " 10193 + "packages. Ignoring package " + pkg.packageName); 10194 } 10195 final int childCount = pkg.childPackages.size(); 10196 for (int i = 0; i < childCount; i++) { 10197 PackageParser.Package childPkg = pkg.childPackages.get(i); 10198 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10199 childPkg.packageName)) { 10200 throw new PackageManagerException("Can't override child of " 10201 + "another disabled app. Ignoring package " + pkg.packageName); 10202 } 10203 } 10204 } 10205 10206 // If we're only installing presumed-existing packages, require that the 10207 // scanned APK is both already known and at the path previously established 10208 // for it. Previously unknown packages we pick up normally, but if we have an 10209 // a priori expectation about this package's install presence, enforce it. 10210 // With a singular exception for new system packages. When an OTA contains 10211 // a new system package, we allow the codepath to change from a system location 10212 // to the user-installed location. If we don't allow this change, any newer, 10213 // user-installed version of the application will be ignored. 10214 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10215 if (mExpectingBetter.containsKey(pkg.packageName)) { 10216 logCriticalInfo(Log.WARN, 10217 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10218 } else { 10219 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10220 if (known != null) { 10221 if (DEBUG_PACKAGE_SCANNING) { 10222 Log.d(TAG, "Examining " + pkg.codePath 10223 + " and requiring known paths " + known.codePathString 10224 + " & " + known.resourcePathString); 10225 } 10226 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10227 || !pkg.applicationInfo.getResourcePath().equals( 10228 known.resourcePathString)) { 10229 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10230 "Application package " + pkg.packageName 10231 + " found at " + pkg.applicationInfo.getCodePath() 10232 + " but expected at " + known.codePathString 10233 + "; ignoring."); 10234 } 10235 } 10236 } 10237 } 10238 10239 // Verify that this new package doesn't have any content providers 10240 // that conflict with existing packages. Only do this if the 10241 // package isn't already installed, since we don't want to break 10242 // things that are installed. 10243 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10244 final int N = pkg.providers.size(); 10245 int i; 10246 for (i=0; i<N; i++) { 10247 PackageParser.Provider p = pkg.providers.get(i); 10248 if (p.info.authority != null) { 10249 String names[] = p.info.authority.split(";"); 10250 for (int j = 0; j < names.length; j++) { 10251 if (mProvidersByAuthority.containsKey(names[j])) { 10252 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10253 final String otherPackageName = 10254 ((other != null && other.getComponentName() != null) ? 10255 other.getComponentName().getPackageName() : "?"); 10256 throw new PackageManagerException( 10257 INSTALL_FAILED_CONFLICTING_PROVIDER, 10258 "Can't install because provider name " + names[j] 10259 + " (in package " + pkg.applicationInfo.packageName 10260 + ") is already used by " + otherPackageName); 10261 } 10262 } 10263 } 10264 } 10265 } 10266 } 10267 } 10268 10269 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10270 int type, String declaringPackageName, int declaringVersionCode) { 10271 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10272 if (versionedLib == null) { 10273 versionedLib = new SparseArray<>(); 10274 mSharedLibraries.put(name, versionedLib); 10275 if (type == SharedLibraryInfo.TYPE_STATIC) { 10276 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10277 } 10278 } else if (versionedLib.indexOfKey(version) >= 0) { 10279 return false; 10280 } 10281 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10282 version, type, declaringPackageName, declaringVersionCode); 10283 versionedLib.put(version, libEntry); 10284 return true; 10285 } 10286 10287 private boolean removeSharedLibraryLPw(String name, int version) { 10288 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10289 if (versionedLib == null) { 10290 return false; 10291 } 10292 final int libIdx = versionedLib.indexOfKey(version); 10293 if (libIdx < 0) { 10294 return false; 10295 } 10296 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10297 versionedLib.remove(version); 10298 if (versionedLib.size() <= 0) { 10299 mSharedLibraries.remove(name); 10300 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10301 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10302 .getPackageName()); 10303 } 10304 } 10305 return true; 10306 } 10307 10308 /** 10309 * Adds a scanned package to the system. When this method is finished, the package will 10310 * be available for query, resolution, etc... 10311 */ 10312 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10313 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10314 final String pkgName = pkg.packageName; 10315 if (mCustomResolverComponentName != null && 10316 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10317 setUpCustomResolverActivity(pkg); 10318 } 10319 10320 if (pkg.packageName.equals("android")) { 10321 synchronized (mPackages) { 10322 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10323 // Set up information for our fall-back user intent resolution activity. 10324 mPlatformPackage = pkg; 10325 pkg.mVersionCode = mSdkVersion; 10326 mAndroidApplication = pkg.applicationInfo; 10327 if (!mResolverReplaced) { 10328 mResolveActivity.applicationInfo = mAndroidApplication; 10329 mResolveActivity.name = ResolverActivity.class.getName(); 10330 mResolveActivity.packageName = mAndroidApplication.packageName; 10331 mResolveActivity.processName = "system:ui"; 10332 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10333 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10334 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10335 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10336 mResolveActivity.exported = true; 10337 mResolveActivity.enabled = true; 10338 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10339 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10340 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10341 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10342 | ActivityInfo.CONFIG_ORIENTATION 10343 | ActivityInfo.CONFIG_KEYBOARD 10344 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10345 mResolveInfo.activityInfo = mResolveActivity; 10346 mResolveInfo.priority = 0; 10347 mResolveInfo.preferredOrder = 0; 10348 mResolveInfo.match = 0; 10349 mResolveComponentName = new ComponentName( 10350 mAndroidApplication.packageName, mResolveActivity.name); 10351 } 10352 } 10353 } 10354 } 10355 10356 ArrayList<PackageParser.Package> clientLibPkgs = null; 10357 // writer 10358 synchronized (mPackages) { 10359 boolean hasStaticSharedLibs = false; 10360 10361 // Any app can add new static shared libraries 10362 if (pkg.staticSharedLibName != null) { 10363 // Static shared libs don't allow renaming as they have synthetic package 10364 // names to allow install of multiple versions, so use name from manifest. 10365 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10366 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10367 pkg.manifestPackageName, pkg.mVersionCode)) { 10368 hasStaticSharedLibs = true; 10369 } else { 10370 Slog.w(TAG, "Package " + pkg.packageName + " library " 10371 + pkg.staticSharedLibName + " already exists; skipping"); 10372 } 10373 // Static shared libs cannot be updated once installed since they 10374 // use synthetic package name which includes the version code, so 10375 // not need to update other packages's shared lib dependencies. 10376 } 10377 10378 if (!hasStaticSharedLibs 10379 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10380 // Only system apps can add new dynamic shared libraries. 10381 if (pkg.libraryNames != null) { 10382 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10383 String name = pkg.libraryNames.get(i); 10384 boolean allowed = false; 10385 if (pkg.isUpdatedSystemApp()) { 10386 // New library entries can only be added through the 10387 // system image. This is important to get rid of a lot 10388 // of nasty edge cases: for example if we allowed a non- 10389 // system update of the app to add a library, then uninstalling 10390 // the update would make the library go away, and assumptions 10391 // we made such as through app install filtering would now 10392 // have allowed apps on the device which aren't compatible 10393 // with it. Better to just have the restriction here, be 10394 // conservative, and create many fewer cases that can negatively 10395 // impact the user experience. 10396 final PackageSetting sysPs = mSettings 10397 .getDisabledSystemPkgLPr(pkg.packageName); 10398 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10399 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10400 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10401 allowed = true; 10402 break; 10403 } 10404 } 10405 } 10406 } else { 10407 allowed = true; 10408 } 10409 if (allowed) { 10410 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10411 SharedLibraryInfo.VERSION_UNDEFINED, 10412 SharedLibraryInfo.TYPE_DYNAMIC, 10413 pkg.packageName, pkg.mVersionCode)) { 10414 Slog.w(TAG, "Package " + pkg.packageName + " library " 10415 + name + " already exists; skipping"); 10416 } 10417 } else { 10418 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10419 + name + " that is not declared on system image; skipping"); 10420 } 10421 } 10422 10423 if ((scanFlags & SCAN_BOOTING) == 0) { 10424 // If we are not booting, we need to update any applications 10425 // that are clients of our shared library. If we are booting, 10426 // this will all be done once the scan is complete. 10427 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10428 } 10429 } 10430 } 10431 } 10432 10433 if ((scanFlags & SCAN_BOOTING) != 0) { 10434 // No apps can run during boot scan, so they don't need to be frozen 10435 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10436 // Caller asked to not kill app, so it's probably not frozen 10437 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10438 // Caller asked us to ignore frozen check for some reason; they 10439 // probably didn't know the package name 10440 } else { 10441 // We're doing major surgery on this package, so it better be frozen 10442 // right now to keep it from launching 10443 checkPackageFrozen(pkgName); 10444 } 10445 10446 // Also need to kill any apps that are dependent on the library. 10447 if (clientLibPkgs != null) { 10448 for (int i=0; i<clientLibPkgs.size(); i++) { 10449 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10450 killApplication(clientPkg.applicationInfo.packageName, 10451 clientPkg.applicationInfo.uid, "update lib"); 10452 } 10453 } 10454 10455 // writer 10456 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10457 10458 synchronized (mPackages) { 10459 // We don't expect installation to fail beyond this point 10460 10461 // Add the new setting to mSettings 10462 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10463 // Add the new setting to mPackages 10464 mPackages.put(pkg.applicationInfo.packageName, pkg); 10465 // Make sure we don't accidentally delete its data. 10466 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10467 while (iter.hasNext()) { 10468 PackageCleanItem item = iter.next(); 10469 if (pkgName.equals(item.packageName)) { 10470 iter.remove(); 10471 } 10472 } 10473 10474 // Add the package's KeySets to the global KeySetManagerService 10475 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10476 ksms.addScannedPackageLPw(pkg); 10477 10478 int N = pkg.providers.size(); 10479 StringBuilder r = null; 10480 int i; 10481 for (i=0; i<N; i++) { 10482 PackageParser.Provider p = pkg.providers.get(i); 10483 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10484 p.info.processName); 10485 mProviders.addProvider(p); 10486 p.syncable = p.info.isSyncable; 10487 if (p.info.authority != null) { 10488 String names[] = p.info.authority.split(";"); 10489 p.info.authority = null; 10490 for (int j = 0; j < names.length; j++) { 10491 if (j == 1 && p.syncable) { 10492 // We only want the first authority for a provider to possibly be 10493 // syncable, so if we already added this provider using a different 10494 // authority clear the syncable flag. We copy the provider before 10495 // changing it because the mProviders object contains a reference 10496 // to a provider that we don't want to change. 10497 // Only do this for the second authority since the resulting provider 10498 // object can be the same for all future authorities for this provider. 10499 p = new PackageParser.Provider(p); 10500 p.syncable = false; 10501 } 10502 if (!mProvidersByAuthority.containsKey(names[j])) { 10503 mProvidersByAuthority.put(names[j], p); 10504 if (p.info.authority == null) { 10505 p.info.authority = names[j]; 10506 } else { 10507 p.info.authority = p.info.authority + ";" + names[j]; 10508 } 10509 if (DEBUG_PACKAGE_SCANNING) { 10510 if (chatty) 10511 Log.d(TAG, "Registered content provider: " + names[j] 10512 + ", className = " + p.info.name + ", isSyncable = " 10513 + p.info.isSyncable); 10514 } 10515 } else { 10516 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10517 Slog.w(TAG, "Skipping provider name " + names[j] + 10518 " (in package " + pkg.applicationInfo.packageName + 10519 "): name already used by " 10520 + ((other != null && other.getComponentName() != null) 10521 ? other.getComponentName().getPackageName() : "?")); 10522 } 10523 } 10524 } 10525 if (chatty) { 10526 if (r == null) { 10527 r = new StringBuilder(256); 10528 } else { 10529 r.append(' '); 10530 } 10531 r.append(p.info.name); 10532 } 10533 } 10534 if (r != null) { 10535 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10536 } 10537 10538 N = pkg.services.size(); 10539 r = null; 10540 for (i=0; i<N; i++) { 10541 PackageParser.Service s = pkg.services.get(i); 10542 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10543 s.info.processName); 10544 mServices.addService(s); 10545 if (chatty) { 10546 if (r == null) { 10547 r = new StringBuilder(256); 10548 } else { 10549 r.append(' '); 10550 } 10551 r.append(s.info.name); 10552 } 10553 } 10554 if (r != null) { 10555 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10556 } 10557 10558 N = pkg.receivers.size(); 10559 r = null; 10560 for (i=0; i<N; i++) { 10561 PackageParser.Activity a = pkg.receivers.get(i); 10562 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10563 a.info.processName); 10564 mReceivers.addActivity(a, "receiver"); 10565 if (chatty) { 10566 if (r == null) { 10567 r = new StringBuilder(256); 10568 } else { 10569 r.append(' '); 10570 } 10571 r.append(a.info.name); 10572 } 10573 } 10574 if (r != null) { 10575 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10576 } 10577 10578 N = pkg.activities.size(); 10579 r = null; 10580 for (i=0; i<N; i++) { 10581 PackageParser.Activity a = pkg.activities.get(i); 10582 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10583 a.info.processName); 10584 mActivities.addActivity(a, "activity"); 10585 if (chatty) { 10586 if (r == null) { 10587 r = new StringBuilder(256); 10588 } else { 10589 r.append(' '); 10590 } 10591 r.append(a.info.name); 10592 } 10593 } 10594 if (r != null) { 10595 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10596 } 10597 10598 N = pkg.permissionGroups.size(); 10599 r = null; 10600 for (i=0; i<N; i++) { 10601 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10602 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10603 final String curPackageName = cur == null ? null : cur.info.packageName; 10604 // Dont allow ephemeral apps to define new permission groups. 10605 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10606 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10607 + pg.info.packageName 10608 + " ignored: instant apps cannot define new permission groups."); 10609 continue; 10610 } 10611 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10612 if (cur == null || isPackageUpdate) { 10613 mPermissionGroups.put(pg.info.name, pg); 10614 if (chatty) { 10615 if (r == null) { 10616 r = new StringBuilder(256); 10617 } else { 10618 r.append(' '); 10619 } 10620 if (isPackageUpdate) { 10621 r.append("UPD:"); 10622 } 10623 r.append(pg.info.name); 10624 } 10625 } else { 10626 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10627 + pg.info.packageName + " ignored: original from " 10628 + cur.info.packageName); 10629 if (chatty) { 10630 if (r == null) { 10631 r = new StringBuilder(256); 10632 } else { 10633 r.append(' '); 10634 } 10635 r.append("DUP:"); 10636 r.append(pg.info.name); 10637 } 10638 } 10639 } 10640 if (r != null) { 10641 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10642 } 10643 10644 N = pkg.permissions.size(); 10645 r = null; 10646 for (i=0; i<N; i++) { 10647 PackageParser.Permission p = pkg.permissions.get(i); 10648 10649 // Dont allow ephemeral apps to define new permissions. 10650 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10651 Slog.w(TAG, "Permission " + p.info.name + " from package " 10652 + p.info.packageName 10653 + " ignored: instant apps cannot define new permissions."); 10654 continue; 10655 } 10656 10657 // Assume by default that we did not install this permission into the system. 10658 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10659 10660 // Now that permission groups have a special meaning, we ignore permission 10661 // groups for legacy apps to prevent unexpected behavior. In particular, 10662 // permissions for one app being granted to someone just becase they happen 10663 // to be in a group defined by another app (before this had no implications). 10664 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10665 p.group = mPermissionGroups.get(p.info.group); 10666 // Warn for a permission in an unknown group. 10667 if (p.info.group != null && p.group == null) { 10668 Slog.w(TAG, "Permission " + p.info.name + " from package " 10669 + p.info.packageName + " in an unknown group " + p.info.group); 10670 } 10671 } 10672 10673 ArrayMap<String, BasePermission> permissionMap = 10674 p.tree ? mSettings.mPermissionTrees 10675 : mSettings.mPermissions; 10676 BasePermission bp = permissionMap.get(p.info.name); 10677 10678 // Allow system apps to redefine non-system permissions 10679 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10680 final boolean currentOwnerIsSystem = (bp.perm != null 10681 && isSystemApp(bp.perm.owner)); 10682 if (isSystemApp(p.owner)) { 10683 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10684 // It's a built-in permission and no owner, take ownership now 10685 bp.packageSetting = pkgSetting; 10686 bp.perm = p; 10687 bp.uid = pkg.applicationInfo.uid; 10688 bp.sourcePackage = p.info.packageName; 10689 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10690 } else if (!currentOwnerIsSystem) { 10691 String msg = "New decl " + p.owner + " of permission " 10692 + p.info.name + " is system; overriding " + bp.sourcePackage; 10693 reportSettingsProblem(Log.WARN, msg); 10694 bp = null; 10695 } 10696 } 10697 } 10698 10699 if (bp == null) { 10700 bp = new BasePermission(p.info.name, p.info.packageName, 10701 BasePermission.TYPE_NORMAL); 10702 permissionMap.put(p.info.name, bp); 10703 } 10704 10705 if (bp.perm == null) { 10706 if (bp.sourcePackage == null 10707 || bp.sourcePackage.equals(p.info.packageName)) { 10708 BasePermission tree = findPermissionTreeLP(p.info.name); 10709 if (tree == null 10710 || tree.sourcePackage.equals(p.info.packageName)) { 10711 bp.packageSetting = pkgSetting; 10712 bp.perm = p; 10713 bp.uid = pkg.applicationInfo.uid; 10714 bp.sourcePackage = p.info.packageName; 10715 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10716 if (chatty) { 10717 if (r == null) { 10718 r = new StringBuilder(256); 10719 } else { 10720 r.append(' '); 10721 } 10722 r.append(p.info.name); 10723 } 10724 } else { 10725 Slog.w(TAG, "Permission " + p.info.name + " from package " 10726 + p.info.packageName + " ignored: base tree " 10727 + tree.name + " is from package " 10728 + tree.sourcePackage); 10729 } 10730 } else { 10731 Slog.w(TAG, "Permission " + p.info.name + " from package " 10732 + p.info.packageName + " ignored: original from " 10733 + bp.sourcePackage); 10734 } 10735 } else if (chatty) { 10736 if (r == null) { 10737 r = new StringBuilder(256); 10738 } else { 10739 r.append(' '); 10740 } 10741 r.append("DUP:"); 10742 r.append(p.info.name); 10743 } 10744 if (bp.perm == p) { 10745 bp.protectionLevel = p.info.protectionLevel; 10746 } 10747 } 10748 10749 if (r != null) { 10750 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10751 } 10752 10753 N = pkg.instrumentation.size(); 10754 r = null; 10755 for (i=0; i<N; i++) { 10756 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10757 a.info.packageName = pkg.applicationInfo.packageName; 10758 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10759 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10760 a.info.splitNames = pkg.splitNames; 10761 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10762 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10763 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10764 a.info.dataDir = pkg.applicationInfo.dataDir; 10765 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10766 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10767 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10768 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10769 mInstrumentation.put(a.getComponentName(), a); 10770 if (chatty) { 10771 if (r == null) { 10772 r = new StringBuilder(256); 10773 } else { 10774 r.append(' '); 10775 } 10776 r.append(a.info.name); 10777 } 10778 } 10779 if (r != null) { 10780 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10781 } 10782 10783 if (pkg.protectedBroadcasts != null) { 10784 N = pkg.protectedBroadcasts.size(); 10785 for (i=0; i<N; i++) { 10786 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10787 } 10788 } 10789 } 10790 10791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10792 } 10793 10794 /** 10795 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10796 * is derived purely on the basis of the contents of {@code scanFile} and 10797 * {@code cpuAbiOverride}. 10798 * 10799 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10800 */ 10801 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10802 String cpuAbiOverride, boolean extractLibs, 10803 File appLib32InstallDir) 10804 throws PackageManagerException { 10805 // Give ourselves some initial paths; we'll come back for another 10806 // pass once we've determined ABI below. 10807 setNativeLibraryPaths(pkg, appLib32InstallDir); 10808 10809 // We would never need to extract libs for forward-locked and external packages, 10810 // since the container service will do it for us. We shouldn't attempt to 10811 // extract libs from system app when it was not updated. 10812 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10813 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10814 extractLibs = false; 10815 } 10816 10817 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10818 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10819 10820 NativeLibraryHelper.Handle handle = null; 10821 try { 10822 handle = NativeLibraryHelper.Handle.create(pkg); 10823 // TODO(multiArch): This can be null for apps that didn't go through the 10824 // usual installation process. We can calculate it again, like we 10825 // do during install time. 10826 // 10827 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10828 // unnecessary. 10829 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10830 10831 // Null out the abis so that they can be recalculated. 10832 pkg.applicationInfo.primaryCpuAbi = null; 10833 pkg.applicationInfo.secondaryCpuAbi = null; 10834 if (isMultiArch(pkg.applicationInfo)) { 10835 // Warn if we've set an abiOverride for multi-lib packages.. 10836 // By definition, we need to copy both 32 and 64 bit libraries for 10837 // such packages. 10838 if (pkg.cpuAbiOverride != null 10839 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10840 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10841 } 10842 10843 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10844 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10845 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10846 if (extractLibs) { 10847 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10848 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10849 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10850 useIsaSpecificSubdirs); 10851 } else { 10852 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10853 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10854 } 10855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10856 } 10857 10858 maybeThrowExceptionForMultiArchCopy( 10859 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10860 10861 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10862 if (extractLibs) { 10863 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10864 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10865 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10866 useIsaSpecificSubdirs); 10867 } else { 10868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10869 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10870 } 10871 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10872 } 10873 10874 maybeThrowExceptionForMultiArchCopy( 10875 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10876 10877 if (abi64 >= 0) { 10878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10879 } 10880 10881 if (abi32 >= 0) { 10882 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10883 if (abi64 >= 0) { 10884 if (pkg.use32bitAbi) { 10885 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10886 pkg.applicationInfo.primaryCpuAbi = abi; 10887 } else { 10888 pkg.applicationInfo.secondaryCpuAbi = abi; 10889 } 10890 } else { 10891 pkg.applicationInfo.primaryCpuAbi = abi; 10892 } 10893 } 10894 10895 } else { 10896 String[] abiList = (cpuAbiOverride != null) ? 10897 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10898 10899 // Enable gross and lame hacks for apps that are built with old 10900 // SDK tools. We must scan their APKs for renderscript bitcode and 10901 // not launch them if it's present. Don't bother checking on devices 10902 // that don't have 64 bit support. 10903 boolean needsRenderScriptOverride = false; 10904 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10905 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10906 abiList = Build.SUPPORTED_32_BIT_ABIS; 10907 needsRenderScriptOverride = true; 10908 } 10909 10910 final int copyRet; 10911 if (extractLibs) { 10912 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10913 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10914 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10915 } else { 10916 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10917 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10918 } 10919 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10920 10921 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10922 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10923 "Error unpackaging native libs for app, errorCode=" + copyRet); 10924 } 10925 10926 if (copyRet >= 0) { 10927 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10928 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10929 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10930 } else if (needsRenderScriptOverride) { 10931 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10932 } 10933 } 10934 } catch (IOException ioe) { 10935 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10936 } finally { 10937 IoUtils.closeQuietly(handle); 10938 } 10939 10940 // Now that we've calculated the ABIs and determined if it's an internal app, 10941 // we will go ahead and populate the nativeLibraryPath. 10942 setNativeLibraryPaths(pkg, appLib32InstallDir); 10943 } 10944 10945 /** 10946 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10947 * i.e, so that all packages can be run inside a single process if required. 10948 * 10949 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10950 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10951 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10952 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10953 * updating a package that belongs to a shared user. 10954 * 10955 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10956 * adds unnecessary complexity. 10957 */ 10958 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10959 PackageParser.Package scannedPackage) { 10960 String requiredInstructionSet = null; 10961 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10962 requiredInstructionSet = VMRuntime.getInstructionSet( 10963 scannedPackage.applicationInfo.primaryCpuAbi); 10964 } 10965 10966 PackageSetting requirer = null; 10967 for (PackageSetting ps : packagesForUser) { 10968 // If packagesForUser contains scannedPackage, we skip it. This will happen 10969 // when scannedPackage is an update of an existing package. Without this check, 10970 // we will never be able to change the ABI of any package belonging to a shared 10971 // user, even if it's compatible with other packages. 10972 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10973 if (ps.primaryCpuAbiString == null) { 10974 continue; 10975 } 10976 10977 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10978 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10979 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10980 // this but there's not much we can do. 10981 String errorMessage = "Instruction set mismatch, " 10982 + ((requirer == null) ? "[caller]" : requirer) 10983 + " requires " + requiredInstructionSet + " whereas " + ps 10984 + " requires " + instructionSet; 10985 Slog.w(TAG, errorMessage); 10986 } 10987 10988 if (requiredInstructionSet == null) { 10989 requiredInstructionSet = instructionSet; 10990 requirer = ps; 10991 } 10992 } 10993 } 10994 10995 if (requiredInstructionSet != null) { 10996 String adjustedAbi; 10997 if (requirer != null) { 10998 // requirer != null implies that either scannedPackage was null or that scannedPackage 10999 // did not require an ABI, in which case we have to adjust scannedPackage to match 11000 // the ABI of the set (which is the same as requirer's ABI) 11001 adjustedAbi = requirer.primaryCpuAbiString; 11002 if (scannedPackage != null) { 11003 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11004 } 11005 } else { 11006 // requirer == null implies that we're updating all ABIs in the set to 11007 // match scannedPackage. 11008 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11009 } 11010 11011 for (PackageSetting ps : packagesForUser) { 11012 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11013 if (ps.primaryCpuAbiString != null) { 11014 continue; 11015 } 11016 11017 ps.primaryCpuAbiString = adjustedAbi; 11018 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11019 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11020 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11021 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11022 + " (requirer=" 11023 + (requirer != null ? requirer.pkg : "null") 11024 + ", scannedPackage=" 11025 + (scannedPackage != null ? scannedPackage : "null") 11026 + ")"); 11027 try { 11028 mInstaller.rmdex(ps.codePathString, 11029 getDexCodeInstructionSet(getPreferredInstructionSet())); 11030 } catch (InstallerException ignored) { 11031 } 11032 } 11033 } 11034 } 11035 } 11036 } 11037 11038 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11039 synchronized (mPackages) { 11040 mResolverReplaced = true; 11041 // Set up information for custom user intent resolution activity. 11042 mResolveActivity.applicationInfo = pkg.applicationInfo; 11043 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11044 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11045 mResolveActivity.processName = pkg.applicationInfo.packageName; 11046 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11047 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11048 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11049 mResolveActivity.theme = 0; 11050 mResolveActivity.exported = true; 11051 mResolveActivity.enabled = true; 11052 mResolveInfo.activityInfo = mResolveActivity; 11053 mResolveInfo.priority = 0; 11054 mResolveInfo.preferredOrder = 0; 11055 mResolveInfo.match = 0; 11056 mResolveComponentName = mCustomResolverComponentName; 11057 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11058 mResolveComponentName); 11059 } 11060 } 11061 11062 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11063 if (installerActivity == null) { 11064 if (DEBUG_EPHEMERAL) { 11065 Slog.d(TAG, "Clear ephemeral installer activity"); 11066 } 11067 mInstantAppInstallerActivity = null; 11068 return; 11069 } 11070 11071 if (DEBUG_EPHEMERAL) { 11072 Slog.d(TAG, "Set ephemeral installer activity: " 11073 + installerActivity.getComponentName()); 11074 } 11075 // Set up information for ephemeral installer activity 11076 mInstantAppInstallerActivity = installerActivity; 11077 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11078 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11079 mInstantAppInstallerActivity.exported = true; 11080 mInstantAppInstallerActivity.enabled = true; 11081 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11082 mInstantAppInstallerInfo.priority = 0; 11083 mInstantAppInstallerInfo.preferredOrder = 1; 11084 mInstantAppInstallerInfo.isDefault = true; 11085 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11086 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11087 } 11088 11089 private static String calculateBundledApkRoot(final String codePathString) { 11090 final File codePath = new File(codePathString); 11091 final File codeRoot; 11092 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11093 codeRoot = Environment.getRootDirectory(); 11094 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11095 codeRoot = Environment.getOemDirectory(); 11096 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11097 codeRoot = Environment.getVendorDirectory(); 11098 } else { 11099 // Unrecognized code path; take its top real segment as the apk root: 11100 // e.g. /something/app/blah.apk => /something 11101 try { 11102 File f = codePath.getCanonicalFile(); 11103 File parent = f.getParentFile(); // non-null because codePath is a file 11104 File tmp; 11105 while ((tmp = parent.getParentFile()) != null) { 11106 f = parent; 11107 parent = tmp; 11108 } 11109 codeRoot = f; 11110 Slog.w(TAG, "Unrecognized code path " 11111 + codePath + " - using " + codeRoot); 11112 } catch (IOException e) { 11113 // Can't canonicalize the code path -- shenanigans? 11114 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11115 return Environment.getRootDirectory().getPath(); 11116 } 11117 } 11118 return codeRoot.getPath(); 11119 } 11120 11121 /** 11122 * Derive and set the location of native libraries for the given package, 11123 * which varies depending on where and how the package was installed. 11124 */ 11125 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11126 final ApplicationInfo info = pkg.applicationInfo; 11127 final String codePath = pkg.codePath; 11128 final File codeFile = new File(codePath); 11129 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11130 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11131 11132 info.nativeLibraryRootDir = null; 11133 info.nativeLibraryRootRequiresIsa = false; 11134 info.nativeLibraryDir = null; 11135 info.secondaryNativeLibraryDir = null; 11136 11137 if (isApkFile(codeFile)) { 11138 // Monolithic install 11139 if (bundledApp) { 11140 // If "/system/lib64/apkname" exists, assume that is the per-package 11141 // native library directory to use; otherwise use "/system/lib/apkname". 11142 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11143 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11144 getPrimaryInstructionSet(info)); 11145 11146 // This is a bundled system app so choose the path based on the ABI. 11147 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11148 // is just the default path. 11149 final String apkName = deriveCodePathName(codePath); 11150 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11151 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11152 apkName).getAbsolutePath(); 11153 11154 if (info.secondaryCpuAbi != null) { 11155 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11156 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11157 secondaryLibDir, apkName).getAbsolutePath(); 11158 } 11159 } else if (asecApp) { 11160 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11161 .getAbsolutePath(); 11162 } else { 11163 final String apkName = deriveCodePathName(codePath); 11164 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11165 .getAbsolutePath(); 11166 } 11167 11168 info.nativeLibraryRootRequiresIsa = false; 11169 info.nativeLibraryDir = info.nativeLibraryRootDir; 11170 } else { 11171 // Cluster install 11172 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11173 info.nativeLibraryRootRequiresIsa = true; 11174 11175 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11176 getPrimaryInstructionSet(info)).getAbsolutePath(); 11177 11178 if (info.secondaryCpuAbi != null) { 11179 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11180 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11181 } 11182 } 11183 } 11184 11185 /** 11186 * Calculate the abis and roots for a bundled app. These can uniquely 11187 * be determined from the contents of the system partition, i.e whether 11188 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11189 * of this information, and instead assume that the system was built 11190 * sensibly. 11191 */ 11192 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11193 PackageSetting pkgSetting) { 11194 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11195 11196 // If "/system/lib64/apkname" exists, assume that is the per-package 11197 // native library directory to use; otherwise use "/system/lib/apkname". 11198 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11199 setBundledAppAbi(pkg, apkRoot, apkName); 11200 // pkgSetting might be null during rescan following uninstall of updates 11201 // to a bundled app, so accommodate that possibility. The settings in 11202 // that case will be established later from the parsed package. 11203 // 11204 // If the settings aren't null, sync them up with what we've just derived. 11205 // note that apkRoot isn't stored in the package settings. 11206 if (pkgSetting != null) { 11207 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11208 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11209 } 11210 } 11211 11212 /** 11213 * Deduces the ABI of a bundled app and sets the relevant fields on the 11214 * parsed pkg object. 11215 * 11216 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11217 * under which system libraries are installed. 11218 * @param apkName the name of the installed package. 11219 */ 11220 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11221 final File codeFile = new File(pkg.codePath); 11222 11223 final boolean has64BitLibs; 11224 final boolean has32BitLibs; 11225 if (isApkFile(codeFile)) { 11226 // Monolithic install 11227 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11228 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11229 } else { 11230 // Cluster install 11231 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11232 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11233 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11234 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11235 has64BitLibs = (new File(rootDir, isa)).exists(); 11236 } else { 11237 has64BitLibs = false; 11238 } 11239 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11240 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11241 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11242 has32BitLibs = (new File(rootDir, isa)).exists(); 11243 } else { 11244 has32BitLibs = false; 11245 } 11246 } 11247 11248 if (has64BitLibs && !has32BitLibs) { 11249 // The package has 64 bit libs, but not 32 bit libs. Its primary 11250 // ABI should be 64 bit. We can safely assume here that the bundled 11251 // native libraries correspond to the most preferred ABI in the list. 11252 11253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11254 pkg.applicationInfo.secondaryCpuAbi = null; 11255 } else if (has32BitLibs && !has64BitLibs) { 11256 // The package has 32 bit libs but not 64 bit libs. Its primary 11257 // ABI should be 32 bit. 11258 11259 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11260 pkg.applicationInfo.secondaryCpuAbi = null; 11261 } else if (has32BitLibs && has64BitLibs) { 11262 // The application has both 64 and 32 bit bundled libraries. We check 11263 // here that the app declares multiArch support, and warn if it doesn't. 11264 // 11265 // We will be lenient here and record both ABIs. The primary will be the 11266 // ABI that's higher on the list, i.e, a device that's configured to prefer 11267 // 64 bit apps will see a 64 bit primary ABI, 11268 11269 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11270 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11271 } 11272 11273 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11274 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11275 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11276 } else { 11277 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11278 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11279 } 11280 } else { 11281 pkg.applicationInfo.primaryCpuAbi = null; 11282 pkg.applicationInfo.secondaryCpuAbi = null; 11283 } 11284 } 11285 11286 private void killApplication(String pkgName, int appId, String reason) { 11287 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11288 } 11289 11290 private void killApplication(String pkgName, int appId, int userId, String reason) { 11291 // Request the ActivityManager to kill the process(only for existing packages) 11292 // so that we do not end up in a confused state while the user is still using the older 11293 // version of the application while the new one gets installed. 11294 final long token = Binder.clearCallingIdentity(); 11295 try { 11296 IActivityManager am = ActivityManager.getService(); 11297 if (am != null) { 11298 try { 11299 am.killApplication(pkgName, appId, userId, reason); 11300 } catch (RemoteException e) { 11301 } 11302 } 11303 } finally { 11304 Binder.restoreCallingIdentity(token); 11305 } 11306 } 11307 11308 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11309 // Remove the parent package setting 11310 PackageSetting ps = (PackageSetting) pkg.mExtras; 11311 if (ps != null) { 11312 removePackageLI(ps, chatty); 11313 } 11314 // Remove the child package setting 11315 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11316 for (int i = 0; i < childCount; i++) { 11317 PackageParser.Package childPkg = pkg.childPackages.get(i); 11318 ps = (PackageSetting) childPkg.mExtras; 11319 if (ps != null) { 11320 removePackageLI(ps, chatty); 11321 } 11322 } 11323 } 11324 11325 void removePackageLI(PackageSetting ps, boolean chatty) { 11326 if (DEBUG_INSTALL) { 11327 if (chatty) 11328 Log.d(TAG, "Removing package " + ps.name); 11329 } 11330 11331 // writer 11332 synchronized (mPackages) { 11333 mPackages.remove(ps.name); 11334 final PackageParser.Package pkg = ps.pkg; 11335 if (pkg != null) { 11336 cleanPackageDataStructuresLILPw(pkg, chatty); 11337 } 11338 } 11339 } 11340 11341 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11342 if (DEBUG_INSTALL) { 11343 if (chatty) 11344 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11345 } 11346 11347 // writer 11348 synchronized (mPackages) { 11349 // Remove the parent package 11350 mPackages.remove(pkg.applicationInfo.packageName); 11351 cleanPackageDataStructuresLILPw(pkg, chatty); 11352 11353 // Remove the child packages 11354 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11355 for (int i = 0; i < childCount; i++) { 11356 PackageParser.Package childPkg = pkg.childPackages.get(i); 11357 mPackages.remove(childPkg.applicationInfo.packageName); 11358 cleanPackageDataStructuresLILPw(childPkg, chatty); 11359 } 11360 } 11361 } 11362 11363 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11364 int N = pkg.providers.size(); 11365 StringBuilder r = null; 11366 int i; 11367 for (i=0; i<N; i++) { 11368 PackageParser.Provider p = pkg.providers.get(i); 11369 mProviders.removeProvider(p); 11370 if (p.info.authority == null) { 11371 11372 /* There was another ContentProvider with this authority when 11373 * this app was installed so this authority is null, 11374 * Ignore it as we don't have to unregister the provider. 11375 */ 11376 continue; 11377 } 11378 String names[] = p.info.authority.split(";"); 11379 for (int j = 0; j < names.length; j++) { 11380 if (mProvidersByAuthority.get(names[j]) == p) { 11381 mProvidersByAuthority.remove(names[j]); 11382 if (DEBUG_REMOVE) { 11383 if (chatty) 11384 Log.d(TAG, "Unregistered content provider: " + names[j] 11385 + ", className = " + p.info.name + ", isSyncable = " 11386 + p.info.isSyncable); 11387 } 11388 } 11389 } 11390 if (DEBUG_REMOVE && chatty) { 11391 if (r == null) { 11392 r = new StringBuilder(256); 11393 } else { 11394 r.append(' '); 11395 } 11396 r.append(p.info.name); 11397 } 11398 } 11399 if (r != null) { 11400 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11401 } 11402 11403 N = pkg.services.size(); 11404 r = null; 11405 for (i=0; i<N; i++) { 11406 PackageParser.Service s = pkg.services.get(i); 11407 mServices.removeService(s); 11408 if (chatty) { 11409 if (r == null) { 11410 r = new StringBuilder(256); 11411 } else { 11412 r.append(' '); 11413 } 11414 r.append(s.info.name); 11415 } 11416 } 11417 if (r != null) { 11418 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11419 } 11420 11421 N = pkg.receivers.size(); 11422 r = null; 11423 for (i=0; i<N; i++) { 11424 PackageParser.Activity a = pkg.receivers.get(i); 11425 mReceivers.removeActivity(a, "receiver"); 11426 if (DEBUG_REMOVE && chatty) { 11427 if (r == null) { 11428 r = new StringBuilder(256); 11429 } else { 11430 r.append(' '); 11431 } 11432 r.append(a.info.name); 11433 } 11434 } 11435 if (r != null) { 11436 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11437 } 11438 11439 N = pkg.activities.size(); 11440 r = null; 11441 for (i=0; i<N; i++) { 11442 PackageParser.Activity a = pkg.activities.get(i); 11443 mActivities.removeActivity(a, "activity"); 11444 if (DEBUG_REMOVE && chatty) { 11445 if (r == null) { 11446 r = new StringBuilder(256); 11447 } else { 11448 r.append(' '); 11449 } 11450 r.append(a.info.name); 11451 } 11452 } 11453 if (r != null) { 11454 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11455 } 11456 11457 N = pkg.permissions.size(); 11458 r = null; 11459 for (i=0; i<N; i++) { 11460 PackageParser.Permission p = pkg.permissions.get(i); 11461 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11462 if (bp == null) { 11463 bp = mSettings.mPermissionTrees.get(p.info.name); 11464 } 11465 if (bp != null && bp.perm == p) { 11466 bp.perm = null; 11467 if (DEBUG_REMOVE && chatty) { 11468 if (r == null) { 11469 r = new StringBuilder(256); 11470 } else { 11471 r.append(' '); 11472 } 11473 r.append(p.info.name); 11474 } 11475 } 11476 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11477 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11478 if (appOpPkgs != null) { 11479 appOpPkgs.remove(pkg.packageName); 11480 } 11481 } 11482 } 11483 if (r != null) { 11484 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11485 } 11486 11487 N = pkg.requestedPermissions.size(); 11488 r = null; 11489 for (i=0; i<N; i++) { 11490 String perm = pkg.requestedPermissions.get(i); 11491 BasePermission bp = mSettings.mPermissions.get(perm); 11492 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11493 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11494 if (appOpPkgs != null) { 11495 appOpPkgs.remove(pkg.packageName); 11496 if (appOpPkgs.isEmpty()) { 11497 mAppOpPermissionPackages.remove(perm); 11498 } 11499 } 11500 } 11501 } 11502 if (r != null) { 11503 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11504 } 11505 11506 N = pkg.instrumentation.size(); 11507 r = null; 11508 for (i=0; i<N; i++) { 11509 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11510 mInstrumentation.remove(a.getComponentName()); 11511 if (DEBUG_REMOVE && chatty) { 11512 if (r == null) { 11513 r = new StringBuilder(256); 11514 } else { 11515 r.append(' '); 11516 } 11517 r.append(a.info.name); 11518 } 11519 } 11520 if (r != null) { 11521 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11522 } 11523 11524 r = null; 11525 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11526 // Only system apps can hold shared libraries. 11527 if (pkg.libraryNames != null) { 11528 for (i = 0; i < pkg.libraryNames.size(); i++) { 11529 String name = pkg.libraryNames.get(i); 11530 if (removeSharedLibraryLPw(name, 0)) { 11531 if (DEBUG_REMOVE && chatty) { 11532 if (r == null) { 11533 r = new StringBuilder(256); 11534 } else { 11535 r.append(' '); 11536 } 11537 r.append(name); 11538 } 11539 } 11540 } 11541 } 11542 } 11543 11544 r = null; 11545 11546 // Any package can hold static shared libraries. 11547 if (pkg.staticSharedLibName != null) { 11548 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11549 if (DEBUG_REMOVE && chatty) { 11550 if (r == null) { 11551 r = new StringBuilder(256); 11552 } else { 11553 r.append(' '); 11554 } 11555 r.append(pkg.staticSharedLibName); 11556 } 11557 } 11558 } 11559 11560 if (r != null) { 11561 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11562 } 11563 } 11564 11565 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11566 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11567 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11568 return true; 11569 } 11570 } 11571 return false; 11572 } 11573 11574 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11575 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11576 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11577 11578 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11579 // Update the parent permissions 11580 updatePermissionsLPw(pkg.packageName, pkg, flags); 11581 // Update the child permissions 11582 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11583 for (int i = 0; i < childCount; i++) { 11584 PackageParser.Package childPkg = pkg.childPackages.get(i); 11585 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11586 } 11587 } 11588 11589 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11590 int flags) { 11591 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11592 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11593 } 11594 11595 private void updatePermissionsLPw(String changingPkg, 11596 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11597 // Make sure there are no dangling permission trees. 11598 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11599 while (it.hasNext()) { 11600 final BasePermission bp = it.next(); 11601 if (bp.packageSetting == null) { 11602 // We may not yet have parsed the package, so just see if 11603 // we still know about its settings. 11604 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11605 } 11606 if (bp.packageSetting == null) { 11607 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11608 + " from package " + bp.sourcePackage); 11609 it.remove(); 11610 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11611 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11612 Slog.i(TAG, "Removing old permission tree: " + bp.name 11613 + " from package " + bp.sourcePackage); 11614 flags |= UPDATE_PERMISSIONS_ALL; 11615 it.remove(); 11616 } 11617 } 11618 } 11619 11620 // Make sure all dynamic permissions have been assigned to a package, 11621 // and make sure there are no dangling permissions. 11622 it = mSettings.mPermissions.values().iterator(); 11623 while (it.hasNext()) { 11624 final BasePermission bp = it.next(); 11625 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11626 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11627 + bp.name + " pkg=" + bp.sourcePackage 11628 + " info=" + bp.pendingInfo); 11629 if (bp.packageSetting == null && bp.pendingInfo != null) { 11630 final BasePermission tree = findPermissionTreeLP(bp.name); 11631 if (tree != null && tree.perm != null) { 11632 bp.packageSetting = tree.packageSetting; 11633 bp.perm = new PackageParser.Permission(tree.perm.owner, 11634 new PermissionInfo(bp.pendingInfo)); 11635 bp.perm.info.packageName = tree.perm.info.packageName; 11636 bp.perm.info.name = bp.name; 11637 bp.uid = tree.uid; 11638 } 11639 } 11640 } 11641 if (bp.packageSetting == null) { 11642 // We may not yet have parsed the package, so just see if 11643 // we still know about its settings. 11644 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11645 } 11646 if (bp.packageSetting == null) { 11647 Slog.w(TAG, "Removing dangling permission: " + bp.name 11648 + " from package " + bp.sourcePackage); 11649 it.remove(); 11650 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11651 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11652 Slog.i(TAG, "Removing old permission: " + bp.name 11653 + " from package " + bp.sourcePackage); 11654 flags |= UPDATE_PERMISSIONS_ALL; 11655 it.remove(); 11656 } 11657 } 11658 } 11659 11660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11661 // Now update the permissions for all packages, in particular 11662 // replace the granted permissions of the system packages. 11663 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11664 for (PackageParser.Package pkg : mPackages.values()) { 11665 if (pkg != pkgInfo) { 11666 // Only replace for packages on requested volume 11667 final String volumeUuid = getVolumeUuidForPackage(pkg); 11668 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11669 && Objects.equals(replaceVolumeUuid, volumeUuid); 11670 grantPermissionsLPw(pkg, replace, changingPkg); 11671 } 11672 } 11673 } 11674 11675 if (pkgInfo != null) { 11676 // Only replace for packages on requested volume 11677 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11678 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11679 && Objects.equals(replaceVolumeUuid, volumeUuid); 11680 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11681 } 11682 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11683 } 11684 11685 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11686 String packageOfInterest) { 11687 // IMPORTANT: There are two types of permissions: install and runtime. 11688 // Install time permissions are granted when the app is installed to 11689 // all device users and users added in the future. Runtime permissions 11690 // are granted at runtime explicitly to specific users. Normal and signature 11691 // protected permissions are install time permissions. Dangerous permissions 11692 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11693 // otherwise they are runtime permissions. This function does not manage 11694 // runtime permissions except for the case an app targeting Lollipop MR1 11695 // being upgraded to target a newer SDK, in which case dangerous permissions 11696 // are transformed from install time to runtime ones. 11697 11698 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11699 if (ps == null) { 11700 return; 11701 } 11702 11703 PermissionsState permissionsState = ps.getPermissionsState(); 11704 PermissionsState origPermissions = permissionsState; 11705 11706 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11707 11708 boolean runtimePermissionsRevoked = false; 11709 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11710 11711 boolean changedInstallPermission = false; 11712 11713 if (replace) { 11714 ps.installPermissionsFixed = false; 11715 if (!ps.isSharedUser()) { 11716 origPermissions = new PermissionsState(permissionsState); 11717 permissionsState.reset(); 11718 } else { 11719 // We need to know only about runtime permission changes since the 11720 // calling code always writes the install permissions state but 11721 // the runtime ones are written only if changed. The only cases of 11722 // changed runtime permissions here are promotion of an install to 11723 // runtime and revocation of a runtime from a shared user. 11724 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11725 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11726 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11727 runtimePermissionsRevoked = true; 11728 } 11729 } 11730 } 11731 11732 permissionsState.setGlobalGids(mGlobalGids); 11733 11734 final int N = pkg.requestedPermissions.size(); 11735 for (int i=0; i<N; i++) { 11736 final String name = pkg.requestedPermissions.get(i); 11737 final BasePermission bp = mSettings.mPermissions.get(name); 11738 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11739 >= Build.VERSION_CODES.M; 11740 11741 if (DEBUG_INSTALL) { 11742 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11743 } 11744 11745 if (bp == null || bp.packageSetting == null) { 11746 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11747 Slog.w(TAG, "Unknown permission " + name 11748 + " in package " + pkg.packageName); 11749 } 11750 continue; 11751 } 11752 11753 11754 // Limit ephemeral apps to ephemeral allowed permissions. 11755 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11756 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11757 + pkg.packageName); 11758 continue; 11759 } 11760 11761 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 11762 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 11763 + pkg.packageName); 11764 continue; 11765 } 11766 11767 final String perm = bp.name; 11768 boolean allowedSig = false; 11769 int grant = GRANT_DENIED; 11770 11771 // Keep track of app op permissions. 11772 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11773 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11774 if (pkgs == null) { 11775 pkgs = new ArraySet<>(); 11776 mAppOpPermissionPackages.put(bp.name, pkgs); 11777 } 11778 pkgs.add(pkg.packageName); 11779 } 11780 11781 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11782 switch (level) { 11783 case PermissionInfo.PROTECTION_NORMAL: { 11784 // For all apps normal permissions are install time ones. 11785 grant = GRANT_INSTALL; 11786 } break; 11787 11788 case PermissionInfo.PROTECTION_DANGEROUS: { 11789 // If a permission review is required for legacy apps we represent 11790 // their permissions as always granted runtime ones since we need 11791 // to keep the review required permission flag per user while an 11792 // install permission's state is shared across all users. 11793 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11794 // For legacy apps dangerous permissions are install time ones. 11795 grant = GRANT_INSTALL; 11796 } else if (origPermissions.hasInstallPermission(bp.name)) { 11797 // For legacy apps that became modern, install becomes runtime. 11798 grant = GRANT_UPGRADE; 11799 } else if (mPromoteSystemApps 11800 && isSystemApp(ps) 11801 && mExistingSystemPackages.contains(ps.name)) { 11802 // For legacy system apps, install becomes runtime. 11803 // We cannot check hasInstallPermission() for system apps since those 11804 // permissions were granted implicitly and not persisted pre-M. 11805 grant = GRANT_UPGRADE; 11806 } else { 11807 // For modern apps keep runtime permissions unchanged. 11808 grant = GRANT_RUNTIME; 11809 } 11810 } break; 11811 11812 case PermissionInfo.PROTECTION_SIGNATURE: { 11813 // For all apps signature permissions are install time ones. 11814 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11815 if (allowedSig) { 11816 grant = GRANT_INSTALL; 11817 } 11818 } break; 11819 } 11820 11821 if (DEBUG_INSTALL) { 11822 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11823 } 11824 11825 if (grant != GRANT_DENIED) { 11826 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11827 // If this is an existing, non-system package, then 11828 // we can't add any new permissions to it. 11829 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11830 // Except... if this is a permission that was added 11831 // to the platform (note: need to only do this when 11832 // updating the platform). 11833 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11834 grant = GRANT_DENIED; 11835 } 11836 } 11837 } 11838 11839 switch (grant) { 11840 case GRANT_INSTALL: { 11841 // Revoke this as runtime permission to handle the case of 11842 // a runtime permission being downgraded to an install one. 11843 // Also in permission review mode we keep dangerous permissions 11844 // for legacy apps 11845 for (int userId : UserManagerService.getInstance().getUserIds()) { 11846 if (origPermissions.getRuntimePermissionState( 11847 bp.name, userId) != null) { 11848 // Revoke the runtime permission and clear the flags. 11849 origPermissions.revokeRuntimePermission(bp, userId); 11850 origPermissions.updatePermissionFlags(bp, userId, 11851 PackageManager.MASK_PERMISSION_FLAGS, 0); 11852 // If we revoked a permission permission, we have to write. 11853 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11854 changedRuntimePermissionUserIds, userId); 11855 } 11856 } 11857 // Grant an install permission. 11858 if (permissionsState.grantInstallPermission(bp) != 11859 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11860 changedInstallPermission = true; 11861 } 11862 } break; 11863 11864 case GRANT_RUNTIME: { 11865 // Grant previously granted runtime permissions. 11866 for (int userId : UserManagerService.getInstance().getUserIds()) { 11867 PermissionState permissionState = origPermissions 11868 .getRuntimePermissionState(bp.name, userId); 11869 int flags = permissionState != null 11870 ? permissionState.getFlags() : 0; 11871 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11872 // Don't propagate the permission in a permission review mode if 11873 // the former was revoked, i.e. marked to not propagate on upgrade. 11874 // Note that in a permission review mode install permissions are 11875 // represented as constantly granted runtime ones since we need to 11876 // keep a per user state associated with the permission. Also the 11877 // revoke on upgrade flag is no longer applicable and is reset. 11878 final boolean revokeOnUpgrade = (flags & PackageManager 11879 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11880 if (revokeOnUpgrade) { 11881 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11882 // Since we changed the flags, we have to write. 11883 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11884 changedRuntimePermissionUserIds, userId); 11885 } 11886 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11887 if (permissionsState.grantRuntimePermission(bp, userId) == 11888 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11889 // If we cannot put the permission as it was, 11890 // we have to write. 11891 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11892 changedRuntimePermissionUserIds, userId); 11893 } 11894 } 11895 11896 // If the app supports runtime permissions no need for a review. 11897 if (mPermissionReviewRequired 11898 && appSupportsRuntimePermissions 11899 && (flags & PackageManager 11900 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11901 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11902 // Since we changed the flags, we have to write. 11903 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11904 changedRuntimePermissionUserIds, userId); 11905 } 11906 } else if (mPermissionReviewRequired 11907 && !appSupportsRuntimePermissions) { 11908 // For legacy apps that need a permission review, every new 11909 // runtime permission is granted but it is pending a review. 11910 // We also need to review only platform defined runtime 11911 // permissions as these are the only ones the platform knows 11912 // how to disable the API to simulate revocation as legacy 11913 // apps don't expect to run with revoked permissions. 11914 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11915 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11916 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11917 // We changed the flags, hence have to write. 11918 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11919 changedRuntimePermissionUserIds, userId); 11920 } 11921 } 11922 if (permissionsState.grantRuntimePermission(bp, userId) 11923 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11924 // We changed the permission, hence have to write. 11925 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11926 changedRuntimePermissionUserIds, userId); 11927 } 11928 } 11929 // Propagate the permission flags. 11930 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11931 } 11932 } break; 11933 11934 case GRANT_UPGRADE: { 11935 // Grant runtime permissions for a previously held install permission. 11936 PermissionState permissionState = origPermissions 11937 .getInstallPermissionState(bp.name); 11938 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11939 11940 if (origPermissions.revokeInstallPermission(bp) 11941 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11942 // We will be transferring the permission flags, so clear them. 11943 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11944 PackageManager.MASK_PERMISSION_FLAGS, 0); 11945 changedInstallPermission = true; 11946 } 11947 11948 // If the permission is not to be promoted to runtime we ignore it and 11949 // also its other flags as they are not applicable to install permissions. 11950 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11951 for (int userId : currentUserIds) { 11952 if (permissionsState.grantRuntimePermission(bp, userId) != 11953 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11954 // Transfer the permission flags. 11955 permissionsState.updatePermissionFlags(bp, userId, 11956 flags, flags); 11957 // If we granted the permission, we have to write. 11958 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11959 changedRuntimePermissionUserIds, userId); 11960 } 11961 } 11962 } 11963 } break; 11964 11965 default: { 11966 if (packageOfInterest == null 11967 || packageOfInterest.equals(pkg.packageName)) { 11968 Slog.w(TAG, "Not granting permission " + perm 11969 + " to package " + pkg.packageName 11970 + " because it was previously installed without"); 11971 } 11972 } break; 11973 } 11974 } else { 11975 if (permissionsState.revokeInstallPermission(bp) != 11976 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11977 // Also drop the permission flags. 11978 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11979 PackageManager.MASK_PERMISSION_FLAGS, 0); 11980 changedInstallPermission = true; 11981 Slog.i(TAG, "Un-granting permission " + perm 11982 + " from package " + pkg.packageName 11983 + " (protectionLevel=" + bp.protectionLevel 11984 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11985 + ")"); 11986 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11987 // Don't print warning for app op permissions, since it is fine for them 11988 // not to be granted, there is a UI for the user to decide. 11989 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11990 Slog.w(TAG, "Not granting permission " + perm 11991 + " to package " + pkg.packageName 11992 + " (protectionLevel=" + bp.protectionLevel 11993 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11994 + ")"); 11995 } 11996 } 11997 } 11998 } 11999 12000 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 12001 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 12002 // This is the first that we have heard about this package, so the 12003 // permissions we have now selected are fixed until explicitly 12004 // changed. 12005 ps.installPermissionsFixed = true; 12006 } 12007 12008 // Persist the runtime permissions state for users with changes. If permissions 12009 // were revoked because no app in the shared user declares them we have to 12010 // write synchronously to avoid losing runtime permissions state. 12011 for (int userId : changedRuntimePermissionUserIds) { 12012 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 12013 } 12014 } 12015 12016 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 12017 boolean allowed = false; 12018 final int NP = PackageParser.NEW_PERMISSIONS.length; 12019 for (int ip=0; ip<NP; ip++) { 12020 final PackageParser.NewPermissionInfo npi 12021 = PackageParser.NEW_PERMISSIONS[ip]; 12022 if (npi.name.equals(perm) 12023 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 12024 allowed = true; 12025 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 12026 + pkg.packageName); 12027 break; 12028 } 12029 } 12030 return allowed; 12031 } 12032 12033 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 12034 BasePermission bp, PermissionsState origPermissions) { 12035 boolean privilegedPermission = (bp.protectionLevel 12036 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 12037 boolean privappPermissionsDisable = 12038 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 12039 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 12040 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 12041 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 12042 && !platformPackage && platformPermission) { 12043 ArraySet<String> wlPermissions = SystemConfig.getInstance() 12044 .getPrivAppPermissions(pkg.packageName); 12045 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 12046 if (!whitelisted) { 12047 Slog.w(TAG, "Privileged permission " + perm + " for package " 12048 + pkg.packageName + " - not in privapp-permissions whitelist"); 12049 // Only report violations for apps on system image 12050 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 12051 if (mPrivappPermissionsViolations == null) { 12052 mPrivappPermissionsViolations = new ArraySet<>(); 12053 } 12054 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 12055 } 12056 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 12057 return false; 12058 } 12059 } 12060 } 12061 boolean allowed = (compareSignatures( 12062 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 12063 == PackageManager.SIGNATURE_MATCH) 12064 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 12065 == PackageManager.SIGNATURE_MATCH); 12066 if (!allowed && privilegedPermission) { 12067 if (isSystemApp(pkg)) { 12068 // For updated system applications, a system permission 12069 // is granted only if it had been defined by the original application. 12070 if (pkg.isUpdatedSystemApp()) { 12071 final PackageSetting sysPs = mSettings 12072 .getDisabledSystemPkgLPr(pkg.packageName); 12073 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 12074 // If the original was granted this permission, we take 12075 // that grant decision as read and propagate it to the 12076 // update. 12077 if (sysPs.isPrivileged()) { 12078 allowed = true; 12079 } 12080 } else { 12081 // The system apk may have been updated with an older 12082 // version of the one on the data partition, but which 12083 // granted a new system permission that it didn't have 12084 // before. In this case we do want to allow the app to 12085 // now get the new permission if the ancestral apk is 12086 // privileged to get it. 12087 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 12088 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 12089 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 12090 allowed = true; 12091 break; 12092 } 12093 } 12094 } 12095 // Also if a privileged parent package on the system image or any of 12096 // its children requested a privileged permission, the updated child 12097 // packages can also get the permission. 12098 if (pkg.parentPackage != null) { 12099 final PackageSetting disabledSysParentPs = mSettings 12100 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 12101 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 12102 && disabledSysParentPs.isPrivileged()) { 12103 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 12104 allowed = true; 12105 } else if (disabledSysParentPs.pkg.childPackages != null) { 12106 final int count = disabledSysParentPs.pkg.childPackages.size(); 12107 for (int i = 0; i < count; i++) { 12108 PackageParser.Package disabledSysChildPkg = 12109 disabledSysParentPs.pkg.childPackages.get(i); 12110 if (isPackageRequestingPermission(disabledSysChildPkg, 12111 perm)) { 12112 allowed = true; 12113 break; 12114 } 12115 } 12116 } 12117 } 12118 } 12119 } 12120 } else { 12121 allowed = isPrivilegedApp(pkg); 12122 } 12123 } 12124 } 12125 if (!allowed) { 12126 if (!allowed && (bp.protectionLevel 12127 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 12128 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 12129 // If this was a previously normal/dangerous permission that got moved 12130 // to a system permission as part of the runtime permission redesign, then 12131 // we still want to blindly grant it to old apps. 12132 allowed = true; 12133 } 12134 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 12135 && pkg.packageName.equals(mRequiredInstallerPackage)) { 12136 // If this permission is to be granted to the system installer and 12137 // this app is an installer, then it gets the permission. 12138 allowed = true; 12139 } 12140 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 12141 && pkg.packageName.equals(mRequiredVerifierPackage)) { 12142 // If this permission is to be granted to the system verifier and 12143 // this app is a verifier, then it gets the permission. 12144 allowed = true; 12145 } 12146 if (!allowed && (bp.protectionLevel 12147 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 12148 && isSystemApp(pkg)) { 12149 // Any pre-installed system app is allowed to get this permission. 12150 allowed = true; 12151 } 12152 if (!allowed && (bp.protectionLevel 12153 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 12154 // For development permissions, a development permission 12155 // is granted only if it was already granted. 12156 allowed = origPermissions.hasInstallPermission(perm); 12157 } 12158 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 12159 && pkg.packageName.equals(mSetupWizardPackage)) { 12160 // If this permission is to be granted to the system setup wizard and 12161 // this app is a setup wizard, then it gets the permission. 12162 allowed = true; 12163 } 12164 } 12165 return allowed; 12166 } 12167 12168 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 12169 final int permCount = pkg.requestedPermissions.size(); 12170 for (int j = 0; j < permCount; j++) { 12171 String requestedPermission = pkg.requestedPermissions.get(j); 12172 if (permission.equals(requestedPermission)) { 12173 return true; 12174 } 12175 } 12176 return false; 12177 } 12178 12179 final class ActivityIntentResolver 12180 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12181 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12182 boolean defaultOnly, int userId) { 12183 if (!sUserManager.exists(userId)) return null; 12184 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12185 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12186 } 12187 12188 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12189 int userId) { 12190 if (!sUserManager.exists(userId)) return null; 12191 mFlags = flags; 12192 return super.queryIntent(intent, resolvedType, 12193 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12194 userId); 12195 } 12196 12197 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12198 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12199 if (!sUserManager.exists(userId)) return null; 12200 if (packageActivities == null) { 12201 return null; 12202 } 12203 mFlags = flags; 12204 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12205 final int N = packageActivities.size(); 12206 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12207 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12208 12209 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12210 for (int i = 0; i < N; ++i) { 12211 intentFilters = packageActivities.get(i).intents; 12212 if (intentFilters != null && intentFilters.size() > 0) { 12213 PackageParser.ActivityIntentInfo[] array = 12214 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12215 intentFilters.toArray(array); 12216 listCut.add(array); 12217 } 12218 } 12219 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12220 } 12221 12222 /** 12223 * Finds a privileged activity that matches the specified activity names. 12224 */ 12225 private PackageParser.Activity findMatchingActivity( 12226 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12227 for (PackageParser.Activity sysActivity : activityList) { 12228 if (sysActivity.info.name.equals(activityInfo.name)) { 12229 return sysActivity; 12230 } 12231 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12232 return sysActivity; 12233 } 12234 if (sysActivity.info.targetActivity != null) { 12235 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12236 return sysActivity; 12237 } 12238 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12239 return sysActivity; 12240 } 12241 } 12242 } 12243 return null; 12244 } 12245 12246 public class IterGenerator<E> { 12247 public Iterator<E> generate(ActivityIntentInfo info) { 12248 return null; 12249 } 12250 } 12251 12252 public class ActionIterGenerator extends IterGenerator<String> { 12253 @Override 12254 public Iterator<String> generate(ActivityIntentInfo info) { 12255 return info.actionsIterator(); 12256 } 12257 } 12258 12259 public class CategoriesIterGenerator extends IterGenerator<String> { 12260 @Override 12261 public Iterator<String> generate(ActivityIntentInfo info) { 12262 return info.categoriesIterator(); 12263 } 12264 } 12265 12266 public class SchemesIterGenerator extends IterGenerator<String> { 12267 @Override 12268 public Iterator<String> generate(ActivityIntentInfo info) { 12269 return info.schemesIterator(); 12270 } 12271 } 12272 12273 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12274 @Override 12275 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12276 return info.authoritiesIterator(); 12277 } 12278 } 12279 12280 /** 12281 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12282 * MODIFIED. Do not pass in a list that should not be changed. 12283 */ 12284 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12285 IterGenerator<T> generator, Iterator<T> searchIterator) { 12286 // loop through the set of actions; every one must be found in the intent filter 12287 while (searchIterator.hasNext()) { 12288 // we must have at least one filter in the list to consider a match 12289 if (intentList.size() == 0) { 12290 break; 12291 } 12292 12293 final T searchAction = searchIterator.next(); 12294 12295 // loop through the set of intent filters 12296 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12297 while (intentIter.hasNext()) { 12298 final ActivityIntentInfo intentInfo = intentIter.next(); 12299 boolean selectionFound = false; 12300 12301 // loop through the intent filter's selection criteria; at least one 12302 // of them must match the searched criteria 12303 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12304 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12305 final T intentSelection = intentSelectionIter.next(); 12306 if (intentSelection != null && intentSelection.equals(searchAction)) { 12307 selectionFound = true; 12308 break; 12309 } 12310 } 12311 12312 // the selection criteria wasn't found in this filter's set; this filter 12313 // is not a potential match 12314 if (!selectionFound) { 12315 intentIter.remove(); 12316 } 12317 } 12318 } 12319 } 12320 12321 private boolean isProtectedAction(ActivityIntentInfo filter) { 12322 final Iterator<String> actionsIter = filter.actionsIterator(); 12323 while (actionsIter != null && actionsIter.hasNext()) { 12324 final String filterAction = actionsIter.next(); 12325 if (PROTECTED_ACTIONS.contains(filterAction)) { 12326 return true; 12327 } 12328 } 12329 return false; 12330 } 12331 12332 /** 12333 * Adjusts the priority of the given intent filter according to policy. 12334 * <p> 12335 * <ul> 12336 * <li>The priority for non privileged applications is capped to '0'</li> 12337 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12338 * <li>The priority for unbundled updates to privileged applications is capped to the 12339 * priority defined on the system partition</li> 12340 * </ul> 12341 * <p> 12342 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12343 * allowed to obtain any priority on any action. 12344 */ 12345 private void adjustPriority( 12346 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12347 // nothing to do; priority is fine as-is 12348 if (intent.getPriority() <= 0) { 12349 return; 12350 } 12351 12352 final ActivityInfo activityInfo = intent.activity.info; 12353 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12354 12355 final boolean privilegedApp = 12356 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12357 if (!privilegedApp) { 12358 // non-privileged applications can never define a priority >0 12359 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12360 + " package: " + applicationInfo.packageName 12361 + " activity: " + intent.activity.className 12362 + " origPrio: " + intent.getPriority()); 12363 intent.setPriority(0); 12364 return; 12365 } 12366 12367 if (systemActivities == null) { 12368 // the system package is not disabled; we're parsing the system partition 12369 if (isProtectedAction(intent)) { 12370 if (mDeferProtectedFilters) { 12371 // We can't deal with these just yet. No component should ever obtain a 12372 // >0 priority for a protected actions, with ONE exception -- the setup 12373 // wizard. The setup wizard, however, cannot be known until we're able to 12374 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12375 // until all intent filters have been processed. Chicken, meet egg. 12376 // Let the filter temporarily have a high priority and rectify the 12377 // priorities after all system packages have been scanned. 12378 mProtectedFilters.add(intent); 12379 if (DEBUG_FILTERS) { 12380 Slog.i(TAG, "Protected action; save for later;" 12381 + " package: " + applicationInfo.packageName 12382 + " activity: " + intent.activity.className 12383 + " origPrio: " + intent.getPriority()); 12384 } 12385 return; 12386 } else { 12387 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12388 Slog.i(TAG, "No setup wizard;" 12389 + " All protected intents capped to priority 0"); 12390 } 12391 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12392 if (DEBUG_FILTERS) { 12393 Slog.i(TAG, "Found setup wizard;" 12394 + " allow priority " + intent.getPriority() + ";" 12395 + " package: " + intent.activity.info.packageName 12396 + " activity: " + intent.activity.className 12397 + " priority: " + intent.getPriority()); 12398 } 12399 // setup wizard gets whatever it wants 12400 return; 12401 } 12402 Slog.w(TAG, "Protected action; cap priority to 0;" 12403 + " package: " + intent.activity.info.packageName 12404 + " activity: " + intent.activity.className 12405 + " origPrio: " + intent.getPriority()); 12406 intent.setPriority(0); 12407 return; 12408 } 12409 } 12410 // privileged apps on the system image get whatever priority they request 12411 return; 12412 } 12413 12414 // privileged app unbundled update ... try to find the same activity 12415 final PackageParser.Activity foundActivity = 12416 findMatchingActivity(systemActivities, activityInfo); 12417 if (foundActivity == null) { 12418 // this is a new activity; it cannot obtain >0 priority 12419 if (DEBUG_FILTERS) { 12420 Slog.i(TAG, "New activity; cap priority to 0;" 12421 + " package: " + applicationInfo.packageName 12422 + " activity: " + intent.activity.className 12423 + " origPrio: " + intent.getPriority()); 12424 } 12425 intent.setPriority(0); 12426 return; 12427 } 12428 12429 // found activity, now check for filter equivalence 12430 12431 // a shallow copy is enough; we modify the list, not its contents 12432 final List<ActivityIntentInfo> intentListCopy = 12433 new ArrayList<>(foundActivity.intents); 12434 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12435 12436 // find matching action subsets 12437 final Iterator<String> actionsIterator = intent.actionsIterator(); 12438 if (actionsIterator != null) { 12439 getIntentListSubset( 12440 intentListCopy, new ActionIterGenerator(), actionsIterator); 12441 if (intentListCopy.size() == 0) { 12442 // no more intents to match; we're not equivalent 12443 if (DEBUG_FILTERS) { 12444 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12445 + " package: " + applicationInfo.packageName 12446 + " activity: " + intent.activity.className 12447 + " origPrio: " + intent.getPriority()); 12448 } 12449 intent.setPriority(0); 12450 return; 12451 } 12452 } 12453 12454 // find matching category subsets 12455 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12456 if (categoriesIterator != null) { 12457 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12458 categoriesIterator); 12459 if (intentListCopy.size() == 0) { 12460 // no more intents to match; we're not equivalent 12461 if (DEBUG_FILTERS) { 12462 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12463 + " package: " + applicationInfo.packageName 12464 + " activity: " + intent.activity.className 12465 + " origPrio: " + intent.getPriority()); 12466 } 12467 intent.setPriority(0); 12468 return; 12469 } 12470 } 12471 12472 // find matching schemes subsets 12473 final Iterator<String> schemesIterator = intent.schemesIterator(); 12474 if (schemesIterator != null) { 12475 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12476 schemesIterator); 12477 if (intentListCopy.size() == 0) { 12478 // no more intents to match; we're not equivalent 12479 if (DEBUG_FILTERS) { 12480 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12481 + " package: " + applicationInfo.packageName 12482 + " activity: " + intent.activity.className 12483 + " origPrio: " + intent.getPriority()); 12484 } 12485 intent.setPriority(0); 12486 return; 12487 } 12488 } 12489 12490 // find matching authorities subsets 12491 final Iterator<IntentFilter.AuthorityEntry> 12492 authoritiesIterator = intent.authoritiesIterator(); 12493 if (authoritiesIterator != null) { 12494 getIntentListSubset(intentListCopy, 12495 new AuthoritiesIterGenerator(), 12496 authoritiesIterator); 12497 if (intentListCopy.size() == 0) { 12498 // no more intents to match; we're not equivalent 12499 if (DEBUG_FILTERS) { 12500 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12501 + " package: " + applicationInfo.packageName 12502 + " activity: " + intent.activity.className 12503 + " origPrio: " + intent.getPriority()); 12504 } 12505 intent.setPriority(0); 12506 return; 12507 } 12508 } 12509 12510 // we found matching filter(s); app gets the max priority of all intents 12511 int cappedPriority = 0; 12512 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12513 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12514 } 12515 if (intent.getPriority() > cappedPriority) { 12516 if (DEBUG_FILTERS) { 12517 Slog.i(TAG, "Found matching filter(s);" 12518 + " cap priority to " + cappedPriority + ";" 12519 + " package: " + applicationInfo.packageName 12520 + " activity: " + intent.activity.className 12521 + " origPrio: " + intent.getPriority()); 12522 } 12523 intent.setPriority(cappedPriority); 12524 return; 12525 } 12526 // all this for nothing; the requested priority was <= what was on the system 12527 } 12528 12529 public final void addActivity(PackageParser.Activity a, String type) { 12530 mActivities.put(a.getComponentName(), a); 12531 if (DEBUG_SHOW_INFO) 12532 Log.v( 12533 TAG, " " + type + " " + 12534 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12535 if (DEBUG_SHOW_INFO) 12536 Log.v(TAG, " Class=" + a.info.name); 12537 final int NI = a.intents.size(); 12538 for (int j=0; j<NI; j++) { 12539 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12540 if ("activity".equals(type)) { 12541 final PackageSetting ps = 12542 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12543 final List<PackageParser.Activity> systemActivities = 12544 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12545 adjustPriority(systemActivities, intent); 12546 } 12547 if (DEBUG_SHOW_INFO) { 12548 Log.v(TAG, " IntentFilter:"); 12549 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12550 } 12551 if (!intent.debugCheck()) { 12552 Log.w(TAG, "==> For Activity " + a.info.name); 12553 } 12554 addFilter(intent); 12555 } 12556 } 12557 12558 public final void removeActivity(PackageParser.Activity a, String type) { 12559 mActivities.remove(a.getComponentName()); 12560 if (DEBUG_SHOW_INFO) { 12561 Log.v(TAG, " " + type + " " 12562 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12563 : a.info.name) + ":"); 12564 Log.v(TAG, " Class=" + a.info.name); 12565 } 12566 final int NI = a.intents.size(); 12567 for (int j=0; j<NI; j++) { 12568 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12569 if (DEBUG_SHOW_INFO) { 12570 Log.v(TAG, " IntentFilter:"); 12571 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12572 } 12573 removeFilter(intent); 12574 } 12575 } 12576 12577 @Override 12578 protected boolean allowFilterResult( 12579 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12580 ActivityInfo filterAi = filter.activity.info; 12581 for (int i=dest.size()-1; i>=0; i--) { 12582 ActivityInfo destAi = dest.get(i).activityInfo; 12583 if (destAi.name == filterAi.name 12584 && destAi.packageName == filterAi.packageName) { 12585 return false; 12586 } 12587 } 12588 return true; 12589 } 12590 12591 @Override 12592 protected ActivityIntentInfo[] newArray(int size) { 12593 return new ActivityIntentInfo[size]; 12594 } 12595 12596 @Override 12597 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12598 if (!sUserManager.exists(userId)) return true; 12599 PackageParser.Package p = filter.activity.owner; 12600 if (p != null) { 12601 PackageSetting ps = (PackageSetting)p.mExtras; 12602 if (ps != null) { 12603 // System apps are never considered stopped for purposes of 12604 // filtering, because there may be no way for the user to 12605 // actually re-launch them. 12606 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12607 && ps.getStopped(userId); 12608 } 12609 } 12610 return false; 12611 } 12612 12613 @Override 12614 protected boolean isPackageForFilter(String packageName, 12615 PackageParser.ActivityIntentInfo info) { 12616 return packageName.equals(info.activity.owner.packageName); 12617 } 12618 12619 @Override 12620 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12621 int match, int userId) { 12622 if (!sUserManager.exists(userId)) return null; 12623 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12624 return null; 12625 } 12626 final PackageParser.Activity activity = info.activity; 12627 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12628 if (ps == null) { 12629 return null; 12630 } 12631 final PackageUserState userState = ps.readUserState(userId); 12632 ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId); 12633 if (ai == null) { 12634 return null; 12635 } 12636 final boolean matchExplicitlyVisibleOnly = 12637 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12638 final boolean matchVisibleToInstantApp = 12639 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12640 final boolean componentVisible = 12641 matchVisibleToInstantApp 12642 && info.isVisibleToInstantApp() 12643 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12644 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12645 // throw out filters that aren't visible to ephemeral apps 12646 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12647 return null; 12648 } 12649 // throw out instant app filters if we're not explicitly requesting them 12650 if (!matchInstantApp && userState.instantApp) { 12651 return null; 12652 } 12653 // throw out instant app filters if updates are available; will trigger 12654 // instant app resolution 12655 if (userState.instantApp && ps.isUpdateAvailable()) { 12656 return null; 12657 } 12658 final ResolveInfo res = new ResolveInfo(); 12659 res.activityInfo = ai; 12660 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12661 res.filter = info; 12662 } 12663 if (info != null) { 12664 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12665 } 12666 res.priority = info.getPriority(); 12667 res.preferredOrder = activity.owner.mPreferredOrder; 12668 //System.out.println("Result: " + res.activityInfo.className + 12669 // " = " + res.priority); 12670 res.match = match; 12671 res.isDefault = info.hasDefault; 12672 res.labelRes = info.labelRes; 12673 res.nonLocalizedLabel = info.nonLocalizedLabel; 12674 if (userNeedsBadging(userId)) { 12675 res.noResourceId = true; 12676 } else { 12677 res.icon = info.icon; 12678 } 12679 res.iconResourceId = info.icon; 12680 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12681 res.isInstantAppAvailable = userState.instantApp; 12682 return res; 12683 } 12684 12685 @Override 12686 protected void sortResults(List<ResolveInfo> results) { 12687 Collections.sort(results, mResolvePrioritySorter); 12688 } 12689 12690 @Override 12691 protected void dumpFilter(PrintWriter out, String prefix, 12692 PackageParser.ActivityIntentInfo filter) { 12693 out.print(prefix); out.print( 12694 Integer.toHexString(System.identityHashCode(filter.activity))); 12695 out.print(' '); 12696 filter.activity.printComponentShortName(out); 12697 out.print(" filter "); 12698 out.println(Integer.toHexString(System.identityHashCode(filter))); 12699 } 12700 12701 @Override 12702 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12703 return filter.activity; 12704 } 12705 12706 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12707 PackageParser.Activity activity = (PackageParser.Activity)label; 12708 out.print(prefix); out.print( 12709 Integer.toHexString(System.identityHashCode(activity))); 12710 out.print(' '); 12711 activity.printComponentShortName(out); 12712 if (count > 1) { 12713 out.print(" ("); out.print(count); out.print(" filters)"); 12714 } 12715 out.println(); 12716 } 12717 12718 // Keys are String (activity class name), values are Activity. 12719 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12720 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12721 private int mFlags; 12722 } 12723 12724 private final class ServiceIntentResolver 12725 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12726 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12727 boolean defaultOnly, int userId) { 12728 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12729 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12730 } 12731 12732 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12733 int userId) { 12734 if (!sUserManager.exists(userId)) return null; 12735 mFlags = flags; 12736 return super.queryIntent(intent, resolvedType, 12737 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12738 userId); 12739 } 12740 12741 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12742 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12743 if (!sUserManager.exists(userId)) return null; 12744 if (packageServices == null) { 12745 return null; 12746 } 12747 mFlags = flags; 12748 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12749 final int N = packageServices.size(); 12750 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12751 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12752 12753 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12754 for (int i = 0; i < N; ++i) { 12755 intentFilters = packageServices.get(i).intents; 12756 if (intentFilters != null && intentFilters.size() > 0) { 12757 PackageParser.ServiceIntentInfo[] array = 12758 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12759 intentFilters.toArray(array); 12760 listCut.add(array); 12761 } 12762 } 12763 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12764 } 12765 12766 public final void addService(PackageParser.Service s) { 12767 mServices.put(s.getComponentName(), s); 12768 if (DEBUG_SHOW_INFO) { 12769 Log.v(TAG, " " 12770 + (s.info.nonLocalizedLabel != null 12771 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12772 Log.v(TAG, " Class=" + s.info.name); 12773 } 12774 final int NI = s.intents.size(); 12775 int j; 12776 for (j=0; j<NI; j++) { 12777 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12778 if (DEBUG_SHOW_INFO) { 12779 Log.v(TAG, " IntentFilter:"); 12780 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12781 } 12782 if (!intent.debugCheck()) { 12783 Log.w(TAG, "==> For Service " + s.info.name); 12784 } 12785 addFilter(intent); 12786 } 12787 } 12788 12789 public final void removeService(PackageParser.Service s) { 12790 mServices.remove(s.getComponentName()); 12791 if (DEBUG_SHOW_INFO) { 12792 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12793 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12794 Log.v(TAG, " Class=" + s.info.name); 12795 } 12796 final int NI = s.intents.size(); 12797 int j; 12798 for (j=0; j<NI; j++) { 12799 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12800 if (DEBUG_SHOW_INFO) { 12801 Log.v(TAG, " IntentFilter:"); 12802 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12803 } 12804 removeFilter(intent); 12805 } 12806 } 12807 12808 @Override 12809 protected boolean allowFilterResult( 12810 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12811 ServiceInfo filterSi = filter.service.info; 12812 for (int i=dest.size()-1; i>=0; i--) { 12813 ServiceInfo destAi = dest.get(i).serviceInfo; 12814 if (destAi.name == filterSi.name 12815 && destAi.packageName == filterSi.packageName) { 12816 return false; 12817 } 12818 } 12819 return true; 12820 } 12821 12822 @Override 12823 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12824 return new PackageParser.ServiceIntentInfo[size]; 12825 } 12826 12827 @Override 12828 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12829 if (!sUserManager.exists(userId)) return true; 12830 PackageParser.Package p = filter.service.owner; 12831 if (p != null) { 12832 PackageSetting ps = (PackageSetting)p.mExtras; 12833 if (ps != null) { 12834 // System apps are never considered stopped for purposes of 12835 // filtering, because there may be no way for the user to 12836 // actually re-launch them. 12837 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12838 && ps.getStopped(userId); 12839 } 12840 } 12841 return false; 12842 } 12843 12844 @Override 12845 protected boolean isPackageForFilter(String packageName, 12846 PackageParser.ServiceIntentInfo info) { 12847 return packageName.equals(info.service.owner.packageName); 12848 } 12849 12850 @Override 12851 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12852 int match, int userId) { 12853 if (!sUserManager.exists(userId)) return null; 12854 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12855 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12856 return null; 12857 } 12858 final PackageParser.Service service = info.service; 12859 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12860 if (ps == null) { 12861 return null; 12862 } 12863 final PackageUserState userState = ps.readUserState(userId); 12864 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12865 userState, userId); 12866 if (si == null) { 12867 return null; 12868 } 12869 final boolean matchVisibleToInstantApp = 12870 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12871 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12872 // throw out filters that aren't visible to ephemeral apps 12873 if (matchVisibleToInstantApp 12874 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12875 return null; 12876 } 12877 // throw out ephemeral filters if we're not explicitly requesting them 12878 if (!isInstantApp && userState.instantApp) { 12879 return null; 12880 } 12881 // throw out instant app filters if updates are available; will trigger 12882 // instant app resolution 12883 if (userState.instantApp && ps.isUpdateAvailable()) { 12884 return null; 12885 } 12886 final ResolveInfo res = new ResolveInfo(); 12887 res.serviceInfo = si; 12888 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12889 res.filter = filter; 12890 } 12891 res.priority = info.getPriority(); 12892 res.preferredOrder = service.owner.mPreferredOrder; 12893 res.match = match; 12894 res.isDefault = info.hasDefault; 12895 res.labelRes = info.labelRes; 12896 res.nonLocalizedLabel = info.nonLocalizedLabel; 12897 res.icon = info.icon; 12898 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12899 return res; 12900 } 12901 12902 @Override 12903 protected void sortResults(List<ResolveInfo> results) { 12904 Collections.sort(results, mResolvePrioritySorter); 12905 } 12906 12907 @Override 12908 protected void dumpFilter(PrintWriter out, String prefix, 12909 PackageParser.ServiceIntentInfo filter) { 12910 out.print(prefix); out.print( 12911 Integer.toHexString(System.identityHashCode(filter.service))); 12912 out.print(' '); 12913 filter.service.printComponentShortName(out); 12914 out.print(" filter "); 12915 out.println(Integer.toHexString(System.identityHashCode(filter))); 12916 } 12917 12918 @Override 12919 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12920 return filter.service; 12921 } 12922 12923 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12924 PackageParser.Service service = (PackageParser.Service)label; 12925 out.print(prefix); out.print( 12926 Integer.toHexString(System.identityHashCode(service))); 12927 out.print(' '); 12928 service.printComponentShortName(out); 12929 if (count > 1) { 12930 out.print(" ("); out.print(count); out.print(" filters)"); 12931 } 12932 out.println(); 12933 } 12934 12935// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12936// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12937// final List<ResolveInfo> retList = Lists.newArrayList(); 12938// while (i.hasNext()) { 12939// final ResolveInfo resolveInfo = (ResolveInfo) i; 12940// if (isEnabledLP(resolveInfo.serviceInfo)) { 12941// retList.add(resolveInfo); 12942// } 12943// } 12944// return retList; 12945// } 12946 12947 // Keys are String (activity class name), values are Activity. 12948 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12949 = new ArrayMap<ComponentName, PackageParser.Service>(); 12950 private int mFlags; 12951 } 12952 12953 private final class ProviderIntentResolver 12954 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12955 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12956 boolean defaultOnly, int userId) { 12957 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12958 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12959 } 12960 12961 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12962 int userId) { 12963 if (!sUserManager.exists(userId)) 12964 return null; 12965 mFlags = flags; 12966 return super.queryIntent(intent, resolvedType, 12967 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12968 userId); 12969 } 12970 12971 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12972 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12973 if (!sUserManager.exists(userId)) 12974 return null; 12975 if (packageProviders == null) { 12976 return null; 12977 } 12978 mFlags = flags; 12979 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12980 final int N = packageProviders.size(); 12981 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12982 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12983 12984 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12985 for (int i = 0; i < N; ++i) { 12986 intentFilters = packageProviders.get(i).intents; 12987 if (intentFilters != null && intentFilters.size() > 0) { 12988 PackageParser.ProviderIntentInfo[] array = 12989 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12990 intentFilters.toArray(array); 12991 listCut.add(array); 12992 } 12993 } 12994 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12995 } 12996 12997 public final void addProvider(PackageParser.Provider p) { 12998 if (mProviders.containsKey(p.getComponentName())) { 12999 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13000 return; 13001 } 13002 13003 mProviders.put(p.getComponentName(), p); 13004 if (DEBUG_SHOW_INFO) { 13005 Log.v(TAG, " " 13006 + (p.info.nonLocalizedLabel != null 13007 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13008 Log.v(TAG, " Class=" + p.info.name); 13009 } 13010 final int NI = p.intents.size(); 13011 int j; 13012 for (j = 0; j < NI; j++) { 13013 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13014 if (DEBUG_SHOW_INFO) { 13015 Log.v(TAG, " IntentFilter:"); 13016 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13017 } 13018 if (!intent.debugCheck()) { 13019 Log.w(TAG, "==> For Provider " + p.info.name); 13020 } 13021 addFilter(intent); 13022 } 13023 } 13024 13025 public final void removeProvider(PackageParser.Provider p) { 13026 mProviders.remove(p.getComponentName()); 13027 if (DEBUG_SHOW_INFO) { 13028 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13029 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13030 Log.v(TAG, " Class=" + p.info.name); 13031 } 13032 final int NI = p.intents.size(); 13033 int j; 13034 for (j = 0; j < NI; j++) { 13035 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13036 if (DEBUG_SHOW_INFO) { 13037 Log.v(TAG, " IntentFilter:"); 13038 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13039 } 13040 removeFilter(intent); 13041 } 13042 } 13043 13044 @Override 13045 protected boolean allowFilterResult( 13046 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13047 ProviderInfo filterPi = filter.provider.info; 13048 for (int i = dest.size() - 1; i >= 0; i--) { 13049 ProviderInfo destPi = dest.get(i).providerInfo; 13050 if (destPi.name == filterPi.name 13051 && destPi.packageName == filterPi.packageName) { 13052 return false; 13053 } 13054 } 13055 return true; 13056 } 13057 13058 @Override 13059 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13060 return new PackageParser.ProviderIntentInfo[size]; 13061 } 13062 13063 @Override 13064 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13065 if (!sUserManager.exists(userId)) 13066 return true; 13067 PackageParser.Package p = filter.provider.owner; 13068 if (p != null) { 13069 PackageSetting ps = (PackageSetting) p.mExtras; 13070 if (ps != null) { 13071 // System apps are never considered stopped for purposes of 13072 // filtering, because there may be no way for the user to 13073 // actually re-launch them. 13074 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13075 && ps.getStopped(userId); 13076 } 13077 } 13078 return false; 13079 } 13080 13081 @Override 13082 protected boolean isPackageForFilter(String packageName, 13083 PackageParser.ProviderIntentInfo info) { 13084 return packageName.equals(info.provider.owner.packageName); 13085 } 13086 13087 @Override 13088 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13089 int match, int userId) { 13090 if (!sUserManager.exists(userId)) 13091 return null; 13092 final PackageParser.ProviderIntentInfo info = filter; 13093 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13094 return null; 13095 } 13096 final PackageParser.Provider provider = info.provider; 13097 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13098 if (ps == null) { 13099 return null; 13100 } 13101 final PackageUserState userState = ps.readUserState(userId); 13102 final boolean matchVisibleToInstantApp = 13103 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13104 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13105 // throw out filters that aren't visible to instant applications 13106 if (matchVisibleToInstantApp 13107 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13108 return null; 13109 } 13110 // throw out instant application filters if we're not explicitly requesting them 13111 if (!isInstantApp && userState.instantApp) { 13112 return null; 13113 } 13114 // throw out instant application filters if updates are available; will trigger 13115 // instant application resolution 13116 if (userState.instantApp && ps.isUpdateAvailable()) { 13117 return null; 13118 } 13119 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13120 userState, userId); 13121 if (pi == null) { 13122 return null; 13123 } 13124 final ResolveInfo res = new ResolveInfo(); 13125 res.providerInfo = pi; 13126 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13127 res.filter = filter; 13128 } 13129 res.priority = info.getPriority(); 13130 res.preferredOrder = provider.owner.mPreferredOrder; 13131 res.match = match; 13132 res.isDefault = info.hasDefault; 13133 res.labelRes = info.labelRes; 13134 res.nonLocalizedLabel = info.nonLocalizedLabel; 13135 res.icon = info.icon; 13136 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13137 return res; 13138 } 13139 13140 @Override 13141 protected void sortResults(List<ResolveInfo> results) { 13142 Collections.sort(results, mResolvePrioritySorter); 13143 } 13144 13145 @Override 13146 protected void dumpFilter(PrintWriter out, String prefix, 13147 PackageParser.ProviderIntentInfo filter) { 13148 out.print(prefix); 13149 out.print( 13150 Integer.toHexString(System.identityHashCode(filter.provider))); 13151 out.print(' '); 13152 filter.provider.printComponentShortName(out); 13153 out.print(" filter "); 13154 out.println(Integer.toHexString(System.identityHashCode(filter))); 13155 } 13156 13157 @Override 13158 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13159 return filter.provider; 13160 } 13161 13162 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13163 PackageParser.Provider provider = (PackageParser.Provider)label; 13164 out.print(prefix); out.print( 13165 Integer.toHexString(System.identityHashCode(provider))); 13166 out.print(' '); 13167 provider.printComponentShortName(out); 13168 if (count > 1) { 13169 out.print(" ("); out.print(count); out.print(" filters)"); 13170 } 13171 out.println(); 13172 } 13173 13174 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13175 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13176 private int mFlags; 13177 } 13178 13179 static final class EphemeralIntentResolver 13180 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13181 /** 13182 * The result that has the highest defined order. Ordering applies on a 13183 * per-package basis. Mapping is from package name to Pair of order and 13184 * EphemeralResolveInfo. 13185 * <p> 13186 * NOTE: This is implemented as a field variable for convenience and efficiency. 13187 * By having a field variable, we're able to track filter ordering as soon as 13188 * a non-zero order is defined. Otherwise, multiple loops across the result set 13189 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13190 * this needs to be contained entirely within {@link #filterResults}. 13191 */ 13192 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13193 13194 @Override 13195 protected AuxiliaryResolveInfo[] newArray(int size) { 13196 return new AuxiliaryResolveInfo[size]; 13197 } 13198 13199 @Override 13200 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13201 return true; 13202 } 13203 13204 @Override 13205 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13206 int userId) { 13207 if (!sUserManager.exists(userId)) { 13208 return null; 13209 } 13210 final String packageName = responseObj.resolveInfo.getPackageName(); 13211 final Integer order = responseObj.getOrder(); 13212 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13213 mOrderResult.get(packageName); 13214 // ordering is enabled and this item's order isn't high enough 13215 if (lastOrderResult != null && lastOrderResult.first >= order) { 13216 return null; 13217 } 13218 final InstantAppResolveInfo res = responseObj.resolveInfo; 13219 if (order > 0) { 13220 // non-zero order, enable ordering 13221 mOrderResult.put(packageName, new Pair<>(order, res)); 13222 } 13223 return responseObj; 13224 } 13225 13226 @Override 13227 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13228 // only do work if ordering is enabled [most of the time it won't be] 13229 if (mOrderResult.size() == 0) { 13230 return; 13231 } 13232 int resultSize = results.size(); 13233 for (int i = 0; i < resultSize; i++) { 13234 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13235 final String packageName = info.getPackageName(); 13236 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13237 if (savedInfo == null) { 13238 // package doesn't having ordering 13239 continue; 13240 } 13241 if (savedInfo.second == info) { 13242 // circled back to the highest ordered item; remove from order list 13243 mOrderResult.remove(savedInfo); 13244 if (mOrderResult.size() == 0) { 13245 // no more ordered items 13246 break; 13247 } 13248 continue; 13249 } 13250 // item has a worse order, remove it from the result list 13251 results.remove(i); 13252 resultSize--; 13253 i--; 13254 } 13255 } 13256 } 13257 13258 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13259 new Comparator<ResolveInfo>() { 13260 public int compare(ResolveInfo r1, ResolveInfo r2) { 13261 int v1 = r1.priority; 13262 int v2 = r2.priority; 13263 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13264 if (v1 != v2) { 13265 return (v1 > v2) ? -1 : 1; 13266 } 13267 v1 = r1.preferredOrder; 13268 v2 = r2.preferredOrder; 13269 if (v1 != v2) { 13270 return (v1 > v2) ? -1 : 1; 13271 } 13272 if (r1.isDefault != r2.isDefault) { 13273 return r1.isDefault ? -1 : 1; 13274 } 13275 v1 = r1.match; 13276 v2 = r2.match; 13277 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13278 if (v1 != v2) { 13279 return (v1 > v2) ? -1 : 1; 13280 } 13281 if (r1.system != r2.system) { 13282 return r1.system ? -1 : 1; 13283 } 13284 if (r1.activityInfo != null) { 13285 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13286 } 13287 if (r1.serviceInfo != null) { 13288 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13289 } 13290 if (r1.providerInfo != null) { 13291 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13292 } 13293 return 0; 13294 } 13295 }; 13296 13297 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13298 new Comparator<ProviderInfo>() { 13299 public int compare(ProviderInfo p1, ProviderInfo p2) { 13300 final int v1 = p1.initOrder; 13301 final int v2 = p2.initOrder; 13302 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13303 } 13304 }; 13305 13306 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13307 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13308 final int[] userIds) { 13309 mHandler.post(new Runnable() { 13310 @Override 13311 public void run() { 13312 try { 13313 final IActivityManager am = ActivityManager.getService(); 13314 if (am == null) return; 13315 final int[] resolvedUserIds; 13316 if (userIds == null) { 13317 resolvedUserIds = am.getRunningUserIds(); 13318 } else { 13319 resolvedUserIds = userIds; 13320 } 13321 for (int id : resolvedUserIds) { 13322 final Intent intent = new Intent(action, 13323 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13324 if (extras != null) { 13325 intent.putExtras(extras); 13326 } 13327 if (targetPkg != null) { 13328 intent.setPackage(targetPkg); 13329 } 13330 // Modify the UID when posting to other users 13331 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13332 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13333 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13334 intent.putExtra(Intent.EXTRA_UID, uid); 13335 } 13336 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13337 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13338 if (DEBUG_BROADCASTS) { 13339 RuntimeException here = new RuntimeException("here"); 13340 here.fillInStackTrace(); 13341 Slog.d(TAG, "Sending to user " + id + ": " 13342 + intent.toShortString(false, true, false, false) 13343 + " " + intent.getExtras(), here); 13344 } 13345 am.broadcastIntent(null, intent, null, finishedReceiver, 13346 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13347 null, finishedReceiver != null, false, id); 13348 } 13349 } catch (RemoteException ex) { 13350 } 13351 } 13352 }); 13353 } 13354 13355 /** 13356 * Check if the external storage media is available. This is true if there 13357 * is a mounted external storage medium or if the external storage is 13358 * emulated. 13359 */ 13360 private boolean isExternalMediaAvailable() { 13361 return mMediaMounted || Environment.isExternalStorageEmulated(); 13362 } 13363 13364 @Override 13365 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13366 // writer 13367 synchronized (mPackages) { 13368 if (!isExternalMediaAvailable()) { 13369 // If the external storage is no longer mounted at this point, 13370 // the caller may not have been able to delete all of this 13371 // packages files and can not delete any more. Bail. 13372 return null; 13373 } 13374 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13375 if (lastPackage != null) { 13376 pkgs.remove(lastPackage); 13377 } 13378 if (pkgs.size() > 0) { 13379 return pkgs.get(0); 13380 } 13381 } 13382 return null; 13383 } 13384 13385 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13386 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13387 userId, andCode ? 1 : 0, packageName); 13388 if (mSystemReady) { 13389 msg.sendToTarget(); 13390 } else { 13391 if (mPostSystemReadyMessages == null) { 13392 mPostSystemReadyMessages = new ArrayList<>(); 13393 } 13394 mPostSystemReadyMessages.add(msg); 13395 } 13396 } 13397 13398 void startCleaningPackages() { 13399 // reader 13400 if (!isExternalMediaAvailable()) { 13401 return; 13402 } 13403 synchronized (mPackages) { 13404 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13405 return; 13406 } 13407 } 13408 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13409 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13410 IActivityManager am = ActivityManager.getService(); 13411 if (am != null) { 13412 int dcsUid = -1; 13413 synchronized (mPackages) { 13414 if (!mDefaultContainerWhitelisted) { 13415 mDefaultContainerWhitelisted = true; 13416 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13417 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13418 } 13419 } 13420 try { 13421 if (dcsUid > 0) { 13422 am.backgroundWhitelistUid(dcsUid); 13423 } 13424 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13425 UserHandle.USER_SYSTEM); 13426 } catch (RemoteException e) { 13427 } 13428 } 13429 } 13430 13431 @Override 13432 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13433 int installFlags, String installerPackageName, int userId) { 13434 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13435 13436 final int callingUid = Binder.getCallingUid(); 13437 enforceCrossUserPermission(callingUid, userId, 13438 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13439 13440 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13441 try { 13442 if (observer != null) { 13443 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13444 } 13445 } catch (RemoteException re) { 13446 } 13447 return; 13448 } 13449 13450 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13451 installFlags |= PackageManager.INSTALL_FROM_ADB; 13452 13453 } else { 13454 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13455 // about installerPackageName. 13456 13457 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13458 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13459 } 13460 13461 UserHandle user; 13462 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13463 user = UserHandle.ALL; 13464 } else { 13465 user = new UserHandle(userId); 13466 } 13467 13468 // Only system components can circumvent runtime permissions when installing. 13469 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13470 && mContext.checkCallingOrSelfPermission(Manifest.permission 13471 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13472 throw new SecurityException("You need the " 13473 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13474 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13475 } 13476 13477 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13478 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13479 throw new IllegalArgumentException( 13480 "New installs into ASEC containers no longer supported"); 13481 } 13482 13483 final File originFile = new File(originPath); 13484 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13485 13486 final Message msg = mHandler.obtainMessage(INIT_COPY); 13487 final VerificationInfo verificationInfo = new VerificationInfo( 13488 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13489 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13490 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13491 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13492 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13493 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13494 msg.obj = params; 13495 13496 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13497 System.identityHashCode(msg.obj)); 13498 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13499 System.identityHashCode(msg.obj)); 13500 13501 mHandler.sendMessage(msg); 13502 } 13503 13504 13505 /** 13506 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13507 * it is acting on behalf on an enterprise or the user). 13508 * 13509 * Note that the ordering of the conditionals in this method is important. The checks we perform 13510 * are as follows, in this order: 13511 * 13512 * 1) If the install is being performed by a system app, we can trust the app to have set the 13513 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13514 * what it is. 13515 * 2) If the install is being performed by a device or profile owner app, the install reason 13516 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13517 * set the install reason correctly. If the app targets an older SDK version where install 13518 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13519 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13520 * 3) In all other cases, the install is being performed by a regular app that is neither part 13521 * of the system nor a device or profile owner. We have no reason to believe that this app is 13522 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13523 * set to enterprise policy and if so, change it to unknown instead. 13524 */ 13525 private int fixUpInstallReason(String installerPackageName, int installerUid, 13526 int installReason) { 13527 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13528 == PERMISSION_GRANTED) { 13529 // If the install is being performed by a system app, we trust that app to have set the 13530 // install reason correctly. 13531 return installReason; 13532 } 13533 13534 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13535 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13536 if (dpm != null) { 13537 ComponentName owner = null; 13538 try { 13539 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13540 if (owner == null) { 13541 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13542 } 13543 } catch (RemoteException e) { 13544 } 13545 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13546 // If the install is being performed by a device or profile owner, the install 13547 // reason should be enterprise policy. 13548 return PackageManager.INSTALL_REASON_POLICY; 13549 } 13550 } 13551 13552 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13553 // If the install is being performed by a regular app (i.e. neither system app nor 13554 // device or profile owner), we have no reason to believe that the app is acting on 13555 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13556 // change it to unknown instead. 13557 return PackageManager.INSTALL_REASON_UNKNOWN; 13558 } 13559 13560 // If the install is being performed by a regular app and the install reason was set to any 13561 // value but enterprise policy, leave the install reason unchanged. 13562 return installReason; 13563 } 13564 13565 void installStage(String packageName, File stagedDir, String stagedCid, 13566 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13567 String installerPackageName, int installerUid, UserHandle user, 13568 Certificate[][] certificates) { 13569 if (DEBUG_EPHEMERAL) { 13570 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13571 Slog.d(TAG, "Ephemeral install of " + packageName); 13572 } 13573 } 13574 final VerificationInfo verificationInfo = new VerificationInfo( 13575 sessionParams.originatingUri, sessionParams.referrerUri, 13576 sessionParams.originatingUid, installerUid); 13577 13578 final OriginInfo origin; 13579 if (stagedDir != null) { 13580 origin = OriginInfo.fromStagedFile(stagedDir); 13581 } else { 13582 origin = OriginInfo.fromStagedContainer(stagedCid); 13583 } 13584 13585 final Message msg = mHandler.obtainMessage(INIT_COPY); 13586 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13587 sessionParams.installReason); 13588 final InstallParams params = new InstallParams(origin, null, observer, 13589 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13590 verificationInfo, user, sessionParams.abiOverride, 13591 sessionParams.grantedRuntimePermissions, certificates, installReason); 13592 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13593 msg.obj = params; 13594 13595 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13596 System.identityHashCode(msg.obj)); 13597 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13598 System.identityHashCode(msg.obj)); 13599 13600 mHandler.sendMessage(msg); 13601 } 13602 13603 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13604 int userId) { 13605 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13606 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13607 } 13608 13609 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) { 13610 if (ArrayUtils.isEmpty(userIds)) { 13611 return; 13612 } 13613 Bundle extras = new Bundle(1); 13614 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13615 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13616 13617 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13618 packageName, extras, 0, null, null, userIds); 13619 if (isSystem) { 13620 mHandler.post(() -> { 13621 for (int userId : userIds) { 13622 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13623 } 13624 } 13625 ); 13626 } 13627 } 13628 13629 /** 13630 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13631 * automatically without needing an explicit launch. 13632 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13633 */ 13634 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13635 // If user is not running, the app didn't miss any broadcast 13636 if (!mUserManagerInternal.isUserRunning(userId)) { 13637 return; 13638 } 13639 final IActivityManager am = ActivityManager.getService(); 13640 try { 13641 // Deliver LOCKED_BOOT_COMPLETED first 13642 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13643 .setPackage(packageName); 13644 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13645 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13646 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13647 13648 // Deliver BOOT_COMPLETED only if user is unlocked 13649 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13650 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13651 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13652 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13653 } 13654 } catch (RemoteException e) { 13655 throw e.rethrowFromSystemServer(); 13656 } 13657 } 13658 13659 @Override 13660 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13661 int userId) { 13662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13663 PackageSetting pkgSetting; 13664 final int uid = Binder.getCallingUid(); 13665 enforceCrossUserPermission(uid, userId, 13666 true /* requireFullPermission */, true /* checkShell */, 13667 "setApplicationHiddenSetting for user " + userId); 13668 13669 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13670 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13671 return false; 13672 } 13673 13674 long callingId = Binder.clearCallingIdentity(); 13675 try { 13676 boolean sendAdded = false; 13677 boolean sendRemoved = false; 13678 // writer 13679 synchronized (mPackages) { 13680 pkgSetting = mSettings.mPackages.get(packageName); 13681 if (pkgSetting == null) { 13682 return false; 13683 } 13684 // Do not allow "android" is being disabled 13685 if ("android".equals(packageName)) { 13686 Slog.w(TAG, "Cannot hide package: android"); 13687 return false; 13688 } 13689 // Cannot hide static shared libs as they are considered 13690 // a part of the using app (emulating static linking). Also 13691 // static libs are installed always on internal storage. 13692 PackageParser.Package pkg = mPackages.get(packageName); 13693 if (pkg != null && pkg.staticSharedLibName != null) { 13694 Slog.w(TAG, "Cannot hide package: " + packageName 13695 + " providing static shared library: " 13696 + pkg.staticSharedLibName); 13697 return false; 13698 } 13699 // Only allow protected packages to hide themselves. 13700 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13701 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13702 Slog.w(TAG, "Not hiding protected package: " + packageName); 13703 return false; 13704 } 13705 13706 if (pkgSetting.getHidden(userId) != hidden) { 13707 pkgSetting.setHidden(hidden, userId); 13708 mSettings.writePackageRestrictionsLPr(userId); 13709 if (hidden) { 13710 sendRemoved = true; 13711 } else { 13712 sendAdded = true; 13713 } 13714 } 13715 } 13716 if (sendAdded) { 13717 sendPackageAddedForUser(packageName, pkgSetting, userId); 13718 return true; 13719 } 13720 if (sendRemoved) { 13721 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13722 "hiding pkg"); 13723 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13724 return true; 13725 } 13726 } finally { 13727 Binder.restoreCallingIdentity(callingId); 13728 } 13729 return false; 13730 } 13731 13732 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13733 int userId) { 13734 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13735 info.removedPackage = packageName; 13736 info.installerPackageName = pkgSetting.installerPackageName; 13737 info.removedUsers = new int[] {userId}; 13738 info.broadcastUsers = new int[] {userId}; 13739 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13740 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13741 } 13742 13743 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13744 if (pkgList.length > 0) { 13745 Bundle extras = new Bundle(1); 13746 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13747 13748 sendPackageBroadcast( 13749 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13750 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13751 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13752 new int[] {userId}); 13753 } 13754 } 13755 13756 /** 13757 * Returns true if application is not found or there was an error. Otherwise it returns 13758 * the hidden state of the package for the given user. 13759 */ 13760 @Override 13761 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13762 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13763 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13764 true /* requireFullPermission */, false /* checkShell */, 13765 "getApplicationHidden for user " + userId); 13766 PackageSetting pkgSetting; 13767 long callingId = Binder.clearCallingIdentity(); 13768 try { 13769 // writer 13770 synchronized (mPackages) { 13771 pkgSetting = mSettings.mPackages.get(packageName); 13772 if (pkgSetting == null) { 13773 return true; 13774 } 13775 return pkgSetting.getHidden(userId); 13776 } 13777 } finally { 13778 Binder.restoreCallingIdentity(callingId); 13779 } 13780 } 13781 13782 /** 13783 * @hide 13784 */ 13785 @Override 13786 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13787 int installReason) { 13788 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13789 null); 13790 PackageSetting pkgSetting; 13791 final int uid = Binder.getCallingUid(); 13792 enforceCrossUserPermission(uid, userId, 13793 true /* requireFullPermission */, true /* checkShell */, 13794 "installExistingPackage for user " + userId); 13795 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13796 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13797 } 13798 13799 long callingId = Binder.clearCallingIdentity(); 13800 try { 13801 boolean installed = false; 13802 final boolean instantApp = 13803 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13804 final boolean fullApp = 13805 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13806 13807 // writer 13808 synchronized (mPackages) { 13809 pkgSetting = mSettings.mPackages.get(packageName); 13810 if (pkgSetting == null) { 13811 return PackageManager.INSTALL_FAILED_INVALID_URI; 13812 } 13813 if (!pkgSetting.getInstalled(userId)) { 13814 pkgSetting.setInstalled(true, userId); 13815 pkgSetting.setHidden(false, userId); 13816 pkgSetting.setInstallReason(installReason, userId); 13817 mSettings.writePackageRestrictionsLPr(userId); 13818 mSettings.writeKernelMappingLPr(pkgSetting); 13819 installed = true; 13820 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13821 // upgrade app from instant to full; we don't allow app downgrade 13822 installed = true; 13823 } 13824 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13825 } 13826 13827 if (installed) { 13828 if (pkgSetting.pkg != null) { 13829 synchronized (mInstallLock) { 13830 // We don't need to freeze for a brand new install 13831 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13832 } 13833 } 13834 sendPackageAddedForUser(packageName, pkgSetting, userId); 13835 synchronized (mPackages) { 13836 updateSequenceNumberLP(packageName, new int[]{ userId }); 13837 } 13838 } 13839 } finally { 13840 Binder.restoreCallingIdentity(callingId); 13841 } 13842 13843 return PackageManager.INSTALL_SUCCEEDED; 13844 } 13845 13846 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13847 boolean instantApp, boolean fullApp) { 13848 // no state specified; do nothing 13849 if (!instantApp && !fullApp) { 13850 return; 13851 } 13852 if (userId != UserHandle.USER_ALL) { 13853 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13854 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13855 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13856 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13857 } 13858 } else { 13859 for (int currentUserId : sUserManager.getUserIds()) { 13860 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13861 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13862 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13863 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13864 } 13865 } 13866 } 13867 } 13868 13869 boolean isUserRestricted(int userId, String restrictionKey) { 13870 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13871 if (restrictions.getBoolean(restrictionKey, false)) { 13872 Log.w(TAG, "User is restricted: " + restrictionKey); 13873 return true; 13874 } 13875 return false; 13876 } 13877 13878 @Override 13879 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13880 int userId) { 13881 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13882 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13883 true /* requireFullPermission */, true /* checkShell */, 13884 "setPackagesSuspended for user " + userId); 13885 13886 if (ArrayUtils.isEmpty(packageNames)) { 13887 return packageNames; 13888 } 13889 13890 // List of package names for whom the suspended state has changed. 13891 List<String> changedPackages = new ArrayList<>(packageNames.length); 13892 // List of package names for whom the suspended state is not set as requested in this 13893 // method. 13894 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13895 long callingId = Binder.clearCallingIdentity(); 13896 try { 13897 for (int i = 0; i < packageNames.length; i++) { 13898 String packageName = packageNames[i]; 13899 boolean changed = false; 13900 final int appId; 13901 synchronized (mPackages) { 13902 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13903 if (pkgSetting == null) { 13904 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13905 + "\". Skipping suspending/un-suspending."); 13906 unactionedPackages.add(packageName); 13907 continue; 13908 } 13909 appId = pkgSetting.appId; 13910 if (pkgSetting.getSuspended(userId) != suspended) { 13911 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13912 unactionedPackages.add(packageName); 13913 continue; 13914 } 13915 pkgSetting.setSuspended(suspended, userId); 13916 mSettings.writePackageRestrictionsLPr(userId); 13917 changed = true; 13918 changedPackages.add(packageName); 13919 } 13920 } 13921 13922 if (changed && suspended) { 13923 killApplication(packageName, UserHandle.getUid(userId, appId), 13924 "suspending package"); 13925 } 13926 } 13927 } finally { 13928 Binder.restoreCallingIdentity(callingId); 13929 } 13930 13931 if (!changedPackages.isEmpty()) { 13932 sendPackagesSuspendedForUser(changedPackages.toArray( 13933 new String[changedPackages.size()]), userId, suspended); 13934 } 13935 13936 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13937 } 13938 13939 @Override 13940 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13941 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13942 true /* requireFullPermission */, false /* checkShell */, 13943 "isPackageSuspendedForUser for user " + userId); 13944 synchronized (mPackages) { 13945 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13946 if (pkgSetting == null) { 13947 throw new IllegalArgumentException("Unknown target package: " + packageName); 13948 } 13949 return pkgSetting.getSuspended(userId); 13950 } 13951 } 13952 13953 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13954 if (isPackageDeviceAdmin(packageName, userId)) { 13955 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13956 + "\": has an active device admin"); 13957 return false; 13958 } 13959 13960 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13961 if (packageName.equals(activeLauncherPackageName)) { 13962 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13963 + "\": contains the active launcher"); 13964 return false; 13965 } 13966 13967 if (packageName.equals(mRequiredInstallerPackage)) { 13968 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13969 + "\": required for package installation"); 13970 return false; 13971 } 13972 13973 if (packageName.equals(mRequiredUninstallerPackage)) { 13974 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13975 + "\": required for package uninstallation"); 13976 return false; 13977 } 13978 13979 if (packageName.equals(mRequiredVerifierPackage)) { 13980 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13981 + "\": required for package verification"); 13982 return false; 13983 } 13984 13985 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13986 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13987 + "\": is the default dialer"); 13988 return false; 13989 } 13990 13991 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13992 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13993 + "\": protected package"); 13994 return false; 13995 } 13996 13997 // Cannot suspend static shared libs as they are considered 13998 // a part of the using app (emulating static linking). Also 13999 // static libs are installed always on internal storage. 14000 PackageParser.Package pkg = mPackages.get(packageName); 14001 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14002 Slog.w(TAG, "Cannot suspend package: " + packageName 14003 + " providing static shared library: " 14004 + pkg.staticSharedLibName); 14005 return false; 14006 } 14007 14008 return true; 14009 } 14010 14011 private String getActiveLauncherPackageName(int userId) { 14012 Intent intent = new Intent(Intent.ACTION_MAIN); 14013 intent.addCategory(Intent.CATEGORY_HOME); 14014 ResolveInfo resolveInfo = resolveIntent( 14015 intent, 14016 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14017 PackageManager.MATCH_DEFAULT_ONLY, 14018 userId); 14019 14020 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14021 } 14022 14023 private String getDefaultDialerPackageName(int userId) { 14024 synchronized (mPackages) { 14025 return mSettings.getDefaultDialerPackageNameLPw(userId); 14026 } 14027 } 14028 14029 @Override 14030 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14031 mContext.enforceCallingOrSelfPermission( 14032 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14033 "Only package verification agents can verify applications"); 14034 14035 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14036 final PackageVerificationResponse response = new PackageVerificationResponse( 14037 verificationCode, Binder.getCallingUid()); 14038 msg.arg1 = id; 14039 msg.obj = response; 14040 mHandler.sendMessage(msg); 14041 } 14042 14043 @Override 14044 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14045 long millisecondsToDelay) { 14046 mContext.enforceCallingOrSelfPermission( 14047 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14048 "Only package verification agents can extend verification timeouts"); 14049 14050 final PackageVerificationState state = mPendingVerification.get(id); 14051 final PackageVerificationResponse response = new PackageVerificationResponse( 14052 verificationCodeAtTimeout, Binder.getCallingUid()); 14053 14054 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14055 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14056 } 14057 if (millisecondsToDelay < 0) { 14058 millisecondsToDelay = 0; 14059 } 14060 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14061 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14062 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14063 } 14064 14065 if ((state != null) && !state.timeoutExtended()) { 14066 state.extendTimeout(); 14067 14068 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14069 msg.arg1 = id; 14070 msg.obj = response; 14071 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14072 } 14073 } 14074 14075 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14076 int verificationCode, UserHandle user) { 14077 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14078 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14079 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14080 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14081 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14082 14083 mContext.sendBroadcastAsUser(intent, user, 14084 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14085 } 14086 14087 private ComponentName matchComponentForVerifier(String packageName, 14088 List<ResolveInfo> receivers) { 14089 ActivityInfo targetReceiver = null; 14090 14091 final int NR = receivers.size(); 14092 for (int i = 0; i < NR; i++) { 14093 final ResolveInfo info = receivers.get(i); 14094 if (info.activityInfo == null) { 14095 continue; 14096 } 14097 14098 if (packageName.equals(info.activityInfo.packageName)) { 14099 targetReceiver = info.activityInfo; 14100 break; 14101 } 14102 } 14103 14104 if (targetReceiver == null) { 14105 return null; 14106 } 14107 14108 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14109 } 14110 14111 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14112 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14113 if (pkgInfo.verifiers.length == 0) { 14114 return null; 14115 } 14116 14117 final int N = pkgInfo.verifiers.length; 14118 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14119 for (int i = 0; i < N; i++) { 14120 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14121 14122 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14123 receivers); 14124 if (comp == null) { 14125 continue; 14126 } 14127 14128 final int verifierUid = getUidForVerifier(verifierInfo); 14129 if (verifierUid == -1) { 14130 continue; 14131 } 14132 14133 if (DEBUG_VERIFY) { 14134 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14135 + " with the correct signature"); 14136 } 14137 sufficientVerifiers.add(comp); 14138 verificationState.addSufficientVerifier(verifierUid); 14139 } 14140 14141 return sufficientVerifiers; 14142 } 14143 14144 private int getUidForVerifier(VerifierInfo verifierInfo) { 14145 synchronized (mPackages) { 14146 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14147 if (pkg == null) { 14148 return -1; 14149 } else if (pkg.mSignatures.length != 1) { 14150 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14151 + " has more than one signature; ignoring"); 14152 return -1; 14153 } 14154 14155 /* 14156 * If the public key of the package's signature does not match 14157 * our expected public key, then this is a different package and 14158 * we should skip. 14159 */ 14160 14161 final byte[] expectedPublicKey; 14162 try { 14163 final Signature verifierSig = pkg.mSignatures[0]; 14164 final PublicKey publicKey = verifierSig.getPublicKey(); 14165 expectedPublicKey = publicKey.getEncoded(); 14166 } catch (CertificateException e) { 14167 return -1; 14168 } 14169 14170 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14171 14172 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14173 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14174 + " does not have the expected public key; ignoring"); 14175 return -1; 14176 } 14177 14178 return pkg.applicationInfo.uid; 14179 } 14180 } 14181 14182 @Override 14183 public void finishPackageInstall(int token, boolean didLaunch) { 14184 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14185 14186 if (DEBUG_INSTALL) { 14187 Slog.v(TAG, "BM finishing package install for " + token); 14188 } 14189 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14190 14191 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14192 mHandler.sendMessage(msg); 14193 } 14194 14195 /** 14196 * Get the verification agent timeout. Used for both the APK verifier and the 14197 * intent filter verifier. 14198 * 14199 * @return verification timeout in milliseconds 14200 */ 14201 private long getVerificationTimeout() { 14202 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14203 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14204 DEFAULT_VERIFICATION_TIMEOUT); 14205 } 14206 14207 /** 14208 * Get the default verification agent response code. 14209 * 14210 * @return default verification response code 14211 */ 14212 private int getDefaultVerificationResponse() { 14213 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14214 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14215 DEFAULT_VERIFICATION_RESPONSE); 14216 } 14217 14218 /** 14219 * Check whether or not package verification has been enabled. 14220 * 14221 * @return true if verification should be performed 14222 */ 14223 private boolean isVerificationEnabled(int userId, int installFlags) { 14224 if (!DEFAULT_VERIFY_ENABLE) { 14225 return false; 14226 } 14227 14228 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14229 14230 // Check if installing from ADB 14231 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14232 // Do not run verification in a test harness environment 14233 if (ActivityManager.isRunningInTestHarness()) { 14234 return false; 14235 } 14236 if (ensureVerifyAppsEnabled) { 14237 return true; 14238 } 14239 // Check if the developer does not want package verification for ADB installs 14240 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14241 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14242 return false; 14243 } 14244 } 14245 14246 if (ensureVerifyAppsEnabled) { 14247 return true; 14248 } 14249 14250 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14251 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14252 } 14253 14254 @Override 14255 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14256 throws RemoteException { 14257 mContext.enforceCallingOrSelfPermission( 14258 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14259 "Only intentfilter verification agents can verify applications"); 14260 14261 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14262 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14263 Binder.getCallingUid(), verificationCode, failedDomains); 14264 msg.arg1 = id; 14265 msg.obj = response; 14266 mHandler.sendMessage(msg); 14267 } 14268 14269 @Override 14270 public int getIntentVerificationStatus(String packageName, int userId) { 14271 synchronized (mPackages) { 14272 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14273 } 14274 } 14275 14276 @Override 14277 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14278 mContext.enforceCallingOrSelfPermission( 14279 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14280 14281 boolean result = false; 14282 synchronized (mPackages) { 14283 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14284 } 14285 if (result) { 14286 scheduleWritePackageRestrictionsLocked(userId); 14287 } 14288 return result; 14289 } 14290 14291 @Override 14292 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14293 String packageName) { 14294 synchronized (mPackages) { 14295 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14296 } 14297 } 14298 14299 @Override 14300 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14301 if (TextUtils.isEmpty(packageName)) { 14302 return ParceledListSlice.emptyList(); 14303 } 14304 synchronized (mPackages) { 14305 PackageParser.Package pkg = mPackages.get(packageName); 14306 if (pkg == null || pkg.activities == null) { 14307 return ParceledListSlice.emptyList(); 14308 } 14309 final int count = pkg.activities.size(); 14310 ArrayList<IntentFilter> result = new ArrayList<>(); 14311 for (int n=0; n<count; n++) { 14312 PackageParser.Activity activity = pkg.activities.get(n); 14313 if (activity.intents != null && activity.intents.size() > 0) { 14314 result.addAll(activity.intents); 14315 } 14316 } 14317 return new ParceledListSlice<>(result); 14318 } 14319 } 14320 14321 @Override 14322 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14323 mContext.enforceCallingOrSelfPermission( 14324 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14325 14326 synchronized (mPackages) { 14327 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14328 if (packageName != null) { 14329 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 14330 packageName, userId); 14331 } 14332 return result; 14333 } 14334 } 14335 14336 @Override 14337 public String getDefaultBrowserPackageName(int userId) { 14338 synchronized (mPackages) { 14339 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14340 } 14341 } 14342 14343 /** 14344 * Get the "allow unknown sources" setting. 14345 * 14346 * @return the current "allow unknown sources" setting 14347 */ 14348 private int getUnknownSourcesSettings() { 14349 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14350 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14351 -1); 14352 } 14353 14354 @Override 14355 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14356 final int uid = Binder.getCallingUid(); 14357 // writer 14358 synchronized (mPackages) { 14359 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14360 if (targetPackageSetting == null) { 14361 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14362 } 14363 14364 PackageSetting installerPackageSetting; 14365 if (installerPackageName != null) { 14366 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14367 if (installerPackageSetting == null) { 14368 throw new IllegalArgumentException("Unknown installer package: " 14369 + installerPackageName); 14370 } 14371 } else { 14372 installerPackageSetting = null; 14373 } 14374 14375 Signature[] callerSignature; 14376 Object obj = mSettings.getUserIdLPr(uid); 14377 if (obj != null) { 14378 if (obj instanceof SharedUserSetting) { 14379 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14380 } else if (obj instanceof PackageSetting) { 14381 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14382 } else { 14383 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14384 } 14385 } else { 14386 throw new SecurityException("Unknown calling UID: " + uid); 14387 } 14388 14389 // Verify: can't set installerPackageName to a package that is 14390 // not signed with the same cert as the caller. 14391 if (installerPackageSetting != null) { 14392 if (compareSignatures(callerSignature, 14393 installerPackageSetting.signatures.mSignatures) 14394 != PackageManager.SIGNATURE_MATCH) { 14395 throw new SecurityException( 14396 "Caller does not have same cert as new installer package " 14397 + installerPackageName); 14398 } 14399 } 14400 14401 // Verify: if target already has an installer package, it must 14402 // be signed with the same cert as the caller. 14403 if (targetPackageSetting.installerPackageName != null) { 14404 PackageSetting setting = mSettings.mPackages.get( 14405 targetPackageSetting.installerPackageName); 14406 // If the currently set package isn't valid, then it's always 14407 // okay to change it. 14408 if (setting != null) { 14409 if (compareSignatures(callerSignature, 14410 setting.signatures.mSignatures) 14411 != PackageManager.SIGNATURE_MATCH) { 14412 throw new SecurityException( 14413 "Caller does not have same cert as old installer package " 14414 + targetPackageSetting.installerPackageName); 14415 } 14416 } 14417 } 14418 14419 // Okay! 14420 targetPackageSetting.installerPackageName = installerPackageName; 14421 if (installerPackageName != null) { 14422 mSettings.mInstallerPackages.add(installerPackageName); 14423 } 14424 scheduleWriteSettingsLocked(); 14425 } 14426 } 14427 14428 @Override 14429 public void setApplicationCategoryHint(String packageName, int categoryHint, 14430 String callerPackageName) { 14431 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14432 callerPackageName); 14433 synchronized (mPackages) { 14434 PackageSetting ps = mSettings.mPackages.get(packageName); 14435 if (ps == null) { 14436 throw new IllegalArgumentException("Unknown target package " + packageName); 14437 } 14438 14439 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14440 throw new IllegalArgumentException("Calling package " + callerPackageName 14441 + " is not installer for " + packageName); 14442 } 14443 14444 if (ps.categoryHint != categoryHint) { 14445 ps.categoryHint = categoryHint; 14446 scheduleWriteSettingsLocked(); 14447 } 14448 } 14449 } 14450 14451 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14452 // Queue up an async operation since the package installation may take a little while. 14453 mHandler.post(new Runnable() { 14454 public void run() { 14455 mHandler.removeCallbacks(this); 14456 // Result object to be returned 14457 PackageInstalledInfo res = new PackageInstalledInfo(); 14458 res.setReturnCode(currentStatus); 14459 res.uid = -1; 14460 res.pkg = null; 14461 res.removedInfo = null; 14462 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14463 args.doPreInstall(res.returnCode); 14464 synchronized (mInstallLock) { 14465 installPackageTracedLI(args, res); 14466 } 14467 args.doPostInstall(res.returnCode, res.uid); 14468 } 14469 14470 // A restore should be performed at this point if (a) the install 14471 // succeeded, (b) the operation is not an update, and (c) the new 14472 // package has not opted out of backup participation. 14473 final boolean update = res.removedInfo != null 14474 && res.removedInfo.removedPackage != null; 14475 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14476 boolean doRestore = !update 14477 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14478 14479 // Set up the post-install work request bookkeeping. This will be used 14480 // and cleaned up by the post-install event handling regardless of whether 14481 // there's a restore pass performed. Token values are >= 1. 14482 int token; 14483 if (mNextInstallToken < 0) mNextInstallToken = 1; 14484 token = mNextInstallToken++; 14485 14486 PostInstallData data = new PostInstallData(args, res); 14487 mRunningInstalls.put(token, data); 14488 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14489 14490 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14491 // Pass responsibility to the Backup Manager. It will perform a 14492 // restore if appropriate, then pass responsibility back to the 14493 // Package Manager to run the post-install observer callbacks 14494 // and broadcasts. 14495 IBackupManager bm = IBackupManager.Stub.asInterface( 14496 ServiceManager.getService(Context.BACKUP_SERVICE)); 14497 if (bm != null) { 14498 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14499 + " to BM for possible restore"); 14500 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14501 try { 14502 // TODO: http://b/22388012 14503 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14504 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14505 } else { 14506 doRestore = false; 14507 } 14508 } catch (RemoteException e) { 14509 // can't happen; the backup manager is local 14510 } catch (Exception e) { 14511 Slog.e(TAG, "Exception trying to enqueue restore", e); 14512 doRestore = false; 14513 } 14514 } else { 14515 Slog.e(TAG, "Backup Manager not found!"); 14516 doRestore = false; 14517 } 14518 } 14519 14520 if (!doRestore) { 14521 // No restore possible, or the Backup Manager was mysteriously not 14522 // available -- just fire the post-install work request directly. 14523 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14524 14525 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14526 14527 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14528 mHandler.sendMessage(msg); 14529 } 14530 } 14531 }); 14532 } 14533 14534 /** 14535 * Callback from PackageSettings whenever an app is first transitioned out of the 14536 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14537 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14538 * here whether the app is the target of an ongoing install, and only send the 14539 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14540 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14541 * handling. 14542 */ 14543 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14544 // Serialize this with the rest of the install-process message chain. In the 14545 // restore-at-install case, this Runnable will necessarily run before the 14546 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14547 // are coherent. In the non-restore case, the app has already completed install 14548 // and been launched through some other means, so it is not in a problematic 14549 // state for observers to see the FIRST_LAUNCH signal. 14550 mHandler.post(new Runnable() { 14551 @Override 14552 public void run() { 14553 for (int i = 0; i < mRunningInstalls.size(); i++) { 14554 final PostInstallData data = mRunningInstalls.valueAt(i); 14555 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14556 continue; 14557 } 14558 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14559 // right package; but is it for the right user? 14560 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14561 if (userId == data.res.newUsers[uIndex]) { 14562 if (DEBUG_BACKUP) { 14563 Slog.i(TAG, "Package " + pkgName 14564 + " being restored so deferring FIRST_LAUNCH"); 14565 } 14566 return; 14567 } 14568 } 14569 } 14570 } 14571 // didn't find it, so not being restored 14572 if (DEBUG_BACKUP) { 14573 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14574 } 14575 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14576 } 14577 }); 14578 } 14579 14580 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14581 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14582 installerPkg, null, userIds); 14583 } 14584 14585 private abstract class HandlerParams { 14586 private static final int MAX_RETRIES = 4; 14587 14588 /** 14589 * Number of times startCopy() has been attempted and had a non-fatal 14590 * error. 14591 */ 14592 private int mRetries = 0; 14593 14594 /** User handle for the user requesting the information or installation. */ 14595 private final UserHandle mUser; 14596 String traceMethod; 14597 int traceCookie; 14598 14599 HandlerParams(UserHandle user) { 14600 mUser = user; 14601 } 14602 14603 UserHandle getUser() { 14604 return mUser; 14605 } 14606 14607 HandlerParams setTraceMethod(String traceMethod) { 14608 this.traceMethod = traceMethod; 14609 return this; 14610 } 14611 14612 HandlerParams setTraceCookie(int traceCookie) { 14613 this.traceCookie = traceCookie; 14614 return this; 14615 } 14616 14617 final boolean startCopy() { 14618 boolean res; 14619 try { 14620 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14621 14622 if (++mRetries > MAX_RETRIES) { 14623 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14624 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14625 handleServiceError(); 14626 return false; 14627 } else { 14628 handleStartCopy(); 14629 res = true; 14630 } 14631 } catch (RemoteException e) { 14632 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14633 mHandler.sendEmptyMessage(MCS_RECONNECT); 14634 res = false; 14635 } 14636 handleReturnCode(); 14637 return res; 14638 } 14639 14640 final void serviceError() { 14641 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14642 handleServiceError(); 14643 handleReturnCode(); 14644 } 14645 14646 abstract void handleStartCopy() throws RemoteException; 14647 abstract void handleServiceError(); 14648 abstract void handleReturnCode(); 14649 } 14650 14651 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14652 for (File path : paths) { 14653 try { 14654 mcs.clearDirectory(path.getAbsolutePath()); 14655 } catch (RemoteException e) { 14656 } 14657 } 14658 } 14659 14660 static class OriginInfo { 14661 /** 14662 * Location where install is coming from, before it has been 14663 * copied/renamed into place. This could be a single monolithic APK 14664 * file, or a cluster directory. This location may be untrusted. 14665 */ 14666 final File file; 14667 final String cid; 14668 14669 /** 14670 * Flag indicating that {@link #file} or {@link #cid} has already been 14671 * staged, meaning downstream users don't need to defensively copy the 14672 * contents. 14673 */ 14674 final boolean staged; 14675 14676 /** 14677 * Flag indicating that {@link #file} or {@link #cid} is an already 14678 * installed app that is being moved. 14679 */ 14680 final boolean existing; 14681 14682 final String resolvedPath; 14683 final File resolvedFile; 14684 14685 static OriginInfo fromNothing() { 14686 return new OriginInfo(null, null, false, false); 14687 } 14688 14689 static OriginInfo fromUntrustedFile(File file) { 14690 return new OriginInfo(file, null, false, false); 14691 } 14692 14693 static OriginInfo fromExistingFile(File file) { 14694 return new OriginInfo(file, null, false, true); 14695 } 14696 14697 static OriginInfo fromStagedFile(File file) { 14698 return new OriginInfo(file, null, true, false); 14699 } 14700 14701 static OriginInfo fromStagedContainer(String cid) { 14702 return new OriginInfo(null, cid, true, false); 14703 } 14704 14705 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14706 this.file = file; 14707 this.cid = cid; 14708 this.staged = staged; 14709 this.existing = existing; 14710 14711 if (cid != null) { 14712 resolvedPath = PackageHelper.getSdDir(cid); 14713 resolvedFile = new File(resolvedPath); 14714 } else if (file != null) { 14715 resolvedPath = file.getAbsolutePath(); 14716 resolvedFile = file; 14717 } else { 14718 resolvedPath = null; 14719 resolvedFile = null; 14720 } 14721 } 14722 } 14723 14724 static class MoveInfo { 14725 final int moveId; 14726 final String fromUuid; 14727 final String toUuid; 14728 final String packageName; 14729 final String dataAppName; 14730 final int appId; 14731 final String seinfo; 14732 final int targetSdkVersion; 14733 14734 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14735 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14736 this.moveId = moveId; 14737 this.fromUuid = fromUuid; 14738 this.toUuid = toUuid; 14739 this.packageName = packageName; 14740 this.dataAppName = dataAppName; 14741 this.appId = appId; 14742 this.seinfo = seinfo; 14743 this.targetSdkVersion = targetSdkVersion; 14744 } 14745 } 14746 14747 static class VerificationInfo { 14748 /** A constant used to indicate that a uid value is not present. */ 14749 public static final int NO_UID = -1; 14750 14751 /** URI referencing where the package was downloaded from. */ 14752 final Uri originatingUri; 14753 14754 /** HTTP referrer URI associated with the originatingURI. */ 14755 final Uri referrer; 14756 14757 /** UID of the application that the install request originated from. */ 14758 final int originatingUid; 14759 14760 /** UID of application requesting the install */ 14761 final int installerUid; 14762 14763 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14764 this.originatingUri = originatingUri; 14765 this.referrer = referrer; 14766 this.originatingUid = originatingUid; 14767 this.installerUid = installerUid; 14768 } 14769 } 14770 14771 class InstallParams extends HandlerParams { 14772 final OriginInfo origin; 14773 final MoveInfo move; 14774 final IPackageInstallObserver2 observer; 14775 int installFlags; 14776 final String installerPackageName; 14777 final String volumeUuid; 14778 private InstallArgs mArgs; 14779 private int mRet; 14780 final String packageAbiOverride; 14781 final String[] grantedRuntimePermissions; 14782 final VerificationInfo verificationInfo; 14783 final Certificate[][] certificates; 14784 final int installReason; 14785 14786 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14787 int installFlags, String installerPackageName, String volumeUuid, 14788 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14789 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14790 super(user); 14791 this.origin = origin; 14792 this.move = move; 14793 this.observer = observer; 14794 this.installFlags = installFlags; 14795 this.installerPackageName = installerPackageName; 14796 this.volumeUuid = volumeUuid; 14797 this.verificationInfo = verificationInfo; 14798 this.packageAbiOverride = packageAbiOverride; 14799 this.grantedRuntimePermissions = grantedPermissions; 14800 this.certificates = certificates; 14801 this.installReason = installReason; 14802 } 14803 14804 @Override 14805 public String toString() { 14806 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14807 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14808 } 14809 14810 private int installLocationPolicy(PackageInfoLite pkgLite) { 14811 String packageName = pkgLite.packageName; 14812 int installLocation = pkgLite.installLocation; 14813 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14814 // reader 14815 synchronized (mPackages) { 14816 // Currently installed package which the new package is attempting to replace or 14817 // null if no such package is installed. 14818 PackageParser.Package installedPkg = mPackages.get(packageName); 14819 // Package which currently owns the data which the new package will own if installed. 14820 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14821 // will be null whereas dataOwnerPkg will contain information about the package 14822 // which was uninstalled while keeping its data. 14823 PackageParser.Package dataOwnerPkg = installedPkg; 14824 if (dataOwnerPkg == null) { 14825 PackageSetting ps = mSettings.mPackages.get(packageName); 14826 if (ps != null) { 14827 dataOwnerPkg = ps.pkg; 14828 } 14829 } 14830 14831 if (dataOwnerPkg != null) { 14832 // If installed, the package will get access to data left on the device by its 14833 // predecessor. As a security measure, this is permited only if this is not a 14834 // version downgrade or if the predecessor package is marked as debuggable and 14835 // a downgrade is explicitly requested. 14836 // 14837 // On debuggable platform builds, downgrades are permitted even for 14838 // non-debuggable packages to make testing easier. Debuggable platform builds do 14839 // not offer security guarantees and thus it's OK to disable some security 14840 // mechanisms to make debugging/testing easier on those builds. However, even on 14841 // debuggable builds downgrades of packages are permitted only if requested via 14842 // installFlags. This is because we aim to keep the behavior of debuggable 14843 // platform builds as close as possible to the behavior of non-debuggable 14844 // platform builds. 14845 final boolean downgradeRequested = 14846 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14847 final boolean packageDebuggable = 14848 (dataOwnerPkg.applicationInfo.flags 14849 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14850 final boolean downgradePermitted = 14851 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14852 if (!downgradePermitted) { 14853 try { 14854 checkDowngrade(dataOwnerPkg, pkgLite); 14855 } catch (PackageManagerException e) { 14856 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14857 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14858 } 14859 } 14860 } 14861 14862 if (installedPkg != null) { 14863 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14864 // Check for updated system application. 14865 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14866 if (onSd) { 14867 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14868 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14869 } 14870 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14871 } else { 14872 if (onSd) { 14873 // Install flag overrides everything. 14874 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14875 } 14876 // If current upgrade specifies particular preference 14877 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14878 // Application explicitly specified internal. 14879 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14880 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14881 // App explictly prefers external. Let policy decide 14882 } else { 14883 // Prefer previous location 14884 if (isExternal(installedPkg)) { 14885 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14886 } 14887 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14888 } 14889 } 14890 } else { 14891 // Invalid install. Return error code 14892 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14893 } 14894 } 14895 } 14896 // All the special cases have been taken care of. 14897 // Return result based on recommended install location. 14898 if (onSd) { 14899 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14900 } 14901 return pkgLite.recommendedInstallLocation; 14902 } 14903 14904 /* 14905 * Invoke remote method to get package information and install 14906 * location values. Override install location based on default 14907 * policy if needed and then create install arguments based 14908 * on the install location. 14909 */ 14910 public void handleStartCopy() throws RemoteException { 14911 int ret = PackageManager.INSTALL_SUCCEEDED; 14912 14913 // If we're already staged, we've firmly committed to an install location 14914 if (origin.staged) { 14915 if (origin.file != null) { 14916 installFlags |= PackageManager.INSTALL_INTERNAL; 14917 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14918 } else if (origin.cid != null) { 14919 installFlags |= PackageManager.INSTALL_EXTERNAL; 14920 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14921 } else { 14922 throw new IllegalStateException("Invalid stage location"); 14923 } 14924 } 14925 14926 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14927 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14928 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14929 PackageInfoLite pkgLite = null; 14930 14931 if (onInt && onSd) { 14932 // Check if both bits are set. 14933 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14934 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14935 } else if (onSd && ephemeral) { 14936 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14937 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14938 } else { 14939 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14940 packageAbiOverride); 14941 14942 if (DEBUG_EPHEMERAL && ephemeral) { 14943 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14944 } 14945 14946 /* 14947 * If we have too little free space, try to free cache 14948 * before giving up. 14949 */ 14950 if (!origin.staged && pkgLite.recommendedInstallLocation 14951 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14952 // TODO: focus freeing disk space on the target device 14953 final StorageManager storage = StorageManager.from(mContext); 14954 final long lowThreshold = storage.getStorageLowBytes( 14955 Environment.getDataDirectory()); 14956 14957 final long sizeBytes = mContainerService.calculateInstalledSize( 14958 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14959 14960 try { 14961 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14962 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14963 installFlags, packageAbiOverride); 14964 } catch (InstallerException e) { 14965 Slog.w(TAG, "Failed to free cache", e); 14966 } 14967 14968 /* 14969 * The cache free must have deleted the file we 14970 * downloaded to install. 14971 * 14972 * TODO: fix the "freeCache" call to not delete 14973 * the file we care about. 14974 */ 14975 if (pkgLite.recommendedInstallLocation 14976 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14977 pkgLite.recommendedInstallLocation 14978 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14979 } 14980 } 14981 } 14982 14983 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14984 int loc = pkgLite.recommendedInstallLocation; 14985 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14986 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14987 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14988 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14989 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14990 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14991 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14992 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14993 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14994 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14995 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14996 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14997 } else { 14998 // Override with defaults if needed. 14999 loc = installLocationPolicy(pkgLite); 15000 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15001 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15002 } else if (!onSd && !onInt) { 15003 // Override install location with flags 15004 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15005 // Set the flag to install on external media. 15006 installFlags |= PackageManager.INSTALL_EXTERNAL; 15007 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15008 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15009 if (DEBUG_EPHEMERAL) { 15010 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15011 } 15012 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15013 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15014 |PackageManager.INSTALL_INTERNAL); 15015 } else { 15016 // Make sure the flag for installing on external 15017 // media is unset 15018 installFlags |= PackageManager.INSTALL_INTERNAL; 15019 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15020 } 15021 } 15022 } 15023 } 15024 15025 final InstallArgs args = createInstallArgs(this); 15026 mArgs = args; 15027 15028 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15029 // TODO: http://b/22976637 15030 // Apps installed for "all" users use the device owner to verify the app 15031 UserHandle verifierUser = getUser(); 15032 if (verifierUser == UserHandle.ALL) { 15033 verifierUser = UserHandle.SYSTEM; 15034 } 15035 15036 /* 15037 * Determine if we have any installed package verifiers. If we 15038 * do, then we'll defer to them to verify the packages. 15039 */ 15040 final int requiredUid = mRequiredVerifierPackage == null ? -1 15041 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15042 verifierUser.getIdentifier()); 15043 if (!origin.existing && requiredUid != -1 15044 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 15045 final Intent verification = new Intent( 15046 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15047 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15048 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15049 PACKAGE_MIME_TYPE); 15050 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15051 15052 // Query all live verifiers based on current user state 15053 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15054 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 15055 15056 if (DEBUG_VERIFY) { 15057 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15058 + verification.toString() + " with " + pkgLite.verifiers.length 15059 + " optional verifiers"); 15060 } 15061 15062 final int verificationId = mPendingVerificationToken++; 15063 15064 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15065 15066 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15067 installerPackageName); 15068 15069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15070 installFlags); 15071 15072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15073 pkgLite.packageName); 15074 15075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15076 pkgLite.versionCode); 15077 15078 if (verificationInfo != null) { 15079 if (verificationInfo.originatingUri != null) { 15080 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15081 verificationInfo.originatingUri); 15082 } 15083 if (verificationInfo.referrer != null) { 15084 verification.putExtra(Intent.EXTRA_REFERRER, 15085 verificationInfo.referrer); 15086 } 15087 if (verificationInfo.originatingUid >= 0) { 15088 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15089 verificationInfo.originatingUid); 15090 } 15091 if (verificationInfo.installerUid >= 0) { 15092 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15093 verificationInfo.installerUid); 15094 } 15095 } 15096 15097 final PackageVerificationState verificationState = new PackageVerificationState( 15098 requiredUid, args); 15099 15100 mPendingVerification.append(verificationId, verificationState); 15101 15102 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15103 receivers, verificationState); 15104 15105 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15106 final long idleDuration = getVerificationTimeout(); 15107 15108 /* 15109 * If any sufficient verifiers were listed in the package 15110 * manifest, attempt to ask them. 15111 */ 15112 if (sufficientVerifiers != null) { 15113 final int N = sufficientVerifiers.size(); 15114 if (N == 0) { 15115 Slog.i(TAG, "Additional verifiers required, but none installed."); 15116 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15117 } else { 15118 for (int i = 0; i < N; i++) { 15119 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15120 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15121 verifierComponent.getPackageName(), idleDuration, 15122 verifierUser.getIdentifier(), false, "package verifier"); 15123 15124 final Intent sufficientIntent = new Intent(verification); 15125 sufficientIntent.setComponent(verifierComponent); 15126 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15127 } 15128 } 15129 } 15130 15131 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15132 mRequiredVerifierPackage, receivers); 15133 if (ret == PackageManager.INSTALL_SUCCEEDED 15134 && mRequiredVerifierPackage != null) { 15135 Trace.asyncTraceBegin( 15136 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15137 /* 15138 * Send the intent to the required verification agent, 15139 * but only start the verification timeout after the 15140 * target BroadcastReceivers have run. 15141 */ 15142 verification.setComponent(requiredVerifierComponent); 15143 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15144 mRequiredVerifierPackage, idleDuration, 15145 verifierUser.getIdentifier(), false, "package verifier"); 15146 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15147 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15148 new BroadcastReceiver() { 15149 @Override 15150 public void onReceive(Context context, Intent intent) { 15151 final Message msg = mHandler 15152 .obtainMessage(CHECK_PENDING_VERIFICATION); 15153 msg.arg1 = verificationId; 15154 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15155 } 15156 }, null, 0, null, null); 15157 15158 /* 15159 * We don't want the copy to proceed until verification 15160 * succeeds, so null out this field. 15161 */ 15162 mArgs = null; 15163 } 15164 } else { 15165 /* 15166 * No package verification is enabled, so immediately start 15167 * the remote call to initiate copy using temporary file. 15168 */ 15169 ret = args.copyApk(mContainerService, true); 15170 } 15171 } 15172 15173 mRet = ret; 15174 } 15175 15176 @Override 15177 void handleReturnCode() { 15178 // If mArgs is null, then MCS couldn't be reached. When it 15179 // reconnects, it will try again to install. At that point, this 15180 // will succeed. 15181 if (mArgs != null) { 15182 processPendingInstall(mArgs, mRet); 15183 } 15184 } 15185 15186 @Override 15187 void handleServiceError() { 15188 mArgs = createInstallArgs(this); 15189 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15190 } 15191 15192 public boolean isForwardLocked() { 15193 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15194 } 15195 } 15196 15197 /** 15198 * Used during creation of InstallArgs 15199 * 15200 * @param installFlags package installation flags 15201 * @return true if should be installed on external storage 15202 */ 15203 private static boolean installOnExternalAsec(int installFlags) { 15204 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 15205 return false; 15206 } 15207 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 15208 return true; 15209 } 15210 return false; 15211 } 15212 15213 /** 15214 * Used during creation of InstallArgs 15215 * 15216 * @param installFlags package installation flags 15217 * @return true if should be installed as forward locked 15218 */ 15219 private static boolean installForwardLocked(int installFlags) { 15220 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15221 } 15222 15223 private InstallArgs createInstallArgs(InstallParams params) { 15224 if (params.move != null) { 15225 return new MoveInstallArgs(params); 15226 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 15227 return new AsecInstallArgs(params); 15228 } else { 15229 return new FileInstallArgs(params); 15230 } 15231 } 15232 15233 /** 15234 * Create args that describe an existing installed package. Typically used 15235 * when cleaning up old installs, or used as a move source. 15236 */ 15237 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15238 String resourcePath, String[] instructionSets) { 15239 final boolean isInAsec; 15240 if (installOnExternalAsec(installFlags)) { 15241 /* Apps on SD card are always in ASEC containers. */ 15242 isInAsec = true; 15243 } else if (installForwardLocked(installFlags) 15244 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 15245 /* 15246 * Forward-locked apps are only in ASEC containers if they're the 15247 * new style 15248 */ 15249 isInAsec = true; 15250 } else { 15251 isInAsec = false; 15252 } 15253 15254 if (isInAsec) { 15255 return new AsecInstallArgs(codePath, instructionSets, 15256 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 15257 } else { 15258 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15259 } 15260 } 15261 15262 static abstract class InstallArgs { 15263 /** @see InstallParams#origin */ 15264 final OriginInfo origin; 15265 /** @see InstallParams#move */ 15266 final MoveInfo move; 15267 15268 final IPackageInstallObserver2 observer; 15269 // Always refers to PackageManager flags only 15270 final int installFlags; 15271 final String installerPackageName; 15272 final String volumeUuid; 15273 final UserHandle user; 15274 final String abiOverride; 15275 final String[] installGrantPermissions; 15276 /** If non-null, drop an async trace when the install completes */ 15277 final String traceMethod; 15278 final int traceCookie; 15279 final Certificate[][] certificates; 15280 final int installReason; 15281 15282 // The list of instruction sets supported by this app. This is currently 15283 // only used during the rmdex() phase to clean up resources. We can get rid of this 15284 // if we move dex files under the common app path. 15285 /* nullable */ String[] instructionSets; 15286 15287 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15288 int installFlags, String installerPackageName, String volumeUuid, 15289 UserHandle user, String[] instructionSets, 15290 String abiOverride, String[] installGrantPermissions, 15291 String traceMethod, int traceCookie, Certificate[][] certificates, 15292 int installReason) { 15293 this.origin = origin; 15294 this.move = move; 15295 this.installFlags = installFlags; 15296 this.observer = observer; 15297 this.installerPackageName = installerPackageName; 15298 this.volumeUuid = volumeUuid; 15299 this.user = user; 15300 this.instructionSets = instructionSets; 15301 this.abiOverride = abiOverride; 15302 this.installGrantPermissions = installGrantPermissions; 15303 this.traceMethod = traceMethod; 15304 this.traceCookie = traceCookie; 15305 this.certificates = certificates; 15306 this.installReason = installReason; 15307 } 15308 15309 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15310 abstract int doPreInstall(int status); 15311 15312 /** 15313 * Rename package into final resting place. All paths on the given 15314 * scanned package should be updated to reflect the rename. 15315 */ 15316 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15317 abstract int doPostInstall(int status, int uid); 15318 15319 /** @see PackageSettingBase#codePathString */ 15320 abstract String getCodePath(); 15321 /** @see PackageSettingBase#resourcePathString */ 15322 abstract String getResourcePath(); 15323 15324 // Need installer lock especially for dex file removal. 15325 abstract void cleanUpResourcesLI(); 15326 abstract boolean doPostDeleteLI(boolean delete); 15327 15328 /** 15329 * Called before the source arguments are copied. This is used mostly 15330 * for MoveParams when it needs to read the source file to put it in the 15331 * destination. 15332 */ 15333 int doPreCopy() { 15334 return PackageManager.INSTALL_SUCCEEDED; 15335 } 15336 15337 /** 15338 * Called after the source arguments are copied. This is used mostly for 15339 * MoveParams when it needs to read the source file to put it in the 15340 * destination. 15341 */ 15342 int doPostCopy(int uid) { 15343 return PackageManager.INSTALL_SUCCEEDED; 15344 } 15345 15346 protected boolean isFwdLocked() { 15347 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15348 } 15349 15350 protected boolean isExternalAsec() { 15351 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15352 } 15353 15354 protected boolean isEphemeral() { 15355 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15356 } 15357 15358 UserHandle getUser() { 15359 return user; 15360 } 15361 } 15362 15363 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15364 if (!allCodePaths.isEmpty()) { 15365 if (instructionSets == null) { 15366 throw new IllegalStateException("instructionSet == null"); 15367 } 15368 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15369 for (String codePath : allCodePaths) { 15370 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15371 try { 15372 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15373 } catch (InstallerException ignored) { 15374 } 15375 } 15376 } 15377 } 15378 } 15379 15380 /** 15381 * Logic to handle installation of non-ASEC applications, including copying 15382 * and renaming logic. 15383 */ 15384 class FileInstallArgs extends InstallArgs { 15385 private File codeFile; 15386 private File resourceFile; 15387 15388 // Example topology: 15389 // /data/app/com.example/base.apk 15390 // /data/app/com.example/split_foo.apk 15391 // /data/app/com.example/lib/arm/libfoo.so 15392 // /data/app/com.example/lib/arm64/libfoo.so 15393 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15394 15395 /** New install */ 15396 FileInstallArgs(InstallParams params) { 15397 super(params.origin, params.move, params.observer, params.installFlags, 15398 params.installerPackageName, params.volumeUuid, 15399 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15400 params.grantedRuntimePermissions, 15401 params.traceMethod, params.traceCookie, params.certificates, 15402 params.installReason); 15403 if (isFwdLocked()) { 15404 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15405 } 15406 } 15407 15408 /** Existing install */ 15409 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15410 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15411 null, null, null, 0, null /*certificates*/, 15412 PackageManager.INSTALL_REASON_UNKNOWN); 15413 this.codeFile = (codePath != null) ? new File(codePath) : null; 15414 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15415 } 15416 15417 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15419 try { 15420 return doCopyApk(imcs, temp); 15421 } finally { 15422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15423 } 15424 } 15425 15426 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15427 if (origin.staged) { 15428 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15429 codeFile = origin.file; 15430 resourceFile = origin.file; 15431 return PackageManager.INSTALL_SUCCEEDED; 15432 } 15433 15434 try { 15435 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15436 final File tempDir = 15437 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15438 codeFile = tempDir; 15439 resourceFile = tempDir; 15440 } catch (IOException e) { 15441 Slog.w(TAG, "Failed to create copy file: " + e); 15442 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15443 } 15444 15445 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15446 @Override 15447 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15448 if (!FileUtils.isValidExtFilename(name)) { 15449 throw new IllegalArgumentException("Invalid filename: " + name); 15450 } 15451 try { 15452 final File file = new File(codeFile, name); 15453 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15454 O_RDWR | O_CREAT, 0644); 15455 Os.chmod(file.getAbsolutePath(), 0644); 15456 return new ParcelFileDescriptor(fd); 15457 } catch (ErrnoException e) { 15458 throw new RemoteException("Failed to open: " + e.getMessage()); 15459 } 15460 } 15461 }; 15462 15463 int ret = PackageManager.INSTALL_SUCCEEDED; 15464 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15465 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15466 Slog.e(TAG, "Failed to copy package"); 15467 return ret; 15468 } 15469 15470 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15471 NativeLibraryHelper.Handle handle = null; 15472 try { 15473 handle = NativeLibraryHelper.Handle.create(codeFile); 15474 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15475 abiOverride); 15476 } catch (IOException e) { 15477 Slog.e(TAG, "Copying native libraries failed", e); 15478 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15479 } finally { 15480 IoUtils.closeQuietly(handle); 15481 } 15482 15483 return ret; 15484 } 15485 15486 int doPreInstall(int status) { 15487 if (status != PackageManager.INSTALL_SUCCEEDED) { 15488 cleanUp(); 15489 } 15490 return status; 15491 } 15492 15493 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15494 if (status != PackageManager.INSTALL_SUCCEEDED) { 15495 cleanUp(); 15496 return false; 15497 } 15498 15499 final File targetDir = codeFile.getParentFile(); 15500 final File beforeCodeFile = codeFile; 15501 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15502 15503 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15504 try { 15505 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15506 } catch (ErrnoException e) { 15507 Slog.w(TAG, "Failed to rename", e); 15508 return false; 15509 } 15510 15511 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15512 Slog.w(TAG, "Failed to restorecon"); 15513 return false; 15514 } 15515 15516 // Reflect the rename internally 15517 codeFile = afterCodeFile; 15518 resourceFile = afterCodeFile; 15519 15520 // Reflect the rename in scanned details 15521 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15522 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15523 afterCodeFile, pkg.baseCodePath)); 15524 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15525 afterCodeFile, pkg.splitCodePaths)); 15526 15527 // Reflect the rename in app info 15528 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15529 pkg.setApplicationInfoCodePath(pkg.codePath); 15530 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15531 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15532 pkg.setApplicationInfoResourcePath(pkg.codePath); 15533 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15534 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15535 15536 return true; 15537 } 15538 15539 int doPostInstall(int status, int uid) { 15540 if (status != PackageManager.INSTALL_SUCCEEDED) { 15541 cleanUp(); 15542 } 15543 return status; 15544 } 15545 15546 @Override 15547 String getCodePath() { 15548 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15549 } 15550 15551 @Override 15552 String getResourcePath() { 15553 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15554 } 15555 15556 private boolean cleanUp() { 15557 if (codeFile == null || !codeFile.exists()) { 15558 return false; 15559 } 15560 15561 removeCodePathLI(codeFile); 15562 15563 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15564 resourceFile.delete(); 15565 } 15566 15567 return true; 15568 } 15569 15570 void cleanUpResourcesLI() { 15571 // Try enumerating all code paths before deleting 15572 List<String> allCodePaths = Collections.EMPTY_LIST; 15573 if (codeFile != null && codeFile.exists()) { 15574 try { 15575 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15576 allCodePaths = pkg.getAllCodePaths(); 15577 } catch (PackageParserException e) { 15578 // Ignored; we tried our best 15579 } 15580 } 15581 15582 cleanUp(); 15583 removeDexFiles(allCodePaths, instructionSets); 15584 } 15585 15586 boolean doPostDeleteLI(boolean delete) { 15587 // XXX err, shouldn't we respect the delete flag? 15588 cleanUpResourcesLI(); 15589 return true; 15590 } 15591 } 15592 15593 private boolean isAsecExternal(String cid) { 15594 final String asecPath = PackageHelper.getSdFilesystem(cid); 15595 return !asecPath.startsWith(mAsecInternalPath); 15596 } 15597 15598 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15599 PackageManagerException { 15600 if (copyRet < 0) { 15601 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15602 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15603 throw new PackageManagerException(copyRet, message); 15604 } 15605 } 15606 } 15607 15608 /** 15609 * Extract the StorageManagerService "container ID" from the full code path of an 15610 * .apk. 15611 */ 15612 static String cidFromCodePath(String fullCodePath) { 15613 int eidx = fullCodePath.lastIndexOf("/"); 15614 String subStr1 = fullCodePath.substring(0, eidx); 15615 int sidx = subStr1.lastIndexOf("/"); 15616 return subStr1.substring(sidx+1, eidx); 15617 } 15618 15619 /** 15620 * Logic to handle installation of ASEC applications, including copying and 15621 * renaming logic. 15622 */ 15623 class AsecInstallArgs extends InstallArgs { 15624 static final String RES_FILE_NAME = "pkg.apk"; 15625 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15626 15627 String cid; 15628 String packagePath; 15629 String resourcePath; 15630 15631 /** New install */ 15632 AsecInstallArgs(InstallParams params) { 15633 super(params.origin, params.move, params.observer, params.installFlags, 15634 params.installerPackageName, params.volumeUuid, 15635 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15636 params.grantedRuntimePermissions, 15637 params.traceMethod, params.traceCookie, params.certificates, 15638 params.installReason); 15639 } 15640 15641 /** Existing install */ 15642 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15643 boolean isExternal, boolean isForwardLocked) { 15644 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15645 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15646 instructionSets, null, null, null, 0, null /*certificates*/, 15647 PackageManager.INSTALL_REASON_UNKNOWN); 15648 // Hackily pretend we're still looking at a full code path 15649 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15650 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15651 } 15652 15653 // Extract cid from fullCodePath 15654 int eidx = fullCodePath.lastIndexOf("/"); 15655 String subStr1 = fullCodePath.substring(0, eidx); 15656 int sidx = subStr1.lastIndexOf("/"); 15657 cid = subStr1.substring(sidx+1, eidx); 15658 setMountPath(subStr1); 15659 } 15660 15661 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15662 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15663 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15664 instructionSets, null, null, null, 0, null /*certificates*/, 15665 PackageManager.INSTALL_REASON_UNKNOWN); 15666 this.cid = cid; 15667 setMountPath(PackageHelper.getSdDir(cid)); 15668 } 15669 15670 void createCopyFile() { 15671 cid = mInstallerService.allocateExternalStageCidLegacy(); 15672 } 15673 15674 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15675 if (origin.staged && origin.cid != null) { 15676 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15677 cid = origin.cid; 15678 setMountPath(PackageHelper.getSdDir(cid)); 15679 return PackageManager.INSTALL_SUCCEEDED; 15680 } 15681 15682 if (temp) { 15683 createCopyFile(); 15684 } else { 15685 /* 15686 * Pre-emptively destroy the container since it's destroyed if 15687 * copying fails due to it existing anyway. 15688 */ 15689 PackageHelper.destroySdDir(cid); 15690 } 15691 15692 final String newMountPath = imcs.copyPackageToContainer( 15693 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15694 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15695 15696 if (newMountPath != null) { 15697 setMountPath(newMountPath); 15698 return PackageManager.INSTALL_SUCCEEDED; 15699 } else { 15700 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15701 } 15702 } 15703 15704 @Override 15705 String getCodePath() { 15706 return packagePath; 15707 } 15708 15709 @Override 15710 String getResourcePath() { 15711 return resourcePath; 15712 } 15713 15714 int doPreInstall(int status) { 15715 if (status != PackageManager.INSTALL_SUCCEEDED) { 15716 // Destroy container 15717 PackageHelper.destroySdDir(cid); 15718 } else { 15719 boolean mounted = PackageHelper.isContainerMounted(cid); 15720 if (!mounted) { 15721 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15722 Process.SYSTEM_UID); 15723 if (newMountPath != null) { 15724 setMountPath(newMountPath); 15725 } else { 15726 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15727 } 15728 } 15729 } 15730 return status; 15731 } 15732 15733 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15734 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15735 String newMountPath = null; 15736 if (PackageHelper.isContainerMounted(cid)) { 15737 // Unmount the container 15738 if (!PackageHelper.unMountSdDir(cid)) { 15739 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15740 return false; 15741 } 15742 } 15743 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15744 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15745 " which might be stale. Will try to clean up."); 15746 // Clean up the stale container and proceed to recreate. 15747 if (!PackageHelper.destroySdDir(newCacheId)) { 15748 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15749 return false; 15750 } 15751 // Successfully cleaned up stale container. Try to rename again. 15752 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15753 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15754 + " inspite of cleaning it up."); 15755 return false; 15756 } 15757 } 15758 if (!PackageHelper.isContainerMounted(newCacheId)) { 15759 Slog.w(TAG, "Mounting container " + newCacheId); 15760 newMountPath = PackageHelper.mountSdDir(newCacheId, 15761 getEncryptKey(), Process.SYSTEM_UID); 15762 } else { 15763 newMountPath = PackageHelper.getSdDir(newCacheId); 15764 } 15765 if (newMountPath == null) { 15766 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15767 return false; 15768 } 15769 Log.i(TAG, "Succesfully renamed " + cid + 15770 " to " + newCacheId + 15771 " at new path: " + newMountPath); 15772 cid = newCacheId; 15773 15774 final File beforeCodeFile = new File(packagePath); 15775 setMountPath(newMountPath); 15776 final File afterCodeFile = new File(packagePath); 15777 15778 // Reflect the rename in scanned details 15779 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15780 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15781 afterCodeFile, pkg.baseCodePath)); 15782 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15783 afterCodeFile, pkg.splitCodePaths)); 15784 15785 // Reflect the rename in app info 15786 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15787 pkg.setApplicationInfoCodePath(pkg.codePath); 15788 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15789 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15790 pkg.setApplicationInfoResourcePath(pkg.codePath); 15791 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15792 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15793 15794 return true; 15795 } 15796 15797 private void setMountPath(String mountPath) { 15798 final File mountFile = new File(mountPath); 15799 15800 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15801 if (monolithicFile.exists()) { 15802 packagePath = monolithicFile.getAbsolutePath(); 15803 if (isFwdLocked()) { 15804 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15805 } else { 15806 resourcePath = packagePath; 15807 } 15808 } else { 15809 packagePath = mountFile.getAbsolutePath(); 15810 resourcePath = packagePath; 15811 } 15812 } 15813 15814 int doPostInstall(int status, int uid) { 15815 if (status != PackageManager.INSTALL_SUCCEEDED) { 15816 cleanUp(); 15817 } else { 15818 final int groupOwner; 15819 final String protectedFile; 15820 if (isFwdLocked()) { 15821 groupOwner = UserHandle.getSharedAppGid(uid); 15822 protectedFile = RES_FILE_NAME; 15823 } else { 15824 groupOwner = -1; 15825 protectedFile = null; 15826 } 15827 15828 if (uid < Process.FIRST_APPLICATION_UID 15829 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15830 Slog.e(TAG, "Failed to finalize " + cid); 15831 PackageHelper.destroySdDir(cid); 15832 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15833 } 15834 15835 boolean mounted = PackageHelper.isContainerMounted(cid); 15836 if (!mounted) { 15837 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15838 } 15839 } 15840 return status; 15841 } 15842 15843 private void cleanUp() { 15844 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15845 15846 // Destroy secure container 15847 PackageHelper.destroySdDir(cid); 15848 } 15849 15850 private List<String> getAllCodePaths() { 15851 final File codeFile = new File(getCodePath()); 15852 if (codeFile != null && codeFile.exists()) { 15853 try { 15854 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15855 return pkg.getAllCodePaths(); 15856 } catch (PackageParserException e) { 15857 // Ignored; we tried our best 15858 } 15859 } 15860 return Collections.EMPTY_LIST; 15861 } 15862 15863 void cleanUpResourcesLI() { 15864 // Enumerate all code paths before deleting 15865 cleanUpResourcesLI(getAllCodePaths()); 15866 } 15867 15868 private void cleanUpResourcesLI(List<String> allCodePaths) { 15869 cleanUp(); 15870 removeDexFiles(allCodePaths, instructionSets); 15871 } 15872 15873 String getPackageName() { 15874 return getAsecPackageName(cid); 15875 } 15876 15877 boolean doPostDeleteLI(boolean delete) { 15878 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15879 final List<String> allCodePaths = getAllCodePaths(); 15880 boolean mounted = PackageHelper.isContainerMounted(cid); 15881 if (mounted) { 15882 // Unmount first 15883 if (PackageHelper.unMountSdDir(cid)) { 15884 mounted = false; 15885 } 15886 } 15887 if (!mounted && delete) { 15888 cleanUpResourcesLI(allCodePaths); 15889 } 15890 return !mounted; 15891 } 15892 15893 @Override 15894 int doPreCopy() { 15895 if (isFwdLocked()) { 15896 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15897 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15898 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15899 } 15900 } 15901 15902 return PackageManager.INSTALL_SUCCEEDED; 15903 } 15904 15905 @Override 15906 int doPostCopy(int uid) { 15907 if (isFwdLocked()) { 15908 if (uid < Process.FIRST_APPLICATION_UID 15909 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15910 RES_FILE_NAME)) { 15911 Slog.e(TAG, "Failed to finalize " + cid); 15912 PackageHelper.destroySdDir(cid); 15913 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15914 } 15915 } 15916 15917 return PackageManager.INSTALL_SUCCEEDED; 15918 } 15919 } 15920 15921 /** 15922 * Logic to handle movement of existing installed applications. 15923 */ 15924 class MoveInstallArgs extends InstallArgs { 15925 private File codeFile; 15926 private File resourceFile; 15927 15928 /** New install */ 15929 MoveInstallArgs(InstallParams params) { 15930 super(params.origin, params.move, params.observer, params.installFlags, 15931 params.installerPackageName, params.volumeUuid, 15932 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15933 params.grantedRuntimePermissions, 15934 params.traceMethod, params.traceCookie, params.certificates, 15935 params.installReason); 15936 } 15937 15938 int copyApk(IMediaContainerService imcs, boolean temp) { 15939 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15940 + move.fromUuid + " to " + move.toUuid); 15941 synchronized (mInstaller) { 15942 try { 15943 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15944 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15945 } catch (InstallerException e) { 15946 Slog.w(TAG, "Failed to move app", e); 15947 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15948 } 15949 } 15950 15951 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15952 resourceFile = codeFile; 15953 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15954 15955 return PackageManager.INSTALL_SUCCEEDED; 15956 } 15957 15958 int doPreInstall(int status) { 15959 if (status != PackageManager.INSTALL_SUCCEEDED) { 15960 cleanUp(move.toUuid); 15961 } 15962 return status; 15963 } 15964 15965 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15966 if (status != PackageManager.INSTALL_SUCCEEDED) { 15967 cleanUp(move.toUuid); 15968 return false; 15969 } 15970 15971 // Reflect the move in app info 15972 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15973 pkg.setApplicationInfoCodePath(pkg.codePath); 15974 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15975 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15976 pkg.setApplicationInfoResourcePath(pkg.codePath); 15977 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15978 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15979 15980 return true; 15981 } 15982 15983 int doPostInstall(int status, int uid) { 15984 if (status == PackageManager.INSTALL_SUCCEEDED) { 15985 cleanUp(move.fromUuid); 15986 } else { 15987 cleanUp(move.toUuid); 15988 } 15989 return status; 15990 } 15991 15992 @Override 15993 String getCodePath() { 15994 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15995 } 15996 15997 @Override 15998 String getResourcePath() { 15999 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 16000 } 16001 16002 private boolean cleanUp(String volumeUuid) { 16003 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 16004 move.dataAppName); 16005 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 16006 final int[] userIds = sUserManager.getUserIds(); 16007 synchronized (mInstallLock) { 16008 // Clean up both app data and code 16009 // All package moves are frozen until finished 16010 for (int userId : userIds) { 16011 try { 16012 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 16013 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 16014 } catch (InstallerException e) { 16015 Slog.w(TAG, String.valueOf(e)); 16016 } 16017 } 16018 removeCodePathLI(codeFile); 16019 } 16020 return true; 16021 } 16022 16023 void cleanUpResourcesLI() { 16024 throw new UnsupportedOperationException(); 16025 } 16026 16027 boolean doPostDeleteLI(boolean delete) { 16028 throw new UnsupportedOperationException(); 16029 } 16030 } 16031 16032 static String getAsecPackageName(String packageCid) { 16033 int idx = packageCid.lastIndexOf("-"); 16034 if (idx == -1) { 16035 return packageCid; 16036 } 16037 return packageCid.substring(0, idx); 16038 } 16039 16040 // Utility method used to create code paths based on package name and available index. 16041 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 16042 String idxStr = ""; 16043 int idx = 1; 16044 // Fall back to default value of idx=1 if prefix is not 16045 // part of oldCodePath 16046 if (oldCodePath != null) { 16047 String subStr = oldCodePath; 16048 // Drop the suffix right away 16049 if (suffix != null && subStr.endsWith(suffix)) { 16050 subStr = subStr.substring(0, subStr.length() - suffix.length()); 16051 } 16052 // If oldCodePath already contains prefix find out the 16053 // ending index to either increment or decrement. 16054 int sidx = subStr.lastIndexOf(prefix); 16055 if (sidx != -1) { 16056 subStr = subStr.substring(sidx + prefix.length()); 16057 if (subStr != null) { 16058 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 16059 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 16060 } 16061 try { 16062 idx = Integer.parseInt(subStr); 16063 if (idx <= 1) { 16064 idx++; 16065 } else { 16066 idx--; 16067 } 16068 } catch(NumberFormatException e) { 16069 } 16070 } 16071 } 16072 } 16073 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16074 return prefix + idxStr; 16075 } 16076 16077 private File getNextCodePath(File targetDir, String packageName) { 16078 File result; 16079 SecureRandom random = new SecureRandom(); 16080 byte[] bytes = new byte[16]; 16081 do { 16082 random.nextBytes(bytes); 16083 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16084 result = new File(targetDir, packageName + "-" + suffix); 16085 } while (result.exists()); 16086 return result; 16087 } 16088 16089 // Utility method that returns the relative package path with respect 16090 // to the installation directory. Like say for /data/data/com.test-1.apk 16091 // string com.test-1 is returned. 16092 static String deriveCodePathName(String codePath) { 16093 if (codePath == null) { 16094 return null; 16095 } 16096 final File codeFile = new File(codePath); 16097 final String name = codeFile.getName(); 16098 if (codeFile.isDirectory()) { 16099 return name; 16100 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16101 final int lastDot = name.lastIndexOf('.'); 16102 return name.substring(0, lastDot); 16103 } else { 16104 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16105 return null; 16106 } 16107 } 16108 16109 static class PackageInstalledInfo { 16110 String name; 16111 int uid; 16112 // The set of users that originally had this package installed. 16113 int[] origUsers; 16114 // The set of users that now have this package installed. 16115 int[] newUsers; 16116 PackageParser.Package pkg; 16117 int returnCode; 16118 String returnMsg; 16119 PackageRemovedInfo removedInfo; 16120 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16121 16122 public void setError(int code, String msg) { 16123 setReturnCode(code); 16124 setReturnMessage(msg); 16125 Slog.w(TAG, msg); 16126 } 16127 16128 public void setError(String msg, PackageParserException e) { 16129 setReturnCode(e.error); 16130 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16131 Slog.w(TAG, msg, e); 16132 } 16133 16134 public void setError(String msg, PackageManagerException e) { 16135 returnCode = e.error; 16136 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16137 Slog.w(TAG, msg, e); 16138 } 16139 16140 public void setReturnCode(int returnCode) { 16141 this.returnCode = returnCode; 16142 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16143 for (int i = 0; i < childCount; i++) { 16144 addedChildPackages.valueAt(i).returnCode = returnCode; 16145 } 16146 } 16147 16148 private void setReturnMessage(String returnMsg) { 16149 this.returnMsg = returnMsg; 16150 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16151 for (int i = 0; i < childCount; i++) { 16152 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16153 } 16154 } 16155 16156 // In some error cases we want to convey more info back to the observer 16157 String origPackage; 16158 String origPermission; 16159 } 16160 16161 /* 16162 * Install a non-existing package. 16163 */ 16164 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 16165 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 16166 PackageInstalledInfo res, int installReason) { 16167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16168 16169 // Remember this for later, in case we need to rollback this install 16170 String pkgName = pkg.packageName; 16171 16172 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16173 16174 synchronized(mPackages) { 16175 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16176 if (renamedPackage != null) { 16177 // A package with the same name is already installed, though 16178 // it has been renamed to an older name. The package we 16179 // are trying to install should be installed as an update to 16180 // the existing one, but that has not been requested, so bail. 16181 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16182 + " without first uninstalling package running as " 16183 + renamedPackage); 16184 return; 16185 } 16186 if (mPackages.containsKey(pkgName)) { 16187 // Don't allow installation over an existing package with the same name. 16188 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16189 + " without first uninstalling."); 16190 return; 16191 } 16192 } 16193 16194 try { 16195 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 16196 System.currentTimeMillis(), user); 16197 16198 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16199 16200 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16201 prepareAppDataAfterInstallLIF(newPackage); 16202 16203 } else { 16204 // Remove package from internal structures, but keep around any 16205 // data that might have already existed 16206 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16207 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16208 } 16209 } catch (PackageManagerException e) { 16210 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16211 } 16212 16213 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16214 } 16215 16216 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 16217 // Can't rotate keys during boot or if sharedUser. 16218 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 16219 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 16220 return false; 16221 } 16222 // app is using upgradeKeySets; make sure all are valid 16223 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16224 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 16225 for (int i = 0; i < upgradeKeySets.length; i++) { 16226 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 16227 Slog.wtf(TAG, "Package " 16228 + (oldPs.name != null ? oldPs.name : "<null>") 16229 + " contains upgrade-key-set reference to unknown key-set: " 16230 + upgradeKeySets[i] 16231 + " reverting to signatures check."); 16232 return false; 16233 } 16234 } 16235 return true; 16236 } 16237 16238 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 16239 // Upgrade keysets are being used. Determine if new package has a superset of the 16240 // required keys. 16241 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 16242 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16243 for (int i = 0; i < upgradeKeySets.length; i++) { 16244 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 16245 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 16246 return true; 16247 } 16248 } 16249 return false; 16250 } 16251 16252 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16253 try (DigestInputStream digestStream = 16254 new DigestInputStream(new FileInputStream(file), digest)) { 16255 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16256 } 16257 } 16258 16259 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 16260 UserHandle user, String installerPackageName, PackageInstalledInfo res, 16261 int installReason) { 16262 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16263 16264 final PackageParser.Package oldPackage; 16265 final PackageSetting ps; 16266 final String pkgName = pkg.packageName; 16267 final int[] allUsers; 16268 final int[] installedUsers; 16269 16270 synchronized(mPackages) { 16271 oldPackage = mPackages.get(pkgName); 16272 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16273 16274 // don't allow upgrade to target a release SDK from a pre-release SDK 16275 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16276 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16277 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16278 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16279 if (oldTargetsPreRelease 16280 && !newTargetsPreRelease 16281 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16282 Slog.w(TAG, "Can't install package targeting released sdk"); 16283 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16284 return; 16285 } 16286 16287 ps = mSettings.mPackages.get(pkgName); 16288 16289 // verify signatures are valid 16290 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 16291 if (!checkUpgradeKeySetLP(ps, pkg)) { 16292 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16293 "New package not signed by keys specified by upgrade-keysets: " 16294 + pkgName); 16295 return; 16296 } 16297 } else { 16298 // default to original signature matching 16299 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 16300 != PackageManager.SIGNATURE_MATCH) { 16301 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16302 "New package has a different signature: " + pkgName); 16303 return; 16304 } 16305 } 16306 16307 // don't allow a system upgrade unless the upgrade hash matches 16308 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 16309 byte[] digestBytes = null; 16310 try { 16311 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16312 updateDigest(digest, new File(pkg.baseCodePath)); 16313 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16314 for (String path : pkg.splitCodePaths) { 16315 updateDigest(digest, new File(path)); 16316 } 16317 } 16318 digestBytes = digest.digest(); 16319 } catch (NoSuchAlgorithmException | IOException e) { 16320 res.setError(INSTALL_FAILED_INVALID_APK, 16321 "Could not compute hash: " + pkgName); 16322 return; 16323 } 16324 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16325 res.setError(INSTALL_FAILED_INVALID_APK, 16326 "New package fails restrict-update check: " + pkgName); 16327 return; 16328 } 16329 // retain upgrade restriction 16330 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16331 } 16332 16333 // Check for shared user id changes 16334 String invalidPackageName = 16335 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16336 if (invalidPackageName != null) { 16337 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16338 "Package " + invalidPackageName + " tried to change user " 16339 + oldPackage.mSharedUserId); 16340 return; 16341 } 16342 16343 // In case of rollback, remember per-user/profile install state 16344 allUsers = sUserManager.getUserIds(); 16345 installedUsers = ps.queryInstalledUsers(allUsers, true); 16346 16347 // don't allow an upgrade from full to ephemeral 16348 if (isInstantApp) { 16349 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16350 for (int currentUser : allUsers) { 16351 if (!ps.getInstantApp(currentUser)) { 16352 // can't downgrade from full to instant 16353 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16354 + " for user: " + currentUser); 16355 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16356 return; 16357 } 16358 } 16359 } else if (!ps.getInstantApp(user.getIdentifier())) { 16360 // can't downgrade from full to instant 16361 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16362 + " for user: " + user.getIdentifier()); 16363 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16364 return; 16365 } 16366 } 16367 } 16368 16369 // Update what is removed 16370 res.removedInfo = new PackageRemovedInfo(this); 16371 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16372 res.removedInfo.removedPackage = oldPackage.packageName; 16373 res.removedInfo.installerPackageName = ps.installerPackageName; 16374 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16375 res.removedInfo.isUpdate = true; 16376 res.removedInfo.origUsers = installedUsers; 16377 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16378 for (int i = 0; i < installedUsers.length; i++) { 16379 final int userId = installedUsers[i]; 16380 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16381 } 16382 16383 final int childCount = (oldPackage.childPackages != null) 16384 ? oldPackage.childPackages.size() : 0; 16385 for (int i = 0; i < childCount; i++) { 16386 boolean childPackageUpdated = false; 16387 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16388 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16389 if (res.addedChildPackages != null) { 16390 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16391 if (childRes != null) { 16392 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16393 childRes.removedInfo.removedPackage = childPkg.packageName; 16394 if (childPs != null) { 16395 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16396 } 16397 childRes.removedInfo.isUpdate = true; 16398 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16399 childPackageUpdated = true; 16400 } 16401 } 16402 if (!childPackageUpdated) { 16403 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16404 childRemovedRes.removedPackage = childPkg.packageName; 16405 if (childPs != null) { 16406 childRemovedRes.installerPackageName = childPs.installerPackageName; 16407 } 16408 childRemovedRes.isUpdate = false; 16409 childRemovedRes.dataRemoved = true; 16410 synchronized (mPackages) { 16411 if (childPs != null) { 16412 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16413 } 16414 } 16415 if (res.removedInfo.removedChildPackages == null) { 16416 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16417 } 16418 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16419 } 16420 } 16421 16422 boolean sysPkg = (isSystemApp(oldPackage)); 16423 if (sysPkg) { 16424 // Set the system/privileged flags as needed 16425 final boolean privileged = 16426 (oldPackage.applicationInfo.privateFlags 16427 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16428 final int systemPolicyFlags = policyFlags 16429 | PackageParser.PARSE_IS_SYSTEM 16430 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16431 16432 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16433 user, allUsers, installerPackageName, res, installReason); 16434 } else { 16435 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16436 user, allUsers, installerPackageName, res, installReason); 16437 } 16438 } 16439 16440 public List<String> getPreviousCodePaths(String packageName) { 16441 final PackageSetting ps = mSettings.mPackages.get(packageName); 16442 final List<String> result = new ArrayList<String>(); 16443 if (ps != null && ps.oldCodePaths != null) { 16444 result.addAll(ps.oldCodePaths); 16445 } 16446 return result; 16447 } 16448 16449 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16450 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16451 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16452 int installReason) { 16453 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16454 + deletedPackage); 16455 16456 String pkgName = deletedPackage.packageName; 16457 boolean deletedPkg = true; 16458 boolean addedPkg = false; 16459 boolean updatedSettings = false; 16460 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16461 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16462 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16463 16464 final long origUpdateTime = (pkg.mExtras != null) 16465 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16466 16467 // First delete the existing package while retaining the data directory 16468 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16469 res.removedInfo, true, pkg)) { 16470 // If the existing package wasn't successfully deleted 16471 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16472 deletedPkg = false; 16473 } else { 16474 // Successfully deleted the old package; proceed with replace. 16475 16476 // If deleted package lived in a container, give users a chance to 16477 // relinquish resources before killing. 16478 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16479 if (DEBUG_INSTALL) { 16480 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16481 } 16482 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16483 final ArrayList<String> pkgList = new ArrayList<String>(1); 16484 pkgList.add(deletedPackage.applicationInfo.packageName); 16485 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16486 } 16487 16488 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16489 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16490 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16491 16492 try { 16493 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16494 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16495 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16496 installReason); 16497 16498 // Update the in-memory copy of the previous code paths. 16499 PackageSetting ps = mSettings.mPackages.get(pkgName); 16500 if (!killApp) { 16501 if (ps.oldCodePaths == null) { 16502 ps.oldCodePaths = new ArraySet<>(); 16503 } 16504 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16505 if (deletedPackage.splitCodePaths != null) { 16506 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16507 } 16508 } else { 16509 ps.oldCodePaths = null; 16510 } 16511 if (ps.childPackageNames != null) { 16512 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16513 final String childPkgName = ps.childPackageNames.get(i); 16514 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16515 childPs.oldCodePaths = ps.oldCodePaths; 16516 } 16517 } 16518 // set instant app status, but, only if it's explicitly specified 16519 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16520 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16521 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16522 prepareAppDataAfterInstallLIF(newPackage); 16523 addedPkg = true; 16524 mDexManager.notifyPackageUpdated(newPackage.packageName, 16525 newPackage.baseCodePath, newPackage.splitCodePaths); 16526 } catch (PackageManagerException e) { 16527 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16528 } 16529 } 16530 16531 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16532 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16533 16534 // Revert all internal state mutations and added folders for the failed install 16535 if (addedPkg) { 16536 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16537 res.removedInfo, true, null); 16538 } 16539 16540 // Restore the old package 16541 if (deletedPkg) { 16542 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16543 File restoreFile = new File(deletedPackage.codePath); 16544 // Parse old package 16545 boolean oldExternal = isExternal(deletedPackage); 16546 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16547 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16548 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16549 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16550 try { 16551 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16552 null); 16553 } catch (PackageManagerException e) { 16554 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16555 + e.getMessage()); 16556 return; 16557 } 16558 16559 synchronized (mPackages) { 16560 // Ensure the installer package name up to date 16561 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16562 16563 // Update permissions for restored package 16564 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16565 16566 mSettings.writeLPr(); 16567 } 16568 16569 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16570 } 16571 } else { 16572 synchronized (mPackages) { 16573 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16574 if (ps != null) { 16575 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16576 if (res.removedInfo.removedChildPackages != null) { 16577 final int childCount = res.removedInfo.removedChildPackages.size(); 16578 // Iterate in reverse as we may modify the collection 16579 for (int i = childCount - 1; i >= 0; i--) { 16580 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16581 if (res.addedChildPackages.containsKey(childPackageName)) { 16582 res.removedInfo.removedChildPackages.removeAt(i); 16583 } else { 16584 PackageRemovedInfo childInfo = res.removedInfo 16585 .removedChildPackages.valueAt(i); 16586 childInfo.removedForAllUsers = mPackages.get( 16587 childInfo.removedPackage) == null; 16588 } 16589 } 16590 } 16591 } 16592 } 16593 } 16594 } 16595 16596 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16597 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16598 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16599 int installReason) { 16600 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16601 + ", old=" + deletedPackage); 16602 16603 final boolean disabledSystem; 16604 16605 // Remove existing system package 16606 removePackageLI(deletedPackage, true); 16607 16608 synchronized (mPackages) { 16609 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16610 } 16611 if (!disabledSystem) { 16612 // We didn't need to disable the .apk as a current system package, 16613 // which means we are replacing another update that is already 16614 // installed. We need to make sure to delete the older one's .apk. 16615 res.removedInfo.args = createInstallArgsForExisting(0, 16616 deletedPackage.applicationInfo.getCodePath(), 16617 deletedPackage.applicationInfo.getResourcePath(), 16618 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16619 } else { 16620 res.removedInfo.args = null; 16621 } 16622 16623 // Successfully disabled the old package. Now proceed with re-installation 16624 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16625 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16626 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16627 16628 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16629 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16630 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16631 16632 PackageParser.Package newPackage = null; 16633 try { 16634 // Add the package to the internal data structures 16635 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16636 16637 // Set the update and install times 16638 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16639 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16640 System.currentTimeMillis()); 16641 16642 // Update the package dynamic state if succeeded 16643 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16644 // Now that the install succeeded make sure we remove data 16645 // directories for any child package the update removed. 16646 final int deletedChildCount = (deletedPackage.childPackages != null) 16647 ? deletedPackage.childPackages.size() : 0; 16648 final int newChildCount = (newPackage.childPackages != null) 16649 ? newPackage.childPackages.size() : 0; 16650 for (int i = 0; i < deletedChildCount; i++) { 16651 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16652 boolean childPackageDeleted = true; 16653 for (int j = 0; j < newChildCount; j++) { 16654 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16655 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16656 childPackageDeleted = false; 16657 break; 16658 } 16659 } 16660 if (childPackageDeleted) { 16661 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16662 deletedChildPkg.packageName); 16663 if (ps != null && res.removedInfo.removedChildPackages != null) { 16664 PackageRemovedInfo removedChildRes = res.removedInfo 16665 .removedChildPackages.get(deletedChildPkg.packageName); 16666 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16667 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16668 } 16669 } 16670 } 16671 16672 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16673 installReason); 16674 prepareAppDataAfterInstallLIF(newPackage); 16675 16676 mDexManager.notifyPackageUpdated(newPackage.packageName, 16677 newPackage.baseCodePath, newPackage.splitCodePaths); 16678 } 16679 } catch (PackageManagerException e) { 16680 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16681 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16682 } 16683 16684 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16685 // Re installation failed. Restore old information 16686 // Remove new pkg information 16687 if (newPackage != null) { 16688 removeInstalledPackageLI(newPackage, true); 16689 } 16690 // Add back the old system package 16691 try { 16692 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16693 } catch (PackageManagerException e) { 16694 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16695 } 16696 16697 synchronized (mPackages) { 16698 if (disabledSystem) { 16699 enableSystemPackageLPw(deletedPackage); 16700 } 16701 16702 // Ensure the installer package name up to date 16703 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16704 16705 // Update permissions for restored package 16706 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16707 16708 mSettings.writeLPr(); 16709 } 16710 16711 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16712 + " after failed upgrade"); 16713 } 16714 } 16715 16716 /** 16717 * Checks whether the parent or any of the child packages have a change shared 16718 * user. For a package to be a valid update the shred users of the parent and 16719 * the children should match. We may later support changing child shared users. 16720 * @param oldPkg The updated package. 16721 * @param newPkg The update package. 16722 * @return The shared user that change between the versions. 16723 */ 16724 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16725 PackageParser.Package newPkg) { 16726 // Check parent shared user 16727 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16728 return newPkg.packageName; 16729 } 16730 // Check child shared users 16731 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16732 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16733 for (int i = 0; i < newChildCount; i++) { 16734 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16735 // If this child was present, did it have the same shared user? 16736 for (int j = 0; j < oldChildCount; j++) { 16737 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16738 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16739 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16740 return newChildPkg.packageName; 16741 } 16742 } 16743 } 16744 return null; 16745 } 16746 16747 private void removeNativeBinariesLI(PackageSetting ps) { 16748 // Remove the lib path for the parent package 16749 if (ps != null) { 16750 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16751 // Remove the lib path for the child packages 16752 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16753 for (int i = 0; i < childCount; i++) { 16754 PackageSetting childPs = null; 16755 synchronized (mPackages) { 16756 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16757 } 16758 if (childPs != null) { 16759 NativeLibraryHelper.removeNativeBinariesLI(childPs 16760 .legacyNativeLibraryPathString); 16761 } 16762 } 16763 } 16764 } 16765 16766 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16767 // Enable the parent package 16768 mSettings.enableSystemPackageLPw(pkg.packageName); 16769 // Enable the child packages 16770 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16771 for (int i = 0; i < childCount; i++) { 16772 PackageParser.Package childPkg = pkg.childPackages.get(i); 16773 mSettings.enableSystemPackageLPw(childPkg.packageName); 16774 } 16775 } 16776 16777 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16778 PackageParser.Package newPkg) { 16779 // Disable the parent package (parent always replaced) 16780 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16781 // Disable the child packages 16782 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16783 for (int i = 0; i < childCount; i++) { 16784 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16785 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16786 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16787 } 16788 return disabled; 16789 } 16790 16791 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16792 String installerPackageName) { 16793 // Enable the parent package 16794 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16795 // Enable the child packages 16796 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16797 for (int i = 0; i < childCount; i++) { 16798 PackageParser.Package childPkg = pkg.childPackages.get(i); 16799 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16800 } 16801 } 16802 16803 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16804 // Collect all used permissions in the UID 16805 ArraySet<String> usedPermissions = new ArraySet<>(); 16806 final int packageCount = su.packages.size(); 16807 for (int i = 0; i < packageCount; i++) { 16808 PackageSetting ps = su.packages.valueAt(i); 16809 if (ps.pkg == null) { 16810 continue; 16811 } 16812 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16813 for (int j = 0; j < requestedPermCount; j++) { 16814 String permission = ps.pkg.requestedPermissions.get(j); 16815 BasePermission bp = mSettings.mPermissions.get(permission); 16816 if (bp != null) { 16817 usedPermissions.add(permission); 16818 } 16819 } 16820 } 16821 16822 PermissionsState permissionsState = su.getPermissionsState(); 16823 // Prune install permissions 16824 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16825 final int installPermCount = installPermStates.size(); 16826 for (int i = installPermCount - 1; i >= 0; i--) { 16827 PermissionState permissionState = installPermStates.get(i); 16828 if (!usedPermissions.contains(permissionState.getName())) { 16829 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16830 if (bp != null) { 16831 permissionsState.revokeInstallPermission(bp); 16832 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16833 PackageManager.MASK_PERMISSION_FLAGS, 0); 16834 } 16835 } 16836 } 16837 16838 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16839 16840 // Prune runtime permissions 16841 for (int userId : allUserIds) { 16842 List<PermissionState> runtimePermStates = permissionsState 16843 .getRuntimePermissionStates(userId); 16844 final int runtimePermCount = runtimePermStates.size(); 16845 for (int i = runtimePermCount - 1; i >= 0; i--) { 16846 PermissionState permissionState = runtimePermStates.get(i); 16847 if (!usedPermissions.contains(permissionState.getName())) { 16848 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16849 if (bp != null) { 16850 permissionsState.revokeRuntimePermission(bp, userId); 16851 permissionsState.updatePermissionFlags(bp, userId, 16852 PackageManager.MASK_PERMISSION_FLAGS, 0); 16853 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16854 runtimePermissionChangedUserIds, userId); 16855 } 16856 } 16857 } 16858 } 16859 16860 return runtimePermissionChangedUserIds; 16861 } 16862 16863 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16864 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16865 // Update the parent package setting 16866 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16867 res, user, installReason); 16868 // Update the child packages setting 16869 final int childCount = (newPackage.childPackages != null) 16870 ? newPackage.childPackages.size() : 0; 16871 for (int i = 0; i < childCount; i++) { 16872 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16873 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16874 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16875 childRes.origUsers, childRes, user, installReason); 16876 } 16877 } 16878 16879 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16880 String installerPackageName, int[] allUsers, int[] installedForUsers, 16881 PackageInstalledInfo res, UserHandle user, int installReason) { 16882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16883 16884 String pkgName = newPackage.packageName; 16885 synchronized (mPackages) { 16886 //write settings. the installStatus will be incomplete at this stage. 16887 //note that the new package setting would have already been 16888 //added to mPackages. It hasn't been persisted yet. 16889 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16890 // TODO: Remove this write? It's also written at the end of this method 16891 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16892 mSettings.writeLPr(); 16893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16894 } 16895 16896 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16897 synchronized (mPackages) { 16898 updatePermissionsLPw(newPackage.packageName, newPackage, 16899 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16900 ? UPDATE_PERMISSIONS_ALL : 0)); 16901 // For system-bundled packages, we assume that installing an upgraded version 16902 // of the package implies that the user actually wants to run that new code, 16903 // so we enable the package. 16904 PackageSetting ps = mSettings.mPackages.get(pkgName); 16905 final int userId = user.getIdentifier(); 16906 if (ps != null) { 16907 if (isSystemApp(newPackage)) { 16908 if (DEBUG_INSTALL) { 16909 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16910 } 16911 // Enable system package for requested users 16912 if (res.origUsers != null) { 16913 for (int origUserId : res.origUsers) { 16914 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16915 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16916 origUserId, installerPackageName); 16917 } 16918 } 16919 } 16920 // Also convey the prior install/uninstall state 16921 if (allUsers != null && installedForUsers != null) { 16922 for (int currentUserId : allUsers) { 16923 final boolean installed = ArrayUtils.contains( 16924 installedForUsers, currentUserId); 16925 if (DEBUG_INSTALL) { 16926 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16927 } 16928 ps.setInstalled(installed, currentUserId); 16929 } 16930 // these install state changes will be persisted in the 16931 // upcoming call to mSettings.writeLPr(). 16932 } 16933 } 16934 // It's implied that when a user requests installation, they want the app to be 16935 // installed and enabled. 16936 if (userId != UserHandle.USER_ALL) { 16937 ps.setInstalled(true, userId); 16938 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16939 } 16940 16941 // When replacing an existing package, preserve the original install reason for all 16942 // users that had the package installed before. 16943 final Set<Integer> previousUserIds = new ArraySet<>(); 16944 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16945 final int installReasonCount = res.removedInfo.installReasons.size(); 16946 for (int i = 0; i < installReasonCount; i++) { 16947 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16948 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16949 ps.setInstallReason(previousInstallReason, previousUserId); 16950 previousUserIds.add(previousUserId); 16951 } 16952 } 16953 16954 // Set install reason for users that are having the package newly installed. 16955 if (userId == UserHandle.USER_ALL) { 16956 for (int currentUserId : sUserManager.getUserIds()) { 16957 if (!previousUserIds.contains(currentUserId)) { 16958 ps.setInstallReason(installReason, currentUserId); 16959 } 16960 } 16961 } else if (!previousUserIds.contains(userId)) { 16962 ps.setInstallReason(installReason, userId); 16963 } 16964 mSettings.writeKernelMappingLPr(ps); 16965 } 16966 res.name = pkgName; 16967 res.uid = newPackage.applicationInfo.uid; 16968 res.pkg = newPackage; 16969 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16970 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16971 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16972 //to update install status 16973 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16974 mSettings.writeLPr(); 16975 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16976 } 16977 16978 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16979 } 16980 16981 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16982 try { 16983 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16984 installPackageLI(args, res); 16985 } finally { 16986 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16987 } 16988 } 16989 16990 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16991 final int installFlags = args.installFlags; 16992 final String installerPackageName = args.installerPackageName; 16993 final String volumeUuid = args.volumeUuid; 16994 final File tmpPackageFile = new File(args.getCodePath()); 16995 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16996 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16997 || (args.volumeUuid != null)); 16998 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16999 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 17000 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 17001 boolean replace = false; 17002 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 17003 if (args.move != null) { 17004 // moving a complete application; perform an initial scan on the new install location 17005 scanFlags |= SCAN_INITIAL; 17006 } 17007 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 17008 scanFlags |= SCAN_DONT_KILL_APP; 17009 } 17010 if (instantApp) { 17011 scanFlags |= SCAN_AS_INSTANT_APP; 17012 } 17013 if (fullApp) { 17014 scanFlags |= SCAN_AS_FULL_APP; 17015 } 17016 17017 // Result object to be returned 17018 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17019 17020 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 17021 17022 // Sanity check 17023 if (instantApp && (forwardLocked || onExternal)) { 17024 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 17025 + " external=" + onExternal); 17026 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17027 return; 17028 } 17029 17030 // Retrieve PackageSettings and parse package 17031 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 17032 | PackageParser.PARSE_ENFORCE_CODE 17033 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 17034 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 17035 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 17036 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 17037 PackageParser pp = new PackageParser(); 17038 pp.setSeparateProcesses(mSeparateProcesses); 17039 pp.setDisplayMetrics(mMetrics); 17040 pp.setCallback(mPackageParserCallback); 17041 17042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 17043 final PackageParser.Package pkg; 17044 try { 17045 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 17046 } catch (PackageParserException e) { 17047 res.setError("Failed parse during installPackageLI", e); 17048 return; 17049 } finally { 17050 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17051 } 17052 17053 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 17054 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 17055 Slog.w(TAG, "Instant app package " + pkg.packageName 17056 + " does not target O, this will be a fatal error."); 17057 // STOPSHIP: Make this a fatal error 17058 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 17059 } 17060 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 17061 Slog.w(TAG, "Instant app package " + pkg.packageName 17062 + " does not target targetSandboxVersion 2, this will be a fatal error."); 17063 // STOPSHIP: Make this a fatal error 17064 pkg.applicationInfo.targetSandboxVersion = 2; 17065 } 17066 17067 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17068 // Static shared libraries have synthetic package names 17069 renameStaticSharedLibraryPackage(pkg); 17070 17071 // No static shared libs on external storage 17072 if (onExternal) { 17073 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17074 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17075 "Packages declaring static-shared libs cannot be updated"); 17076 return; 17077 } 17078 } 17079 17080 // If we are installing a clustered package add results for the children 17081 if (pkg.childPackages != null) { 17082 synchronized (mPackages) { 17083 final int childCount = pkg.childPackages.size(); 17084 for (int i = 0; i < childCount; i++) { 17085 PackageParser.Package childPkg = pkg.childPackages.get(i); 17086 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17087 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17088 childRes.pkg = childPkg; 17089 childRes.name = childPkg.packageName; 17090 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17091 if (childPs != null) { 17092 childRes.origUsers = childPs.queryInstalledUsers( 17093 sUserManager.getUserIds(), true); 17094 } 17095 if ((mPackages.containsKey(childPkg.packageName))) { 17096 childRes.removedInfo = new PackageRemovedInfo(this); 17097 childRes.removedInfo.removedPackage = childPkg.packageName; 17098 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17099 } 17100 if (res.addedChildPackages == null) { 17101 res.addedChildPackages = new ArrayMap<>(); 17102 } 17103 res.addedChildPackages.put(childPkg.packageName, childRes); 17104 } 17105 } 17106 } 17107 17108 // If package doesn't declare API override, mark that we have an install 17109 // time CPU ABI override. 17110 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17111 pkg.cpuAbiOverride = args.abiOverride; 17112 } 17113 17114 String pkgName = res.name = pkg.packageName; 17115 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17116 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17117 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17118 return; 17119 } 17120 } 17121 17122 try { 17123 // either use what we've been given or parse directly from the APK 17124 if (args.certificates != null) { 17125 try { 17126 PackageParser.populateCertificates(pkg, args.certificates); 17127 } catch (PackageParserException e) { 17128 // there was something wrong with the certificates we were given; 17129 // try to pull them from the APK 17130 PackageParser.collectCertificates(pkg, parseFlags); 17131 } 17132 } else { 17133 PackageParser.collectCertificates(pkg, parseFlags); 17134 } 17135 } catch (PackageParserException e) { 17136 res.setError("Failed collect during installPackageLI", e); 17137 return; 17138 } 17139 17140 // Get rid of all references to package scan path via parser. 17141 pp = null; 17142 String oldCodePath = null; 17143 boolean systemApp = false; 17144 synchronized (mPackages) { 17145 // Check if installing already existing package 17146 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17147 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17148 if (pkg.mOriginalPackages != null 17149 && pkg.mOriginalPackages.contains(oldName) 17150 && mPackages.containsKey(oldName)) { 17151 // This package is derived from an original package, 17152 // and this device has been updating from that original 17153 // name. We must continue using the original name, so 17154 // rename the new package here. 17155 pkg.setPackageName(oldName); 17156 pkgName = pkg.packageName; 17157 replace = true; 17158 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17159 + oldName + " pkgName=" + pkgName); 17160 } else if (mPackages.containsKey(pkgName)) { 17161 // This package, under its official name, already exists 17162 // on the device; we should replace it. 17163 replace = true; 17164 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17165 } 17166 17167 // Child packages are installed through the parent package 17168 if (pkg.parentPackage != null) { 17169 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17170 "Package " + pkg.packageName + " is child of package " 17171 + pkg.parentPackage.parentPackage + ". Child packages " 17172 + "can be updated only through the parent package."); 17173 return; 17174 } 17175 17176 if (replace) { 17177 // Prevent apps opting out from runtime permissions 17178 PackageParser.Package oldPackage = mPackages.get(pkgName); 17179 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17180 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17181 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17182 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17183 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17184 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17185 + " doesn't support runtime permissions but the old" 17186 + " target SDK " + oldTargetSdk + " does."); 17187 return; 17188 } 17189 // Prevent apps from downgrading their targetSandbox. 17190 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17191 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17192 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17193 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17194 "Package " + pkg.packageName + " new target sandbox " 17195 + newTargetSandbox + " is incompatible with the previous value of" 17196 + oldTargetSandbox + "."); 17197 return; 17198 } 17199 17200 // Prevent installing of child packages 17201 if (oldPackage.parentPackage != null) { 17202 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17203 "Package " + pkg.packageName + " is child of package " 17204 + oldPackage.parentPackage + ". Child packages " 17205 + "can be updated only through the parent package."); 17206 return; 17207 } 17208 } 17209 } 17210 17211 PackageSetting ps = mSettings.mPackages.get(pkgName); 17212 if (ps != null) { 17213 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17214 17215 // Static shared libs have same package with different versions where 17216 // we internally use a synthetic package name to allow multiple versions 17217 // of the same package, therefore we need to compare signatures against 17218 // the package setting for the latest library version. 17219 PackageSetting signatureCheckPs = ps; 17220 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17221 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17222 if (libraryEntry != null) { 17223 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17224 } 17225 } 17226 17227 // Quick sanity check that we're signed correctly if updating; 17228 // we'll check this again later when scanning, but we want to 17229 // bail early here before tripping over redefined permissions. 17230 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 17231 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 17232 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17233 + pkg.packageName + " upgrade keys do not match the " 17234 + "previously installed version"); 17235 return; 17236 } 17237 } else { 17238 try { 17239 verifySignaturesLP(signatureCheckPs, pkg); 17240 } catch (PackageManagerException e) { 17241 res.setError(e.error, e.getMessage()); 17242 return; 17243 } 17244 } 17245 17246 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17247 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17248 systemApp = (ps.pkg.applicationInfo.flags & 17249 ApplicationInfo.FLAG_SYSTEM) != 0; 17250 } 17251 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17252 } 17253 17254 int N = pkg.permissions.size(); 17255 for (int i = N-1; i >= 0; i--) { 17256 PackageParser.Permission perm = pkg.permissions.get(i); 17257 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 17258 17259 // Don't allow anyone but the system to define ephemeral permissions. 17260 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 17261 && !systemApp) { 17262 Slog.w(TAG, "Non-System package " + pkg.packageName 17263 + " attempting to delcare ephemeral permission " 17264 + perm.info.name + "; Removing ephemeral."); 17265 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 17266 } 17267 // Check whether the newly-scanned package wants to define an already-defined perm 17268 if (bp != null) { 17269 // If the defining package is signed with our cert, it's okay. This 17270 // also includes the "updating the same package" case, of course. 17271 // "updating same package" could also involve key-rotation. 17272 final boolean sigsOk; 17273 if (bp.sourcePackage.equals(pkg.packageName) 17274 && (bp.packageSetting instanceof PackageSetting) 17275 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 17276 scanFlags))) { 17277 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 17278 } else { 17279 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 17280 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 17281 } 17282 if (!sigsOk) { 17283 // If the owning package is the system itself, we log but allow 17284 // install to proceed; we fail the install on all other permission 17285 // redefinitions. 17286 if (!bp.sourcePackage.equals("android")) { 17287 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17288 + pkg.packageName + " attempting to redeclare permission " 17289 + perm.info.name + " already owned by " + bp.sourcePackage); 17290 res.origPermission = perm.info.name; 17291 res.origPackage = bp.sourcePackage; 17292 return; 17293 } else { 17294 Slog.w(TAG, "Package " + pkg.packageName 17295 + " attempting to redeclare system permission " 17296 + perm.info.name + "; ignoring new declaration"); 17297 pkg.permissions.remove(i); 17298 } 17299 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17300 // Prevent apps to change protection level to dangerous from any other 17301 // type as this would allow a privilege escalation where an app adds a 17302 // normal/signature permission in other app's group and later redefines 17303 // it as dangerous leading to the group auto-grant. 17304 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17305 == PermissionInfo.PROTECTION_DANGEROUS) { 17306 if (bp != null && !bp.isRuntime()) { 17307 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17308 + "non-runtime permission " + perm.info.name 17309 + " to runtime; keeping old protection level"); 17310 perm.info.protectionLevel = bp.protectionLevel; 17311 } 17312 } 17313 } 17314 } 17315 } 17316 } 17317 17318 if (systemApp) { 17319 if (onExternal) { 17320 // Abort update; system app can't be replaced with app on sdcard 17321 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17322 "Cannot install updates to system apps on sdcard"); 17323 return; 17324 } else if (instantApp) { 17325 // Abort update; system app can't be replaced with an instant app 17326 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17327 "Cannot update a system app with an instant app"); 17328 return; 17329 } 17330 } 17331 17332 if (args.move != null) { 17333 // We did an in-place move, so dex is ready to roll 17334 scanFlags |= SCAN_NO_DEX; 17335 scanFlags |= SCAN_MOVE; 17336 17337 synchronized (mPackages) { 17338 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17339 if (ps == null) { 17340 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17341 "Missing settings for moved package " + pkgName); 17342 } 17343 17344 // We moved the entire application as-is, so bring over the 17345 // previously derived ABI information. 17346 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17347 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17348 } 17349 17350 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17351 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17352 scanFlags |= SCAN_NO_DEX; 17353 17354 try { 17355 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17356 args.abiOverride : pkg.cpuAbiOverride); 17357 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17358 true /*extractLibs*/, mAppLib32InstallDir); 17359 } catch (PackageManagerException pme) { 17360 Slog.e(TAG, "Error deriving application ABI", pme); 17361 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17362 return; 17363 } 17364 17365 // Shared libraries for the package need to be updated. 17366 synchronized (mPackages) { 17367 try { 17368 updateSharedLibrariesLPr(pkg, null); 17369 } catch (PackageManagerException e) { 17370 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17371 } 17372 } 17373 17374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17375 // Do not run PackageDexOptimizer through the local performDexOpt 17376 // method because `pkg` may not be in `mPackages` yet. 17377 // 17378 // Also, don't fail application installs if the dexopt step fails. 17379 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17380 null /* instructionSets */, false /* checkProfiles */, 17381 getCompilerFilterForReason(REASON_INSTALL), 17382 getOrCreateCompilerPackageStats(pkg), 17383 mDexManager.isUsedByOtherApps(pkg.packageName)); 17384 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17385 17386 // Notify BackgroundDexOptService that the package has been changed. 17387 // If this is an update of a package which used to fail to compile, 17388 // BDOS will remove it from its blacklist. 17389 // TODO: Layering violation 17390 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17391 } 17392 17393 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17394 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17395 return; 17396 } 17397 17398 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17399 17400 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17401 "installPackageLI")) { 17402 if (replace) { 17403 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17404 // Static libs have a synthetic package name containing the version 17405 // and cannot be updated as an update would get a new package name, 17406 // unless this is the exact same version code which is useful for 17407 // development. 17408 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17409 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17410 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17411 + "static-shared libs cannot be updated"); 17412 return; 17413 } 17414 } 17415 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17416 installerPackageName, res, args.installReason); 17417 } else { 17418 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17419 args.user, installerPackageName, volumeUuid, res, args.installReason); 17420 } 17421 } 17422 17423 synchronized (mPackages) { 17424 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17425 if (ps != null) { 17426 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17427 ps.setUpdateAvailable(false /*updateAvailable*/); 17428 } 17429 17430 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17431 for (int i = 0; i < childCount; i++) { 17432 PackageParser.Package childPkg = pkg.childPackages.get(i); 17433 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17434 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17435 if (childPs != null) { 17436 childRes.newUsers = childPs.queryInstalledUsers( 17437 sUserManager.getUserIds(), true); 17438 } 17439 } 17440 17441 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17442 updateSequenceNumberLP(pkgName, res.newUsers); 17443 updateInstantAppInstallerLocked(pkgName); 17444 } 17445 } 17446 } 17447 17448 private void startIntentFilterVerifications(int userId, boolean replacing, 17449 PackageParser.Package pkg) { 17450 if (mIntentFilterVerifierComponent == null) { 17451 Slog.w(TAG, "No IntentFilter verification will not be done as " 17452 + "there is no IntentFilterVerifier available!"); 17453 return; 17454 } 17455 17456 final int verifierUid = getPackageUid( 17457 mIntentFilterVerifierComponent.getPackageName(), 17458 MATCH_DEBUG_TRIAGED_MISSING, 17459 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17460 17461 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17462 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17463 mHandler.sendMessage(msg); 17464 17465 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17466 for (int i = 0; i < childCount; i++) { 17467 PackageParser.Package childPkg = pkg.childPackages.get(i); 17468 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17469 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17470 mHandler.sendMessage(msg); 17471 } 17472 } 17473 17474 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17475 PackageParser.Package pkg) { 17476 int size = pkg.activities.size(); 17477 if (size == 0) { 17478 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17479 "No activity, so no need to verify any IntentFilter!"); 17480 return; 17481 } 17482 17483 final boolean hasDomainURLs = hasDomainURLs(pkg); 17484 if (!hasDomainURLs) { 17485 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17486 "No domain URLs, so no need to verify any IntentFilter!"); 17487 return; 17488 } 17489 17490 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17491 + " if any IntentFilter from the " + size 17492 + " Activities needs verification ..."); 17493 17494 int count = 0; 17495 final String packageName = pkg.packageName; 17496 17497 synchronized (mPackages) { 17498 // If this is a new install and we see that we've already run verification for this 17499 // package, we have nothing to do: it means the state was restored from backup. 17500 if (!replacing) { 17501 IntentFilterVerificationInfo ivi = 17502 mSettings.getIntentFilterVerificationLPr(packageName); 17503 if (ivi != null) { 17504 if (DEBUG_DOMAIN_VERIFICATION) { 17505 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17506 + ivi.getStatusString()); 17507 } 17508 return; 17509 } 17510 } 17511 17512 // If any filters need to be verified, then all need to be. 17513 boolean needToVerify = false; 17514 for (PackageParser.Activity a : pkg.activities) { 17515 for (ActivityIntentInfo filter : a.intents) { 17516 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17517 if (DEBUG_DOMAIN_VERIFICATION) { 17518 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17519 } 17520 needToVerify = true; 17521 break; 17522 } 17523 } 17524 } 17525 17526 if (needToVerify) { 17527 final int verificationId = mIntentFilterVerificationToken++; 17528 for (PackageParser.Activity a : pkg.activities) { 17529 for (ActivityIntentInfo filter : a.intents) { 17530 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17531 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17532 "Verification needed for IntentFilter:" + filter.toString()); 17533 mIntentFilterVerifier.addOneIntentFilterVerification( 17534 verifierUid, userId, verificationId, filter, packageName); 17535 count++; 17536 } 17537 } 17538 } 17539 } 17540 } 17541 17542 if (count > 0) { 17543 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17544 + " IntentFilter verification" + (count > 1 ? "s" : "") 17545 + " for userId:" + userId); 17546 mIntentFilterVerifier.startVerifications(userId); 17547 } else { 17548 if (DEBUG_DOMAIN_VERIFICATION) { 17549 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17550 } 17551 } 17552 } 17553 17554 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17555 final ComponentName cn = filter.activity.getComponentName(); 17556 final String packageName = cn.getPackageName(); 17557 17558 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17559 packageName); 17560 if (ivi == null) { 17561 return true; 17562 } 17563 int status = ivi.getStatus(); 17564 switch (status) { 17565 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17566 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17567 return true; 17568 17569 default: 17570 // Nothing to do 17571 return false; 17572 } 17573 } 17574 17575 private static boolean isMultiArch(ApplicationInfo info) { 17576 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17577 } 17578 17579 private static boolean isExternal(PackageParser.Package pkg) { 17580 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17581 } 17582 17583 private static boolean isExternal(PackageSetting ps) { 17584 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17585 } 17586 17587 private static boolean isSystemApp(PackageParser.Package pkg) { 17588 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17589 } 17590 17591 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17592 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17593 } 17594 17595 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17596 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17597 } 17598 17599 private static boolean isSystemApp(PackageSetting ps) { 17600 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17601 } 17602 17603 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17604 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17605 } 17606 17607 private int packageFlagsToInstallFlags(PackageSetting ps) { 17608 int installFlags = 0; 17609 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17610 // This existing package was an external ASEC install when we have 17611 // the external flag without a UUID 17612 installFlags |= PackageManager.INSTALL_EXTERNAL; 17613 } 17614 if (ps.isForwardLocked()) { 17615 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17616 } 17617 return installFlags; 17618 } 17619 17620 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17621 if (isExternal(pkg)) { 17622 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17623 return StorageManager.UUID_PRIMARY_PHYSICAL; 17624 } else { 17625 return pkg.volumeUuid; 17626 } 17627 } else { 17628 return StorageManager.UUID_PRIVATE_INTERNAL; 17629 } 17630 } 17631 17632 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17633 if (isExternal(pkg)) { 17634 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17635 return mSettings.getExternalVersion(); 17636 } else { 17637 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17638 } 17639 } else { 17640 return mSettings.getInternalVersion(); 17641 } 17642 } 17643 17644 private void deleteTempPackageFiles() { 17645 final FilenameFilter filter = new FilenameFilter() { 17646 public boolean accept(File dir, String name) { 17647 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17648 } 17649 }; 17650 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17651 file.delete(); 17652 } 17653 } 17654 17655 @Override 17656 public void deletePackageAsUser(String packageName, int versionCode, 17657 IPackageDeleteObserver observer, int userId, int flags) { 17658 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17659 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17660 } 17661 17662 @Override 17663 public void deletePackageVersioned(VersionedPackage versionedPackage, 17664 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17665 mContext.enforceCallingOrSelfPermission( 17666 android.Manifest.permission.DELETE_PACKAGES, null); 17667 Preconditions.checkNotNull(versionedPackage); 17668 Preconditions.checkNotNull(observer); 17669 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17670 PackageManager.VERSION_CODE_HIGHEST, 17671 Integer.MAX_VALUE, "versionCode must be >= -1"); 17672 17673 final String packageName = versionedPackage.getPackageName(); 17674 // TODO: We will change version code to long, so in the new API it is long 17675 final int versionCode = (int) versionedPackage.getVersionCode(); 17676 final String internalPackageName; 17677 synchronized (mPackages) { 17678 // Normalize package name to handle renamed packages and static libs 17679 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17680 // TODO: We will change version code to long, so in the new API it is long 17681 (int) versionedPackage.getVersionCode()); 17682 } 17683 17684 final int uid = Binder.getCallingUid(); 17685 if (!isOrphaned(internalPackageName) 17686 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17687 try { 17688 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17689 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17690 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17691 observer.onUserActionRequired(intent); 17692 } catch (RemoteException re) { 17693 } 17694 return; 17695 } 17696 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17697 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17698 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17699 mContext.enforceCallingOrSelfPermission( 17700 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17701 "deletePackage for user " + userId); 17702 } 17703 17704 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17705 try { 17706 observer.onPackageDeleted(packageName, 17707 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17708 } catch (RemoteException re) { 17709 } 17710 return; 17711 } 17712 17713 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17714 try { 17715 observer.onPackageDeleted(packageName, 17716 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17717 } catch (RemoteException re) { 17718 } 17719 return; 17720 } 17721 17722 if (DEBUG_REMOVE) { 17723 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17724 + " deleteAllUsers: " + deleteAllUsers + " version=" 17725 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17726 ? "VERSION_CODE_HIGHEST" : versionCode)); 17727 } 17728 // Queue up an async operation since the package deletion may take a little while. 17729 mHandler.post(new Runnable() { 17730 public void run() { 17731 mHandler.removeCallbacks(this); 17732 int returnCode; 17733 if (!deleteAllUsers) { 17734 returnCode = deletePackageX(internalPackageName, versionCode, 17735 userId, deleteFlags); 17736 } else { 17737 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17738 internalPackageName, users); 17739 // If nobody is blocking uninstall, proceed with delete for all users 17740 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17741 returnCode = deletePackageX(internalPackageName, versionCode, 17742 userId, deleteFlags); 17743 } else { 17744 // Otherwise uninstall individually for users with blockUninstalls=false 17745 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17746 for (int userId : users) { 17747 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17748 returnCode = deletePackageX(internalPackageName, versionCode, 17749 userId, userFlags); 17750 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17751 Slog.w(TAG, "Package delete failed for user " + userId 17752 + ", returnCode " + returnCode); 17753 } 17754 } 17755 } 17756 // The app has only been marked uninstalled for certain users. 17757 // We still need to report that delete was blocked 17758 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17759 } 17760 } 17761 try { 17762 observer.onPackageDeleted(packageName, returnCode, null); 17763 } catch (RemoteException e) { 17764 Log.i(TAG, "Observer no longer exists."); 17765 } //end catch 17766 } //end run 17767 }); 17768 } 17769 17770 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17771 if (pkg.staticSharedLibName != null) { 17772 return pkg.manifestPackageName; 17773 } 17774 return pkg.packageName; 17775 } 17776 17777 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17778 // Handle renamed packages 17779 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17780 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17781 17782 // Is this a static library? 17783 SparseArray<SharedLibraryEntry> versionedLib = 17784 mStaticLibsByDeclaringPackage.get(packageName); 17785 if (versionedLib == null || versionedLib.size() <= 0) { 17786 return packageName; 17787 } 17788 17789 // Figure out which lib versions the caller can see 17790 SparseIntArray versionsCallerCanSee = null; 17791 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17792 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17793 && callingAppId != Process.ROOT_UID) { 17794 versionsCallerCanSee = new SparseIntArray(); 17795 String libName = versionedLib.valueAt(0).info.getName(); 17796 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17797 if (uidPackages != null) { 17798 for (String uidPackage : uidPackages) { 17799 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17800 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17801 if (libIdx >= 0) { 17802 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17803 versionsCallerCanSee.append(libVersion, libVersion); 17804 } 17805 } 17806 } 17807 } 17808 17809 // Caller can see nothing - done 17810 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17811 return packageName; 17812 } 17813 17814 // Find the version the caller can see and the app version code 17815 SharedLibraryEntry highestVersion = null; 17816 final int versionCount = versionedLib.size(); 17817 for (int i = 0; i < versionCount; i++) { 17818 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17819 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17820 libEntry.info.getVersion()) < 0) { 17821 continue; 17822 } 17823 // TODO: We will change version code to long, so in the new API it is long 17824 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17825 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17826 if (libVersionCode == versionCode) { 17827 return libEntry.apk; 17828 } 17829 } else if (highestVersion == null) { 17830 highestVersion = libEntry; 17831 } else if (libVersionCode > highestVersion.info 17832 .getDeclaringPackage().getVersionCode()) { 17833 highestVersion = libEntry; 17834 } 17835 } 17836 17837 if (highestVersion != null) { 17838 return highestVersion.apk; 17839 } 17840 17841 return packageName; 17842 } 17843 17844 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17845 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17846 || callingUid == Process.SYSTEM_UID) { 17847 return true; 17848 } 17849 final int callingUserId = UserHandle.getUserId(callingUid); 17850 // If the caller installed the pkgName, then allow it to silently uninstall. 17851 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17852 return true; 17853 } 17854 17855 // Allow package verifier to silently uninstall. 17856 if (mRequiredVerifierPackage != null && 17857 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17858 return true; 17859 } 17860 17861 // Allow package uninstaller to silently uninstall. 17862 if (mRequiredUninstallerPackage != null && 17863 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17864 return true; 17865 } 17866 17867 // Allow storage manager to silently uninstall. 17868 if (mStorageManagerPackage != null && 17869 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17870 return true; 17871 } 17872 return false; 17873 } 17874 17875 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17876 int[] result = EMPTY_INT_ARRAY; 17877 for (int userId : userIds) { 17878 if (getBlockUninstallForUser(packageName, userId)) { 17879 result = ArrayUtils.appendInt(result, userId); 17880 } 17881 } 17882 return result; 17883 } 17884 17885 @Override 17886 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17887 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17888 } 17889 17890 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17891 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17892 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17893 try { 17894 if (dpm != null) { 17895 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17896 /* callingUserOnly =*/ false); 17897 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17898 : deviceOwnerComponentName.getPackageName(); 17899 // Does the package contains the device owner? 17900 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17901 // this check is probably not needed, since DO should be registered as a device 17902 // admin on some user too. (Original bug for this: b/17657954) 17903 if (packageName.equals(deviceOwnerPackageName)) { 17904 return true; 17905 } 17906 // Does it contain a device admin for any user? 17907 int[] users; 17908 if (userId == UserHandle.USER_ALL) { 17909 users = sUserManager.getUserIds(); 17910 } else { 17911 users = new int[]{userId}; 17912 } 17913 for (int i = 0; i < users.length; ++i) { 17914 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17915 return true; 17916 } 17917 } 17918 } 17919 } catch (RemoteException e) { 17920 } 17921 return false; 17922 } 17923 17924 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17925 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17926 } 17927 17928 /** 17929 * This method is an internal method that could be get invoked either 17930 * to delete an installed package or to clean up a failed installation. 17931 * After deleting an installed package, a broadcast is sent to notify any 17932 * listeners that the package has been removed. For cleaning up a failed 17933 * installation, the broadcast is not necessary since the package's 17934 * installation wouldn't have sent the initial broadcast either 17935 * The key steps in deleting a package are 17936 * deleting the package information in internal structures like mPackages, 17937 * deleting the packages base directories through installd 17938 * updating mSettings to reflect current status 17939 * persisting settings for later use 17940 * sending a broadcast if necessary 17941 */ 17942 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17943 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17944 final boolean res; 17945 17946 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17947 ? UserHandle.USER_ALL : userId; 17948 17949 if (isPackageDeviceAdmin(packageName, removeUser)) { 17950 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17951 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17952 } 17953 17954 PackageSetting uninstalledPs = null; 17955 PackageParser.Package pkg = null; 17956 17957 // for the uninstall-updates case and restricted profiles, remember the per- 17958 // user handle installed state 17959 int[] allUsers; 17960 synchronized (mPackages) { 17961 uninstalledPs = mSettings.mPackages.get(packageName); 17962 if (uninstalledPs == null) { 17963 Slog.w(TAG, "Not removing non-existent package " + packageName); 17964 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17965 } 17966 17967 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17968 && uninstalledPs.versionCode != versionCode) { 17969 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17970 + uninstalledPs.versionCode + " != " + versionCode); 17971 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17972 } 17973 17974 // Static shared libs can be declared by any package, so let us not 17975 // allow removing a package if it provides a lib others depend on. 17976 pkg = mPackages.get(packageName); 17977 if (pkg != null && pkg.staticSharedLibName != null) { 17978 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17979 pkg.staticSharedLibVersion); 17980 if (libEntry != null) { 17981 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17982 libEntry.info, 0, userId); 17983 if (!ArrayUtils.isEmpty(libClientPackages)) { 17984 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17985 + " hosting lib " + libEntry.info.getName() + " version " 17986 + libEntry.info.getVersion() + " used by " + libClientPackages); 17987 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17988 } 17989 } 17990 } 17991 17992 allUsers = sUserManager.getUserIds(); 17993 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17994 } 17995 17996 final int freezeUser; 17997 if (isUpdatedSystemApp(uninstalledPs) 17998 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17999 // We're downgrading a system app, which will apply to all users, so 18000 // freeze them all during the downgrade 18001 freezeUser = UserHandle.USER_ALL; 18002 } else { 18003 freezeUser = removeUser; 18004 } 18005 18006 synchronized (mInstallLock) { 18007 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18008 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18009 deleteFlags, "deletePackageX")) { 18010 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18011 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 18012 } 18013 synchronized (mPackages) { 18014 if (res) { 18015 if (pkg != null) { 18016 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18017 } 18018 updateSequenceNumberLP(packageName, info.removedUsers); 18019 updateInstantAppInstallerLocked(packageName); 18020 } 18021 } 18022 } 18023 18024 if (res) { 18025 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18026 info.sendPackageRemovedBroadcasts(killApp); 18027 info.sendSystemPackageUpdatedBroadcasts(); 18028 info.sendSystemPackageAppearedBroadcasts(); 18029 } 18030 // Force a gc here. 18031 Runtime.getRuntime().gc(); 18032 // Delete the resources here after sending the broadcast to let 18033 // other processes clean up before deleting resources. 18034 if (info.args != null) { 18035 synchronized (mInstallLock) { 18036 info.args.doPostDeleteLI(true); 18037 } 18038 } 18039 18040 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18041 } 18042 18043 static class PackageRemovedInfo { 18044 final PackageSender packageSender; 18045 String removedPackage; 18046 String installerPackageName; 18047 int uid = -1; 18048 int removedAppId = -1; 18049 int[] origUsers; 18050 int[] removedUsers = null; 18051 int[] broadcastUsers = null; 18052 SparseArray<Integer> installReasons; 18053 boolean isRemovedPackageSystemUpdate = false; 18054 boolean isUpdate; 18055 boolean dataRemoved; 18056 boolean removedForAllUsers; 18057 boolean isStaticSharedLib; 18058 // Clean up resources deleted packages. 18059 InstallArgs args = null; 18060 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18061 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18062 18063 PackageRemovedInfo(PackageSender packageSender) { 18064 this.packageSender = packageSender; 18065 } 18066 18067 void sendPackageRemovedBroadcasts(boolean killApp) { 18068 sendPackageRemovedBroadcastInternal(killApp); 18069 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18070 for (int i = 0; i < childCount; i++) { 18071 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18072 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18073 } 18074 } 18075 18076 void sendSystemPackageUpdatedBroadcasts() { 18077 if (isRemovedPackageSystemUpdate) { 18078 sendSystemPackageUpdatedBroadcastsInternal(); 18079 final int childCount = (removedChildPackages != null) 18080 ? removedChildPackages.size() : 0; 18081 for (int i = 0; i < childCount; i++) { 18082 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18083 if (childInfo.isRemovedPackageSystemUpdate) { 18084 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18085 } 18086 } 18087 } 18088 } 18089 18090 void sendSystemPackageAppearedBroadcasts() { 18091 final int packageCount = (appearedChildPackages != null) 18092 ? appearedChildPackages.size() : 0; 18093 for (int i = 0; i < packageCount; i++) { 18094 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18095 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18096 true, UserHandle.getAppId(installedInfo.uid), 18097 installedInfo.newUsers); 18098 } 18099 } 18100 18101 private void sendSystemPackageUpdatedBroadcastsInternal() { 18102 Bundle extras = new Bundle(2); 18103 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18104 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18105 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18106 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18107 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18108 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18109 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18110 null, null, 0, removedPackage, null, null); 18111 if (installerPackageName != null) { 18112 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18113 removedPackage, extras, 0 /*flags*/, 18114 installerPackageName, null, null); 18115 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18116 removedPackage, extras, 0 /*flags*/, 18117 installerPackageName, null, null); 18118 } 18119 } 18120 18121 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18122 // Don't send static shared library removal broadcasts as these 18123 // libs are visible only the the apps that depend on them an one 18124 // cannot remove the library if it has a dependency. 18125 if (isStaticSharedLib) { 18126 return; 18127 } 18128 Bundle extras = new Bundle(2); 18129 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18130 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18131 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18132 if (isUpdate || isRemovedPackageSystemUpdate) { 18133 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18134 } 18135 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18136 if (removedPackage != null) { 18137 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18138 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 18139 if (installerPackageName != null) { 18140 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18141 removedPackage, extras, 0 /*flags*/, 18142 installerPackageName, null, broadcastUsers); 18143 } 18144 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18145 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18146 removedPackage, extras, 18147 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18148 null, null, broadcastUsers); 18149 } 18150 } 18151 if (removedAppId >= 0) { 18152 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 18153 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers); 18154 } 18155 } 18156 18157 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18158 removedUsers = userIds; 18159 if (removedUsers == null) { 18160 broadcastUsers = null; 18161 return; 18162 } 18163 18164 broadcastUsers = EMPTY_INT_ARRAY; 18165 for (int i = userIds.length - 1; i >= 0; --i) { 18166 final int userId = userIds[i]; 18167 if (deletedPackageSetting.getInstantApp(userId)) { 18168 continue; 18169 } 18170 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18171 } 18172 } 18173 } 18174 18175 /* 18176 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18177 * flag is not set, the data directory is removed as well. 18178 * make sure this flag is set for partially installed apps. If not its meaningless to 18179 * delete a partially installed application. 18180 */ 18181 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18182 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18183 String packageName = ps.name; 18184 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18185 // Retrieve object to delete permissions for shared user later on 18186 final PackageParser.Package deletedPkg; 18187 final PackageSetting deletedPs; 18188 // reader 18189 synchronized (mPackages) { 18190 deletedPkg = mPackages.get(packageName); 18191 deletedPs = mSettings.mPackages.get(packageName); 18192 if (outInfo != null) { 18193 outInfo.removedPackage = packageName; 18194 outInfo.installerPackageName = ps.installerPackageName; 18195 outInfo.isStaticSharedLib = deletedPkg != null 18196 && deletedPkg.staticSharedLibName != null; 18197 outInfo.populateUsers(deletedPs == null ? null 18198 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18199 } 18200 } 18201 18202 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 18203 18204 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18205 final PackageParser.Package resolvedPkg; 18206 if (deletedPkg != null) { 18207 resolvedPkg = deletedPkg; 18208 } else { 18209 // We don't have a parsed package when it lives on an ejected 18210 // adopted storage device, so fake something together 18211 resolvedPkg = new PackageParser.Package(ps.name); 18212 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18213 } 18214 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18215 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18216 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18217 if (outInfo != null) { 18218 outInfo.dataRemoved = true; 18219 } 18220 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18221 } 18222 18223 int removedAppId = -1; 18224 18225 // writer 18226 synchronized (mPackages) { 18227 boolean installedStateChanged = false; 18228 if (deletedPs != null) { 18229 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18230 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18231 clearDefaultBrowserIfNeeded(packageName); 18232 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18233 removedAppId = mSettings.removePackageLPw(packageName); 18234 if (outInfo != null) { 18235 outInfo.removedAppId = removedAppId; 18236 } 18237 updatePermissionsLPw(deletedPs.name, null, 0); 18238 if (deletedPs.sharedUser != null) { 18239 // Remove permissions associated with package. Since runtime 18240 // permissions are per user we have to kill the removed package 18241 // or packages running under the shared user of the removed 18242 // package if revoking the permissions requested only by the removed 18243 // package is successful and this causes a change in gids. 18244 for (int userId : UserManagerService.getInstance().getUserIds()) { 18245 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18246 userId); 18247 if (userIdToKill == UserHandle.USER_ALL 18248 || userIdToKill >= UserHandle.USER_SYSTEM) { 18249 // If gids changed for this user, kill all affected packages. 18250 mHandler.post(new Runnable() { 18251 @Override 18252 public void run() { 18253 // This has to happen with no lock held. 18254 killApplication(deletedPs.name, deletedPs.appId, 18255 KILL_APP_REASON_GIDS_CHANGED); 18256 } 18257 }); 18258 break; 18259 } 18260 } 18261 } 18262 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18263 } 18264 // make sure to preserve per-user disabled state if this removal was just 18265 // a downgrade of a system app to the factory package 18266 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18267 if (DEBUG_REMOVE) { 18268 Slog.d(TAG, "Propagating install state across downgrade"); 18269 } 18270 for (int userId : allUserHandles) { 18271 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18272 if (DEBUG_REMOVE) { 18273 Slog.d(TAG, " user " + userId + " => " + installed); 18274 } 18275 if (installed != ps.getInstalled(userId)) { 18276 installedStateChanged = true; 18277 } 18278 ps.setInstalled(installed, userId); 18279 } 18280 } 18281 } 18282 // can downgrade to reader 18283 if (writeSettings) { 18284 // Save settings now 18285 mSettings.writeLPr(); 18286 } 18287 if (installedStateChanged) { 18288 mSettings.writeKernelMappingLPr(ps); 18289 } 18290 } 18291 if (removedAppId != -1) { 18292 // A user ID was deleted here. Go through all users and remove it 18293 // from KeyStore. 18294 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18295 } 18296 } 18297 18298 static boolean locationIsPrivileged(File path) { 18299 try { 18300 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 18301 .getCanonicalPath(); 18302 return path.getCanonicalPath().startsWith(privilegedAppDir); 18303 } catch (IOException e) { 18304 Slog.e(TAG, "Unable to access code path " + path); 18305 } 18306 return false; 18307 } 18308 18309 /* 18310 * Tries to delete system package. 18311 */ 18312 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18313 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18314 boolean writeSettings) { 18315 if (deletedPs.parentPackageName != null) { 18316 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18317 return false; 18318 } 18319 18320 final boolean applyUserRestrictions 18321 = (allUserHandles != null) && (outInfo.origUsers != null); 18322 final PackageSetting disabledPs; 18323 // Confirm if the system package has been updated 18324 // An updated system app can be deleted. This will also have to restore 18325 // the system pkg from system partition 18326 // reader 18327 synchronized (mPackages) { 18328 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18329 } 18330 18331 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18332 + " disabledPs=" + disabledPs); 18333 18334 if (disabledPs == null) { 18335 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18336 return false; 18337 } else if (DEBUG_REMOVE) { 18338 Slog.d(TAG, "Deleting system pkg from data partition"); 18339 } 18340 18341 if (DEBUG_REMOVE) { 18342 if (applyUserRestrictions) { 18343 Slog.d(TAG, "Remembering install states:"); 18344 for (int userId : allUserHandles) { 18345 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18346 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18347 } 18348 } 18349 } 18350 18351 // Delete the updated package 18352 outInfo.isRemovedPackageSystemUpdate = true; 18353 if (outInfo.removedChildPackages != null) { 18354 final int childCount = (deletedPs.childPackageNames != null) 18355 ? deletedPs.childPackageNames.size() : 0; 18356 for (int i = 0; i < childCount; i++) { 18357 String childPackageName = deletedPs.childPackageNames.get(i); 18358 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18359 .contains(childPackageName)) { 18360 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18361 childPackageName); 18362 if (childInfo != null) { 18363 childInfo.isRemovedPackageSystemUpdate = true; 18364 } 18365 } 18366 } 18367 } 18368 18369 if (disabledPs.versionCode < deletedPs.versionCode) { 18370 // Delete data for downgrades 18371 flags &= ~PackageManager.DELETE_KEEP_DATA; 18372 } else { 18373 // Preserve data by setting flag 18374 flags |= PackageManager.DELETE_KEEP_DATA; 18375 } 18376 18377 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18378 outInfo, writeSettings, disabledPs.pkg); 18379 if (!ret) { 18380 return false; 18381 } 18382 18383 // writer 18384 synchronized (mPackages) { 18385 // Reinstate the old system package 18386 enableSystemPackageLPw(disabledPs.pkg); 18387 // Remove any native libraries from the upgraded package. 18388 removeNativeBinariesLI(deletedPs); 18389 } 18390 18391 // Install the system package 18392 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18393 int parseFlags = mDefParseFlags 18394 | PackageParser.PARSE_MUST_BE_APK 18395 | PackageParser.PARSE_IS_SYSTEM 18396 | PackageParser.PARSE_IS_SYSTEM_DIR; 18397 if (locationIsPrivileged(disabledPs.codePath)) { 18398 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18399 } 18400 18401 final PackageParser.Package newPkg; 18402 try { 18403 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18404 0 /* currentTime */, null); 18405 } catch (PackageManagerException e) { 18406 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18407 + e.getMessage()); 18408 return false; 18409 } 18410 18411 try { 18412 // update shared libraries for the newly re-installed system package 18413 updateSharedLibrariesLPr(newPkg, null); 18414 } catch (PackageManagerException e) { 18415 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18416 } 18417 18418 prepareAppDataAfterInstallLIF(newPkg); 18419 18420 // writer 18421 synchronized (mPackages) { 18422 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18423 18424 // Propagate the permissions state as we do not want to drop on the floor 18425 // runtime permissions. The update permissions method below will take 18426 // care of removing obsolete permissions and grant install permissions. 18427 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18428 updatePermissionsLPw(newPkg.packageName, newPkg, 18429 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18430 18431 if (applyUserRestrictions) { 18432 boolean installedStateChanged = false; 18433 if (DEBUG_REMOVE) { 18434 Slog.d(TAG, "Propagating install state across reinstall"); 18435 } 18436 for (int userId : allUserHandles) { 18437 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18438 if (DEBUG_REMOVE) { 18439 Slog.d(TAG, " user " + userId + " => " + installed); 18440 } 18441 if (installed != ps.getInstalled(userId)) { 18442 installedStateChanged = true; 18443 } 18444 ps.setInstalled(installed, userId); 18445 18446 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18447 } 18448 // Regardless of writeSettings we need to ensure that this restriction 18449 // state propagation is persisted 18450 mSettings.writeAllUsersPackageRestrictionsLPr(); 18451 if (installedStateChanged) { 18452 mSettings.writeKernelMappingLPr(ps); 18453 } 18454 } 18455 // can downgrade to reader here 18456 if (writeSettings) { 18457 mSettings.writeLPr(); 18458 } 18459 } 18460 return true; 18461 } 18462 18463 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18464 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18465 PackageRemovedInfo outInfo, boolean writeSettings, 18466 PackageParser.Package replacingPackage) { 18467 synchronized (mPackages) { 18468 if (outInfo != null) { 18469 outInfo.uid = ps.appId; 18470 } 18471 18472 if (outInfo != null && outInfo.removedChildPackages != null) { 18473 final int childCount = (ps.childPackageNames != null) 18474 ? ps.childPackageNames.size() : 0; 18475 for (int i = 0; i < childCount; i++) { 18476 String childPackageName = ps.childPackageNames.get(i); 18477 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18478 if (childPs == null) { 18479 return false; 18480 } 18481 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18482 childPackageName); 18483 if (childInfo != null) { 18484 childInfo.uid = childPs.appId; 18485 } 18486 } 18487 } 18488 } 18489 18490 // Delete package data from internal structures and also remove data if flag is set 18491 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18492 18493 // Delete the child packages data 18494 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18495 for (int i = 0; i < childCount; i++) { 18496 PackageSetting childPs; 18497 synchronized (mPackages) { 18498 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18499 } 18500 if (childPs != null) { 18501 PackageRemovedInfo childOutInfo = (outInfo != null 18502 && outInfo.removedChildPackages != null) 18503 ? outInfo.removedChildPackages.get(childPs.name) : null; 18504 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18505 && (replacingPackage != null 18506 && !replacingPackage.hasChildPackage(childPs.name)) 18507 ? flags & ~DELETE_KEEP_DATA : flags; 18508 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18509 deleteFlags, writeSettings); 18510 } 18511 } 18512 18513 // Delete application code and resources only for parent packages 18514 if (ps.parentPackageName == null) { 18515 if (deleteCodeAndResources && (outInfo != null)) { 18516 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18517 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18518 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18519 } 18520 } 18521 18522 return true; 18523 } 18524 18525 @Override 18526 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18527 int userId) { 18528 mContext.enforceCallingOrSelfPermission( 18529 android.Manifest.permission.DELETE_PACKAGES, null); 18530 synchronized (mPackages) { 18531 // Cannot block uninstall of static shared libs as they are 18532 // considered a part of the using app (emulating static linking). 18533 // Also static libs are installed always on internal storage. 18534 PackageParser.Package pkg = mPackages.get(packageName); 18535 if (pkg != null && pkg.staticSharedLibName != null) { 18536 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18537 + " providing static shared library: " + pkg.staticSharedLibName); 18538 return false; 18539 } 18540 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18541 mSettings.writePackageRestrictionsLPr(userId); 18542 } 18543 return true; 18544 } 18545 18546 @Override 18547 public boolean getBlockUninstallForUser(String packageName, int userId) { 18548 synchronized (mPackages) { 18549 return mSettings.getBlockUninstallLPr(userId, packageName); 18550 } 18551 } 18552 18553 @Override 18554 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18555 int callingUid = Binder.getCallingUid(); 18556 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18557 throw new SecurityException( 18558 "setRequiredForSystemUser can only be run by the system or root"); 18559 } 18560 synchronized (mPackages) { 18561 PackageSetting ps = mSettings.mPackages.get(packageName); 18562 if (ps == null) { 18563 Log.w(TAG, "Package doesn't exist: " + packageName); 18564 return false; 18565 } 18566 if (systemUserApp) { 18567 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18568 } else { 18569 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18570 } 18571 mSettings.writeLPr(); 18572 } 18573 return true; 18574 } 18575 18576 /* 18577 * This method handles package deletion in general 18578 */ 18579 private boolean deletePackageLIF(String packageName, UserHandle user, 18580 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18581 PackageRemovedInfo outInfo, boolean writeSettings, 18582 PackageParser.Package replacingPackage) { 18583 if (packageName == null) { 18584 Slog.w(TAG, "Attempt to delete null packageName."); 18585 return false; 18586 } 18587 18588 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18589 18590 PackageSetting ps; 18591 synchronized (mPackages) { 18592 ps = mSettings.mPackages.get(packageName); 18593 if (ps == null) { 18594 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18595 return false; 18596 } 18597 18598 if (ps.parentPackageName != null && (!isSystemApp(ps) 18599 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18600 if (DEBUG_REMOVE) { 18601 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18602 + ((user == null) ? UserHandle.USER_ALL : user)); 18603 } 18604 final int removedUserId = (user != null) ? user.getIdentifier() 18605 : UserHandle.USER_ALL; 18606 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18607 return false; 18608 } 18609 markPackageUninstalledForUserLPw(ps, user); 18610 scheduleWritePackageRestrictionsLocked(user); 18611 return true; 18612 } 18613 } 18614 18615 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18616 && user.getIdentifier() != UserHandle.USER_ALL)) { 18617 // The caller is asking that the package only be deleted for a single 18618 // user. To do this, we just mark its uninstalled state and delete 18619 // its data. If this is a system app, we only allow this to happen if 18620 // they have set the special DELETE_SYSTEM_APP which requests different 18621 // semantics than normal for uninstalling system apps. 18622 markPackageUninstalledForUserLPw(ps, user); 18623 18624 if (!isSystemApp(ps)) { 18625 // Do not uninstall the APK if an app should be cached 18626 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18627 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18628 // Other user still have this package installed, so all 18629 // we need to do is clear this user's data and save that 18630 // it is uninstalled. 18631 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18632 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18633 return false; 18634 } 18635 scheduleWritePackageRestrictionsLocked(user); 18636 return true; 18637 } else { 18638 // We need to set it back to 'installed' so the uninstall 18639 // broadcasts will be sent correctly. 18640 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18641 ps.setInstalled(true, user.getIdentifier()); 18642 mSettings.writeKernelMappingLPr(ps); 18643 } 18644 } else { 18645 // This is a system app, so we assume that the 18646 // other users still have this package installed, so all 18647 // we need to do is clear this user's data and save that 18648 // it is uninstalled. 18649 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18650 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18651 return false; 18652 } 18653 scheduleWritePackageRestrictionsLocked(user); 18654 return true; 18655 } 18656 } 18657 18658 // If we are deleting a composite package for all users, keep track 18659 // of result for each child. 18660 if (ps.childPackageNames != null && outInfo != null) { 18661 synchronized (mPackages) { 18662 final int childCount = ps.childPackageNames.size(); 18663 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18664 for (int i = 0; i < childCount; i++) { 18665 String childPackageName = ps.childPackageNames.get(i); 18666 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18667 childInfo.removedPackage = childPackageName; 18668 childInfo.installerPackageName = ps.installerPackageName; 18669 outInfo.removedChildPackages.put(childPackageName, childInfo); 18670 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18671 if (childPs != null) { 18672 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18673 } 18674 } 18675 } 18676 } 18677 18678 boolean ret = false; 18679 if (isSystemApp(ps)) { 18680 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18681 // When an updated system application is deleted we delete the existing resources 18682 // as well and fall back to existing code in system partition 18683 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18684 } else { 18685 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18686 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18687 outInfo, writeSettings, replacingPackage); 18688 } 18689 18690 // Take a note whether we deleted the package for all users 18691 if (outInfo != null) { 18692 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18693 if (outInfo.removedChildPackages != null) { 18694 synchronized (mPackages) { 18695 final int childCount = outInfo.removedChildPackages.size(); 18696 for (int i = 0; i < childCount; i++) { 18697 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18698 if (childInfo != null) { 18699 childInfo.removedForAllUsers = mPackages.get( 18700 childInfo.removedPackage) == null; 18701 } 18702 } 18703 } 18704 } 18705 // If we uninstalled an update to a system app there may be some 18706 // child packages that appeared as they are declared in the system 18707 // app but were not declared in the update. 18708 if (isSystemApp(ps)) { 18709 synchronized (mPackages) { 18710 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18711 final int childCount = (updatedPs.childPackageNames != null) 18712 ? updatedPs.childPackageNames.size() : 0; 18713 for (int i = 0; i < childCount; i++) { 18714 String childPackageName = updatedPs.childPackageNames.get(i); 18715 if (outInfo.removedChildPackages == null 18716 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18717 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18718 if (childPs == null) { 18719 continue; 18720 } 18721 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18722 installRes.name = childPackageName; 18723 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18724 installRes.pkg = mPackages.get(childPackageName); 18725 installRes.uid = childPs.pkg.applicationInfo.uid; 18726 if (outInfo.appearedChildPackages == null) { 18727 outInfo.appearedChildPackages = new ArrayMap<>(); 18728 } 18729 outInfo.appearedChildPackages.put(childPackageName, installRes); 18730 } 18731 } 18732 } 18733 } 18734 } 18735 18736 return ret; 18737 } 18738 18739 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18740 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18741 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18742 for (int nextUserId : userIds) { 18743 if (DEBUG_REMOVE) { 18744 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18745 } 18746 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18747 false /*installed*/, 18748 true /*stopped*/, 18749 true /*notLaunched*/, 18750 false /*hidden*/, 18751 false /*suspended*/, 18752 false /*instantApp*/, 18753 null /*lastDisableAppCaller*/, 18754 null /*enabledComponents*/, 18755 null /*disabledComponents*/, 18756 ps.readUserState(nextUserId).domainVerificationStatus, 18757 0, PackageManager.INSTALL_REASON_UNKNOWN); 18758 } 18759 mSettings.writeKernelMappingLPr(ps); 18760 } 18761 18762 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18763 PackageRemovedInfo outInfo) { 18764 final PackageParser.Package pkg; 18765 synchronized (mPackages) { 18766 pkg = mPackages.get(ps.name); 18767 } 18768 18769 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18770 : new int[] {userId}; 18771 for (int nextUserId : userIds) { 18772 if (DEBUG_REMOVE) { 18773 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18774 + nextUserId); 18775 } 18776 18777 destroyAppDataLIF(pkg, userId, 18778 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18779 destroyAppProfilesLIF(pkg, userId); 18780 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18781 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18782 schedulePackageCleaning(ps.name, nextUserId, false); 18783 synchronized (mPackages) { 18784 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18785 scheduleWritePackageRestrictionsLocked(nextUserId); 18786 } 18787 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18788 } 18789 } 18790 18791 if (outInfo != null) { 18792 outInfo.removedPackage = ps.name; 18793 outInfo.installerPackageName = ps.installerPackageName; 18794 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18795 outInfo.removedAppId = ps.appId; 18796 outInfo.removedUsers = userIds; 18797 outInfo.broadcastUsers = userIds; 18798 } 18799 18800 return true; 18801 } 18802 18803 private final class ClearStorageConnection implements ServiceConnection { 18804 IMediaContainerService mContainerService; 18805 18806 @Override 18807 public void onServiceConnected(ComponentName name, IBinder service) { 18808 synchronized (this) { 18809 mContainerService = IMediaContainerService.Stub 18810 .asInterface(Binder.allowBlocking(service)); 18811 notifyAll(); 18812 } 18813 } 18814 18815 @Override 18816 public void onServiceDisconnected(ComponentName name) { 18817 } 18818 } 18819 18820 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18821 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18822 18823 final boolean mounted; 18824 if (Environment.isExternalStorageEmulated()) { 18825 mounted = true; 18826 } else { 18827 final String status = Environment.getExternalStorageState(); 18828 18829 mounted = status.equals(Environment.MEDIA_MOUNTED) 18830 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18831 } 18832 18833 if (!mounted) { 18834 return; 18835 } 18836 18837 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18838 int[] users; 18839 if (userId == UserHandle.USER_ALL) { 18840 users = sUserManager.getUserIds(); 18841 } else { 18842 users = new int[] { userId }; 18843 } 18844 final ClearStorageConnection conn = new ClearStorageConnection(); 18845 if (mContext.bindServiceAsUser( 18846 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18847 try { 18848 for (int curUser : users) { 18849 long timeout = SystemClock.uptimeMillis() + 5000; 18850 synchronized (conn) { 18851 long now; 18852 while (conn.mContainerService == null && 18853 (now = SystemClock.uptimeMillis()) < timeout) { 18854 try { 18855 conn.wait(timeout - now); 18856 } catch (InterruptedException e) { 18857 } 18858 } 18859 } 18860 if (conn.mContainerService == null) { 18861 return; 18862 } 18863 18864 final UserEnvironment userEnv = new UserEnvironment(curUser); 18865 clearDirectory(conn.mContainerService, 18866 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18867 if (allData) { 18868 clearDirectory(conn.mContainerService, 18869 userEnv.buildExternalStorageAppDataDirs(packageName)); 18870 clearDirectory(conn.mContainerService, 18871 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18872 } 18873 } 18874 } finally { 18875 mContext.unbindService(conn); 18876 } 18877 } 18878 } 18879 18880 @Override 18881 public void clearApplicationProfileData(String packageName) { 18882 enforceSystemOrRoot("Only the system can clear all profile data"); 18883 18884 final PackageParser.Package pkg; 18885 synchronized (mPackages) { 18886 pkg = mPackages.get(packageName); 18887 } 18888 18889 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18890 synchronized (mInstallLock) { 18891 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18892 } 18893 } 18894 } 18895 18896 @Override 18897 public void clearApplicationUserData(final String packageName, 18898 final IPackageDataObserver observer, final int userId) { 18899 mContext.enforceCallingOrSelfPermission( 18900 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18901 18902 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18903 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18904 18905 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18906 throw new SecurityException("Cannot clear data for a protected package: " 18907 + packageName); 18908 } 18909 // Queue up an async operation since the package deletion may take a little while. 18910 mHandler.post(new Runnable() { 18911 public void run() { 18912 mHandler.removeCallbacks(this); 18913 final boolean succeeded; 18914 try (PackageFreezer freezer = freezePackage(packageName, 18915 "clearApplicationUserData")) { 18916 synchronized (mInstallLock) { 18917 succeeded = clearApplicationUserDataLIF(packageName, userId); 18918 } 18919 clearExternalStorageDataSync(packageName, userId, true); 18920 synchronized (mPackages) { 18921 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18922 packageName, userId); 18923 } 18924 } 18925 if (succeeded) { 18926 // invoke DeviceStorageMonitor's update method to clear any notifications 18927 DeviceStorageMonitorInternal dsm = LocalServices 18928 .getService(DeviceStorageMonitorInternal.class); 18929 if (dsm != null) { 18930 dsm.checkMemory(); 18931 } 18932 } 18933 if(observer != null) { 18934 try { 18935 observer.onRemoveCompleted(packageName, succeeded); 18936 } catch (RemoteException e) { 18937 Log.i(TAG, "Observer no longer exists."); 18938 } 18939 } //end if observer 18940 } //end run 18941 }); 18942 } 18943 18944 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18945 if (packageName == null) { 18946 Slog.w(TAG, "Attempt to delete null packageName."); 18947 return false; 18948 } 18949 18950 // Try finding details about the requested package 18951 PackageParser.Package pkg; 18952 synchronized (mPackages) { 18953 pkg = mPackages.get(packageName); 18954 if (pkg == null) { 18955 final PackageSetting ps = mSettings.mPackages.get(packageName); 18956 if (ps != null) { 18957 pkg = ps.pkg; 18958 } 18959 } 18960 18961 if (pkg == null) { 18962 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18963 return false; 18964 } 18965 18966 PackageSetting ps = (PackageSetting) pkg.mExtras; 18967 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18968 } 18969 18970 clearAppDataLIF(pkg, userId, 18971 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18972 18973 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18974 removeKeystoreDataIfNeeded(userId, appId); 18975 18976 UserManagerInternal umInternal = getUserManagerInternal(); 18977 final int flags; 18978 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18979 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18980 } else if (umInternal.isUserRunning(userId)) { 18981 flags = StorageManager.FLAG_STORAGE_DE; 18982 } else { 18983 flags = 0; 18984 } 18985 prepareAppDataContentsLIF(pkg, userId, flags); 18986 18987 return true; 18988 } 18989 18990 /** 18991 * Reverts user permission state changes (permissions and flags) in 18992 * all packages for a given user. 18993 * 18994 * @param userId The device user for which to do a reset. 18995 */ 18996 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18997 final int packageCount = mPackages.size(); 18998 for (int i = 0; i < packageCount; i++) { 18999 PackageParser.Package pkg = mPackages.valueAt(i); 19000 PackageSetting ps = (PackageSetting) pkg.mExtras; 19001 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19002 } 19003 } 19004 19005 private void resetNetworkPolicies(int userId) { 19006 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19007 } 19008 19009 /** 19010 * Reverts user permission state changes (permissions and flags). 19011 * 19012 * @param ps The package for which to reset. 19013 * @param userId The device user for which to do a reset. 19014 */ 19015 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19016 final PackageSetting ps, final int userId) { 19017 if (ps.pkg == null) { 19018 return; 19019 } 19020 19021 // These are flags that can change base on user actions. 19022 final int userSettableMask = FLAG_PERMISSION_USER_SET 19023 | FLAG_PERMISSION_USER_FIXED 19024 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19025 | FLAG_PERMISSION_REVIEW_REQUIRED; 19026 19027 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19028 | FLAG_PERMISSION_POLICY_FIXED; 19029 19030 boolean writeInstallPermissions = false; 19031 boolean writeRuntimePermissions = false; 19032 19033 final int permissionCount = ps.pkg.requestedPermissions.size(); 19034 for (int i = 0; i < permissionCount; i++) { 19035 String permission = ps.pkg.requestedPermissions.get(i); 19036 19037 BasePermission bp = mSettings.mPermissions.get(permission); 19038 if (bp == null) { 19039 continue; 19040 } 19041 19042 // If shared user we just reset the state to which only this app contributed. 19043 if (ps.sharedUser != null) { 19044 boolean used = false; 19045 final int packageCount = ps.sharedUser.packages.size(); 19046 for (int j = 0; j < packageCount; j++) { 19047 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19048 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19049 && pkg.pkg.requestedPermissions.contains(permission)) { 19050 used = true; 19051 break; 19052 } 19053 } 19054 if (used) { 19055 continue; 19056 } 19057 } 19058 19059 PermissionsState permissionsState = ps.getPermissionsState(); 19060 19061 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 19062 19063 // Always clear the user settable flags. 19064 final boolean hasInstallState = permissionsState.getInstallPermissionState( 19065 bp.name) != null; 19066 // If permission review is enabled and this is a legacy app, mark the 19067 // permission as requiring a review as this is the initial state. 19068 int flags = 0; 19069 if (mPermissionReviewRequired 19070 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19071 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19072 } 19073 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19074 if (hasInstallState) { 19075 writeInstallPermissions = true; 19076 } else { 19077 writeRuntimePermissions = true; 19078 } 19079 } 19080 19081 // Below is only runtime permission handling. 19082 if (!bp.isRuntime()) { 19083 continue; 19084 } 19085 19086 // Never clobber system or policy. 19087 if ((oldFlags & policyOrSystemFlags) != 0) { 19088 continue; 19089 } 19090 19091 // If this permission was granted by default, make sure it is. 19092 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19093 if (permissionsState.grantRuntimePermission(bp, userId) 19094 != PERMISSION_OPERATION_FAILURE) { 19095 writeRuntimePermissions = true; 19096 } 19097 // If permission review is enabled the permissions for a legacy apps 19098 // are represented as constantly granted runtime ones, so don't revoke. 19099 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19100 // Otherwise, reset the permission. 19101 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19102 switch (revokeResult) { 19103 case PERMISSION_OPERATION_SUCCESS: 19104 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19105 writeRuntimePermissions = true; 19106 final int appId = ps.appId; 19107 mHandler.post(new Runnable() { 19108 @Override 19109 public void run() { 19110 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19111 } 19112 }); 19113 } break; 19114 } 19115 } 19116 } 19117 19118 // Synchronously write as we are taking permissions away. 19119 if (writeRuntimePermissions) { 19120 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19121 } 19122 19123 // Synchronously write as we are taking permissions away. 19124 if (writeInstallPermissions) { 19125 mSettings.writeLPr(); 19126 } 19127 } 19128 19129 /** 19130 * Remove entries from the keystore daemon. Will only remove it if the 19131 * {@code appId} is valid. 19132 */ 19133 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19134 if (appId < 0) { 19135 return; 19136 } 19137 19138 final KeyStore keyStore = KeyStore.getInstance(); 19139 if (keyStore != null) { 19140 if (userId == UserHandle.USER_ALL) { 19141 for (final int individual : sUserManager.getUserIds()) { 19142 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19143 } 19144 } else { 19145 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19146 } 19147 } else { 19148 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19149 } 19150 } 19151 19152 @Override 19153 public void deleteApplicationCacheFiles(final String packageName, 19154 final IPackageDataObserver observer) { 19155 final int userId = UserHandle.getCallingUserId(); 19156 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19157 } 19158 19159 @Override 19160 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19161 final IPackageDataObserver observer) { 19162 mContext.enforceCallingOrSelfPermission( 19163 android.Manifest.permission.DELETE_CACHE_FILES, null); 19164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 19165 /* requireFullPermission= */ true, /* checkShell= */ false, 19166 "delete application cache files"); 19167 19168 final PackageParser.Package pkg; 19169 synchronized (mPackages) { 19170 pkg = mPackages.get(packageName); 19171 } 19172 19173 // Queue up an async operation since the package deletion may take a little while. 19174 mHandler.post(new Runnable() { 19175 public void run() { 19176 synchronized (mInstallLock) { 19177 final int flags = StorageManager.FLAG_STORAGE_DE 19178 | StorageManager.FLAG_STORAGE_CE; 19179 // We're only clearing cache files, so we don't care if the 19180 // app is unfrozen and still able to run 19181 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19182 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19183 } 19184 clearExternalStorageDataSync(packageName, userId, false); 19185 if (observer != null) { 19186 try { 19187 observer.onRemoveCompleted(packageName, true); 19188 } catch (RemoteException e) { 19189 Log.i(TAG, "Observer no longer exists."); 19190 } 19191 } 19192 } 19193 }); 19194 } 19195 19196 @Override 19197 public void getPackageSizeInfo(final String packageName, int userHandle, 19198 final IPackageStatsObserver observer) { 19199 throw new UnsupportedOperationException( 19200 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19201 } 19202 19203 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19204 final PackageSetting ps; 19205 synchronized (mPackages) { 19206 ps = mSettings.mPackages.get(packageName); 19207 if (ps == null) { 19208 Slog.w(TAG, "Failed to find settings for " + packageName); 19209 return false; 19210 } 19211 } 19212 19213 final String[] packageNames = { packageName }; 19214 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19215 final String[] codePaths = { ps.codePathString }; 19216 19217 try { 19218 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19219 ps.appId, ceDataInodes, codePaths, stats); 19220 19221 // For now, ignore code size of packages on system partition 19222 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19223 stats.codeSize = 0; 19224 } 19225 19226 // External clients expect these to be tracked separately 19227 stats.dataSize -= stats.cacheSize; 19228 19229 } catch (InstallerException e) { 19230 Slog.w(TAG, String.valueOf(e)); 19231 return false; 19232 } 19233 19234 return true; 19235 } 19236 19237 private int getUidTargetSdkVersionLockedLPr(int uid) { 19238 Object obj = mSettings.getUserIdLPr(uid); 19239 if (obj instanceof SharedUserSetting) { 19240 final SharedUserSetting sus = (SharedUserSetting) obj; 19241 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19242 final Iterator<PackageSetting> it = sus.packages.iterator(); 19243 while (it.hasNext()) { 19244 final PackageSetting ps = it.next(); 19245 if (ps.pkg != null) { 19246 int v = ps.pkg.applicationInfo.targetSdkVersion; 19247 if (v < vers) vers = v; 19248 } 19249 } 19250 return vers; 19251 } else if (obj instanceof PackageSetting) { 19252 final PackageSetting ps = (PackageSetting) obj; 19253 if (ps.pkg != null) { 19254 return ps.pkg.applicationInfo.targetSdkVersion; 19255 } 19256 } 19257 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19258 } 19259 19260 @Override 19261 public void addPreferredActivity(IntentFilter filter, int match, 19262 ComponentName[] set, ComponentName activity, int userId) { 19263 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19264 "Adding preferred"); 19265 } 19266 19267 private void addPreferredActivityInternal(IntentFilter filter, int match, 19268 ComponentName[] set, ComponentName activity, boolean always, int userId, 19269 String opname) { 19270 // writer 19271 int callingUid = Binder.getCallingUid(); 19272 enforceCrossUserPermission(callingUid, userId, 19273 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19274 if (filter.countActions() == 0) { 19275 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19276 return; 19277 } 19278 synchronized (mPackages) { 19279 if (mContext.checkCallingOrSelfPermission( 19280 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19281 != PackageManager.PERMISSION_GRANTED) { 19282 if (getUidTargetSdkVersionLockedLPr(callingUid) 19283 < Build.VERSION_CODES.FROYO) { 19284 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19285 + callingUid); 19286 return; 19287 } 19288 mContext.enforceCallingOrSelfPermission( 19289 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19290 } 19291 19292 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19293 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19294 + userId + ":"); 19295 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19296 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19297 scheduleWritePackageRestrictionsLocked(userId); 19298 postPreferredActivityChangedBroadcast(userId); 19299 } 19300 } 19301 19302 private void postPreferredActivityChangedBroadcast(int userId) { 19303 mHandler.post(() -> { 19304 final IActivityManager am = ActivityManager.getService(); 19305 if (am == null) { 19306 return; 19307 } 19308 19309 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19310 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19311 try { 19312 am.broadcastIntent(null, intent, null, null, 19313 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19314 null, false, false, userId); 19315 } catch (RemoteException e) { 19316 } 19317 }); 19318 } 19319 19320 @Override 19321 public void replacePreferredActivity(IntentFilter filter, int match, 19322 ComponentName[] set, ComponentName activity, int userId) { 19323 if (filter.countActions() != 1) { 19324 throw new IllegalArgumentException( 19325 "replacePreferredActivity expects filter to have only 1 action."); 19326 } 19327 if (filter.countDataAuthorities() != 0 19328 || filter.countDataPaths() != 0 19329 || filter.countDataSchemes() > 1 19330 || filter.countDataTypes() != 0) { 19331 throw new IllegalArgumentException( 19332 "replacePreferredActivity expects filter to have no data authorities, " + 19333 "paths, or types; and at most one scheme."); 19334 } 19335 19336 final int callingUid = Binder.getCallingUid(); 19337 enforceCrossUserPermission(callingUid, userId, 19338 true /* requireFullPermission */, false /* checkShell */, 19339 "replace preferred activity"); 19340 synchronized (mPackages) { 19341 if (mContext.checkCallingOrSelfPermission( 19342 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19343 != PackageManager.PERMISSION_GRANTED) { 19344 if (getUidTargetSdkVersionLockedLPr(callingUid) 19345 < Build.VERSION_CODES.FROYO) { 19346 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19347 + Binder.getCallingUid()); 19348 return; 19349 } 19350 mContext.enforceCallingOrSelfPermission( 19351 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19352 } 19353 19354 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19355 if (pir != null) { 19356 // Get all of the existing entries that exactly match this filter. 19357 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19358 if (existing != null && existing.size() == 1) { 19359 PreferredActivity cur = existing.get(0); 19360 if (DEBUG_PREFERRED) { 19361 Slog.i(TAG, "Checking replace of preferred:"); 19362 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19363 if (!cur.mPref.mAlways) { 19364 Slog.i(TAG, " -- CUR; not mAlways!"); 19365 } else { 19366 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19367 Slog.i(TAG, " -- CUR: mSet=" 19368 + Arrays.toString(cur.mPref.mSetComponents)); 19369 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19370 Slog.i(TAG, " -- NEW: mMatch=" 19371 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19372 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19373 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19374 } 19375 } 19376 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19377 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19378 && cur.mPref.sameSet(set)) { 19379 // Setting the preferred activity to what it happens to be already 19380 if (DEBUG_PREFERRED) { 19381 Slog.i(TAG, "Replacing with same preferred activity " 19382 + cur.mPref.mShortComponent + " for user " 19383 + userId + ":"); 19384 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19385 } 19386 return; 19387 } 19388 } 19389 19390 if (existing != null) { 19391 if (DEBUG_PREFERRED) { 19392 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19393 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19394 } 19395 for (int i = 0; i < existing.size(); i++) { 19396 PreferredActivity pa = existing.get(i); 19397 if (DEBUG_PREFERRED) { 19398 Slog.i(TAG, "Removing existing preferred activity " 19399 + pa.mPref.mComponent + ":"); 19400 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19401 } 19402 pir.removeFilter(pa); 19403 } 19404 } 19405 } 19406 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19407 "Replacing preferred"); 19408 } 19409 } 19410 19411 @Override 19412 public void clearPackagePreferredActivities(String packageName) { 19413 final int uid = Binder.getCallingUid(); 19414 // writer 19415 synchronized (mPackages) { 19416 PackageParser.Package pkg = mPackages.get(packageName); 19417 if (pkg == null || pkg.applicationInfo.uid != uid) { 19418 if (mContext.checkCallingOrSelfPermission( 19419 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19420 != PackageManager.PERMISSION_GRANTED) { 19421 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19422 < Build.VERSION_CODES.FROYO) { 19423 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19424 + Binder.getCallingUid()); 19425 return; 19426 } 19427 mContext.enforceCallingOrSelfPermission( 19428 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19429 } 19430 } 19431 19432 int user = UserHandle.getCallingUserId(); 19433 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19434 scheduleWritePackageRestrictionsLocked(user); 19435 } 19436 } 19437 } 19438 19439 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19440 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19441 ArrayList<PreferredActivity> removed = null; 19442 boolean changed = false; 19443 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19444 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19445 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19446 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19447 continue; 19448 } 19449 Iterator<PreferredActivity> it = pir.filterIterator(); 19450 while (it.hasNext()) { 19451 PreferredActivity pa = it.next(); 19452 // Mark entry for removal only if it matches the package name 19453 // and the entry is of type "always". 19454 if (packageName == null || 19455 (pa.mPref.mComponent.getPackageName().equals(packageName) 19456 && pa.mPref.mAlways)) { 19457 if (removed == null) { 19458 removed = new ArrayList<PreferredActivity>(); 19459 } 19460 removed.add(pa); 19461 } 19462 } 19463 if (removed != null) { 19464 for (int j=0; j<removed.size(); j++) { 19465 PreferredActivity pa = removed.get(j); 19466 pir.removeFilter(pa); 19467 } 19468 changed = true; 19469 } 19470 } 19471 if (changed) { 19472 postPreferredActivityChangedBroadcast(userId); 19473 } 19474 return changed; 19475 } 19476 19477 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19478 private void clearIntentFilterVerificationsLPw(int userId) { 19479 final int packageCount = mPackages.size(); 19480 for (int i = 0; i < packageCount; i++) { 19481 PackageParser.Package pkg = mPackages.valueAt(i); 19482 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19483 } 19484 } 19485 19486 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19487 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19488 if (userId == UserHandle.USER_ALL) { 19489 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19490 sUserManager.getUserIds())) { 19491 for (int oneUserId : sUserManager.getUserIds()) { 19492 scheduleWritePackageRestrictionsLocked(oneUserId); 19493 } 19494 } 19495 } else { 19496 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19497 scheduleWritePackageRestrictionsLocked(userId); 19498 } 19499 } 19500 } 19501 19502 /** Clears state for all users, and touches intent filter verification policy */ 19503 void clearDefaultBrowserIfNeeded(String packageName) { 19504 for (int oneUserId : sUserManager.getUserIds()) { 19505 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19506 } 19507 } 19508 19509 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19510 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19511 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19512 if (packageName.equals(defaultBrowserPackageName)) { 19513 setDefaultBrowserPackageName(null, userId); 19514 } 19515 } 19516 } 19517 19518 @Override 19519 public void resetApplicationPreferences(int userId) { 19520 mContext.enforceCallingOrSelfPermission( 19521 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19522 final long identity = Binder.clearCallingIdentity(); 19523 // writer 19524 try { 19525 synchronized (mPackages) { 19526 clearPackagePreferredActivitiesLPw(null, userId); 19527 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19528 // TODO: We have to reset the default SMS and Phone. This requires 19529 // significant refactoring to keep all default apps in the package 19530 // manager (cleaner but more work) or have the services provide 19531 // callbacks to the package manager to request a default app reset. 19532 applyFactoryDefaultBrowserLPw(userId); 19533 clearIntentFilterVerificationsLPw(userId); 19534 primeDomainVerificationsLPw(userId); 19535 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19536 scheduleWritePackageRestrictionsLocked(userId); 19537 } 19538 resetNetworkPolicies(userId); 19539 } finally { 19540 Binder.restoreCallingIdentity(identity); 19541 } 19542 } 19543 19544 @Override 19545 public int getPreferredActivities(List<IntentFilter> outFilters, 19546 List<ComponentName> outActivities, String packageName) { 19547 19548 int num = 0; 19549 final int userId = UserHandle.getCallingUserId(); 19550 // reader 19551 synchronized (mPackages) { 19552 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19553 if (pir != null) { 19554 final Iterator<PreferredActivity> it = pir.filterIterator(); 19555 while (it.hasNext()) { 19556 final PreferredActivity pa = it.next(); 19557 if (packageName == null 19558 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19559 && pa.mPref.mAlways)) { 19560 if (outFilters != null) { 19561 outFilters.add(new IntentFilter(pa)); 19562 } 19563 if (outActivities != null) { 19564 outActivities.add(pa.mPref.mComponent); 19565 } 19566 } 19567 } 19568 } 19569 } 19570 19571 return num; 19572 } 19573 19574 @Override 19575 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19576 int userId) { 19577 int callingUid = Binder.getCallingUid(); 19578 if (callingUid != Process.SYSTEM_UID) { 19579 throw new SecurityException( 19580 "addPersistentPreferredActivity can only be run by the system"); 19581 } 19582 if (filter.countActions() == 0) { 19583 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19584 return; 19585 } 19586 synchronized (mPackages) { 19587 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19588 ":"); 19589 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19590 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19591 new PersistentPreferredActivity(filter, activity)); 19592 scheduleWritePackageRestrictionsLocked(userId); 19593 postPreferredActivityChangedBroadcast(userId); 19594 } 19595 } 19596 19597 @Override 19598 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19599 int callingUid = Binder.getCallingUid(); 19600 if (callingUid != Process.SYSTEM_UID) { 19601 throw new SecurityException( 19602 "clearPackagePersistentPreferredActivities can only be run by the system"); 19603 } 19604 ArrayList<PersistentPreferredActivity> removed = null; 19605 boolean changed = false; 19606 synchronized (mPackages) { 19607 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19608 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19609 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19610 .valueAt(i); 19611 if (userId != thisUserId) { 19612 continue; 19613 } 19614 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19615 while (it.hasNext()) { 19616 PersistentPreferredActivity ppa = it.next(); 19617 // Mark entry for removal only if it matches the package name. 19618 if (ppa.mComponent.getPackageName().equals(packageName)) { 19619 if (removed == null) { 19620 removed = new ArrayList<PersistentPreferredActivity>(); 19621 } 19622 removed.add(ppa); 19623 } 19624 } 19625 if (removed != null) { 19626 for (int j=0; j<removed.size(); j++) { 19627 PersistentPreferredActivity ppa = removed.get(j); 19628 ppir.removeFilter(ppa); 19629 } 19630 changed = true; 19631 } 19632 } 19633 19634 if (changed) { 19635 scheduleWritePackageRestrictionsLocked(userId); 19636 postPreferredActivityChangedBroadcast(userId); 19637 } 19638 } 19639 } 19640 19641 /** 19642 * Common machinery for picking apart a restored XML blob and passing 19643 * it to a caller-supplied functor to be applied to the running system. 19644 */ 19645 private void restoreFromXml(XmlPullParser parser, int userId, 19646 String expectedStartTag, BlobXmlRestorer functor) 19647 throws IOException, XmlPullParserException { 19648 int type; 19649 while ((type = parser.next()) != XmlPullParser.START_TAG 19650 && type != XmlPullParser.END_DOCUMENT) { 19651 } 19652 if (type != XmlPullParser.START_TAG) { 19653 // oops didn't find a start tag?! 19654 if (DEBUG_BACKUP) { 19655 Slog.e(TAG, "Didn't find start tag during restore"); 19656 } 19657 return; 19658 } 19659Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19660 // this is supposed to be TAG_PREFERRED_BACKUP 19661 if (!expectedStartTag.equals(parser.getName())) { 19662 if (DEBUG_BACKUP) { 19663 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19664 } 19665 return; 19666 } 19667 19668 // skip interfering stuff, then we're aligned with the backing implementation 19669 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19670Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19671 functor.apply(parser, userId); 19672 } 19673 19674 private interface BlobXmlRestorer { 19675 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19676 } 19677 19678 /** 19679 * Non-Binder method, support for the backup/restore mechanism: write the 19680 * full set of preferred activities in its canonical XML format. Returns the 19681 * XML output as a byte array, or null if there is none. 19682 */ 19683 @Override 19684 public byte[] getPreferredActivityBackup(int userId) { 19685 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19686 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19687 } 19688 19689 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19690 try { 19691 final XmlSerializer serializer = new FastXmlSerializer(); 19692 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19693 serializer.startDocument(null, true); 19694 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19695 19696 synchronized (mPackages) { 19697 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19698 } 19699 19700 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19701 serializer.endDocument(); 19702 serializer.flush(); 19703 } catch (Exception e) { 19704 if (DEBUG_BACKUP) { 19705 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19706 } 19707 return null; 19708 } 19709 19710 return dataStream.toByteArray(); 19711 } 19712 19713 @Override 19714 public void restorePreferredActivities(byte[] backup, int userId) { 19715 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19716 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19717 } 19718 19719 try { 19720 final XmlPullParser parser = Xml.newPullParser(); 19721 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19722 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19723 new BlobXmlRestorer() { 19724 @Override 19725 public void apply(XmlPullParser parser, int userId) 19726 throws XmlPullParserException, IOException { 19727 synchronized (mPackages) { 19728 mSettings.readPreferredActivitiesLPw(parser, userId); 19729 } 19730 } 19731 } ); 19732 } catch (Exception e) { 19733 if (DEBUG_BACKUP) { 19734 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19735 } 19736 } 19737 } 19738 19739 /** 19740 * Non-Binder method, support for the backup/restore mechanism: write the 19741 * default browser (etc) settings in its canonical XML format. Returns the default 19742 * browser XML representation as a byte array, or null if there is none. 19743 */ 19744 @Override 19745 public byte[] getDefaultAppsBackup(int userId) { 19746 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19747 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19748 } 19749 19750 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19751 try { 19752 final XmlSerializer serializer = new FastXmlSerializer(); 19753 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19754 serializer.startDocument(null, true); 19755 serializer.startTag(null, TAG_DEFAULT_APPS); 19756 19757 synchronized (mPackages) { 19758 mSettings.writeDefaultAppsLPr(serializer, userId); 19759 } 19760 19761 serializer.endTag(null, TAG_DEFAULT_APPS); 19762 serializer.endDocument(); 19763 serializer.flush(); 19764 } catch (Exception e) { 19765 if (DEBUG_BACKUP) { 19766 Slog.e(TAG, "Unable to write default apps for backup", e); 19767 } 19768 return null; 19769 } 19770 19771 return dataStream.toByteArray(); 19772 } 19773 19774 @Override 19775 public void restoreDefaultApps(byte[] backup, int userId) { 19776 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19777 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19778 } 19779 19780 try { 19781 final XmlPullParser parser = Xml.newPullParser(); 19782 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19783 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19784 new BlobXmlRestorer() { 19785 @Override 19786 public void apply(XmlPullParser parser, int userId) 19787 throws XmlPullParserException, IOException { 19788 synchronized (mPackages) { 19789 mSettings.readDefaultAppsLPw(parser, userId); 19790 } 19791 } 19792 } ); 19793 } catch (Exception e) { 19794 if (DEBUG_BACKUP) { 19795 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19796 } 19797 } 19798 } 19799 19800 @Override 19801 public byte[] getIntentFilterVerificationBackup(int userId) { 19802 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19803 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19804 } 19805 19806 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19807 try { 19808 final XmlSerializer serializer = new FastXmlSerializer(); 19809 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19810 serializer.startDocument(null, true); 19811 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19812 19813 synchronized (mPackages) { 19814 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19815 } 19816 19817 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19818 serializer.endDocument(); 19819 serializer.flush(); 19820 } catch (Exception e) { 19821 if (DEBUG_BACKUP) { 19822 Slog.e(TAG, "Unable to write default apps for backup", e); 19823 } 19824 return null; 19825 } 19826 19827 return dataStream.toByteArray(); 19828 } 19829 19830 @Override 19831 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19832 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19833 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19834 } 19835 19836 try { 19837 final XmlPullParser parser = Xml.newPullParser(); 19838 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19839 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19840 new BlobXmlRestorer() { 19841 @Override 19842 public void apply(XmlPullParser parser, int userId) 19843 throws XmlPullParserException, IOException { 19844 synchronized (mPackages) { 19845 mSettings.readAllDomainVerificationsLPr(parser, userId); 19846 mSettings.writeLPr(); 19847 } 19848 } 19849 } ); 19850 } catch (Exception e) { 19851 if (DEBUG_BACKUP) { 19852 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19853 } 19854 } 19855 } 19856 19857 @Override 19858 public byte[] getPermissionGrantBackup(int userId) { 19859 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19860 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19861 } 19862 19863 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19864 try { 19865 final XmlSerializer serializer = new FastXmlSerializer(); 19866 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19867 serializer.startDocument(null, true); 19868 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19869 19870 synchronized (mPackages) { 19871 serializeRuntimePermissionGrantsLPr(serializer, userId); 19872 } 19873 19874 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19875 serializer.endDocument(); 19876 serializer.flush(); 19877 } catch (Exception e) { 19878 if (DEBUG_BACKUP) { 19879 Slog.e(TAG, "Unable to write default apps for backup", e); 19880 } 19881 return null; 19882 } 19883 19884 return dataStream.toByteArray(); 19885 } 19886 19887 @Override 19888 public void restorePermissionGrants(byte[] backup, int userId) { 19889 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19890 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19891 } 19892 19893 try { 19894 final XmlPullParser parser = Xml.newPullParser(); 19895 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19896 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19897 new BlobXmlRestorer() { 19898 @Override 19899 public void apply(XmlPullParser parser, int userId) 19900 throws XmlPullParserException, IOException { 19901 synchronized (mPackages) { 19902 processRestoredPermissionGrantsLPr(parser, userId); 19903 } 19904 } 19905 } ); 19906 } catch (Exception e) { 19907 if (DEBUG_BACKUP) { 19908 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19909 } 19910 } 19911 } 19912 19913 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19914 throws IOException { 19915 serializer.startTag(null, TAG_ALL_GRANTS); 19916 19917 final int N = mSettings.mPackages.size(); 19918 for (int i = 0; i < N; i++) { 19919 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19920 boolean pkgGrantsKnown = false; 19921 19922 PermissionsState packagePerms = ps.getPermissionsState(); 19923 19924 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19925 final int grantFlags = state.getFlags(); 19926 // only look at grants that are not system/policy fixed 19927 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19928 final boolean isGranted = state.isGranted(); 19929 // And only back up the user-twiddled state bits 19930 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19931 final String packageName = mSettings.mPackages.keyAt(i); 19932 if (!pkgGrantsKnown) { 19933 serializer.startTag(null, TAG_GRANT); 19934 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19935 pkgGrantsKnown = true; 19936 } 19937 19938 final boolean userSet = 19939 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19940 final boolean userFixed = 19941 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19942 final boolean revoke = 19943 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19944 19945 serializer.startTag(null, TAG_PERMISSION); 19946 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19947 if (isGranted) { 19948 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19949 } 19950 if (userSet) { 19951 serializer.attribute(null, ATTR_USER_SET, "true"); 19952 } 19953 if (userFixed) { 19954 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19955 } 19956 if (revoke) { 19957 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19958 } 19959 serializer.endTag(null, TAG_PERMISSION); 19960 } 19961 } 19962 } 19963 19964 if (pkgGrantsKnown) { 19965 serializer.endTag(null, TAG_GRANT); 19966 } 19967 } 19968 19969 serializer.endTag(null, TAG_ALL_GRANTS); 19970 } 19971 19972 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19973 throws XmlPullParserException, IOException { 19974 String pkgName = null; 19975 int outerDepth = parser.getDepth(); 19976 int type; 19977 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19978 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19979 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19980 continue; 19981 } 19982 19983 final String tagName = parser.getName(); 19984 if (tagName.equals(TAG_GRANT)) { 19985 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19986 if (DEBUG_BACKUP) { 19987 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19988 } 19989 } else if (tagName.equals(TAG_PERMISSION)) { 19990 19991 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19992 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19993 19994 int newFlagSet = 0; 19995 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19996 newFlagSet |= FLAG_PERMISSION_USER_SET; 19997 } 19998 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19999 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20000 } 20001 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20002 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20003 } 20004 if (DEBUG_BACKUP) { 20005 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 20006 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 20007 } 20008 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20009 if (ps != null) { 20010 // Already installed so we apply the grant immediately 20011 if (DEBUG_BACKUP) { 20012 Slog.v(TAG, " + already installed; applying"); 20013 } 20014 PermissionsState perms = ps.getPermissionsState(); 20015 BasePermission bp = mSettings.mPermissions.get(permName); 20016 if (bp != null) { 20017 if (isGranted) { 20018 perms.grantRuntimePermission(bp, userId); 20019 } 20020 if (newFlagSet != 0) { 20021 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20022 } 20023 } 20024 } else { 20025 // Need to wait for post-restore install to apply the grant 20026 if (DEBUG_BACKUP) { 20027 Slog.v(TAG, " - not yet installed; saving for later"); 20028 } 20029 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20030 isGranted, newFlagSet, userId); 20031 } 20032 } else { 20033 PackageManagerService.reportSettingsProblem(Log.WARN, 20034 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20035 XmlUtils.skipCurrentTag(parser); 20036 } 20037 } 20038 20039 scheduleWriteSettingsLocked(); 20040 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20041 } 20042 20043 @Override 20044 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20045 int sourceUserId, int targetUserId, int flags) { 20046 mContext.enforceCallingOrSelfPermission( 20047 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20048 int callingUid = Binder.getCallingUid(); 20049 enforceOwnerRights(ownerPackage, callingUid); 20050 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20051 if (intentFilter.countActions() == 0) { 20052 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20053 return; 20054 } 20055 synchronized (mPackages) { 20056 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20057 ownerPackage, targetUserId, flags); 20058 CrossProfileIntentResolver resolver = 20059 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20060 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20061 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20062 if (existing != null) { 20063 int size = existing.size(); 20064 for (int i = 0; i < size; i++) { 20065 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20066 return; 20067 } 20068 } 20069 } 20070 resolver.addFilter(newFilter); 20071 scheduleWritePackageRestrictionsLocked(sourceUserId); 20072 } 20073 } 20074 20075 @Override 20076 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20077 mContext.enforceCallingOrSelfPermission( 20078 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20079 int callingUid = Binder.getCallingUid(); 20080 enforceOwnerRights(ownerPackage, callingUid); 20081 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20082 synchronized (mPackages) { 20083 CrossProfileIntentResolver resolver = 20084 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20085 ArraySet<CrossProfileIntentFilter> set = 20086 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20087 for (CrossProfileIntentFilter filter : set) { 20088 if (filter.getOwnerPackage().equals(ownerPackage)) { 20089 resolver.removeFilter(filter); 20090 } 20091 } 20092 scheduleWritePackageRestrictionsLocked(sourceUserId); 20093 } 20094 } 20095 20096 // Enforcing that callingUid is owning pkg on userId 20097 private void enforceOwnerRights(String pkg, int callingUid) { 20098 // The system owns everything. 20099 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20100 return; 20101 } 20102 int callingUserId = UserHandle.getUserId(callingUid); 20103 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20104 if (pi == null) { 20105 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20106 + callingUserId); 20107 } 20108 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20109 throw new SecurityException("Calling uid " + callingUid 20110 + " does not own package " + pkg); 20111 } 20112 } 20113 20114 @Override 20115 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20116 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20117 } 20118 20119 /** 20120 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20121 * then reports the most likely home activity or null if there are more than one. 20122 */ 20123 public ComponentName getDefaultHomeActivity(int userId) { 20124 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20125 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20126 if (cn != null) { 20127 return cn; 20128 } 20129 20130 // Find the launcher with the highest priority and return that component if there are no 20131 // other home activity with the same priority. 20132 int lastPriority = Integer.MIN_VALUE; 20133 ComponentName lastComponent = null; 20134 final int size = allHomeCandidates.size(); 20135 for (int i = 0; i < size; i++) { 20136 final ResolveInfo ri = allHomeCandidates.get(i); 20137 if (ri.priority > lastPriority) { 20138 lastComponent = ri.activityInfo.getComponentName(); 20139 lastPriority = ri.priority; 20140 } else if (ri.priority == lastPriority) { 20141 // Two components found with same priority. 20142 lastComponent = null; 20143 } 20144 } 20145 return lastComponent; 20146 } 20147 20148 private Intent getHomeIntent() { 20149 Intent intent = new Intent(Intent.ACTION_MAIN); 20150 intent.addCategory(Intent.CATEGORY_HOME); 20151 intent.addCategory(Intent.CATEGORY_DEFAULT); 20152 return intent; 20153 } 20154 20155 private IntentFilter getHomeFilter() { 20156 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20157 filter.addCategory(Intent.CATEGORY_HOME); 20158 filter.addCategory(Intent.CATEGORY_DEFAULT); 20159 return filter; 20160 } 20161 20162 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20163 int userId) { 20164 Intent intent = getHomeIntent(); 20165 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20166 PackageManager.GET_META_DATA, userId); 20167 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20168 true, false, false, userId); 20169 20170 allHomeCandidates.clear(); 20171 if (list != null) { 20172 for (ResolveInfo ri : list) { 20173 allHomeCandidates.add(ri); 20174 } 20175 } 20176 return (preferred == null || preferred.activityInfo == null) 20177 ? null 20178 : new ComponentName(preferred.activityInfo.packageName, 20179 preferred.activityInfo.name); 20180 } 20181 20182 @Override 20183 public void setHomeActivity(ComponentName comp, int userId) { 20184 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20185 getHomeActivitiesAsUser(homeActivities, userId); 20186 20187 boolean found = false; 20188 20189 final int size = homeActivities.size(); 20190 final ComponentName[] set = new ComponentName[size]; 20191 for (int i = 0; i < size; i++) { 20192 final ResolveInfo candidate = homeActivities.get(i); 20193 final ActivityInfo info = candidate.activityInfo; 20194 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20195 set[i] = activityName; 20196 if (!found && activityName.equals(comp)) { 20197 found = true; 20198 } 20199 } 20200 if (!found) { 20201 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20202 + userId); 20203 } 20204 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20205 set, comp, userId); 20206 } 20207 20208 private @Nullable String getSetupWizardPackageName() { 20209 final Intent intent = new Intent(Intent.ACTION_MAIN); 20210 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20211 20212 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20213 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20214 | MATCH_DISABLED_COMPONENTS, 20215 UserHandle.myUserId()); 20216 if (matches.size() == 1) { 20217 return matches.get(0).getComponentInfo().packageName; 20218 } else { 20219 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20220 + ": matches=" + matches); 20221 return null; 20222 } 20223 } 20224 20225 private @Nullable String getStorageManagerPackageName() { 20226 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20227 20228 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20229 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20230 | MATCH_DISABLED_COMPONENTS, 20231 UserHandle.myUserId()); 20232 if (matches.size() == 1) { 20233 return matches.get(0).getComponentInfo().packageName; 20234 } else { 20235 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20236 + matches.size() + ": matches=" + matches); 20237 return null; 20238 } 20239 } 20240 20241 @Override 20242 public void setApplicationEnabledSetting(String appPackageName, 20243 int newState, int flags, int userId, String callingPackage) { 20244 if (!sUserManager.exists(userId)) return; 20245 if (callingPackage == null) { 20246 callingPackage = Integer.toString(Binder.getCallingUid()); 20247 } 20248 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20249 } 20250 20251 @Override 20252 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20254 synchronized (mPackages) { 20255 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20256 if (pkgSetting != null) { 20257 pkgSetting.setUpdateAvailable(updateAvailable); 20258 } 20259 } 20260 } 20261 20262 @Override 20263 public void setComponentEnabledSetting(ComponentName componentName, 20264 int newState, int flags, int userId) { 20265 if (!sUserManager.exists(userId)) return; 20266 setEnabledSetting(componentName.getPackageName(), 20267 componentName.getClassName(), newState, flags, userId, null); 20268 } 20269 20270 private void setEnabledSetting(final String packageName, String className, int newState, 20271 final int flags, int userId, String callingPackage) { 20272 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20273 || newState == COMPONENT_ENABLED_STATE_ENABLED 20274 || newState == COMPONENT_ENABLED_STATE_DISABLED 20275 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20276 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20277 throw new IllegalArgumentException("Invalid new component state: " 20278 + newState); 20279 } 20280 PackageSetting pkgSetting; 20281 final int uid = Binder.getCallingUid(); 20282 final int permission; 20283 if (uid == Process.SYSTEM_UID) { 20284 permission = PackageManager.PERMISSION_GRANTED; 20285 } else { 20286 permission = mContext.checkCallingOrSelfPermission( 20287 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20288 } 20289 enforceCrossUserPermission(uid, userId, 20290 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20291 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20292 boolean sendNow = false; 20293 boolean isApp = (className == null); 20294 String componentName = isApp ? packageName : className; 20295 int packageUid = -1; 20296 ArrayList<String> components; 20297 20298 // writer 20299 synchronized (mPackages) { 20300 pkgSetting = mSettings.mPackages.get(packageName); 20301 if (pkgSetting == null) { 20302 if (className == null) { 20303 throw new IllegalArgumentException("Unknown package: " + packageName); 20304 } 20305 throw new IllegalArgumentException( 20306 "Unknown component: " + packageName + "/" + className); 20307 } 20308 } 20309 20310 // Limit who can change which apps 20311 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 20312 // Don't allow apps that don't have permission to modify other apps 20313 if (!allowedByPermission) { 20314 throw new SecurityException( 20315 "Permission Denial: attempt to change component state from pid=" 20316 + Binder.getCallingPid() 20317 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 20318 } 20319 // Don't allow changing protected packages. 20320 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20321 throw new SecurityException("Cannot disable a protected package: " + packageName); 20322 } 20323 } 20324 20325 synchronized (mPackages) { 20326 if (uid == Process.SHELL_UID 20327 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20328 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20329 // unless it is a test package. 20330 int oldState = pkgSetting.getEnabled(userId); 20331 if (className == null 20332 && 20333 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20334 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20335 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20336 && 20337 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20338 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20339 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20340 // ok 20341 } else { 20342 throw new SecurityException( 20343 "Shell cannot change component state for " + packageName + "/" 20344 + className + " to " + newState); 20345 } 20346 } 20347 if (className == null) { 20348 // We're dealing with an application/package level state change 20349 if (pkgSetting.getEnabled(userId) == newState) { 20350 // Nothing to do 20351 return; 20352 } 20353 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20354 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20355 // Don't care about who enables an app. 20356 callingPackage = null; 20357 } 20358 pkgSetting.setEnabled(newState, userId, callingPackage); 20359 // pkgSetting.pkg.mSetEnabled = newState; 20360 } else { 20361 // We're dealing with a component level state change 20362 // First, verify that this is a valid class name. 20363 PackageParser.Package pkg = pkgSetting.pkg; 20364 if (pkg == null || !pkg.hasComponentClassName(className)) { 20365 if (pkg != null && 20366 pkg.applicationInfo.targetSdkVersion >= 20367 Build.VERSION_CODES.JELLY_BEAN) { 20368 throw new IllegalArgumentException("Component class " + className 20369 + " does not exist in " + packageName); 20370 } else { 20371 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20372 + className + " does not exist in " + packageName); 20373 } 20374 } 20375 switch (newState) { 20376 case COMPONENT_ENABLED_STATE_ENABLED: 20377 if (!pkgSetting.enableComponentLPw(className, userId)) { 20378 return; 20379 } 20380 break; 20381 case COMPONENT_ENABLED_STATE_DISABLED: 20382 if (!pkgSetting.disableComponentLPw(className, userId)) { 20383 return; 20384 } 20385 break; 20386 case COMPONENT_ENABLED_STATE_DEFAULT: 20387 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20388 return; 20389 } 20390 break; 20391 default: 20392 Slog.e(TAG, "Invalid new component state: " + newState); 20393 return; 20394 } 20395 } 20396 scheduleWritePackageRestrictionsLocked(userId); 20397 updateSequenceNumberLP(packageName, new int[] { userId }); 20398 final long callingId = Binder.clearCallingIdentity(); 20399 try { 20400 updateInstantAppInstallerLocked(packageName); 20401 } finally { 20402 Binder.restoreCallingIdentity(callingId); 20403 } 20404 components = mPendingBroadcasts.get(userId, packageName); 20405 final boolean newPackage = components == null; 20406 if (newPackage) { 20407 components = new ArrayList<String>(); 20408 } 20409 if (!components.contains(componentName)) { 20410 components.add(componentName); 20411 } 20412 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20413 sendNow = true; 20414 // Purge entry from pending broadcast list if another one exists already 20415 // since we are sending one right away. 20416 mPendingBroadcasts.remove(userId, packageName); 20417 } else { 20418 if (newPackage) { 20419 mPendingBroadcasts.put(userId, packageName, components); 20420 } 20421 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20422 // Schedule a message 20423 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20424 } 20425 } 20426 } 20427 20428 long callingId = Binder.clearCallingIdentity(); 20429 try { 20430 if (sendNow) { 20431 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20432 sendPackageChangedBroadcast(packageName, 20433 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20434 } 20435 } finally { 20436 Binder.restoreCallingIdentity(callingId); 20437 } 20438 } 20439 20440 @Override 20441 public void flushPackageRestrictionsAsUser(int userId) { 20442 if (!sUserManager.exists(userId)) { 20443 return; 20444 } 20445 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20446 false /* checkShell */, "flushPackageRestrictions"); 20447 synchronized (mPackages) { 20448 mSettings.writePackageRestrictionsLPr(userId); 20449 mDirtyUsers.remove(userId); 20450 if (mDirtyUsers.isEmpty()) { 20451 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20452 } 20453 } 20454 } 20455 20456 private void sendPackageChangedBroadcast(String packageName, 20457 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20458 if (DEBUG_INSTALL) 20459 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20460 + componentNames); 20461 Bundle extras = new Bundle(4); 20462 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20463 String nameList[] = new String[componentNames.size()]; 20464 componentNames.toArray(nameList); 20465 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20466 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20467 extras.putInt(Intent.EXTRA_UID, packageUid); 20468 // If this is not reporting a change of the overall package, then only send it 20469 // to registered receivers. We don't want to launch a swath of apps for every 20470 // little component state change. 20471 final int flags = !componentNames.contains(packageName) 20472 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20473 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20474 new int[] {UserHandle.getUserId(packageUid)}); 20475 } 20476 20477 @Override 20478 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20479 if (!sUserManager.exists(userId)) return; 20480 final int uid = Binder.getCallingUid(); 20481 final int permission = mContext.checkCallingOrSelfPermission( 20482 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20483 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20484 enforceCrossUserPermission(uid, userId, 20485 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20486 // writer 20487 synchronized (mPackages) { 20488 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20489 allowedByPermission, uid, userId)) { 20490 scheduleWritePackageRestrictionsLocked(userId); 20491 } 20492 } 20493 } 20494 20495 @Override 20496 public String getInstallerPackageName(String packageName) { 20497 // reader 20498 synchronized (mPackages) { 20499 return mSettings.getInstallerPackageNameLPr(packageName); 20500 } 20501 } 20502 20503 public boolean isOrphaned(String packageName) { 20504 // reader 20505 synchronized (mPackages) { 20506 return mSettings.isOrphaned(packageName); 20507 } 20508 } 20509 20510 @Override 20511 public int getApplicationEnabledSetting(String packageName, int userId) { 20512 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20513 int uid = Binder.getCallingUid(); 20514 enforceCrossUserPermission(uid, userId, 20515 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20516 // reader 20517 synchronized (mPackages) { 20518 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20519 } 20520 } 20521 20522 @Override 20523 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20524 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20525 int uid = Binder.getCallingUid(); 20526 enforceCrossUserPermission(uid, userId, 20527 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20528 // reader 20529 synchronized (mPackages) { 20530 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20531 } 20532 } 20533 20534 @Override 20535 public void enterSafeMode() { 20536 enforceSystemOrRoot("Only the system can request entering safe mode"); 20537 20538 if (!mSystemReady) { 20539 mSafeMode = true; 20540 } 20541 } 20542 20543 @Override 20544 public void systemReady() { 20545 mSystemReady = true; 20546 final ContentResolver resolver = mContext.getContentResolver(); 20547 ContentObserver co = new ContentObserver(mHandler) { 20548 @Override 20549 public void onChange(boolean selfChange) { 20550 mEphemeralAppsDisabled = 20551 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20552 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20553 } 20554 }; 20555 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20556 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20557 false, co, UserHandle.USER_SYSTEM); 20558 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20559 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20560 co.onChange(true); 20561 20562 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20563 // disabled after already being started. 20564 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20565 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20566 20567 // Read the compatibilty setting when the system is ready. 20568 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20569 mContext.getContentResolver(), 20570 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20571 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20572 if (DEBUG_SETTINGS) { 20573 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20574 } 20575 20576 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20577 20578 synchronized (mPackages) { 20579 // Verify that all of the preferred activity components actually 20580 // exist. It is possible for applications to be updated and at 20581 // that point remove a previously declared activity component that 20582 // had been set as a preferred activity. We try to clean this up 20583 // the next time we encounter that preferred activity, but it is 20584 // possible for the user flow to never be able to return to that 20585 // situation so here we do a sanity check to make sure we haven't 20586 // left any junk around. 20587 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20588 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20589 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20590 removed.clear(); 20591 for (PreferredActivity pa : pir.filterSet()) { 20592 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20593 removed.add(pa); 20594 } 20595 } 20596 if (removed.size() > 0) { 20597 for (int r=0; r<removed.size(); r++) { 20598 PreferredActivity pa = removed.get(r); 20599 Slog.w(TAG, "Removing dangling preferred activity: " 20600 + pa.mPref.mComponent); 20601 pir.removeFilter(pa); 20602 } 20603 mSettings.writePackageRestrictionsLPr( 20604 mSettings.mPreferredActivities.keyAt(i)); 20605 } 20606 } 20607 20608 for (int userId : UserManagerService.getInstance().getUserIds()) { 20609 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20610 grantPermissionsUserIds = ArrayUtils.appendInt( 20611 grantPermissionsUserIds, userId); 20612 } 20613 } 20614 } 20615 sUserManager.systemReady(); 20616 20617 // If we upgraded grant all default permissions before kicking off. 20618 for (int userId : grantPermissionsUserIds) { 20619 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20620 } 20621 20622 // If we did not grant default permissions, we preload from this the 20623 // default permission exceptions lazily to ensure we don't hit the 20624 // disk on a new user creation. 20625 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20626 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20627 } 20628 20629 // Kick off any messages waiting for system ready 20630 if (mPostSystemReadyMessages != null) { 20631 for (Message msg : mPostSystemReadyMessages) { 20632 msg.sendToTarget(); 20633 } 20634 mPostSystemReadyMessages = null; 20635 } 20636 20637 // Watch for external volumes that come and go over time 20638 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20639 storage.registerListener(mStorageListener); 20640 20641 mInstallerService.systemReady(); 20642 mPackageDexOptimizer.systemReady(); 20643 20644 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20645 StorageManagerInternal.class); 20646 StorageManagerInternal.addExternalStoragePolicy( 20647 new StorageManagerInternal.ExternalStorageMountPolicy() { 20648 @Override 20649 public int getMountMode(int uid, String packageName) { 20650 if (Process.isIsolated(uid)) { 20651 return Zygote.MOUNT_EXTERNAL_NONE; 20652 } 20653 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20654 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20655 } 20656 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20657 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20658 } 20659 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20660 return Zygote.MOUNT_EXTERNAL_READ; 20661 } 20662 return Zygote.MOUNT_EXTERNAL_WRITE; 20663 } 20664 20665 @Override 20666 public boolean hasExternalStorage(int uid, String packageName) { 20667 return true; 20668 } 20669 }); 20670 20671 // Now that we're mostly running, clean up stale users and apps 20672 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20673 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20674 20675 if (mPrivappPermissionsViolations != null) { 20676 Slog.wtf(TAG,"Signature|privileged permissions not in " 20677 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20678 mPrivappPermissionsViolations = null; 20679 } 20680 } 20681 20682 public void waitForAppDataPrepared() { 20683 if (mPrepareAppDataFuture == null) { 20684 return; 20685 } 20686 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20687 mPrepareAppDataFuture = null; 20688 } 20689 20690 @Override 20691 public boolean isSafeMode() { 20692 return mSafeMode; 20693 } 20694 20695 @Override 20696 public boolean hasSystemUidErrors() { 20697 return mHasSystemUidErrors; 20698 } 20699 20700 static String arrayToString(int[] array) { 20701 StringBuffer buf = new StringBuffer(128); 20702 buf.append('['); 20703 if (array != null) { 20704 for (int i=0; i<array.length; i++) { 20705 if (i > 0) buf.append(", "); 20706 buf.append(array[i]); 20707 } 20708 } 20709 buf.append(']'); 20710 return buf.toString(); 20711 } 20712 20713 static class DumpState { 20714 public static final int DUMP_LIBS = 1 << 0; 20715 public static final int DUMP_FEATURES = 1 << 1; 20716 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20717 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20718 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20719 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20720 public static final int DUMP_PERMISSIONS = 1 << 6; 20721 public static final int DUMP_PACKAGES = 1 << 7; 20722 public static final int DUMP_SHARED_USERS = 1 << 8; 20723 public static final int DUMP_MESSAGES = 1 << 9; 20724 public static final int DUMP_PROVIDERS = 1 << 10; 20725 public static final int DUMP_VERIFIERS = 1 << 11; 20726 public static final int DUMP_PREFERRED = 1 << 12; 20727 public static final int DUMP_PREFERRED_XML = 1 << 13; 20728 public static final int DUMP_KEYSETS = 1 << 14; 20729 public static final int DUMP_VERSION = 1 << 15; 20730 public static final int DUMP_INSTALLS = 1 << 16; 20731 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20732 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20733 public static final int DUMP_FROZEN = 1 << 19; 20734 public static final int DUMP_DEXOPT = 1 << 20; 20735 public static final int DUMP_COMPILER_STATS = 1 << 21; 20736 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20737 public static final int DUMP_CHANGES = 1 << 23; 20738 20739 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20740 20741 private int mTypes; 20742 20743 private int mOptions; 20744 20745 private boolean mTitlePrinted; 20746 20747 private SharedUserSetting mSharedUser; 20748 20749 public boolean isDumping(int type) { 20750 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20751 return true; 20752 } 20753 20754 return (mTypes & type) != 0; 20755 } 20756 20757 public void setDump(int type) { 20758 mTypes |= type; 20759 } 20760 20761 public boolean isOptionEnabled(int option) { 20762 return (mOptions & option) != 0; 20763 } 20764 20765 public void setOptionEnabled(int option) { 20766 mOptions |= option; 20767 } 20768 20769 public boolean onTitlePrinted() { 20770 final boolean printed = mTitlePrinted; 20771 mTitlePrinted = true; 20772 return printed; 20773 } 20774 20775 public boolean getTitlePrinted() { 20776 return mTitlePrinted; 20777 } 20778 20779 public void setTitlePrinted(boolean enabled) { 20780 mTitlePrinted = enabled; 20781 } 20782 20783 public SharedUserSetting getSharedUser() { 20784 return mSharedUser; 20785 } 20786 20787 public void setSharedUser(SharedUserSetting user) { 20788 mSharedUser = user; 20789 } 20790 } 20791 20792 @Override 20793 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20794 FileDescriptor err, String[] args, ShellCallback callback, 20795 ResultReceiver resultReceiver) { 20796 (new PackageManagerShellCommand(this)).exec( 20797 this, in, out, err, args, callback, resultReceiver); 20798 } 20799 20800 @Override 20801 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20802 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20803 20804 DumpState dumpState = new DumpState(); 20805 boolean fullPreferred = false; 20806 boolean checkin = false; 20807 20808 String packageName = null; 20809 ArraySet<String> permissionNames = null; 20810 20811 int opti = 0; 20812 while (opti < args.length) { 20813 String opt = args[opti]; 20814 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20815 break; 20816 } 20817 opti++; 20818 20819 if ("-a".equals(opt)) { 20820 // Right now we only know how to print all. 20821 } else if ("-h".equals(opt)) { 20822 pw.println("Package manager dump options:"); 20823 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20824 pw.println(" --checkin: dump for a checkin"); 20825 pw.println(" -f: print details of intent filters"); 20826 pw.println(" -h: print this help"); 20827 pw.println(" cmd may be one of:"); 20828 pw.println(" l[ibraries]: list known shared libraries"); 20829 pw.println(" f[eatures]: list device features"); 20830 pw.println(" k[eysets]: print known keysets"); 20831 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20832 pw.println(" perm[issions]: dump permissions"); 20833 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20834 pw.println(" pref[erred]: print preferred package settings"); 20835 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20836 pw.println(" prov[iders]: dump content providers"); 20837 pw.println(" p[ackages]: dump installed packages"); 20838 pw.println(" s[hared-users]: dump shared user IDs"); 20839 pw.println(" m[essages]: print collected runtime messages"); 20840 pw.println(" v[erifiers]: print package verifier info"); 20841 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20842 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20843 pw.println(" version: print database version info"); 20844 pw.println(" write: write current settings now"); 20845 pw.println(" installs: details about install sessions"); 20846 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20847 pw.println(" dexopt: dump dexopt state"); 20848 pw.println(" compiler-stats: dump compiler statistics"); 20849 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20850 pw.println(" <package.name>: info about given package"); 20851 return; 20852 } else if ("--checkin".equals(opt)) { 20853 checkin = true; 20854 } else if ("-f".equals(opt)) { 20855 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20856 } else if ("--proto".equals(opt)) { 20857 dumpProto(fd); 20858 return; 20859 } else { 20860 pw.println("Unknown argument: " + opt + "; use -h for help"); 20861 } 20862 } 20863 20864 // Is the caller requesting to dump a particular piece of data? 20865 if (opti < args.length) { 20866 String cmd = args[opti]; 20867 opti++; 20868 // Is this a package name? 20869 if ("android".equals(cmd) || cmd.contains(".")) { 20870 packageName = cmd; 20871 // When dumping a single package, we always dump all of its 20872 // filter information since the amount of data will be reasonable. 20873 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20874 } else if ("check-permission".equals(cmd)) { 20875 if (opti >= args.length) { 20876 pw.println("Error: check-permission missing permission argument"); 20877 return; 20878 } 20879 String perm = args[opti]; 20880 opti++; 20881 if (opti >= args.length) { 20882 pw.println("Error: check-permission missing package argument"); 20883 return; 20884 } 20885 20886 String pkg = args[opti]; 20887 opti++; 20888 int user = UserHandle.getUserId(Binder.getCallingUid()); 20889 if (opti < args.length) { 20890 try { 20891 user = Integer.parseInt(args[opti]); 20892 } catch (NumberFormatException e) { 20893 pw.println("Error: check-permission user argument is not a number: " 20894 + args[opti]); 20895 return; 20896 } 20897 } 20898 20899 // Normalize package name to handle renamed packages and static libs 20900 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20901 20902 pw.println(checkPermission(perm, pkg, user)); 20903 return; 20904 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20905 dumpState.setDump(DumpState.DUMP_LIBS); 20906 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20907 dumpState.setDump(DumpState.DUMP_FEATURES); 20908 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20909 if (opti >= args.length) { 20910 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20911 | DumpState.DUMP_SERVICE_RESOLVERS 20912 | DumpState.DUMP_RECEIVER_RESOLVERS 20913 | DumpState.DUMP_CONTENT_RESOLVERS); 20914 } else { 20915 while (opti < args.length) { 20916 String name = args[opti]; 20917 if ("a".equals(name) || "activity".equals(name)) { 20918 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20919 } else if ("s".equals(name) || "service".equals(name)) { 20920 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20921 } else if ("r".equals(name) || "receiver".equals(name)) { 20922 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20923 } else if ("c".equals(name) || "content".equals(name)) { 20924 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20925 } else { 20926 pw.println("Error: unknown resolver table type: " + name); 20927 return; 20928 } 20929 opti++; 20930 } 20931 } 20932 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20933 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20934 } else if ("permission".equals(cmd)) { 20935 if (opti >= args.length) { 20936 pw.println("Error: permission requires permission name"); 20937 return; 20938 } 20939 permissionNames = new ArraySet<>(); 20940 while (opti < args.length) { 20941 permissionNames.add(args[opti]); 20942 opti++; 20943 } 20944 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20945 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20946 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20947 dumpState.setDump(DumpState.DUMP_PREFERRED); 20948 } else if ("preferred-xml".equals(cmd)) { 20949 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20950 if (opti < args.length && "--full".equals(args[opti])) { 20951 fullPreferred = true; 20952 opti++; 20953 } 20954 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20955 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20956 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20957 dumpState.setDump(DumpState.DUMP_PACKAGES); 20958 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20959 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20960 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20961 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20962 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20963 dumpState.setDump(DumpState.DUMP_MESSAGES); 20964 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20965 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20966 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20967 || "intent-filter-verifiers".equals(cmd)) { 20968 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20969 } else if ("version".equals(cmd)) { 20970 dumpState.setDump(DumpState.DUMP_VERSION); 20971 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20972 dumpState.setDump(DumpState.DUMP_KEYSETS); 20973 } else if ("installs".equals(cmd)) { 20974 dumpState.setDump(DumpState.DUMP_INSTALLS); 20975 } else if ("frozen".equals(cmd)) { 20976 dumpState.setDump(DumpState.DUMP_FROZEN); 20977 } else if ("dexopt".equals(cmd)) { 20978 dumpState.setDump(DumpState.DUMP_DEXOPT); 20979 } else if ("compiler-stats".equals(cmd)) { 20980 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20981 } else if ("enabled-overlays".equals(cmd)) { 20982 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20983 } else if ("changes".equals(cmd)) { 20984 dumpState.setDump(DumpState.DUMP_CHANGES); 20985 } else if ("write".equals(cmd)) { 20986 synchronized (mPackages) { 20987 mSettings.writeLPr(); 20988 pw.println("Settings written."); 20989 return; 20990 } 20991 } 20992 } 20993 20994 if (checkin) { 20995 pw.println("vers,1"); 20996 } 20997 20998 // reader 20999 synchronized (mPackages) { 21000 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21001 if (!checkin) { 21002 if (dumpState.onTitlePrinted()) 21003 pw.println(); 21004 pw.println("Database versions:"); 21005 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21006 } 21007 } 21008 21009 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21010 if (!checkin) { 21011 if (dumpState.onTitlePrinted()) 21012 pw.println(); 21013 pw.println("Verifiers:"); 21014 pw.print(" Required: "); 21015 pw.print(mRequiredVerifierPackage); 21016 pw.print(" (uid="); 21017 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21018 UserHandle.USER_SYSTEM)); 21019 pw.println(")"); 21020 } else if (mRequiredVerifierPackage != null) { 21021 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21022 pw.print(","); 21023 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21024 UserHandle.USER_SYSTEM)); 21025 } 21026 } 21027 21028 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21029 packageName == null) { 21030 if (mIntentFilterVerifierComponent != null) { 21031 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21032 if (!checkin) { 21033 if (dumpState.onTitlePrinted()) 21034 pw.println(); 21035 pw.println("Intent Filter Verifier:"); 21036 pw.print(" Using: "); 21037 pw.print(verifierPackageName); 21038 pw.print(" (uid="); 21039 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21040 UserHandle.USER_SYSTEM)); 21041 pw.println(")"); 21042 } else if (verifierPackageName != null) { 21043 pw.print("ifv,"); pw.print(verifierPackageName); 21044 pw.print(","); 21045 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21046 UserHandle.USER_SYSTEM)); 21047 } 21048 } else { 21049 pw.println(); 21050 pw.println("No Intent Filter Verifier available!"); 21051 } 21052 } 21053 21054 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21055 boolean printedHeader = false; 21056 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21057 while (it.hasNext()) { 21058 String libName = it.next(); 21059 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21060 if (versionedLib == null) { 21061 continue; 21062 } 21063 final int versionCount = versionedLib.size(); 21064 for (int i = 0; i < versionCount; i++) { 21065 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21066 if (!checkin) { 21067 if (!printedHeader) { 21068 if (dumpState.onTitlePrinted()) 21069 pw.println(); 21070 pw.println("Libraries:"); 21071 printedHeader = true; 21072 } 21073 pw.print(" "); 21074 } else { 21075 pw.print("lib,"); 21076 } 21077 pw.print(libEntry.info.getName()); 21078 if (libEntry.info.isStatic()) { 21079 pw.print(" version=" + libEntry.info.getVersion()); 21080 } 21081 if (!checkin) { 21082 pw.print(" -> "); 21083 } 21084 if (libEntry.path != null) { 21085 pw.print(" (jar) "); 21086 pw.print(libEntry.path); 21087 } else { 21088 pw.print(" (apk) "); 21089 pw.print(libEntry.apk); 21090 } 21091 pw.println(); 21092 } 21093 } 21094 } 21095 21096 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21097 if (dumpState.onTitlePrinted()) 21098 pw.println(); 21099 if (!checkin) { 21100 pw.println("Features:"); 21101 } 21102 21103 synchronized (mAvailableFeatures) { 21104 for (FeatureInfo feat : mAvailableFeatures.values()) { 21105 if (checkin) { 21106 pw.print("feat,"); 21107 pw.print(feat.name); 21108 pw.print(","); 21109 pw.println(feat.version); 21110 } else { 21111 pw.print(" "); 21112 pw.print(feat.name); 21113 if (feat.version > 0) { 21114 pw.print(" version="); 21115 pw.print(feat.version); 21116 } 21117 pw.println(); 21118 } 21119 } 21120 } 21121 } 21122 21123 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21124 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21125 : "Activity Resolver Table:", " ", packageName, 21126 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21127 dumpState.setTitlePrinted(true); 21128 } 21129 } 21130 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21131 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21132 : "Receiver Resolver Table:", " ", packageName, 21133 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21134 dumpState.setTitlePrinted(true); 21135 } 21136 } 21137 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21138 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21139 : "Service Resolver Table:", " ", packageName, 21140 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21141 dumpState.setTitlePrinted(true); 21142 } 21143 } 21144 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21145 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21146 : "Provider Resolver Table:", " ", packageName, 21147 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21148 dumpState.setTitlePrinted(true); 21149 } 21150 } 21151 21152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21153 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21154 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21155 int user = mSettings.mPreferredActivities.keyAt(i); 21156 if (pir.dump(pw, 21157 dumpState.getTitlePrinted() 21158 ? "\nPreferred Activities User " + user + ":" 21159 : "Preferred Activities User " + user + ":", " ", 21160 packageName, true, false)) { 21161 dumpState.setTitlePrinted(true); 21162 } 21163 } 21164 } 21165 21166 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21167 pw.flush(); 21168 FileOutputStream fout = new FileOutputStream(fd); 21169 BufferedOutputStream str = new BufferedOutputStream(fout); 21170 XmlSerializer serializer = new FastXmlSerializer(); 21171 try { 21172 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21173 serializer.startDocument(null, true); 21174 serializer.setFeature( 21175 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21176 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21177 serializer.endDocument(); 21178 serializer.flush(); 21179 } catch (IllegalArgumentException e) { 21180 pw.println("Failed writing: " + e); 21181 } catch (IllegalStateException e) { 21182 pw.println("Failed writing: " + e); 21183 } catch (IOException e) { 21184 pw.println("Failed writing: " + e); 21185 } 21186 } 21187 21188 if (!checkin 21189 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21190 && packageName == null) { 21191 pw.println(); 21192 int count = mSettings.mPackages.size(); 21193 if (count == 0) { 21194 pw.println("No applications!"); 21195 pw.println(); 21196 } else { 21197 final String prefix = " "; 21198 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21199 if (allPackageSettings.size() == 0) { 21200 pw.println("No domain preferred apps!"); 21201 pw.println(); 21202 } else { 21203 pw.println("App verification status:"); 21204 pw.println(); 21205 count = 0; 21206 for (PackageSetting ps : allPackageSettings) { 21207 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21208 if (ivi == null || ivi.getPackageName() == null) continue; 21209 pw.println(prefix + "Package: " + ivi.getPackageName()); 21210 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21211 pw.println(prefix + "Status: " + ivi.getStatusString()); 21212 pw.println(); 21213 count++; 21214 } 21215 if (count == 0) { 21216 pw.println(prefix + "No app verification established."); 21217 pw.println(); 21218 } 21219 for (int userId : sUserManager.getUserIds()) { 21220 pw.println("App linkages for user " + userId + ":"); 21221 pw.println(); 21222 count = 0; 21223 for (PackageSetting ps : allPackageSettings) { 21224 final long status = ps.getDomainVerificationStatusForUser(userId); 21225 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21226 && !DEBUG_DOMAIN_VERIFICATION) { 21227 continue; 21228 } 21229 pw.println(prefix + "Package: " + ps.name); 21230 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21231 String statusStr = IntentFilterVerificationInfo. 21232 getStatusStringFromValue(status); 21233 pw.println(prefix + "Status: " + statusStr); 21234 pw.println(); 21235 count++; 21236 } 21237 if (count == 0) { 21238 pw.println(prefix + "No configured app linkages."); 21239 pw.println(); 21240 } 21241 } 21242 } 21243 } 21244 } 21245 21246 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21247 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21248 if (packageName == null && permissionNames == null) { 21249 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 21250 if (iperm == 0) { 21251 if (dumpState.onTitlePrinted()) 21252 pw.println(); 21253 pw.println("AppOp Permissions:"); 21254 } 21255 pw.print(" AppOp Permission "); 21256 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 21257 pw.println(":"); 21258 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 21259 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 21260 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 21261 } 21262 } 21263 } 21264 } 21265 21266 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21267 boolean printedSomething = false; 21268 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21269 if (packageName != null && !packageName.equals(p.info.packageName)) { 21270 continue; 21271 } 21272 if (!printedSomething) { 21273 if (dumpState.onTitlePrinted()) 21274 pw.println(); 21275 pw.println("Registered ContentProviders:"); 21276 printedSomething = true; 21277 } 21278 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21279 pw.print(" "); pw.println(p.toString()); 21280 } 21281 printedSomething = false; 21282 for (Map.Entry<String, PackageParser.Provider> entry : 21283 mProvidersByAuthority.entrySet()) { 21284 PackageParser.Provider p = entry.getValue(); 21285 if (packageName != null && !packageName.equals(p.info.packageName)) { 21286 continue; 21287 } 21288 if (!printedSomething) { 21289 if (dumpState.onTitlePrinted()) 21290 pw.println(); 21291 pw.println("ContentProvider Authorities:"); 21292 printedSomething = true; 21293 } 21294 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21295 pw.print(" "); pw.println(p.toString()); 21296 if (p.info != null && p.info.applicationInfo != null) { 21297 final String appInfo = p.info.applicationInfo.toString(); 21298 pw.print(" applicationInfo="); pw.println(appInfo); 21299 } 21300 } 21301 } 21302 21303 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21304 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21305 } 21306 21307 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21308 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21309 } 21310 21311 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21312 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21313 } 21314 21315 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21316 if (dumpState.onTitlePrinted()) pw.println(); 21317 pw.println("Package Changes:"); 21318 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21319 final int K = mChangedPackages.size(); 21320 for (int i = 0; i < K; i++) { 21321 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21322 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21323 final int N = changes.size(); 21324 if (N == 0) { 21325 pw.print(" "); pw.println("No packages changed"); 21326 } else { 21327 for (int j = 0; j < N; j++) { 21328 final String pkgName = changes.valueAt(j); 21329 final int sequenceNumber = changes.keyAt(j); 21330 pw.print(" "); 21331 pw.print("seq="); 21332 pw.print(sequenceNumber); 21333 pw.print(", package="); 21334 pw.println(pkgName); 21335 } 21336 } 21337 } 21338 } 21339 21340 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21341 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21342 } 21343 21344 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21345 // XXX should handle packageName != null by dumping only install data that 21346 // the given package is involved with. 21347 if (dumpState.onTitlePrinted()) pw.println(); 21348 21349 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21350 ipw.println(); 21351 ipw.println("Frozen packages:"); 21352 ipw.increaseIndent(); 21353 if (mFrozenPackages.size() == 0) { 21354 ipw.println("(none)"); 21355 } else { 21356 for (int i = 0; i < mFrozenPackages.size(); i++) { 21357 ipw.println(mFrozenPackages.valueAt(i)); 21358 } 21359 } 21360 ipw.decreaseIndent(); 21361 } 21362 21363 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21364 if (dumpState.onTitlePrinted()) pw.println(); 21365 dumpDexoptStateLPr(pw, packageName); 21366 } 21367 21368 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21369 if (dumpState.onTitlePrinted()) pw.println(); 21370 dumpCompilerStatsLPr(pw, packageName); 21371 } 21372 21373 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 21374 if (dumpState.onTitlePrinted()) pw.println(); 21375 dumpEnabledOverlaysLPr(pw); 21376 } 21377 21378 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21379 if (dumpState.onTitlePrinted()) pw.println(); 21380 mSettings.dumpReadMessagesLPr(pw, dumpState); 21381 21382 pw.println(); 21383 pw.println("Package warning messages:"); 21384 BufferedReader in = null; 21385 String line = null; 21386 try { 21387 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21388 while ((line = in.readLine()) != null) { 21389 if (line.contains("ignored: updated version")) continue; 21390 pw.println(line); 21391 } 21392 } catch (IOException ignored) { 21393 } finally { 21394 IoUtils.closeQuietly(in); 21395 } 21396 } 21397 21398 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21399 BufferedReader in = null; 21400 String line = null; 21401 try { 21402 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21403 while ((line = in.readLine()) != null) { 21404 if (line.contains("ignored: updated version")) continue; 21405 pw.print("msg,"); 21406 pw.println(line); 21407 } 21408 } catch (IOException ignored) { 21409 } finally { 21410 IoUtils.closeQuietly(in); 21411 } 21412 } 21413 } 21414 21415 // PackageInstaller should be called outside of mPackages lock 21416 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21417 // XXX should handle packageName != null by dumping only install data that 21418 // the given package is involved with. 21419 if (dumpState.onTitlePrinted()) pw.println(); 21420 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21421 } 21422 } 21423 21424 private void dumpProto(FileDescriptor fd) { 21425 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21426 21427 synchronized (mPackages) { 21428 final long requiredVerifierPackageToken = 21429 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21430 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21431 proto.write( 21432 PackageServiceDumpProto.PackageShortProto.UID, 21433 getPackageUid( 21434 mRequiredVerifierPackage, 21435 MATCH_DEBUG_TRIAGED_MISSING, 21436 UserHandle.USER_SYSTEM)); 21437 proto.end(requiredVerifierPackageToken); 21438 21439 if (mIntentFilterVerifierComponent != null) { 21440 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21441 final long verifierPackageToken = 21442 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21443 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21444 proto.write( 21445 PackageServiceDumpProto.PackageShortProto.UID, 21446 getPackageUid( 21447 verifierPackageName, 21448 MATCH_DEBUG_TRIAGED_MISSING, 21449 UserHandle.USER_SYSTEM)); 21450 proto.end(verifierPackageToken); 21451 } 21452 21453 dumpSharedLibrariesProto(proto); 21454 dumpFeaturesProto(proto); 21455 mSettings.dumpPackagesProto(proto); 21456 mSettings.dumpSharedUsersProto(proto); 21457 dumpMessagesProto(proto); 21458 } 21459 proto.flush(); 21460 } 21461 21462 private void dumpMessagesProto(ProtoOutputStream proto) { 21463 BufferedReader in = null; 21464 String line = null; 21465 try { 21466 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21467 while ((line = in.readLine()) != null) { 21468 if (line.contains("ignored: updated version")) continue; 21469 proto.write(PackageServiceDumpProto.MESSAGES, line); 21470 } 21471 } catch (IOException ignored) { 21472 } finally { 21473 IoUtils.closeQuietly(in); 21474 } 21475 } 21476 21477 private void dumpFeaturesProto(ProtoOutputStream proto) { 21478 synchronized (mAvailableFeatures) { 21479 final int count = mAvailableFeatures.size(); 21480 for (int i = 0; i < count; i++) { 21481 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21482 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21483 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21484 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21485 proto.end(featureToken); 21486 } 21487 } 21488 } 21489 21490 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21491 final int count = mSharedLibraries.size(); 21492 for (int i = 0; i < count; i++) { 21493 final String libName = mSharedLibraries.keyAt(i); 21494 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21495 if (versionedLib == null) { 21496 continue; 21497 } 21498 final int versionCount = versionedLib.size(); 21499 for (int j = 0; j < versionCount; j++) { 21500 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21501 final long sharedLibraryToken = 21502 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21503 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21504 final boolean isJar = (libEntry.path != null); 21505 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21506 if (isJar) { 21507 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21508 } else { 21509 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21510 } 21511 proto.end(sharedLibraryToken); 21512 } 21513 } 21514 } 21515 21516 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21517 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21518 ipw.println(); 21519 ipw.println("Dexopt state:"); 21520 ipw.increaseIndent(); 21521 Collection<PackageParser.Package> packages = null; 21522 if (packageName != null) { 21523 PackageParser.Package targetPackage = mPackages.get(packageName); 21524 if (targetPackage != null) { 21525 packages = Collections.singletonList(targetPackage); 21526 } else { 21527 ipw.println("Unable to find package: " + packageName); 21528 return; 21529 } 21530 } else { 21531 packages = mPackages.values(); 21532 } 21533 21534 for (PackageParser.Package pkg : packages) { 21535 ipw.println("[" + pkg.packageName + "]"); 21536 ipw.increaseIndent(); 21537 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21538 ipw.decreaseIndent(); 21539 } 21540 } 21541 21542 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21543 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21544 ipw.println(); 21545 ipw.println("Compiler stats:"); 21546 ipw.increaseIndent(); 21547 Collection<PackageParser.Package> packages = null; 21548 if (packageName != null) { 21549 PackageParser.Package targetPackage = mPackages.get(packageName); 21550 if (targetPackage != null) { 21551 packages = Collections.singletonList(targetPackage); 21552 } else { 21553 ipw.println("Unable to find package: " + packageName); 21554 return; 21555 } 21556 } else { 21557 packages = mPackages.values(); 21558 } 21559 21560 for (PackageParser.Package pkg : packages) { 21561 ipw.println("[" + pkg.packageName + "]"); 21562 ipw.increaseIndent(); 21563 21564 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21565 if (stats == null) { 21566 ipw.println("(No recorded stats)"); 21567 } else { 21568 stats.dump(ipw); 21569 } 21570 ipw.decreaseIndent(); 21571 } 21572 } 21573 21574 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21575 pw.println("Enabled overlay paths:"); 21576 final int N = mEnabledOverlayPaths.size(); 21577 for (int i = 0; i < N; i++) { 21578 final int userId = mEnabledOverlayPaths.keyAt(i); 21579 pw.println(String.format(" User %d:", userId)); 21580 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21581 mEnabledOverlayPaths.valueAt(i); 21582 final int M = userSpecificOverlays.size(); 21583 for (int j = 0; j < M; j++) { 21584 final String targetPackageName = userSpecificOverlays.keyAt(j); 21585 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21586 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21587 } 21588 } 21589 } 21590 21591 private String dumpDomainString(String packageName) { 21592 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21593 .getList(); 21594 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21595 21596 ArraySet<String> result = new ArraySet<>(); 21597 if (iviList.size() > 0) { 21598 for (IntentFilterVerificationInfo ivi : iviList) { 21599 for (String host : ivi.getDomains()) { 21600 result.add(host); 21601 } 21602 } 21603 } 21604 if (filters != null && filters.size() > 0) { 21605 for (IntentFilter filter : filters) { 21606 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21607 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21608 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21609 result.addAll(filter.getHostsList()); 21610 } 21611 } 21612 } 21613 21614 StringBuilder sb = new StringBuilder(result.size() * 16); 21615 for (String domain : result) { 21616 if (sb.length() > 0) sb.append(" "); 21617 sb.append(domain); 21618 } 21619 return sb.toString(); 21620 } 21621 21622 // ------- apps on sdcard specific code ------- 21623 static final boolean DEBUG_SD_INSTALL = false; 21624 21625 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21626 21627 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21628 21629 private boolean mMediaMounted = false; 21630 21631 static String getEncryptKey() { 21632 try { 21633 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21634 SD_ENCRYPTION_KEYSTORE_NAME); 21635 if (sdEncKey == null) { 21636 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21637 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21638 if (sdEncKey == null) { 21639 Slog.e(TAG, "Failed to create encryption keys"); 21640 return null; 21641 } 21642 } 21643 return sdEncKey; 21644 } catch (NoSuchAlgorithmException nsae) { 21645 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21646 return null; 21647 } catch (IOException ioe) { 21648 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21649 return null; 21650 } 21651 } 21652 21653 /* 21654 * Update media status on PackageManager. 21655 */ 21656 @Override 21657 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21658 int callingUid = Binder.getCallingUid(); 21659 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21660 throw new SecurityException("Media status can only be updated by the system"); 21661 } 21662 // reader; this apparently protects mMediaMounted, but should probably 21663 // be a different lock in that case. 21664 synchronized (mPackages) { 21665 Log.i(TAG, "Updating external media status from " 21666 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21667 + (mediaStatus ? "mounted" : "unmounted")); 21668 if (DEBUG_SD_INSTALL) 21669 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21670 + ", mMediaMounted=" + mMediaMounted); 21671 if (mediaStatus == mMediaMounted) { 21672 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21673 : 0, -1); 21674 mHandler.sendMessage(msg); 21675 return; 21676 } 21677 mMediaMounted = mediaStatus; 21678 } 21679 // Queue up an async operation since the package installation may take a 21680 // little while. 21681 mHandler.post(new Runnable() { 21682 public void run() { 21683 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21684 } 21685 }); 21686 } 21687 21688 /** 21689 * Called by StorageManagerService when the initial ASECs to scan are available. 21690 * Should block until all the ASEC containers are finished being scanned. 21691 */ 21692 public void scanAvailableAsecs() { 21693 updateExternalMediaStatusInner(true, false, false); 21694 } 21695 21696 /* 21697 * Collect information of applications on external media, map them against 21698 * existing containers and update information based on current mount status. 21699 * Please note that we always have to report status if reportStatus has been 21700 * set to true especially when unloading packages. 21701 */ 21702 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21703 boolean externalStorage) { 21704 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21705 int[] uidArr = EmptyArray.INT; 21706 21707 final String[] list = PackageHelper.getSecureContainerList(); 21708 if (ArrayUtils.isEmpty(list)) { 21709 Log.i(TAG, "No secure containers found"); 21710 } else { 21711 // Process list of secure containers and categorize them 21712 // as active or stale based on their package internal state. 21713 21714 // reader 21715 synchronized (mPackages) { 21716 for (String cid : list) { 21717 // Leave stages untouched for now; installer service owns them 21718 if (PackageInstallerService.isStageName(cid)) continue; 21719 21720 if (DEBUG_SD_INSTALL) 21721 Log.i(TAG, "Processing container " + cid); 21722 String pkgName = getAsecPackageName(cid); 21723 if (pkgName == null) { 21724 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21725 continue; 21726 } 21727 if (DEBUG_SD_INSTALL) 21728 Log.i(TAG, "Looking for pkg : " + pkgName); 21729 21730 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21731 if (ps == null) { 21732 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21733 continue; 21734 } 21735 21736 /* 21737 * Skip packages that are not external if we're unmounting 21738 * external storage. 21739 */ 21740 if (externalStorage && !isMounted && !isExternal(ps)) { 21741 continue; 21742 } 21743 21744 final AsecInstallArgs args = new AsecInstallArgs(cid, 21745 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21746 // The package status is changed only if the code path 21747 // matches between settings and the container id. 21748 if (ps.codePathString != null 21749 && ps.codePathString.startsWith(args.getCodePath())) { 21750 if (DEBUG_SD_INSTALL) { 21751 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21752 + " at code path: " + ps.codePathString); 21753 } 21754 21755 // We do have a valid package installed on sdcard 21756 processCids.put(args, ps.codePathString); 21757 final int uid = ps.appId; 21758 if (uid != -1) { 21759 uidArr = ArrayUtils.appendInt(uidArr, uid); 21760 } 21761 } else { 21762 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21763 + ps.codePathString); 21764 } 21765 } 21766 } 21767 21768 Arrays.sort(uidArr); 21769 } 21770 21771 // Process packages with valid entries. 21772 if (isMounted) { 21773 if (DEBUG_SD_INSTALL) 21774 Log.i(TAG, "Loading packages"); 21775 loadMediaPackages(processCids, uidArr, externalStorage); 21776 startCleaningPackages(); 21777 mInstallerService.onSecureContainersAvailable(); 21778 } else { 21779 if (DEBUG_SD_INSTALL) 21780 Log.i(TAG, "Unloading packages"); 21781 unloadMediaPackages(processCids, uidArr, reportStatus); 21782 } 21783 } 21784 21785 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21786 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21787 final int size = infos.size(); 21788 final String[] packageNames = new String[size]; 21789 final int[] packageUids = new int[size]; 21790 for (int i = 0; i < size; i++) { 21791 final ApplicationInfo info = infos.get(i); 21792 packageNames[i] = info.packageName; 21793 packageUids[i] = info.uid; 21794 } 21795 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21796 finishedReceiver); 21797 } 21798 21799 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21800 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21801 sendResourcesChangedBroadcast(mediaStatus, replacing, 21802 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21803 } 21804 21805 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21806 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21807 int size = pkgList.length; 21808 if (size > 0) { 21809 // Send broadcasts here 21810 Bundle extras = new Bundle(); 21811 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21812 if (uidArr != null) { 21813 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21814 } 21815 if (replacing) { 21816 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21817 } 21818 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21819 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21820 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21821 } 21822 } 21823 21824 /* 21825 * Look at potentially valid container ids from processCids If package 21826 * information doesn't match the one on record or package scanning fails, 21827 * the cid is added to list of removeCids. We currently don't delete stale 21828 * containers. 21829 */ 21830 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21831 boolean externalStorage) { 21832 ArrayList<String> pkgList = new ArrayList<String>(); 21833 Set<AsecInstallArgs> keys = processCids.keySet(); 21834 21835 for (AsecInstallArgs args : keys) { 21836 String codePath = processCids.get(args); 21837 if (DEBUG_SD_INSTALL) 21838 Log.i(TAG, "Loading container : " + args.cid); 21839 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21840 try { 21841 // Make sure there are no container errors first. 21842 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21843 Slog.e(TAG, "Failed to mount cid : " + args.cid 21844 + " when installing from sdcard"); 21845 continue; 21846 } 21847 // Check code path here. 21848 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21849 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21850 + " does not match one in settings " + codePath); 21851 continue; 21852 } 21853 // Parse package 21854 int parseFlags = mDefParseFlags; 21855 if (args.isExternalAsec()) { 21856 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21857 } 21858 if (args.isFwdLocked()) { 21859 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21860 } 21861 21862 synchronized (mInstallLock) { 21863 PackageParser.Package pkg = null; 21864 try { 21865 // Sadly we don't know the package name yet to freeze it 21866 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21867 SCAN_IGNORE_FROZEN, 0, null); 21868 } catch (PackageManagerException e) { 21869 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21870 } 21871 // Scan the package 21872 if (pkg != null) { 21873 /* 21874 * TODO why is the lock being held? doPostInstall is 21875 * called in other places without the lock. This needs 21876 * to be straightened out. 21877 */ 21878 // writer 21879 synchronized (mPackages) { 21880 retCode = PackageManager.INSTALL_SUCCEEDED; 21881 pkgList.add(pkg.packageName); 21882 // Post process args 21883 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21884 pkg.applicationInfo.uid); 21885 } 21886 } else { 21887 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21888 } 21889 } 21890 21891 } finally { 21892 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21893 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21894 } 21895 } 21896 } 21897 // writer 21898 synchronized (mPackages) { 21899 // If the platform SDK has changed since the last time we booted, 21900 // we need to re-grant app permission to catch any new ones that 21901 // appear. This is really a hack, and means that apps can in some 21902 // cases get permissions that the user didn't initially explicitly 21903 // allow... it would be nice to have some better way to handle 21904 // this situation. 21905 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21906 : mSettings.getInternalVersion(); 21907 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21908 : StorageManager.UUID_PRIVATE_INTERNAL; 21909 21910 int updateFlags = UPDATE_PERMISSIONS_ALL; 21911 if (ver.sdkVersion != mSdkVersion) { 21912 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21913 + mSdkVersion + "; regranting permissions for external"); 21914 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21915 } 21916 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21917 21918 // Yay, everything is now upgraded 21919 ver.forceCurrent(); 21920 21921 // can downgrade to reader 21922 // Persist settings 21923 mSettings.writeLPr(); 21924 } 21925 // Send a broadcast to let everyone know we are done processing 21926 if (pkgList.size() > 0) { 21927 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21928 } 21929 } 21930 21931 /* 21932 * Utility method to unload a list of specified containers 21933 */ 21934 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21935 // Just unmount all valid containers. 21936 for (AsecInstallArgs arg : cidArgs) { 21937 synchronized (mInstallLock) { 21938 arg.doPostDeleteLI(false); 21939 } 21940 } 21941 } 21942 21943 /* 21944 * Unload packages mounted on external media. This involves deleting package 21945 * data from internal structures, sending broadcasts about disabled packages, 21946 * gc'ing to free up references, unmounting all secure containers 21947 * corresponding to packages on external media, and posting a 21948 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21949 * that we always have to post this message if status has been requested no 21950 * matter what. 21951 */ 21952 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21953 final boolean reportStatus) { 21954 if (DEBUG_SD_INSTALL) 21955 Log.i(TAG, "unloading media packages"); 21956 ArrayList<String> pkgList = new ArrayList<String>(); 21957 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21958 final Set<AsecInstallArgs> keys = processCids.keySet(); 21959 for (AsecInstallArgs args : keys) { 21960 String pkgName = args.getPackageName(); 21961 if (DEBUG_SD_INSTALL) 21962 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21963 // Delete package internally 21964 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21965 synchronized (mInstallLock) { 21966 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21967 final boolean res; 21968 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21969 "unloadMediaPackages")) { 21970 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21971 null); 21972 } 21973 if (res) { 21974 pkgList.add(pkgName); 21975 } else { 21976 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21977 failedList.add(args); 21978 } 21979 } 21980 } 21981 21982 // reader 21983 synchronized (mPackages) { 21984 // We didn't update the settings after removing each package; 21985 // write them now for all packages. 21986 mSettings.writeLPr(); 21987 } 21988 21989 // We have to absolutely send UPDATED_MEDIA_STATUS only 21990 // after confirming that all the receivers processed the ordered 21991 // broadcast when packages get disabled, force a gc to clean things up. 21992 // and unload all the containers. 21993 if (pkgList.size() > 0) { 21994 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21995 new IIntentReceiver.Stub() { 21996 public void performReceive(Intent intent, int resultCode, String data, 21997 Bundle extras, boolean ordered, boolean sticky, 21998 int sendingUser) throws RemoteException { 21999 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 22000 reportStatus ? 1 : 0, 1, keys); 22001 mHandler.sendMessage(msg); 22002 } 22003 }); 22004 } else { 22005 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 22006 keys); 22007 mHandler.sendMessage(msg); 22008 } 22009 } 22010 22011 private void loadPrivatePackages(final VolumeInfo vol) { 22012 mHandler.post(new Runnable() { 22013 @Override 22014 public void run() { 22015 loadPrivatePackagesInner(vol); 22016 } 22017 }); 22018 } 22019 22020 private void loadPrivatePackagesInner(VolumeInfo vol) { 22021 final String volumeUuid = vol.fsUuid; 22022 if (TextUtils.isEmpty(volumeUuid)) { 22023 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22024 return; 22025 } 22026 22027 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22028 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22029 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22030 22031 final VersionInfo ver; 22032 final List<PackageSetting> packages; 22033 synchronized (mPackages) { 22034 ver = mSettings.findOrCreateVersion(volumeUuid); 22035 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22036 } 22037 22038 for (PackageSetting ps : packages) { 22039 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22040 synchronized (mInstallLock) { 22041 final PackageParser.Package pkg; 22042 try { 22043 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22044 loaded.add(pkg.applicationInfo); 22045 22046 } catch (PackageManagerException e) { 22047 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22048 } 22049 22050 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22051 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 22052 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 22053 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22054 } 22055 } 22056 } 22057 22058 // Reconcile app data for all started/unlocked users 22059 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22060 final UserManager um = mContext.getSystemService(UserManager.class); 22061 UserManagerInternal umInternal = getUserManagerInternal(); 22062 for (UserInfo user : um.getUsers()) { 22063 final int flags; 22064 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22065 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22066 } else if (umInternal.isUserRunning(user.id)) { 22067 flags = StorageManager.FLAG_STORAGE_DE; 22068 } else { 22069 continue; 22070 } 22071 22072 try { 22073 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22074 synchronized (mInstallLock) { 22075 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22076 } 22077 } catch (IllegalStateException e) { 22078 // Device was probably ejected, and we'll process that event momentarily 22079 Slog.w(TAG, "Failed to prepare storage: " + e); 22080 } 22081 } 22082 22083 synchronized (mPackages) { 22084 int updateFlags = UPDATE_PERMISSIONS_ALL; 22085 if (ver.sdkVersion != mSdkVersion) { 22086 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22087 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22088 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22089 } 22090 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22091 22092 // Yay, everything is now upgraded 22093 ver.forceCurrent(); 22094 22095 mSettings.writeLPr(); 22096 } 22097 22098 for (PackageFreezer freezer : freezers) { 22099 freezer.close(); 22100 } 22101 22102 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22103 sendResourcesChangedBroadcast(true, false, loaded, null); 22104 } 22105 22106 private void unloadPrivatePackages(final VolumeInfo vol) { 22107 mHandler.post(new Runnable() { 22108 @Override 22109 public void run() { 22110 unloadPrivatePackagesInner(vol); 22111 } 22112 }); 22113 } 22114 22115 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22116 final String volumeUuid = vol.fsUuid; 22117 if (TextUtils.isEmpty(volumeUuid)) { 22118 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22119 return; 22120 } 22121 22122 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22123 synchronized (mInstallLock) { 22124 synchronized (mPackages) { 22125 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22126 for (PackageSetting ps : packages) { 22127 if (ps.pkg == null) continue; 22128 22129 final ApplicationInfo info = ps.pkg.applicationInfo; 22130 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22131 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22132 22133 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22134 "unloadPrivatePackagesInner")) { 22135 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22136 false, null)) { 22137 unloaded.add(info); 22138 } else { 22139 Slog.w(TAG, "Failed to unload " + ps.codePath); 22140 } 22141 } 22142 22143 // Try very hard to release any references to this package 22144 // so we don't risk the system server being killed due to 22145 // open FDs 22146 AttributeCache.instance().removePackage(ps.name); 22147 } 22148 22149 mSettings.writeLPr(); 22150 } 22151 } 22152 22153 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22154 sendResourcesChangedBroadcast(false, false, unloaded, null); 22155 22156 // Try very hard to release any references to this path so we don't risk 22157 // the system server being killed due to open FDs 22158 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22159 22160 for (int i = 0; i < 3; i++) { 22161 System.gc(); 22162 System.runFinalization(); 22163 } 22164 } 22165 22166 private void assertPackageKnown(String volumeUuid, String packageName) 22167 throws PackageManagerException { 22168 synchronized (mPackages) { 22169 // Normalize package name to handle renamed packages 22170 packageName = normalizePackageNameLPr(packageName); 22171 22172 final PackageSetting ps = mSettings.mPackages.get(packageName); 22173 if (ps == null) { 22174 throw new PackageManagerException("Package " + packageName + " is unknown"); 22175 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22176 throw new PackageManagerException( 22177 "Package " + packageName + " found on unknown volume " + volumeUuid 22178 + "; expected volume " + ps.volumeUuid); 22179 } 22180 } 22181 } 22182 22183 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22184 throws PackageManagerException { 22185 synchronized (mPackages) { 22186 // Normalize package name to handle renamed packages 22187 packageName = normalizePackageNameLPr(packageName); 22188 22189 final PackageSetting ps = mSettings.mPackages.get(packageName); 22190 if (ps == null) { 22191 throw new PackageManagerException("Package " + packageName + " is unknown"); 22192 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22193 throw new PackageManagerException( 22194 "Package " + packageName + " found on unknown volume " + volumeUuid 22195 + "; expected volume " + ps.volumeUuid); 22196 } else if (!ps.getInstalled(userId)) { 22197 throw new PackageManagerException( 22198 "Package " + packageName + " not installed for user " + userId); 22199 } 22200 } 22201 } 22202 22203 private List<String> collectAbsoluteCodePaths() { 22204 synchronized (mPackages) { 22205 List<String> codePaths = new ArrayList<>(); 22206 final int packageCount = mSettings.mPackages.size(); 22207 for (int i = 0; i < packageCount; i++) { 22208 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22209 codePaths.add(ps.codePath.getAbsolutePath()); 22210 } 22211 return codePaths; 22212 } 22213 } 22214 22215 /** 22216 * Examine all apps present on given mounted volume, and destroy apps that 22217 * aren't expected, either due to uninstallation or reinstallation on 22218 * another volume. 22219 */ 22220 private void reconcileApps(String volumeUuid) { 22221 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22222 List<File> filesToDelete = null; 22223 22224 final File[] files = FileUtils.listFilesOrEmpty( 22225 Environment.getDataAppDirectory(volumeUuid)); 22226 for (File file : files) { 22227 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22228 && !PackageInstallerService.isStageName(file.getName()); 22229 if (!isPackage) { 22230 // Ignore entries which are not packages 22231 continue; 22232 } 22233 22234 String absolutePath = file.getAbsolutePath(); 22235 22236 boolean pathValid = false; 22237 final int absoluteCodePathCount = absoluteCodePaths.size(); 22238 for (int i = 0; i < absoluteCodePathCount; i++) { 22239 String absoluteCodePath = absoluteCodePaths.get(i); 22240 if (absolutePath.startsWith(absoluteCodePath)) { 22241 pathValid = true; 22242 break; 22243 } 22244 } 22245 22246 if (!pathValid) { 22247 if (filesToDelete == null) { 22248 filesToDelete = new ArrayList<>(); 22249 } 22250 filesToDelete.add(file); 22251 } 22252 } 22253 22254 if (filesToDelete != null) { 22255 final int fileToDeleteCount = filesToDelete.size(); 22256 for (int i = 0; i < fileToDeleteCount; i++) { 22257 File fileToDelete = filesToDelete.get(i); 22258 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22259 synchronized (mInstallLock) { 22260 removeCodePathLI(fileToDelete); 22261 } 22262 } 22263 } 22264 } 22265 22266 /** 22267 * Reconcile all app data for the given user. 22268 * <p> 22269 * Verifies that directories exist and that ownership and labeling is 22270 * correct for all installed apps on all mounted volumes. 22271 */ 22272 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22273 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22274 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22275 final String volumeUuid = vol.getFsUuid(); 22276 synchronized (mInstallLock) { 22277 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22278 } 22279 } 22280 } 22281 22282 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22283 boolean migrateAppData) { 22284 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22285 } 22286 22287 /** 22288 * Reconcile all app data on given mounted volume. 22289 * <p> 22290 * Destroys app data that isn't expected, either due to uninstallation or 22291 * reinstallation on another volume. 22292 * <p> 22293 * Verifies that directories exist and that ownership and labeling is 22294 * correct for all installed apps. 22295 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22296 */ 22297 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22298 boolean migrateAppData, boolean onlyCoreApps) { 22299 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22300 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22301 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22302 22303 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22304 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22305 22306 // First look for stale data that doesn't belong, and check if things 22307 // have changed since we did our last restorecon 22308 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22309 if (StorageManager.isFileEncryptedNativeOrEmulated() 22310 && !StorageManager.isUserKeyUnlocked(userId)) { 22311 throw new RuntimeException( 22312 "Yikes, someone asked us to reconcile CE storage while " + userId 22313 + " was still locked; this would have caused massive data loss!"); 22314 } 22315 22316 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22317 for (File file : files) { 22318 final String packageName = file.getName(); 22319 try { 22320 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22321 } catch (PackageManagerException e) { 22322 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22323 try { 22324 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22325 StorageManager.FLAG_STORAGE_CE, 0); 22326 } catch (InstallerException e2) { 22327 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22328 } 22329 } 22330 } 22331 } 22332 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22333 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22334 for (File file : files) { 22335 final String packageName = file.getName(); 22336 try { 22337 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22338 } catch (PackageManagerException e) { 22339 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22340 try { 22341 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22342 StorageManager.FLAG_STORAGE_DE, 0); 22343 } catch (InstallerException e2) { 22344 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22345 } 22346 } 22347 } 22348 } 22349 22350 // Ensure that data directories are ready to roll for all packages 22351 // installed for this volume and user 22352 final List<PackageSetting> packages; 22353 synchronized (mPackages) { 22354 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22355 } 22356 int preparedCount = 0; 22357 for (PackageSetting ps : packages) { 22358 final String packageName = ps.name; 22359 if (ps.pkg == null) { 22360 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22361 // TODO: might be due to legacy ASEC apps; we should circle back 22362 // and reconcile again once they're scanned 22363 continue; 22364 } 22365 // Skip non-core apps if requested 22366 if (onlyCoreApps && !ps.pkg.coreApp) { 22367 result.add(packageName); 22368 continue; 22369 } 22370 22371 if (ps.getInstalled(userId)) { 22372 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22373 preparedCount++; 22374 } 22375 } 22376 22377 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22378 return result; 22379 } 22380 22381 /** 22382 * Prepare app data for the given app just after it was installed or 22383 * upgraded. This method carefully only touches users that it's installed 22384 * for, and it forces a restorecon to handle any seinfo changes. 22385 * <p> 22386 * Verifies that directories exist and that ownership and labeling is 22387 * correct for all installed apps. If there is an ownership mismatch, it 22388 * will try recovering system apps by wiping data; third-party app data is 22389 * left intact. 22390 * <p> 22391 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22392 */ 22393 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22394 final PackageSetting ps; 22395 synchronized (mPackages) { 22396 ps = mSettings.mPackages.get(pkg.packageName); 22397 mSettings.writeKernelMappingLPr(ps); 22398 } 22399 22400 final UserManager um = mContext.getSystemService(UserManager.class); 22401 UserManagerInternal umInternal = getUserManagerInternal(); 22402 for (UserInfo user : um.getUsers()) { 22403 final int flags; 22404 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22405 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22406 } else if (umInternal.isUserRunning(user.id)) { 22407 flags = StorageManager.FLAG_STORAGE_DE; 22408 } else { 22409 continue; 22410 } 22411 22412 if (ps.getInstalled(user.id)) { 22413 // TODO: when user data is locked, mark that we're still dirty 22414 prepareAppDataLIF(pkg, user.id, flags); 22415 } 22416 } 22417 } 22418 22419 /** 22420 * Prepare app data for the given app. 22421 * <p> 22422 * Verifies that directories exist and that ownership and labeling is 22423 * correct for all installed apps. If there is an ownership mismatch, this 22424 * will try recovering system apps by wiping data; third-party app data is 22425 * left intact. 22426 */ 22427 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22428 if (pkg == null) { 22429 Slog.wtf(TAG, "Package was null!", new Throwable()); 22430 return; 22431 } 22432 prepareAppDataLeafLIF(pkg, userId, flags); 22433 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22434 for (int i = 0; i < childCount; i++) { 22435 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22436 } 22437 } 22438 22439 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22440 boolean maybeMigrateAppData) { 22441 prepareAppDataLIF(pkg, userId, flags); 22442 22443 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22444 // We may have just shuffled around app data directories, so 22445 // prepare them one more time 22446 prepareAppDataLIF(pkg, userId, flags); 22447 } 22448 } 22449 22450 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22451 if (DEBUG_APP_DATA) { 22452 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22453 + Integer.toHexString(flags)); 22454 } 22455 22456 final String volumeUuid = pkg.volumeUuid; 22457 final String packageName = pkg.packageName; 22458 final ApplicationInfo app = pkg.applicationInfo; 22459 final int appId = UserHandle.getAppId(app.uid); 22460 22461 Preconditions.checkNotNull(app.seInfo); 22462 22463 long ceDataInode = -1; 22464 try { 22465 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22466 appId, app.seInfo, app.targetSdkVersion); 22467 } catch (InstallerException e) { 22468 if (app.isSystemApp()) { 22469 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22470 + ", but trying to recover: " + e); 22471 destroyAppDataLeafLIF(pkg, userId, flags); 22472 try { 22473 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22474 appId, app.seInfo, app.targetSdkVersion); 22475 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22476 } catch (InstallerException e2) { 22477 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22478 } 22479 } else { 22480 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22481 } 22482 } 22483 22484 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22485 // TODO: mark this structure as dirty so we persist it! 22486 synchronized (mPackages) { 22487 final PackageSetting ps = mSettings.mPackages.get(packageName); 22488 if (ps != null) { 22489 ps.setCeDataInode(ceDataInode, userId); 22490 } 22491 } 22492 } 22493 22494 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22495 } 22496 22497 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22498 if (pkg == null) { 22499 Slog.wtf(TAG, "Package was null!", new Throwable()); 22500 return; 22501 } 22502 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22503 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22504 for (int i = 0; i < childCount; i++) { 22505 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22506 } 22507 } 22508 22509 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22510 final String volumeUuid = pkg.volumeUuid; 22511 final String packageName = pkg.packageName; 22512 final ApplicationInfo app = pkg.applicationInfo; 22513 22514 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22515 // Create a native library symlink only if we have native libraries 22516 // and if the native libraries are 32 bit libraries. We do not provide 22517 // this symlink for 64 bit libraries. 22518 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22519 final String nativeLibPath = app.nativeLibraryDir; 22520 try { 22521 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22522 nativeLibPath, userId); 22523 } catch (InstallerException e) { 22524 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22525 } 22526 } 22527 } 22528 } 22529 22530 /** 22531 * For system apps on non-FBE devices, this method migrates any existing 22532 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22533 * requested by the app. 22534 */ 22535 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22536 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22537 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22538 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22539 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22540 try { 22541 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22542 storageTarget); 22543 } catch (InstallerException e) { 22544 logCriticalInfo(Log.WARN, 22545 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22546 } 22547 return true; 22548 } else { 22549 return false; 22550 } 22551 } 22552 22553 public PackageFreezer freezePackage(String packageName, String killReason) { 22554 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22555 } 22556 22557 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22558 return new PackageFreezer(packageName, userId, killReason); 22559 } 22560 22561 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22562 String killReason) { 22563 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22564 } 22565 22566 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22567 String killReason) { 22568 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22569 return new PackageFreezer(); 22570 } else { 22571 return freezePackage(packageName, userId, killReason); 22572 } 22573 } 22574 22575 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22576 String killReason) { 22577 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22578 } 22579 22580 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22581 String killReason) { 22582 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22583 return new PackageFreezer(); 22584 } else { 22585 return freezePackage(packageName, userId, killReason); 22586 } 22587 } 22588 22589 /** 22590 * Class that freezes and kills the given package upon creation, and 22591 * unfreezes it upon closing. This is typically used when doing surgery on 22592 * app code/data to prevent the app from running while you're working. 22593 */ 22594 private class PackageFreezer implements AutoCloseable { 22595 private final String mPackageName; 22596 private final PackageFreezer[] mChildren; 22597 22598 private final boolean mWeFroze; 22599 22600 private final AtomicBoolean mClosed = new AtomicBoolean(); 22601 private final CloseGuard mCloseGuard = CloseGuard.get(); 22602 22603 /** 22604 * Create and return a stub freezer that doesn't actually do anything, 22605 * typically used when someone requested 22606 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22607 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22608 */ 22609 public PackageFreezer() { 22610 mPackageName = null; 22611 mChildren = null; 22612 mWeFroze = false; 22613 mCloseGuard.open("close"); 22614 } 22615 22616 public PackageFreezer(String packageName, int userId, String killReason) { 22617 synchronized (mPackages) { 22618 mPackageName = packageName; 22619 mWeFroze = mFrozenPackages.add(mPackageName); 22620 22621 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22622 if (ps != null) { 22623 killApplication(ps.name, ps.appId, userId, killReason); 22624 } 22625 22626 final PackageParser.Package p = mPackages.get(packageName); 22627 if (p != null && p.childPackages != null) { 22628 final int N = p.childPackages.size(); 22629 mChildren = new PackageFreezer[N]; 22630 for (int i = 0; i < N; i++) { 22631 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22632 userId, killReason); 22633 } 22634 } else { 22635 mChildren = null; 22636 } 22637 } 22638 mCloseGuard.open("close"); 22639 } 22640 22641 @Override 22642 protected void finalize() throws Throwable { 22643 try { 22644 mCloseGuard.warnIfOpen(); 22645 close(); 22646 } finally { 22647 super.finalize(); 22648 } 22649 } 22650 22651 @Override 22652 public void close() { 22653 mCloseGuard.close(); 22654 if (mClosed.compareAndSet(false, true)) { 22655 synchronized (mPackages) { 22656 if (mWeFroze) { 22657 mFrozenPackages.remove(mPackageName); 22658 } 22659 22660 if (mChildren != null) { 22661 for (PackageFreezer freezer : mChildren) { 22662 freezer.close(); 22663 } 22664 } 22665 } 22666 } 22667 } 22668 } 22669 22670 /** 22671 * Verify that given package is currently frozen. 22672 */ 22673 private void checkPackageFrozen(String packageName) { 22674 synchronized (mPackages) { 22675 if (!mFrozenPackages.contains(packageName)) { 22676 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22677 } 22678 } 22679 } 22680 22681 @Override 22682 public int movePackage(final String packageName, final String volumeUuid) { 22683 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22684 22685 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22686 final int moveId = mNextMoveId.getAndIncrement(); 22687 mHandler.post(new Runnable() { 22688 @Override 22689 public void run() { 22690 try { 22691 movePackageInternal(packageName, volumeUuid, moveId, user); 22692 } catch (PackageManagerException e) { 22693 Slog.w(TAG, "Failed to move " + packageName, e); 22694 mMoveCallbacks.notifyStatusChanged(moveId, 22695 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22696 } 22697 } 22698 }); 22699 return moveId; 22700 } 22701 22702 private void movePackageInternal(final String packageName, final String volumeUuid, 22703 final int moveId, UserHandle user) throws PackageManagerException { 22704 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22705 final PackageManager pm = mContext.getPackageManager(); 22706 22707 final boolean currentAsec; 22708 final String currentVolumeUuid; 22709 final File codeFile; 22710 final String installerPackageName; 22711 final String packageAbiOverride; 22712 final int appId; 22713 final String seinfo; 22714 final String label; 22715 final int targetSdkVersion; 22716 final PackageFreezer freezer; 22717 final int[] installedUserIds; 22718 22719 // reader 22720 synchronized (mPackages) { 22721 final PackageParser.Package pkg = mPackages.get(packageName); 22722 final PackageSetting ps = mSettings.mPackages.get(packageName); 22723 if (pkg == null || ps == null) { 22724 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22725 } 22726 22727 if (pkg.applicationInfo.isSystemApp()) { 22728 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22729 "Cannot move system application"); 22730 } 22731 22732 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22733 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22734 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22735 if (isInternalStorage && !allow3rdPartyOnInternal) { 22736 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22737 "3rd party apps are not allowed on internal storage"); 22738 } 22739 22740 if (pkg.applicationInfo.isExternalAsec()) { 22741 currentAsec = true; 22742 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22743 } else if (pkg.applicationInfo.isForwardLocked()) { 22744 currentAsec = true; 22745 currentVolumeUuid = "forward_locked"; 22746 } else { 22747 currentAsec = false; 22748 currentVolumeUuid = ps.volumeUuid; 22749 22750 final File probe = new File(pkg.codePath); 22751 final File probeOat = new File(probe, "oat"); 22752 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22753 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22754 "Move only supported for modern cluster style installs"); 22755 } 22756 } 22757 22758 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22759 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22760 "Package already moved to " + volumeUuid); 22761 } 22762 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22763 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22764 "Device admin cannot be moved"); 22765 } 22766 22767 if (mFrozenPackages.contains(packageName)) { 22768 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22769 "Failed to move already frozen package"); 22770 } 22771 22772 codeFile = new File(pkg.codePath); 22773 installerPackageName = ps.installerPackageName; 22774 packageAbiOverride = ps.cpuAbiOverrideString; 22775 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22776 seinfo = pkg.applicationInfo.seInfo; 22777 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22778 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22779 freezer = freezePackage(packageName, "movePackageInternal"); 22780 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22781 } 22782 22783 final Bundle extras = new Bundle(); 22784 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22785 extras.putString(Intent.EXTRA_TITLE, label); 22786 mMoveCallbacks.notifyCreated(moveId, extras); 22787 22788 int installFlags; 22789 final boolean moveCompleteApp; 22790 final File measurePath; 22791 22792 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22793 installFlags = INSTALL_INTERNAL; 22794 moveCompleteApp = !currentAsec; 22795 measurePath = Environment.getDataAppDirectory(volumeUuid); 22796 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22797 installFlags = INSTALL_EXTERNAL; 22798 moveCompleteApp = false; 22799 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22800 } else { 22801 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22802 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22803 || !volume.isMountedWritable()) { 22804 freezer.close(); 22805 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22806 "Move location not mounted private volume"); 22807 } 22808 22809 Preconditions.checkState(!currentAsec); 22810 22811 installFlags = INSTALL_INTERNAL; 22812 moveCompleteApp = true; 22813 measurePath = Environment.getDataAppDirectory(volumeUuid); 22814 } 22815 22816 final PackageStats stats = new PackageStats(null, -1); 22817 synchronized (mInstaller) { 22818 for (int userId : installedUserIds) { 22819 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22820 freezer.close(); 22821 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22822 "Failed to measure package size"); 22823 } 22824 } 22825 } 22826 22827 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22828 + stats.dataSize); 22829 22830 final long startFreeBytes = measurePath.getUsableSpace(); 22831 final long sizeBytes; 22832 if (moveCompleteApp) { 22833 sizeBytes = stats.codeSize + stats.dataSize; 22834 } else { 22835 sizeBytes = stats.codeSize; 22836 } 22837 22838 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22839 freezer.close(); 22840 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22841 "Not enough free space to move"); 22842 } 22843 22844 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22845 22846 final CountDownLatch installedLatch = new CountDownLatch(1); 22847 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22848 @Override 22849 public void onUserActionRequired(Intent intent) throws RemoteException { 22850 throw new IllegalStateException(); 22851 } 22852 22853 @Override 22854 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22855 Bundle extras) throws RemoteException { 22856 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22857 + PackageManager.installStatusToString(returnCode, msg)); 22858 22859 installedLatch.countDown(); 22860 freezer.close(); 22861 22862 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22863 switch (status) { 22864 case PackageInstaller.STATUS_SUCCESS: 22865 mMoveCallbacks.notifyStatusChanged(moveId, 22866 PackageManager.MOVE_SUCCEEDED); 22867 break; 22868 case PackageInstaller.STATUS_FAILURE_STORAGE: 22869 mMoveCallbacks.notifyStatusChanged(moveId, 22870 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22871 break; 22872 default: 22873 mMoveCallbacks.notifyStatusChanged(moveId, 22874 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22875 break; 22876 } 22877 } 22878 }; 22879 22880 final MoveInfo move; 22881 if (moveCompleteApp) { 22882 // Kick off a thread to report progress estimates 22883 new Thread() { 22884 @Override 22885 public void run() { 22886 while (true) { 22887 try { 22888 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22889 break; 22890 } 22891 } catch (InterruptedException ignored) { 22892 } 22893 22894 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22895 final int progress = 10 + (int) MathUtils.constrain( 22896 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22897 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22898 } 22899 } 22900 }.start(); 22901 22902 final String dataAppName = codeFile.getName(); 22903 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22904 dataAppName, appId, seinfo, targetSdkVersion); 22905 } else { 22906 move = null; 22907 } 22908 22909 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22910 22911 final Message msg = mHandler.obtainMessage(INIT_COPY); 22912 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22913 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22914 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22915 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22916 PackageManager.INSTALL_REASON_UNKNOWN); 22917 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22918 msg.obj = params; 22919 22920 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22921 System.identityHashCode(msg.obj)); 22922 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22923 System.identityHashCode(msg.obj)); 22924 22925 mHandler.sendMessage(msg); 22926 } 22927 22928 @Override 22929 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22930 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22931 22932 final int realMoveId = mNextMoveId.getAndIncrement(); 22933 final Bundle extras = new Bundle(); 22934 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22935 mMoveCallbacks.notifyCreated(realMoveId, extras); 22936 22937 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22938 @Override 22939 public void onCreated(int moveId, Bundle extras) { 22940 // Ignored 22941 } 22942 22943 @Override 22944 public void onStatusChanged(int moveId, int status, long estMillis) { 22945 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22946 } 22947 }; 22948 22949 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22950 storage.setPrimaryStorageUuid(volumeUuid, callback); 22951 return realMoveId; 22952 } 22953 22954 @Override 22955 public int getMoveStatus(int moveId) { 22956 mContext.enforceCallingOrSelfPermission( 22957 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22958 return mMoveCallbacks.mLastStatus.get(moveId); 22959 } 22960 22961 @Override 22962 public void registerMoveCallback(IPackageMoveObserver callback) { 22963 mContext.enforceCallingOrSelfPermission( 22964 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22965 mMoveCallbacks.register(callback); 22966 } 22967 22968 @Override 22969 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22970 mContext.enforceCallingOrSelfPermission( 22971 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22972 mMoveCallbacks.unregister(callback); 22973 } 22974 22975 @Override 22976 public boolean setInstallLocation(int loc) { 22977 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22978 null); 22979 if (getInstallLocation() == loc) { 22980 return true; 22981 } 22982 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22983 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22984 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22985 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22986 return true; 22987 } 22988 return false; 22989 } 22990 22991 @Override 22992 public int getInstallLocation() { 22993 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22994 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22995 PackageHelper.APP_INSTALL_AUTO); 22996 } 22997 22998 /** Called by UserManagerService */ 22999 void cleanUpUser(UserManagerService userManager, int userHandle) { 23000 synchronized (mPackages) { 23001 mDirtyUsers.remove(userHandle); 23002 mUserNeedsBadging.delete(userHandle); 23003 mSettings.removeUserLPw(userHandle); 23004 mPendingBroadcasts.remove(userHandle); 23005 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23006 removeUnusedPackagesLPw(userManager, userHandle); 23007 } 23008 } 23009 23010 /** 23011 * We're removing userHandle and would like to remove any downloaded packages 23012 * that are no longer in use by any other user. 23013 * @param userHandle the user being removed 23014 */ 23015 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23016 final boolean DEBUG_CLEAN_APKS = false; 23017 int [] users = userManager.getUserIds(); 23018 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23019 while (psit.hasNext()) { 23020 PackageSetting ps = psit.next(); 23021 if (ps.pkg == null) { 23022 continue; 23023 } 23024 final String packageName = ps.pkg.packageName; 23025 // Skip over if system app 23026 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23027 continue; 23028 } 23029 if (DEBUG_CLEAN_APKS) { 23030 Slog.i(TAG, "Checking package " + packageName); 23031 } 23032 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23033 if (keep) { 23034 if (DEBUG_CLEAN_APKS) { 23035 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23036 } 23037 } else { 23038 for (int i = 0; i < users.length; i++) { 23039 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23040 keep = true; 23041 if (DEBUG_CLEAN_APKS) { 23042 Slog.i(TAG, " Keeping package " + packageName + " for user " 23043 + users[i]); 23044 } 23045 break; 23046 } 23047 } 23048 } 23049 if (!keep) { 23050 if (DEBUG_CLEAN_APKS) { 23051 Slog.i(TAG, " Removing package " + packageName); 23052 } 23053 mHandler.post(new Runnable() { 23054 public void run() { 23055 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23056 userHandle, 0); 23057 } //end run 23058 }); 23059 } 23060 } 23061 } 23062 23063 /** Called by UserManagerService */ 23064 void createNewUser(int userId, String[] disallowedPackages) { 23065 synchronized (mInstallLock) { 23066 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23067 } 23068 synchronized (mPackages) { 23069 scheduleWritePackageRestrictionsLocked(userId); 23070 scheduleWritePackageListLocked(userId); 23071 applyFactoryDefaultBrowserLPw(userId); 23072 primeDomainVerificationsLPw(userId); 23073 } 23074 } 23075 23076 void onNewUserCreated(final int userId) { 23077 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23078 // If permission review for legacy apps is required, we represent 23079 // dagerous permissions for such apps as always granted runtime 23080 // permissions to keep per user flag state whether review is needed. 23081 // Hence, if a new user is added we have to propagate dangerous 23082 // permission grants for these legacy apps. 23083 if (mPermissionReviewRequired) { 23084 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 23085 | UPDATE_PERMISSIONS_REPLACE_ALL); 23086 } 23087 } 23088 23089 @Override 23090 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23091 mContext.enforceCallingOrSelfPermission( 23092 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23093 "Only package verification agents can read the verifier device identity"); 23094 23095 synchronized (mPackages) { 23096 return mSettings.getVerifierDeviceIdentityLPw(); 23097 } 23098 } 23099 23100 @Override 23101 public void setPermissionEnforced(String permission, boolean enforced) { 23102 // TODO: Now that we no longer change GID for storage, this should to away. 23103 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23104 "setPermissionEnforced"); 23105 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23106 synchronized (mPackages) { 23107 if (mSettings.mReadExternalStorageEnforced == null 23108 || mSettings.mReadExternalStorageEnforced != enforced) { 23109 mSettings.mReadExternalStorageEnforced = enforced; 23110 mSettings.writeLPr(); 23111 } 23112 } 23113 // kill any non-foreground processes so we restart them and 23114 // grant/revoke the GID. 23115 final IActivityManager am = ActivityManager.getService(); 23116 if (am != null) { 23117 final long token = Binder.clearCallingIdentity(); 23118 try { 23119 am.killProcessesBelowForeground("setPermissionEnforcement"); 23120 } catch (RemoteException e) { 23121 } finally { 23122 Binder.restoreCallingIdentity(token); 23123 } 23124 } 23125 } else { 23126 throw new IllegalArgumentException("No selective enforcement for " + permission); 23127 } 23128 } 23129 23130 @Override 23131 @Deprecated 23132 public boolean isPermissionEnforced(String permission) { 23133 return true; 23134 } 23135 23136 @Override 23137 public boolean isStorageLow() { 23138 final long token = Binder.clearCallingIdentity(); 23139 try { 23140 final DeviceStorageMonitorInternal 23141 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23142 if (dsm != null) { 23143 return dsm.isMemoryLow(); 23144 } else { 23145 return false; 23146 } 23147 } finally { 23148 Binder.restoreCallingIdentity(token); 23149 } 23150 } 23151 23152 @Override 23153 public IPackageInstaller getPackageInstaller() { 23154 return mInstallerService; 23155 } 23156 23157 private boolean userNeedsBadging(int userId) { 23158 int index = mUserNeedsBadging.indexOfKey(userId); 23159 if (index < 0) { 23160 final UserInfo userInfo; 23161 final long token = Binder.clearCallingIdentity(); 23162 try { 23163 userInfo = sUserManager.getUserInfo(userId); 23164 } finally { 23165 Binder.restoreCallingIdentity(token); 23166 } 23167 final boolean b; 23168 if (userInfo != null && userInfo.isManagedProfile()) { 23169 b = true; 23170 } else { 23171 b = false; 23172 } 23173 mUserNeedsBadging.put(userId, b); 23174 return b; 23175 } 23176 return mUserNeedsBadging.valueAt(index); 23177 } 23178 23179 @Override 23180 public KeySet getKeySetByAlias(String packageName, String alias) { 23181 if (packageName == null || alias == null) { 23182 return null; 23183 } 23184 synchronized(mPackages) { 23185 final PackageParser.Package pkg = mPackages.get(packageName); 23186 if (pkg == null) { 23187 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23188 throw new IllegalArgumentException("Unknown package: " + packageName); 23189 } 23190 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23191 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23192 } 23193 } 23194 23195 @Override 23196 public KeySet getSigningKeySet(String packageName) { 23197 if (packageName == null) { 23198 return null; 23199 } 23200 synchronized(mPackages) { 23201 final PackageParser.Package pkg = mPackages.get(packageName); 23202 if (pkg == null) { 23203 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23204 throw new IllegalArgumentException("Unknown package: " + packageName); 23205 } 23206 if (pkg.applicationInfo.uid != Binder.getCallingUid() 23207 && Process.SYSTEM_UID != Binder.getCallingUid()) { 23208 throw new SecurityException("May not access signing KeySet of other apps."); 23209 } 23210 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23211 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23212 } 23213 } 23214 23215 @Override 23216 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23217 if (packageName == null || ks == null) { 23218 return false; 23219 } 23220 synchronized(mPackages) { 23221 final PackageParser.Package pkg = mPackages.get(packageName); 23222 if (pkg == null) { 23223 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23224 throw new IllegalArgumentException("Unknown package: " + packageName); 23225 } 23226 IBinder ksh = ks.getToken(); 23227 if (ksh instanceof KeySetHandle) { 23228 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23229 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23230 } 23231 return false; 23232 } 23233 } 23234 23235 @Override 23236 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23237 if (packageName == null || ks == null) { 23238 return false; 23239 } 23240 synchronized(mPackages) { 23241 final PackageParser.Package pkg = mPackages.get(packageName); 23242 if (pkg == null) { 23243 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23244 throw new IllegalArgumentException("Unknown package: " + packageName); 23245 } 23246 IBinder ksh = ks.getToken(); 23247 if (ksh instanceof KeySetHandle) { 23248 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23249 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23250 } 23251 return false; 23252 } 23253 } 23254 23255 private void deletePackageIfUnusedLPr(final String packageName) { 23256 PackageSetting ps = mSettings.mPackages.get(packageName); 23257 if (ps == null) { 23258 return; 23259 } 23260 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23261 // TODO Implement atomic delete if package is unused 23262 // It is currently possible that the package will be deleted even if it is installed 23263 // after this method returns. 23264 mHandler.post(new Runnable() { 23265 public void run() { 23266 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23267 0, PackageManager.DELETE_ALL_USERS); 23268 } 23269 }); 23270 } 23271 } 23272 23273 /** 23274 * Check and throw if the given before/after packages would be considered a 23275 * downgrade. 23276 */ 23277 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23278 throws PackageManagerException { 23279 if (after.versionCode < before.mVersionCode) { 23280 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23281 "Update version code " + after.versionCode + " is older than current " 23282 + before.mVersionCode); 23283 } else if (after.versionCode == before.mVersionCode) { 23284 if (after.baseRevisionCode < before.baseRevisionCode) { 23285 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23286 "Update base revision code " + after.baseRevisionCode 23287 + " is older than current " + before.baseRevisionCode); 23288 } 23289 23290 if (!ArrayUtils.isEmpty(after.splitNames)) { 23291 for (int i = 0; i < after.splitNames.length; i++) { 23292 final String splitName = after.splitNames[i]; 23293 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23294 if (j != -1) { 23295 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23296 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23297 "Update split " + splitName + " revision code " 23298 + after.splitRevisionCodes[i] + " is older than current " 23299 + before.splitRevisionCodes[j]); 23300 } 23301 } 23302 } 23303 } 23304 } 23305 } 23306 23307 private static class MoveCallbacks extends Handler { 23308 private static final int MSG_CREATED = 1; 23309 private static final int MSG_STATUS_CHANGED = 2; 23310 23311 private final RemoteCallbackList<IPackageMoveObserver> 23312 mCallbacks = new RemoteCallbackList<>(); 23313 23314 private final SparseIntArray mLastStatus = new SparseIntArray(); 23315 23316 public MoveCallbacks(Looper looper) { 23317 super(looper); 23318 } 23319 23320 public void register(IPackageMoveObserver callback) { 23321 mCallbacks.register(callback); 23322 } 23323 23324 public void unregister(IPackageMoveObserver callback) { 23325 mCallbacks.unregister(callback); 23326 } 23327 23328 @Override 23329 public void handleMessage(Message msg) { 23330 final SomeArgs args = (SomeArgs) msg.obj; 23331 final int n = mCallbacks.beginBroadcast(); 23332 for (int i = 0; i < n; i++) { 23333 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23334 try { 23335 invokeCallback(callback, msg.what, args); 23336 } catch (RemoteException ignored) { 23337 } 23338 } 23339 mCallbacks.finishBroadcast(); 23340 args.recycle(); 23341 } 23342 23343 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23344 throws RemoteException { 23345 switch (what) { 23346 case MSG_CREATED: { 23347 callback.onCreated(args.argi1, (Bundle) args.arg2); 23348 break; 23349 } 23350 case MSG_STATUS_CHANGED: { 23351 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23352 break; 23353 } 23354 } 23355 } 23356 23357 private void notifyCreated(int moveId, Bundle extras) { 23358 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23359 23360 final SomeArgs args = SomeArgs.obtain(); 23361 args.argi1 = moveId; 23362 args.arg2 = extras; 23363 obtainMessage(MSG_CREATED, args).sendToTarget(); 23364 } 23365 23366 private void notifyStatusChanged(int moveId, int status) { 23367 notifyStatusChanged(moveId, status, -1); 23368 } 23369 23370 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23371 Slog.v(TAG, "Move " + moveId + " status " + status); 23372 23373 final SomeArgs args = SomeArgs.obtain(); 23374 args.argi1 = moveId; 23375 args.argi2 = status; 23376 args.arg3 = estMillis; 23377 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23378 23379 synchronized (mLastStatus) { 23380 mLastStatus.put(moveId, status); 23381 } 23382 } 23383 } 23384 23385 private final static class OnPermissionChangeListeners extends Handler { 23386 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23387 23388 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23389 new RemoteCallbackList<>(); 23390 23391 public OnPermissionChangeListeners(Looper looper) { 23392 super(looper); 23393 } 23394 23395 @Override 23396 public void handleMessage(Message msg) { 23397 switch (msg.what) { 23398 case MSG_ON_PERMISSIONS_CHANGED: { 23399 final int uid = msg.arg1; 23400 handleOnPermissionsChanged(uid); 23401 } break; 23402 } 23403 } 23404 23405 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23406 mPermissionListeners.register(listener); 23407 23408 } 23409 23410 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23411 mPermissionListeners.unregister(listener); 23412 } 23413 23414 public void onPermissionsChanged(int uid) { 23415 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23416 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23417 } 23418 } 23419 23420 private void handleOnPermissionsChanged(int uid) { 23421 final int count = mPermissionListeners.beginBroadcast(); 23422 try { 23423 for (int i = 0; i < count; i++) { 23424 IOnPermissionsChangeListener callback = mPermissionListeners 23425 .getBroadcastItem(i); 23426 try { 23427 callback.onPermissionsChanged(uid); 23428 } catch (RemoteException e) { 23429 Log.e(TAG, "Permission listener is dead", e); 23430 } 23431 } 23432 } finally { 23433 mPermissionListeners.finishBroadcast(); 23434 } 23435 } 23436 } 23437 23438 private class PackageManagerInternalImpl extends PackageManagerInternal { 23439 @Override 23440 public void setLocationPackagesProvider(PackagesProvider provider) { 23441 synchronized (mPackages) { 23442 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23443 } 23444 } 23445 23446 @Override 23447 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23448 synchronized (mPackages) { 23449 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23450 } 23451 } 23452 23453 @Override 23454 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23455 synchronized (mPackages) { 23456 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23457 } 23458 } 23459 23460 @Override 23461 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23462 synchronized (mPackages) { 23463 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23464 } 23465 } 23466 23467 @Override 23468 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23469 synchronized (mPackages) { 23470 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23471 } 23472 } 23473 23474 @Override 23475 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23476 synchronized (mPackages) { 23477 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23478 } 23479 } 23480 23481 @Override 23482 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23483 synchronized (mPackages) { 23484 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23485 packageName, userId); 23486 } 23487 } 23488 23489 @Override 23490 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23491 synchronized (mPackages) { 23492 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23493 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23494 packageName, userId); 23495 } 23496 } 23497 23498 @Override 23499 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23500 synchronized (mPackages) { 23501 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23502 packageName, userId); 23503 } 23504 } 23505 23506 @Override 23507 public void setKeepUninstalledPackages(final List<String> packageList) { 23508 Preconditions.checkNotNull(packageList); 23509 List<String> removedFromList = null; 23510 synchronized (mPackages) { 23511 if (mKeepUninstalledPackages != null) { 23512 final int packagesCount = mKeepUninstalledPackages.size(); 23513 for (int i = 0; i < packagesCount; i++) { 23514 String oldPackage = mKeepUninstalledPackages.get(i); 23515 if (packageList != null && packageList.contains(oldPackage)) { 23516 continue; 23517 } 23518 if (removedFromList == null) { 23519 removedFromList = new ArrayList<>(); 23520 } 23521 removedFromList.add(oldPackage); 23522 } 23523 } 23524 mKeepUninstalledPackages = new ArrayList<>(packageList); 23525 if (removedFromList != null) { 23526 final int removedCount = removedFromList.size(); 23527 for (int i = 0; i < removedCount; i++) { 23528 deletePackageIfUnusedLPr(removedFromList.get(i)); 23529 } 23530 } 23531 } 23532 } 23533 23534 @Override 23535 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23536 synchronized (mPackages) { 23537 // If we do not support permission review, done. 23538 if (!mPermissionReviewRequired) { 23539 return false; 23540 } 23541 23542 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23543 if (packageSetting == null) { 23544 return false; 23545 } 23546 23547 // Permission review applies only to apps not supporting the new permission model. 23548 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23549 return false; 23550 } 23551 23552 // Legacy apps have the permission and get user consent on launch. 23553 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23554 return permissionsState.isPermissionReviewRequired(userId); 23555 } 23556 } 23557 23558 @Override 23559 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23560 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23561 } 23562 23563 @Override 23564 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23565 int userId) { 23566 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23567 } 23568 23569 @Override 23570 public void setDeviceAndProfileOwnerPackages( 23571 int deviceOwnerUserId, String deviceOwnerPackage, 23572 SparseArray<String> profileOwnerPackages) { 23573 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23574 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23575 } 23576 23577 @Override 23578 public boolean isPackageDataProtected(int userId, String packageName) { 23579 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23580 } 23581 23582 @Override 23583 public boolean isPackageEphemeral(int userId, String packageName) { 23584 synchronized (mPackages) { 23585 final PackageSetting ps = mSettings.mPackages.get(packageName); 23586 return ps != null ? ps.getInstantApp(userId) : false; 23587 } 23588 } 23589 23590 @Override 23591 public boolean wasPackageEverLaunched(String packageName, int userId) { 23592 synchronized (mPackages) { 23593 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23594 } 23595 } 23596 23597 @Override 23598 public void grantRuntimePermission(String packageName, String name, int userId, 23599 boolean overridePolicy) { 23600 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23601 overridePolicy); 23602 } 23603 23604 @Override 23605 public void revokeRuntimePermission(String packageName, String name, int userId, 23606 boolean overridePolicy) { 23607 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23608 overridePolicy); 23609 } 23610 23611 @Override 23612 public String getNameForUid(int uid) { 23613 return PackageManagerService.this.getNameForUid(uid); 23614 } 23615 23616 @Override 23617 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23618 Intent origIntent, String resolvedType, String callingPackage, 23619 Bundle verificationBundle, int userId) { 23620 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23621 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23622 userId); 23623 } 23624 23625 @Override 23626 public void grantEphemeralAccess(int userId, Intent intent, 23627 int targetAppId, int ephemeralAppId) { 23628 synchronized (mPackages) { 23629 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23630 targetAppId, ephemeralAppId); 23631 } 23632 } 23633 23634 @Override 23635 public boolean isInstantAppInstallerComponent(ComponentName component) { 23636 synchronized (mPackages) { 23637 return mInstantAppInstallerActivity != null 23638 && mInstantAppInstallerActivity.getComponentName().equals(component); 23639 } 23640 } 23641 23642 @Override 23643 public void pruneInstantApps() { 23644 synchronized (mPackages) { 23645 mInstantAppRegistry.pruneInstantAppsLPw(); 23646 } 23647 } 23648 23649 @Override 23650 public String getSetupWizardPackageName() { 23651 return mSetupWizardPackage; 23652 } 23653 23654 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23655 if (policy != null) { 23656 mExternalSourcesPolicy = policy; 23657 } 23658 } 23659 23660 @Override 23661 public boolean isPackagePersistent(String packageName) { 23662 synchronized (mPackages) { 23663 PackageParser.Package pkg = mPackages.get(packageName); 23664 return pkg != null 23665 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23666 | ApplicationInfo.FLAG_PERSISTENT)) == 23667 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23668 : false; 23669 } 23670 } 23671 23672 @Override 23673 public List<PackageInfo> getOverlayPackages(int userId) { 23674 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23675 synchronized (mPackages) { 23676 for (PackageParser.Package p : mPackages.values()) { 23677 if (p.mOverlayTarget != null) { 23678 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23679 if (pkg != null) { 23680 overlayPackages.add(pkg); 23681 } 23682 } 23683 } 23684 } 23685 return overlayPackages; 23686 } 23687 23688 @Override 23689 public List<String> getTargetPackageNames(int userId) { 23690 List<String> targetPackages = new ArrayList<>(); 23691 synchronized (mPackages) { 23692 for (PackageParser.Package p : mPackages.values()) { 23693 if (p.mOverlayTarget == null) { 23694 targetPackages.add(p.packageName); 23695 } 23696 } 23697 } 23698 return targetPackages; 23699 } 23700 23701 @Override 23702 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23703 @Nullable List<String> overlayPackageNames) { 23704 synchronized (mPackages) { 23705 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23706 Slog.e(TAG, "failed to find package " + targetPackageName); 23707 return false; 23708 } 23709 23710 ArrayList<String> paths = null; 23711 if (overlayPackageNames != null) { 23712 final int N = overlayPackageNames.size(); 23713 paths = new ArrayList<>(N); 23714 for (int i = 0; i < N; i++) { 23715 final String packageName = overlayPackageNames.get(i); 23716 final PackageParser.Package pkg = mPackages.get(packageName); 23717 if (pkg == null) { 23718 Slog.e(TAG, "failed to find package " + packageName); 23719 return false; 23720 } 23721 paths.add(pkg.baseCodePath); 23722 } 23723 } 23724 23725 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23726 mEnabledOverlayPaths.get(userId); 23727 if (userSpecificOverlays == null) { 23728 userSpecificOverlays = new ArrayMap<>(); 23729 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23730 } 23731 23732 if (paths != null && paths.size() > 0) { 23733 userSpecificOverlays.put(targetPackageName, paths); 23734 } else { 23735 userSpecificOverlays.remove(targetPackageName); 23736 } 23737 return true; 23738 } 23739 } 23740 23741 @Override 23742 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23743 int flags, int userId) { 23744 return resolveIntentInternal( 23745 intent, resolvedType, flags, userId, true /*resolveForStart*/); 23746 } 23747 23748 @Override 23749 public ResolveInfo resolveService(Intent intent, String resolvedType, 23750 int flags, int userId, int callingUid) { 23751 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23752 } 23753 23754 @Override 23755 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23756 synchronized (mPackages) { 23757 mIsolatedOwners.put(isolatedUid, ownerUid); 23758 } 23759 } 23760 23761 @Override 23762 public void removeIsolatedUid(int isolatedUid) { 23763 synchronized (mPackages) { 23764 mIsolatedOwners.delete(isolatedUid); 23765 } 23766 } 23767 23768 @Override 23769 public int getUidTargetSdkVersion(int uid) { 23770 synchronized (mPackages) { 23771 return getUidTargetSdkVersionLockedLPr(uid); 23772 } 23773 } 23774 } 23775 23776 @Override 23777 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23778 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23779 synchronized (mPackages) { 23780 final long identity = Binder.clearCallingIdentity(); 23781 try { 23782 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23783 packageNames, userId); 23784 } finally { 23785 Binder.restoreCallingIdentity(identity); 23786 } 23787 } 23788 } 23789 23790 @Override 23791 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23792 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23793 synchronized (mPackages) { 23794 final long identity = Binder.clearCallingIdentity(); 23795 try { 23796 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23797 packageNames, userId); 23798 } finally { 23799 Binder.restoreCallingIdentity(identity); 23800 } 23801 } 23802 } 23803 23804 private static void enforceSystemOrPhoneCaller(String tag) { 23805 int callingUid = Binder.getCallingUid(); 23806 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23807 throw new SecurityException( 23808 "Cannot call " + tag + " from UID " + callingUid); 23809 } 23810 } 23811 23812 boolean isHistoricalPackageUsageAvailable() { 23813 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23814 } 23815 23816 /** 23817 * Return a <b>copy</b> of the collection of packages known to the package manager. 23818 * @return A copy of the values of mPackages. 23819 */ 23820 Collection<PackageParser.Package> getPackages() { 23821 synchronized (mPackages) { 23822 return new ArrayList<>(mPackages.values()); 23823 } 23824 } 23825 23826 /** 23827 * Logs process start information (including base APK hash) to the security log. 23828 * @hide 23829 */ 23830 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23831 String apkFile, int pid) { 23832 if (!SecurityLog.isLoggingEnabled()) { 23833 return; 23834 } 23835 Bundle data = new Bundle(); 23836 data.putLong("startTimestamp", System.currentTimeMillis()); 23837 data.putString("processName", processName); 23838 data.putInt("uid", uid); 23839 data.putString("seinfo", seinfo); 23840 data.putString("apkFile", apkFile); 23841 data.putInt("pid", pid); 23842 Message msg = mProcessLoggingHandler.obtainMessage( 23843 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23844 msg.setData(data); 23845 mProcessLoggingHandler.sendMessage(msg); 23846 } 23847 23848 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23849 return mCompilerStats.getPackageStats(pkgName); 23850 } 23851 23852 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23853 return getOrCreateCompilerPackageStats(pkg.packageName); 23854 } 23855 23856 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23857 return mCompilerStats.getOrCreatePackageStats(pkgName); 23858 } 23859 23860 public void deleteCompilerPackageStats(String pkgName) { 23861 mCompilerStats.deletePackageStats(pkgName); 23862 } 23863 23864 @Override 23865 public int getInstallReason(String packageName, int userId) { 23866 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23867 true /* requireFullPermission */, false /* checkShell */, 23868 "get install reason"); 23869 synchronized (mPackages) { 23870 final PackageSetting ps = mSettings.mPackages.get(packageName); 23871 if (ps != null) { 23872 return ps.getInstallReason(userId); 23873 } 23874 } 23875 return PackageManager.INSTALL_REASON_UNKNOWN; 23876 } 23877 23878 @Override 23879 public boolean canRequestPackageInstalls(String packageName, int userId) { 23880 int callingUid = Binder.getCallingUid(); 23881 int uid = getPackageUid(packageName, 0, userId); 23882 if (callingUid != uid && callingUid != Process.ROOT_UID 23883 && callingUid != Process.SYSTEM_UID) { 23884 throw new SecurityException( 23885 "Caller uid " + callingUid + " does not own package " + packageName); 23886 } 23887 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23888 if (info == null) { 23889 return false; 23890 } 23891 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23892 throw new UnsupportedOperationException( 23893 "Operation only supported on apps targeting Android O or higher"); 23894 } 23895 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23896 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23897 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23898 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23899 } 23900 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23901 return false; 23902 } 23903 if (mExternalSourcesPolicy != null) { 23904 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23905 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23906 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23907 } 23908 } 23909 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23910 } 23911 23912 @Override 23913 public ComponentName getInstantAppResolverSettingsComponent() { 23914 return mInstantAppResolverSettingsComponent; 23915 } 23916 23917 @Override 23918 public ComponentName getInstantAppInstallerComponent() { 23919 return mInstantAppInstallerActivity == null 23920 ? null : mInstantAppInstallerActivity.getComponentName(); 23921 } 23922 23923 @Override 23924 public String getInstantAppAndroidId(String packageName, int userId) { 23925 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23926 "getInstantAppAndroidId"); 23927 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23928 true /* requireFullPermission */, false /* checkShell */, 23929 "getInstantAppAndroidId"); 23930 // Make sure the target is an Instant App. 23931 if (!isInstantApp(packageName, userId)) { 23932 return null; 23933 } 23934 synchronized (mPackages) { 23935 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23936 } 23937 } 23938} 23939 23940interface PackageSender { 23941 void sendPackageBroadcast(final String action, final String pkg, 23942 final Bundle extras, final int flags, final String targetPkg, 23943 final IIntentReceiver finishedReceiver, final int[] userIds); 23944 void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 23945 int appId, int... userIds); 23946} 23947